90a94b208004cda219dd11a01c879df1170ccd5a
[platform/upstream/gst-plugins-good.git] / sys / v4l2 / gstv4l2bufferpool.c
1 /* GStreamer
2  *
3  * Copyright (C) 2001-2002 Ronald Bultje <rbultje@ronald.bitfreak.net>
4  *               2006 Edgard Lima <edgard.lima@indt.org.br>
5  *               2009 Texas Instruments, Inc - http://www.ti.com/
6  *
7  * gstv4l2bufferpool.c V4L2 buffer pool class
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Library General Public
11  * License as published by the Free Software Foundation; either
12  * version 2 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Library General Public License for more details.
18  *
19  * You should have received a copy of the GNU Library General Public
20  * License along with this library; if not, write to the
21  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
22  * Boston, MA 02110-1301, USA.
23  */
24
25 #ifdef HAVE_CONFIG_H
26 #  include <config.h>
27 #endif
28
29 #if HAVE_DECL_V4L2_MEMORY_DMABUF
30 #ifndef _GNU_SOURCE
31 # define _GNU_SOURCE            /* O_CLOEXEC */
32 #endif
33 #include <fcntl.h>
34 #endif
35
36 #include <sys/mman.h>
37 #include <string.h>
38 #include <unistd.h>
39
40 #include "gst/video/video.h"
41 #include "gst/video/gstvideometa.h"
42 #include "gst/video/gstvideopool.h"
43 #include "gst/allocators/gstdmabuf.h"
44
45 #include <gstv4l2bufferpool.h>
46
47 #include "v4l2_calls.h"
48 #include "gst/gst-i18n-plugin.h"
49 #include <gst/glib-compat-private.h>
50
51 /* videodev2.h is not versioned and we can't easily check for the presence
52  * of enum values at compile time, but the V4L2_CAP_VIDEO_OUTPUT_OVERLAY define
53  * was added in the same commit as V4L2_FIELD_INTERLACED_{TB,BT} (b2787845) */
54 #ifndef V4L2_CAP_VIDEO_OUTPUT_OVERLAY
55 #define V4L2_FIELD_INTERLACED_TB 8
56 #define V4L2_FIELD_INTERLACED_BT 9
57 #endif
58
59 GST_DEBUG_CATEGORY_EXTERN (v4l2_debug);
60 #define GST_CAT_DEFAULT v4l2_debug
61
62 /*
63  * GstV4l2Buffer:
64  */
65 GType
66 gst_v4l2_meta_api_get_type (void)
67 {
68   static volatile GType type;
69   static const gchar *tags[] =
70       { GST_META_TAG_VIDEO_STR, GST_META_TAG_MEMORY_STR, NULL };
71
72   if (g_once_init_enter (&type)) {
73     GType _type = gst_meta_api_type_register ("GstV4l2MetaAPI", tags);
74     g_once_init_leave (&type, _type);
75   }
76   return type;
77 }
78
79 const GstMetaInfo *
80 gst_v4l2_meta_get_info (void)
81 {
82   static const GstMetaInfo *meta_info = NULL;
83
84   if (g_once_init_enter (&meta_info)) {
85     const GstMetaInfo *meta =
86         gst_meta_register (gst_v4l2_meta_api_get_type (), "GstV4l2Meta",
87         sizeof (GstV4l2Meta), (GstMetaInitFunction) NULL,
88         (GstMetaFreeFunction) NULL, (GstMetaTransformFunction) NULL);
89     g_once_init_leave (&meta_info, meta);
90   }
91   return meta_info;
92 }
93
94 /*
95  * GstV4l2BufferPool:
96  */
97 #define gst_v4l2_buffer_pool_parent_class parent_class
98 G_DEFINE_TYPE (GstV4l2BufferPool, gst_v4l2_buffer_pool, GST_TYPE_BUFFER_POOL);
99
100 static void gst_v4l2_buffer_pool_release_buffer (GstBufferPool * bpool,
101     GstBuffer * buffer);
102
103 static void
104 gst_v4l2_buffer_pool_free_buffer (GstBufferPool * bpool, GstBuffer * buffer)
105 {
106   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
107   GstV4l2Object *obj;
108
109   obj = pool->obj;
110
111   switch (obj->mode) {
112     case GST_V4L2_IO_RW:
113     case GST_V4L2_IO_DMABUF:
114       break;
115     case GST_V4L2_IO_MMAP:
116     {
117       GstV4l2Meta *meta;
118       gint index;
119       gint i = 0;
120
121       meta = GST_V4L2_META_GET (buffer);
122       g_assert (meta != NULL);
123
124       index = meta->vbuffer.index;
125
126       for (i = 0; i < meta->n_planes; i++) {
127         GST_LOG_OBJECT (pool,
128             "unmap multiplanar buffer %p idx %d (data %p, len %u, plane %u)",
129             buffer, index, meta->mem[i], meta->vplanes[i].length, i);
130
131         v4l2_munmap (meta->mem[i], meta->vplanes[i].length);
132       }
133
134       pool->buffers[index] = NULL;
135       break;
136     }
137     case GST_V4L2_IO_USERPTR:
138     default:
139       g_assert_not_reached ();
140       break;
141   }
142   gst_buffer_unref (buffer);
143 }
144
145 static GstFlowReturn
146 gst_v4l2_buffer_pool_alloc_buffer (GstBufferPool * bpool, GstBuffer ** buffer,
147     GstBufferPoolAcquireParams * params)
148 {
149   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
150   GstBuffer *newbuf;
151   GstV4l2Meta *meta;
152   GstV4l2Object *obj;
153   GstVideoInfo *info;
154   guint index;
155   gint i;
156
157   obj = pool->obj;
158   info = &obj->info;
159
160   switch (obj->mode) {
161     case GST_V4L2_IO_RW:
162     {
163       newbuf =
164           gst_buffer_new_allocate (pool->allocator, pool->size, &pool->params);
165       break;
166     }
167     case GST_V4L2_IO_MMAP:
168     case GST_V4L2_IO_DMABUF:
169     {
170 #ifdef VIDIOC_CREATE_BUFS
171       if (pool->num_allocated == pool->num_buffers) {
172         struct v4l2_create_buffers create_bufs;
173
174         memset (&create_bufs, 0, sizeof (struct v4l2_create_buffers));
175         create_bufs.count = 1;
176         create_bufs.memory = V4L2_MEMORY_MMAP;
177         create_bufs.format.type = obj->type;
178
179         if (v4l2_ioctl (pool->video_fd, VIDIOC_G_FMT, &create_bufs.format) < 0)
180           goto g_fmt_failed;
181
182         if (v4l2_ioctl (pool->video_fd, VIDIOC_CREATE_BUFS, &create_bufs) < 0)
183           goto create_bufs_failed;
184
185         GST_LOG_OBJECT (pool, "created buffer with index: %u",
186             create_bufs.index);
187         pool->num_buffers++;
188         pool->buffers = g_renew (GstBuffer *, pool->buffers, pool->num_buffers);
189         pool->buffers[pool->num_buffers - 1] = NULL;
190       }
191 #endif
192       newbuf = gst_buffer_new ();
193       meta = GST_V4L2_META_ADD (newbuf);
194
195       index = pool->num_allocated;
196
197       GST_LOG_OBJECT (pool, "creating buffer %u, %p", index, newbuf);
198
199       /* prepare the buffer */
200       memset (&meta->vbuffer, 0x0, sizeof (struct v4l2_buffer));
201       meta->vbuffer.index = index;
202       meta->vbuffer.type = obj->type;
203       meta->vbuffer.memory = V4L2_MEMORY_MMAP;
204
205       /* main information */
206       meta->n_planes = obj->n_v4l2_planes;
207
208       /* prepare the planes of the buffer */
209       if (V4L2_TYPE_IS_MULTIPLANAR (obj->type)) {
210         /* length is the number of elements in the
211          * vplanes array */
212         meta->vbuffer.length = obj->n_v4l2_planes;
213         meta->vbuffer.m.planes = meta->vplanes;
214       }
215
216       /* the buffer is prepared, now fill in it with meaningful values */
217       if (v4l2_ioctl (pool->video_fd, VIDIOC_QUERYBUF, &meta->vbuffer) < 0)
218         goto querybuf_failed;
219
220       /* in non MPLANE mode we emulate one plane in order to
221        * factorize the code */
222       if (!V4L2_TYPE_IS_MULTIPLANAR (obj->type)) {
223         /* here meta->n_planes == 1 */
224         meta->vplanes[0].length = meta->vbuffer.length;
225         meta->vplanes[0].bytesused = meta->vbuffer.bytesused;
226         meta->vplanes[0].m.mem_offset = meta->vbuffer.m.offset;
227         meta->vplanes[0].data_offset = 0;
228       }
229
230       GST_LOG_OBJECT (pool, "  index:     %u", meta->vbuffer.index);
231       GST_LOG_OBJECT (pool, "  type:      %d", meta->vbuffer.type);
232       GST_LOG_OBJECT (pool, "  flags:     %08x", meta->vbuffer.flags);
233       GST_LOG_OBJECT (pool, "  field:     %d", meta->vbuffer.field);
234       GST_LOG_OBJECT (pool, "  memory:    %d", meta->vbuffer.memory);
235       GST_LOG_OBJECT (pool, "  planes:    %d", meta->n_planes);
236
237 #ifndef GST_DISABLE_GST_DEBUG
238       if (meta->vbuffer.memory == V4L2_MEMORY_MMAP) {
239         for (i = 0; i < meta->n_planes; i++) {
240           GST_LOG_OBJECT (pool, "  bytesused: %u, plane: %u",
241               meta->vplanes[i].bytesused, i);
242           GST_LOG_OBJECT (pool, "  MMAP offset:  %u, plane: %u",
243               meta->vplanes[i].m.mem_offset, i);
244         }
245       }
246 #endif
247
248       if (obj->mode == GST_V4L2_IO_MMAP) {
249         /* append one gstmemory for each plane */
250         for (i = 0; i < meta->n_planes; i++) {
251           meta->mem[i] = v4l2_mmap (0, meta->vplanes[i].length,
252               PROT_READ | PROT_WRITE, MAP_SHARED, pool->video_fd,
253               meta->vplanes[i].m.mem_offset);
254           if (meta->mem[i] == MAP_FAILED)
255             goto mmap_failed;
256
257           GST_LOG_OBJECT (pool, "  buffer length %d, data offset %d, plane %d",
258               meta->vplanes[i].length, meta->vplanes[i].data_offset, i);
259
260           gst_buffer_append_memory (newbuf,
261               gst_memory_new_wrapped (GST_MEMORY_FLAG_NO_SHARE,
262                   meta->mem[i], meta->vplanes[i].length,
263                   meta->vplanes[i].data_offset,
264                   meta->vplanes[i].length, NULL, NULL));
265         }
266       }
267 #if HAVE_DECL_V4L2_MEMORY_DMABUF
268       if (obj->mode == GST_V4L2_IO_DMABUF) {
269         struct v4l2_exportbuffer expbuf;
270
271         memset (&expbuf, 0, sizeof (struct v4l2_exportbuffer));
272         expbuf.type = meta->vbuffer.type;
273         expbuf.index = meta->vbuffer.index;
274         expbuf.flags = O_CLOEXEC;
275
276         for (i = 0; i < meta->n_planes; i++) {
277           expbuf.plane = i;
278
279           if (v4l2_ioctl (pool->video_fd, VIDIOC_EXPBUF, &expbuf) < 0)
280             goto expbuf_failed;
281
282           gst_buffer_append_memory (newbuf,
283               gst_dmabuf_allocator_alloc (pool->allocator, expbuf.fd,
284                   meta->vplanes[i].length));
285         }
286
287         meta->vbuffer.memory = V4L2_MEMORY_DMABUF;
288
289         /* in non-MPLANE mode our meta is not automatically updated
290          * because the plane is emulated (not referenced by
291          * meta->vbuffer) */
292         if (!V4L2_TYPE_IS_MULTIPLANAR (obj->type))
293           meta->vplanes[0].m.fd = meta->vbuffer.m.fd;
294       }
295 #endif
296       /* add metadata to raw video buffers */
297       if (pool->add_videometa && info->finfo) {
298         const GstVideoFormatInfo *finfo = info->finfo;
299         gsize offset[GST_VIDEO_MAX_PLANES];
300         gint width, height, n_gst_planes, offs, i, stride[GST_VIDEO_MAX_PLANES];
301
302         width = GST_VIDEO_INFO_WIDTH (info);
303         height = GST_VIDEO_INFO_HEIGHT (info);
304
305         /* n_gst_planes is the number of planes
306          * (RGB: 1, YUY2: 1, NV12: 2, I420: 3)
307          * It's greater or equal than the number of v4l2 planes. */
308         n_gst_planes = GST_VIDEO_INFO_N_PLANES (info);
309
310         /* the basic are common between MPLANE mode and non MPLANE mode
311          * except a special case inside the loop at the end
312          */
313         offs = 0;
314         for (i = 0; i < n_gst_planes; i++) {
315           GST_DEBUG_OBJECT (pool, "adding video meta, bytesperline %d",
316               obj->bytesperline[i]);
317
318           offset[i] = offs;
319
320           if (GST_VIDEO_FORMAT_INFO_IS_TILED (finfo)) {
321             guint x_tiles, y_tiles, ws, hs, tile_height;
322
323             ws = GST_VIDEO_FORMAT_INFO_TILE_WS (finfo);
324             hs = GST_VIDEO_FORMAT_INFO_TILE_HS (finfo);
325             tile_height = 1 << hs;
326
327             x_tiles = obj->bytesperline[i] >> ws;
328             y_tiles = GST_VIDEO_FORMAT_INFO_SCALE_HEIGHT (finfo, i,
329                 GST_ROUND_UP_N (height, tile_height) >> hs);
330             stride[i] = GST_VIDEO_TILE_MAKE_STRIDE (x_tiles, y_tiles);
331           } else {
332             stride[i] = obj->bytesperline[i];
333           }
334
335           /* when using multiplanar mode and if there is more then one v4l
336            * plane for each gst plane
337            */
338           if (V4L2_TYPE_IS_MULTIPLANAR (obj->type) && meta->n_planes > 1)
339             /* non_contiguous case here so we have to make sure that gst goes to the
340              * next plane (using default gstvideometa.c::default_map).
341              * And the next plane is after length bytes of the previous one from
342              * the gst buffer point of view. */
343             offs += meta->vplanes[i].length;
344           else
345             offs += obj->bytesperline[i] *
346                 GST_VIDEO_FORMAT_INFO_SCALE_HEIGHT (finfo, i, height);
347         }
348
349         gst_buffer_add_video_meta_full (newbuf, GST_VIDEO_FRAME_FLAG_NONE,
350             GST_VIDEO_INFO_FORMAT (info), width, height, n_gst_planes,
351             offset, stride);
352       }
353       break;
354     }
355     case GST_V4L2_IO_USERPTR:
356     default:
357       newbuf = NULL;
358       g_assert_not_reached ();
359   }
360
361   pool->num_allocated++;
362
363   *buffer = newbuf;
364
365   return GST_FLOW_OK;
366
367   /* ERRORS */
368 #ifdef VIDIOC_CREATE_BUFS
369 g_fmt_failed:
370   {
371     gint errnosave = errno;
372
373     GST_WARNING ("Failed G_FMT: %s", g_strerror (errnosave));
374     errno = errnosave;
375     return GST_FLOW_ERROR;
376   }
377 create_bufs_failed:
378   {
379     gint errnosave = errno;
380
381     GST_WARNING ("Failed CREATE_BUFS: %s", g_strerror (errnosave));
382     errno = errnosave;
383     return GST_FLOW_ERROR;
384   }
385 #endif
386 querybuf_failed:
387   {
388     gint errnosave = errno;
389
390     GST_WARNING ("Failed QUERYBUF: %s", g_strerror (errnosave));
391     gst_buffer_unref (newbuf);
392     errno = errnosave;
393     return GST_FLOW_ERROR;
394   }
395 mmap_failed:
396   {
397     gint errnosave = errno;
398
399     GST_WARNING ("Failed to mmap: %s", g_strerror (errnosave));
400     gst_buffer_unref (newbuf);
401     errno = errnosave;
402     return GST_FLOW_ERROR;
403   }
404 #if HAVE_DECL_V4L2_MEMORY_DMABUF
405 expbuf_failed:
406   {
407     gint errnosave = errno;
408
409     GST_WARNING ("Failed EXPBUF: %s", g_strerror (errnosave));
410     gst_buffer_unref (newbuf);
411     errno = errnosave;
412     return GST_FLOW_ERROR;
413   }
414 #endif
415 }
416
417 static gboolean
418 gst_v4l2_buffer_pool_set_config (GstBufferPool * bpool, GstStructure * config)
419 {
420   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
421   GstV4l2Object *obj = pool->obj;
422   GstCaps *caps;
423   guint size, min_buffers, max_buffers;
424   GstAllocator *allocator;
425   GstAllocationParams params;
426
427   GST_DEBUG_OBJECT (pool, "set config");
428
429   pool->add_videometa =
430       gst_buffer_pool_config_has_option (config,
431       GST_BUFFER_POOL_OPTION_VIDEO_META);
432
433   if (!pool->add_videometa &&
434       GST_VIDEO_INFO_FORMAT (&obj->info) != GST_VIDEO_FORMAT_ENCODED) {
435     /* in non MPLANE mode, there is only one  bytesperline field */
436     gint nb_checked_planes =
437         V4L2_TYPE_IS_MULTIPLANAR (obj->type) ? GST_VIDEO_INFO_N_PLANES (&obj->
438         info) : 1;
439     gint stride = 0;
440     gint i = 0;
441     for (i = 0; i < nb_checked_planes; i++) {
442       /* we don't have video metadata, and we are dealing with raw video,
443        * see if the strides are compatible */
444       stride = GST_VIDEO_INFO_PLANE_STRIDE (&obj->info, i);
445
446       if (GST_VIDEO_FORMAT_INFO_IS_TILED (obj->info.finfo)) {
447         stride = GST_VIDEO_TILE_X_TILES (stride) <<
448             GST_VIDEO_FORMAT_INFO_TILE_WS ((obj->info.finfo));
449       }
450
451       GST_DEBUG_OBJECT (pool, "no videometadata, checking strides %d and %u",
452           stride, obj->bytesperline[i]);
453
454       if (stride != obj->bytesperline[i])
455         goto missing_video_api;
456     }
457   }
458
459   /* parse the config and keep around */
460   if (!gst_buffer_pool_config_get_params (config, &caps, &size, &min_buffers,
461           &max_buffers))
462     goto wrong_config;
463
464   /* FIXME Check alignement, and S_FMT with new size if different */
465
466   if (!gst_buffer_pool_config_get_allocator (config, &allocator, &params))
467     goto wrong_config;
468
469   GST_DEBUG_OBJECT (pool, "config %" GST_PTR_FORMAT, config);
470
471   if (obj->mode == GST_V4L2_IO_DMABUF)
472     allocator = gst_dmabuf_allocator_new ();
473
474   if (pool->allocator)
475     gst_object_unref (pool->allocator);
476   if ((pool->allocator = allocator))
477     gst_object_ref (allocator);
478   pool->params = params;
479
480   gst_buffer_pool_config_set_params (config, caps, size, min_buffers,
481       max_buffers);
482
483   return GST_BUFFER_POOL_CLASS (parent_class)->set_config (bpool, config);
484
485   /* ERRORS */
486 missing_video_api:
487   {
488     GST_ERROR_OBJECT (pool, "missing GstMetaVideo API in config, "
489         "default stride: %d, wanted stride %u",
490         GST_VIDEO_INFO_PLANE_STRIDE (&obj->info, 0), obj->bytesperline[0]);
491     return FALSE;
492   }
493 wrong_config:
494   {
495     GST_ERROR_OBJECT (pool, "invalid config %" GST_PTR_FORMAT, config);
496     return FALSE;
497   }
498 }
499
500 static gboolean
501 start_streaming (GstV4l2BufferPool * pool)
502 {
503   GstV4l2Object *obj = pool->obj;
504
505   switch (obj->mode) {
506     case GST_V4L2_IO_RW:
507       break;
508     case GST_V4L2_IO_MMAP:
509     case GST_V4L2_IO_USERPTR:
510     case GST_V4L2_IO_DMABUF:
511       GST_DEBUG_OBJECT (pool, "STREAMON");
512       if (v4l2_ioctl (pool->video_fd, VIDIOC_STREAMON, &obj->type) < 0)
513         goto start_failed;
514       break;
515     default:
516       g_assert_not_reached ();
517       break;
518   }
519
520   pool->streaming = TRUE;
521
522   return TRUE;
523
524   /* ERRORS */
525 start_failed:
526   {
527     GST_ERROR_OBJECT (pool, "error with STREAMON %d (%s)", errno,
528         g_strerror (errno));
529     return FALSE;
530   }
531 }
532
533 static gboolean
534 gst_v4l2_buffer_pool_start (GstBufferPool * bpool)
535 {
536   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
537   GstV4l2Object *obj = pool->obj;
538   GstStructure *config;
539   GstCaps *caps;
540   guint size, num_buffers, min_buffers, max_buffers, copy_threshold;
541   struct v4l2_requestbuffers breq;
542
543   config = gst_buffer_pool_get_config (bpool);
544   if (!gst_buffer_pool_config_get_params (config, &caps, &size, &min_buffers,
545           &max_buffers))
546     goto wrong_config;
547
548   switch (obj->mode) {
549     case GST_V4L2_IO_RW:
550       /* we preallocate 1 buffer, this value also instructs the latency
551        * calculation to have 1 frame latency max */
552       num_buffers = 1;
553       copy_threshold = 0;
554       break;
555     case GST_V4L2_IO_DMABUF:
556     case GST_V4L2_IO_MMAP:
557     {
558       /* request a reasonable number of buffers when no max specified. We will
559        * copy when we run out of buffers */
560       if (max_buffers == 0)
561         num_buffers = MAX (4, min_buffers);
562       else
563         num_buffers = max_buffers;
564
565       /* first, lets request buffers, and see how many we can get: */
566       GST_DEBUG_OBJECT (pool, "starting, requesting %d MMAP buffers",
567           num_buffers);
568
569       memset (&breq, 0, sizeof (struct v4l2_requestbuffers));
570       breq.type = obj->type;
571       breq.count = num_buffers;
572       breq.memory = V4L2_MEMORY_MMAP;
573
574       if (v4l2_ioctl (pool->video_fd, VIDIOC_REQBUFS, &breq) < 0)
575         goto reqbufs_failed;
576
577       GST_LOG_OBJECT (pool, " count:  %u", breq.count);
578       GST_LOG_OBJECT (pool, " type:   %d", breq.type);
579       GST_LOG_OBJECT (pool, " memory: %d", breq.memory);
580
581       if (breq.count < GST_V4L2_MIN_BUFFERS)
582         goto no_buffers;
583
584       if (num_buffers != breq.count) {
585         GST_WARNING_OBJECT (pool, "using %u buffers instead", breq.count);
586         num_buffers = breq.count;
587       }
588       /* update min buffers with the amount of buffers we just reserved. We need
589        * to configure this value in the bufferpool so that the default start
590        * implementation calls our allocate function */
591       min_buffers = breq.count;
592
593       if (max_buffers == 0 || num_buffers < max_buffers) {
594         /* if we are asked to provide more buffers than we have allocated, start
595          * copying buffers when we only have 2 buffers left in the pool */
596         copy_threshold = 2;
597       } else {
598         /* we are certain that we have enough buffers so we don't need to
599          * copy */
600         copy_threshold = 0;
601       }
602
603       /* FIXME try to call CREATEBUFS with count 0 to check if max shall
604        * remain 0 */
605       break;
606     }
607     case GST_V4L2_IO_USERPTR:
608     default:
609       num_buffers = 0;
610       copy_threshold = 0;
611       g_assert_not_reached ();
612       break;
613   }
614
615   pool->size = size;
616   pool->num_buffers = num_buffers;
617   pool->copy_threshold = copy_threshold;
618
619   gst_buffer_pool_config_set_params (config, caps, size, min_buffers,
620       max_buffers);
621   GST_BUFFER_POOL_CLASS (parent_class)->set_config (bpool, config);
622
623   pool->obj = obj;
624   pool->buffers = g_new0 (GstBuffer *, pool->num_buffers);
625   pool->num_allocated = 0;
626
627   /* now, allocate the buffers: */
628   if (!GST_BUFFER_POOL_CLASS (parent_class)->start (bpool))
629     goto start_failed;
630
631   /* we can start capturing now, we wait for the playback case until we queued
632    * the first buffer */
633   if (!V4L2_TYPE_IS_OUTPUT (obj->type))
634     if (!start_streaming (pool))
635       goto start_failed;
636
637   gst_poll_set_flushing (obj->poll, FALSE);
638
639   return TRUE;
640
641   /* ERRORS */
642 wrong_config:
643   {
644     GST_ERROR_OBJECT (pool, "invalid config %" GST_PTR_FORMAT, config);
645     return FALSE;
646   }
647 reqbufs_failed:
648   {
649     GST_ERROR_OBJECT (pool,
650         "error requesting %d buffers: %s", num_buffers, g_strerror (errno));
651     return FALSE;
652   }
653 no_buffers:
654   {
655     GST_ERROR_OBJECT (pool,
656         "we received %d from device '%s', we want at least %d",
657         breq.count, obj->videodev, GST_V4L2_MIN_BUFFERS);
658     return FALSE;
659   }
660 start_failed:
661   {
662     GST_ERROR_OBJECT (pool, "failed to start streaming");
663     return FALSE;
664   }
665 }
666
667 static void
668 gst_v4l2_buffer_pool_free_buffers (GstV4l2BufferPool * pool)
669 {
670   if (pool->num_buffers > 0) {
671     struct v4l2_requestbuffers breq;
672     memset (&breq, 0, sizeof (struct v4l2_requestbuffers));
673     breq.type = pool->obj->type;
674     breq.count = 0;
675     breq.memory = V4L2_MEMORY_MMAP;
676     if (v4l2_ioctl (pool->video_fd, VIDIOC_REQBUFS, &breq) < 0) {
677       GST_ERROR_OBJECT (pool, "error releasing buffers: %s",
678           g_strerror (errno));
679     }
680     pool->num_buffers = 0;
681   }
682 }
683
684 static gboolean
685 stop_streaming (GstV4l2BufferPool * pool)
686 {
687   GstV4l2Object *obj = pool->obj;
688
689   GST_DEBUG_OBJECT (pool, "stopping stream");
690
691   gst_poll_set_flushing (obj->poll, TRUE);
692
693   if (!pool->streaming) {
694     /* it avoid error: STREAMOFF 22 (Invalid argument) when
695      * attempting to stop a stream not previously started */
696     GST_DEBUG_OBJECT (pool, "no need to stop, was not previously started");
697     return TRUE;
698   }
699
700   switch (obj->mode) {
701     case GST_V4L2_IO_RW:
702       break;
703     case GST_V4L2_IO_MMAP:
704     case GST_V4L2_IO_USERPTR:
705     case GST_V4L2_IO_DMABUF:
706       GST_DEBUG_OBJECT (pool, "STREAMOFF");
707       if (v4l2_ioctl (pool->video_fd, VIDIOC_STREAMOFF, &obj->type) < 0)
708         goto stop_failed;
709       break;
710     default:
711       g_assert_not_reached ();
712       break;
713   }
714
715   pool->streaming = FALSE;
716
717   return TRUE;
718
719   /* ERRORS */
720 stop_failed:
721   {
722     GST_ERROR_OBJECT (pool, "error with STREAMOFF %d (%s)", errno,
723         g_strerror (errno));
724     return FALSE;
725   }
726 }
727
728 static gboolean
729 gst_v4l2_buffer_pool_stop (GstBufferPool * bpool)
730 {
731   gboolean ret;
732   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
733   GstV4l2Object *obj = pool->obj;
734   guint n;
735
736   GST_DEBUG_OBJECT (pool, "stopping pool");
737
738   gst_poll_set_flushing (obj->poll, TRUE);
739
740   if (pool->streaming) {
741     switch (obj->mode) {
742       case GST_V4L2_IO_RW:
743         break;
744       case GST_V4L2_IO_MMAP:
745       case GST_V4L2_IO_USERPTR:
746       case GST_V4L2_IO_DMABUF:
747         /* we actually need to sync on all queued buffers but not
748          * on the non-queued ones */
749         GST_DEBUG_OBJECT (pool, "STREAMOFF");
750         if (v4l2_ioctl (pool->video_fd, VIDIOC_STREAMOFF, &obj->type) < 0)
751           goto stop_failed;
752         break;
753       default:
754         g_assert_not_reached ();
755         break;
756     }
757     pool->streaming = FALSE;
758   }
759
760   /* first free the buffers in the queue */
761   ret = GST_BUFFER_POOL_CLASS (parent_class)->stop (bpool);
762
763   /* then free the remaining buffers */
764   for (n = 0; n < pool->num_buffers; n++) {
765     if (pool->buffers[n])
766       gst_v4l2_buffer_pool_free_buffer (bpool, pool->buffers[n]);
767   }
768   pool->num_queued = 0;
769   g_free (pool->buffers);
770   pool->buffers = NULL;
771
772   gst_v4l2_buffer_pool_free_buffers (pool);
773
774   return ret;
775
776   /* ERRORS */
777 stop_failed:
778   {
779     GST_ERROR_OBJECT (pool, "error with STREAMOFF %d (%s)", errno,
780         g_strerror (errno));
781     return FALSE;
782   }
783 }
784
785 static GstFlowReturn
786 gst_v4l2_object_poll (GstV4l2Object * v4l2object)
787 {
788   gint ret;
789
790   if (v4l2object->can_poll_device) {
791     GST_LOG_OBJECT (v4l2object->element, "polling device");
792     ret = gst_poll_wait (v4l2object->poll, GST_CLOCK_TIME_NONE);
793     if (G_UNLIKELY (ret < 0)) {
794       if (errno == EBUSY)
795         goto stopped;
796       if (errno == ENXIO) {
797         GST_WARNING_OBJECT (v4l2object->element,
798             "v4l2 device doesn't support polling. Disabling");
799         v4l2object->can_poll_device = FALSE;
800       } else {
801         if (errno != EAGAIN && errno != EINTR)
802           goto select_error;
803       }
804     }
805   }
806   return GST_FLOW_OK;
807
808   /* ERRORS */
809 stopped:
810   {
811     GST_DEBUG ("stop called");
812     return GST_FLOW_FLUSHING;
813   }
814 select_error:
815   {
816     GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, READ, (NULL),
817         ("poll error %d: %s (%d)", ret, g_strerror (errno), errno));
818     return GST_FLOW_ERROR;
819   }
820 }
821
822 static GstFlowReturn
823 gst_v4l2_buffer_pool_qbuf (GstV4l2BufferPool * pool, GstBuffer * buf)
824 {
825   GstV4l2Meta *meta;
826   gint index;
827   gint i = 0;
828
829   meta = GST_V4L2_META_GET (buf);
830   if (meta == NULL) {
831     GST_LOG_OBJECT (pool, "unref copied buffer %p", buf);
832     /* no meta, it was a copied buffer that we can unref */
833     gst_buffer_unref (buf);
834     return GST_FLOW_OK;
835   }
836
837   index = meta->vbuffer.index;
838
839   /* this field is common to MPLANE and not MPLANE */
840   meta->vbuffer.bytesused = gst_buffer_get_size (buf);
841
842   for (i = 0; i < meta->n_planes; i++) {
843     meta->vplanes[i].bytesused =
844         gst_buffer_get_sizes_range (buf, i, 1, NULL, NULL);
845
846     GST_LOG_OBJECT (pool,
847         "enqueue buffer %p, index:%d, queued:%d, flags:%08x mem:%p used:%d, plane:%d",
848         buf, index, pool->num_queued, meta->vbuffer.flags,
849         meta->mem[i], meta->vplanes[i].bytesused, i);
850   }
851
852   if (pool->buffers[index] != NULL)
853     goto already_queued;
854
855   GST_LOG_OBJECT (pool, "doing QBUF");
856   if (v4l2_ioctl (pool->video_fd, VIDIOC_QBUF, &meta->vbuffer) < 0)
857     goto queue_failed;
858
859   pool->buffers[index] = buf;
860   pool->num_queued++;
861
862   return GST_FLOW_OK;
863
864   /* ERRORS */
865 already_queued:
866   {
867     GST_WARNING_OBJECT (pool, "the buffer was already queued");
868     return GST_FLOW_ERROR;
869   }
870 queue_failed:
871   {
872     GST_WARNING_OBJECT (pool, "could not queue a buffer %d (%s)", errno,
873         g_strerror (errno));
874     return GST_FLOW_ERROR;
875   }
876 }
877
878 static GstFlowReturn
879 gst_v4l2_buffer_pool_dqbuf (GstV4l2BufferPool * pool, GstBuffer ** buffer)
880 {
881   GstFlowReturn res;
882   GstBuffer *outbuf;
883   struct v4l2_buffer vbuffer;
884   struct v4l2_plane vplanes[GST_VIDEO_MAX_PLANES];
885   GstV4l2Object *obj = pool->obj;
886   GstClockTime timestamp;
887   GstV4l2Meta *meta;
888   gint i;
889
890   if ((res = gst_v4l2_object_poll (obj)) != GST_FLOW_OK)
891     goto poll_error;
892
893   /* prepare the buffer */
894   memset (&vbuffer, 0x00, sizeof (vbuffer));
895   vbuffer.type = obj->type;
896 #if HAVE_DECL_V4L2_MEMORY_DMABUF
897   if (obj->mode == GST_V4L2_IO_DMABUF)
898     vbuffer.memory = V4L2_MEMORY_DMABUF;
899   else
900 #endif
901     vbuffer.memory = V4L2_MEMORY_MMAP;
902
903   /* prepare the planes of the buffer */
904   if (V4L2_TYPE_IS_MULTIPLANAR (obj->type)) {
905     /* length is the number of elements in the
906      * vplanes array */
907     vbuffer.length = obj->n_v4l2_planes;
908     vbuffer.m.planes = vplanes;
909   }
910
911   /* the buffer is prepared, now fill in it with meaningful values */
912   GST_LOG_OBJECT (pool, "doing DQBUF");
913   if (v4l2_ioctl (pool->video_fd, VIDIOC_DQBUF, &vbuffer) < 0)
914     goto error;
915
916   /* get our GstBuffer with that index from the pool, if the buffer was
917    * outstanding we have a serious problem.
918    */
919   outbuf = pool->buffers[vbuffer.index];
920   if (outbuf == NULL)
921     goto no_buffer;
922
923   /* mark the buffer outstanding */
924   pool->buffers[vbuffer.index] = NULL;
925   pool->num_queued--;
926
927   timestamp = GST_TIMEVAL_TO_TIME (vbuffer.timestamp);
928
929   meta = GST_V4L2_META_GET (outbuf);
930   g_assert (meta != NULL);
931
932   /* The size can change at every frame, esp. with jpeg. The GstMemory
933    * inside the GstBuffer could have been changed by some other
934    * element. So update our meta */
935   if (obj->type == V4L2_BUF_TYPE_VIDEO_CAPTURE
936       || obj->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) {
937
938     /* this field is common to MPLANE and not MPLANE */
939     meta->vbuffer.length = vbuffer.length;
940     meta->vbuffer.bytesused = vbuffer.bytesused;
941
942     if (obj->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) {
943       for (i = 0; i < meta->n_planes; i++) {
944         /* the following also update meta->vbuffer.m.planes[i].length */
945         meta->vplanes[i].length = vbuffer.m.planes[i].length;
946         /* the following also update meta->vbuffer.m.planes[i].bytesused */
947         meta->vplanes[i].bytesused = vbuffer.m.planes[i].bytesused;
948         /* the following also update meta->vbuffer.m.planes[i].data_offset */
949         meta->vplanes[i].data_offset = vbuffer.m.planes[i].data_offset;
950       }
951     } else {
952       meta->vplanes[0].length = vbuffer.length;
953       meta->vplanes[0].bytesused = vbuffer.bytesused;
954       meta->vplanes[0].data_offset = 0;
955     }
956   }
957 #ifndef GST_DISABLE_GST_DEBUG
958   for (i = 0; i < meta->n_planes; i++) {
959     GST_LOG_OBJECT (pool,
960         "dequeued buffer %p seq:%d (ix=%d), mem %p used %d, plane=%d, flags %08x, ts %"
961         GST_TIME_FORMAT ", pool-queued=%d, buffer=%p", outbuf,
962         vbuffer.sequence, vbuffer.index, meta->mem[i],
963         meta->vplanes[i].bytesused, i, vbuffer.flags,
964         GST_TIME_ARGS (timestamp), pool->num_queued, outbuf);
965   }
966 #endif
967
968   /* set top/bottom field first if v4l2_buffer has the information */
969   if (vbuffer.field == V4L2_FIELD_INTERLACED_TB) {
970     GST_BUFFER_FLAG_SET (outbuf, GST_VIDEO_BUFFER_FLAG_TFF);
971   }
972   if (vbuffer.field == V4L2_FIELD_INTERLACED_BT) {
973     GST_BUFFER_FLAG_UNSET (outbuf, GST_VIDEO_BUFFER_FLAG_TFF);
974   }
975
976   /* The size can change at every frame, esp. with jpeg. The GstMemory
977    * inside the GstBuffer could have been changed by some other
978    * element, so just put back the original one. We always set it as
979    * no share, so if it's not there, it's not used at all.
980    */
981   if (obj->type == V4L2_BUF_TYPE_VIDEO_CAPTURE
982       || obj->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) {
983     gst_buffer_remove_all_memory (outbuf);
984     for (i = 0; i < meta->n_planes; i++) {
985       gst_buffer_append_memory (outbuf,
986           gst_memory_new_wrapped (GST_MEMORY_FLAG_NO_SHARE,
987               meta->mem[i], meta->vplanes[i].length,
988               meta->vplanes[i].data_offset,
989               meta->vplanes[i].bytesused, NULL, NULL));
990     }
991   }
992
993   GST_BUFFER_TIMESTAMP (outbuf) = timestamp;
994
995   *buffer = outbuf;
996
997   return GST_FLOW_OK;
998
999   /* ERRORS */
1000 poll_error:
1001   {
1002     GST_DEBUG_OBJECT (pool, "poll error %s", gst_flow_get_name (res));
1003     return res;
1004   }
1005 error:
1006   {
1007     GST_WARNING_OBJECT (pool,
1008         "problem dequeuing frame %d (ix=%d), pool-ct=%d, buf.flags=%d",
1009         vbuffer.sequence, vbuffer.index,
1010         GST_MINI_OBJECT_REFCOUNT (pool), vbuffer.flags);
1011
1012     switch (errno) {
1013       case EAGAIN:
1014         GST_WARNING_OBJECT (pool,
1015             "Non-blocking I/O has been selected using O_NONBLOCK and"
1016             " no buffer was in the outgoing queue. device %s", obj->videodev);
1017         break;
1018       case EINVAL:
1019         GST_ERROR_OBJECT (pool,
1020             "The buffer type is not supported, or the index is out of bounds, "
1021             "or no buffers have been allocated yet, or the userptr "
1022             "or length are invalid. device %s", obj->videodev);
1023         break;
1024       case ENOMEM:
1025         GST_ERROR_OBJECT (pool,
1026             "insufficient memory to enqueue a user pointer buffer");
1027         break;
1028       case EIO:
1029         GST_INFO_OBJECT (pool,
1030             "VIDIOC_DQBUF failed due to an internal error."
1031             " Can also indicate temporary problems like signal loss."
1032             " Note the driver might dequeue an (empty) buffer despite"
1033             " returning an error, or even stop capturing."
1034             " device %s", obj->videodev);
1035         /* have we de-queued a buffer ? */
1036         if (!(vbuffer.flags & (V4L2_BUF_FLAG_QUEUED | V4L2_BUF_FLAG_DONE))) {
1037           GST_DEBUG_OBJECT (pool, "reenqueing buffer");
1038           /* FIXME ... should we do something here? */
1039         }
1040         break;
1041       case EINTR:
1042         GST_WARNING_OBJECT (pool,
1043             "could not sync on a buffer on device %s", obj->videodev);
1044         break;
1045       default:
1046         GST_WARNING_OBJECT (pool,
1047             "Grabbing frame got interrupted on %s unexpectedly. %d: %s.",
1048             obj->videodev, errno, g_strerror (errno));
1049         break;
1050     }
1051     return GST_FLOW_ERROR;
1052   }
1053 no_buffer:
1054   {
1055     GST_ERROR_OBJECT (pool, "No free buffer found in the pool at index %d.",
1056         vbuffer.index);
1057     return GST_FLOW_ERROR;
1058   }
1059 }
1060
1061 static GstFlowReturn
1062 gst_v4l2_buffer_pool_acquire_buffer (GstBufferPool * bpool, GstBuffer ** buffer,
1063     GstBufferPoolAcquireParams * params)
1064 {
1065   GstFlowReturn ret;
1066   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
1067   GstV4l2Object *obj = pool->obj;
1068
1069   GST_DEBUG_OBJECT (pool, "acquire");
1070
1071   if (GST_BUFFER_POOL_IS_FLUSHING (bpool))
1072     goto flushing;
1073
1074   switch (obj->type) {
1075     case V4L2_BUF_TYPE_VIDEO_CAPTURE:
1076     case V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE:
1077       /* capture, This function should return a buffer with new captured data */
1078       switch (obj->mode) {
1079         case GST_V4L2_IO_RW:
1080           /* take empty buffer from the pool */
1081           ret = GST_BUFFER_POOL_CLASS (parent_class)->acquire_buffer (bpool,
1082               buffer, params);
1083           break;
1084         case GST_V4L2_IO_DMABUF:
1085         case GST_V4L2_IO_MMAP:
1086           /* just dequeue a buffer, we basically use the queue of v4l2 as the
1087            * storage for our buffers. This function does poll first so we can
1088            * interrupt it fine. */
1089           ret = gst_v4l2_buffer_pool_dqbuf (pool, buffer);
1090           if (G_UNLIKELY (ret != GST_FLOW_OK))
1091             goto done;
1092
1093           /* start copying buffers when we are running low on buffers */
1094           if (pool->num_queued < pool->copy_threshold) {
1095             GstBuffer *copy;
1096 #ifdef VIDIOC_CREATE_BUFS
1097             if (pool->can_alloc) {
1098               if (GST_BUFFER_POOL_CLASS (parent_class)->acquire_buffer (bpool,
1099                       &copy, params) == GST_FLOW_OK) {
1100                 gst_v4l2_buffer_pool_release_buffer (bpool, copy);
1101                 break;
1102               } else {
1103                 pool->can_alloc = FALSE;
1104               }
1105             }
1106 #endif
1107
1108             /* copy the buffer */
1109             copy = gst_buffer_copy_region (*buffer,
1110                 GST_BUFFER_COPY_ALL | GST_BUFFER_COPY_DEEP, 0, -1);
1111             GST_LOG_OBJECT (pool, "copy buffer %p->%p", *buffer, copy);
1112
1113             /* and requeue so that we can continue capturing */
1114             ret = gst_v4l2_buffer_pool_qbuf (pool, *buffer);
1115             *buffer = copy;
1116           }
1117           break;
1118
1119         case GST_V4L2_IO_USERPTR:
1120         default:
1121           ret = GST_FLOW_ERROR;
1122           g_assert_not_reached ();
1123           break;
1124       }
1125       break;
1126
1127     case V4L2_BUF_TYPE_VIDEO_OUTPUT:
1128     case V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE:
1129       /* playback, This function should return an empty buffer */
1130       switch (obj->mode) {
1131         case GST_V4L2_IO_RW:
1132           /* get an empty buffer */
1133           ret = GST_BUFFER_POOL_CLASS (parent_class)->acquire_buffer (bpool,
1134               buffer, params);
1135           break;
1136
1137         case GST_V4L2_IO_MMAP:
1138           /* get a free unqueued buffer */
1139           ret = GST_BUFFER_POOL_CLASS (parent_class)->acquire_buffer (bpool,
1140               buffer, params);
1141           break;
1142
1143         case GST_V4L2_IO_USERPTR:
1144         default:
1145           ret = GST_FLOW_ERROR;
1146           g_assert_not_reached ();
1147           break;
1148       }
1149       break;
1150
1151     default:
1152       ret = GST_FLOW_ERROR;
1153       g_assert_not_reached ();
1154       break;
1155   }
1156 done:
1157   return ret;
1158
1159   /* ERRORS */
1160 flushing:
1161   {
1162     GST_DEBUG_OBJECT (pool, "We are flushing");
1163     return GST_FLOW_FLUSHING;
1164   }
1165 }
1166
1167 static void
1168 gst_v4l2_buffer_pool_release_buffer (GstBufferPool * bpool, GstBuffer * buffer)
1169 {
1170   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
1171   GstV4l2Object *obj = pool->obj;
1172
1173   GST_DEBUG_OBJECT (pool, "release buffer %p", buffer);
1174
1175   switch (obj->type) {
1176     case V4L2_BUF_TYPE_VIDEO_CAPTURE:
1177     case V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE:
1178       /* capture, put the buffer back in the queue so that we can refill it
1179        * later. */
1180       switch (obj->mode) {
1181         case GST_V4L2_IO_RW:
1182           /* release back in the pool */
1183           GST_BUFFER_POOL_CLASS (parent_class)->release_buffer (bpool, buffer);
1184           break;
1185
1186         case GST_V4L2_IO_DMABUF:
1187         case GST_V4L2_IO_MMAP:
1188           /* queue back in the device */
1189           gst_v4l2_buffer_pool_qbuf (pool, buffer);
1190           break;
1191
1192         case GST_V4L2_IO_USERPTR:
1193         default:
1194           g_assert_not_reached ();
1195           break;
1196       }
1197       break;
1198
1199     case V4L2_BUF_TYPE_VIDEO_OUTPUT:
1200     case V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE:
1201       switch (obj->mode) {
1202         case GST_V4L2_IO_RW:
1203           /* release back in the pool */
1204           GST_BUFFER_POOL_CLASS (parent_class)->release_buffer (bpool, buffer);
1205           break;
1206
1207         case GST_V4L2_IO_MMAP:
1208         {
1209           GstV4l2Meta *meta;
1210           guint index;
1211
1212           meta = GST_V4L2_META_GET (buffer);
1213           g_assert (meta != NULL);
1214
1215           index = meta->vbuffer.index;
1216
1217           if (pool->buffers[index] == NULL) {
1218             GST_LOG_OBJECT (pool, "buffer %u not queued, putting on free list",
1219                 index);
1220
1221             /* reset to the full length, in case it was changed */
1222             if (V4L2_TYPE_IS_MULTIPLANAR (obj->type)) {
1223               gint i = 0;
1224               gint total_length = 0;
1225               for (i = 0; i < meta->n_planes; i++)
1226                 total_length += meta->vplanes[i].length;
1227
1228               if (total_length != gst_buffer_get_size (buffer) &&
1229                   obj->info.finfo->n_planes > 1) {
1230                 /* FIXME if the lengths has actually changed it may require
1231                  * to restore the sizes of the individual memories and
1232                  * re-add them */
1233                 GST_WARNING_OBJECT (pool,
1234                     "lengths changed, more work required");
1235               }
1236
1237               gst_buffer_resize (buffer, 0, total_length);
1238             } else {
1239               gst_buffer_resize (buffer, 0, meta->vbuffer.length);
1240             }
1241
1242             /* playback, put the buffer back in the queue to refill later. */
1243             GST_BUFFER_POOL_CLASS (parent_class)->release_buffer (bpool,
1244                 buffer);
1245           } else {
1246             /* the buffer is queued in the device but maybe not played yet. We just
1247              * leave it there and not make it available for future calls to acquire
1248              * for now. The buffer will be dequeued and reused later. */
1249             GST_LOG_OBJECT (pool, "buffer %u is queued", index);
1250           }
1251           break;
1252         }
1253
1254         case GST_V4L2_IO_USERPTR:
1255         default:
1256           g_assert_not_reached ();
1257           break;
1258       }
1259       break;
1260
1261     default:
1262       g_assert_not_reached ();
1263       break;
1264   }
1265 }
1266
1267 static void
1268 gst_v4l2_buffer_pool_finalize (GObject * object)
1269 {
1270   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (object);
1271
1272   gst_v4l2_buffer_pool_free_buffers (pool);
1273
1274   if (pool->video_fd >= 0)
1275     v4l2_close (pool->video_fd);
1276   if (pool->allocator)
1277     gst_object_unref (pool->allocator);
1278   g_free (pool->buffers);
1279
1280   gst_object_unref (pool->obj->element);
1281
1282   G_OBJECT_CLASS (parent_class)->finalize (object);
1283 }
1284
1285 static void
1286 gst_v4l2_buffer_pool_init (GstV4l2BufferPool * pool)
1287 {
1288 }
1289
1290 static void
1291 gst_v4l2_buffer_pool_class_init (GstV4l2BufferPoolClass * klass)
1292 {
1293   GObjectClass *object_class = G_OBJECT_CLASS (klass);
1294   GstBufferPoolClass *bufferpool_class = GST_BUFFER_POOL_CLASS (klass);
1295
1296   object_class->finalize = gst_v4l2_buffer_pool_finalize;
1297
1298   bufferpool_class->start = gst_v4l2_buffer_pool_start;
1299   bufferpool_class->stop = gst_v4l2_buffer_pool_stop;
1300   bufferpool_class->set_config = gst_v4l2_buffer_pool_set_config;
1301   bufferpool_class->alloc_buffer = gst_v4l2_buffer_pool_alloc_buffer;
1302   bufferpool_class->acquire_buffer = gst_v4l2_buffer_pool_acquire_buffer;
1303   bufferpool_class->release_buffer = gst_v4l2_buffer_pool_release_buffer;
1304   bufferpool_class->free_buffer = gst_v4l2_buffer_pool_free_buffer;
1305 }
1306
1307 /**
1308  * gst_v4l2_buffer_pool_new:
1309  * @obj:  the v4l2 object owning the pool
1310  *
1311  * Construct a new buffer pool.
1312  *
1313  * Returns: the new pool, use gst_object_unref() to free resources
1314  */
1315 GstBufferPool *
1316 gst_v4l2_buffer_pool_new (GstV4l2Object * obj, GstCaps * caps)
1317 {
1318   GstV4l2BufferPool *pool;
1319   GstStructure *config;
1320   gboolean res = FALSE;
1321   gint fd;
1322
1323   fd = v4l2_dup (obj->video_fd);
1324   if (fd < 0)
1325     goto dup_failed;
1326
1327   pool = (GstV4l2BufferPool *) g_object_new (GST_TYPE_V4L2_BUFFER_POOL, NULL);
1328   pool->video_fd = fd;
1329   pool->obj = obj;
1330   pool->can_alloc = TRUE;
1331
1332   config = gst_buffer_pool_get_config (GST_BUFFER_POOL_CAST (pool));
1333   gst_buffer_pool_config_set_params (config, caps, obj->sizeimage, 2, 0);
1334
1335   res = gst_buffer_pool_set_config (GST_BUFFER_POOL_CAST (pool), config);
1336   if (!res)
1337     goto config_failed;
1338
1339   gst_object_ref (obj->element);
1340
1341   return GST_BUFFER_POOL (pool);
1342
1343   /* ERRORS */
1344 dup_failed:
1345   {
1346     GST_DEBUG ("failed to dup fd %d (%s)", errno, g_strerror (errno));
1347     return NULL;
1348   }
1349 config_failed:
1350   {
1351     GST_WARNING ("failed to set pool config");
1352     return NULL;
1353   }
1354 }
1355
1356 static GstFlowReturn
1357 gst_v4l2_do_read (GstV4l2BufferPool * pool, GstBuffer * buf)
1358 {
1359   GstFlowReturn res;
1360   GstV4l2Object *obj = pool->obj;
1361   gint amount;
1362   GstMapInfo map;
1363   gint toread;
1364
1365   toread = obj->sizeimage;
1366
1367   GST_LOG_OBJECT (pool, "reading %d bytes into buffer %p", toread, buf);
1368
1369   gst_buffer_map (buf, &map, GST_MAP_WRITE);
1370
1371   do {
1372     if ((res = gst_v4l2_object_poll (obj)) != GST_FLOW_OK)
1373       goto poll_error;
1374
1375     amount = v4l2_read (obj->video_fd, map.data, toread);
1376
1377     if (amount == toread) {
1378       break;
1379     } else if (amount == -1) {
1380       if (errno == EAGAIN || errno == EINTR) {
1381         continue;
1382       } else
1383         goto read_error;
1384     } else {
1385       /* short reads can happen if a signal interrupts the read */
1386       continue;
1387     }
1388   } while (TRUE);
1389
1390   GST_LOG_OBJECT (pool, "read %d bytes", amount);
1391   gst_buffer_unmap (buf, &map);
1392   gst_buffer_resize (buf, 0, amount);
1393
1394   return GST_FLOW_OK;
1395
1396   /* ERRORS */
1397 poll_error:
1398   {
1399     GST_DEBUG ("poll error %s", gst_flow_get_name (res));
1400     goto cleanup;
1401   }
1402 read_error:
1403   {
1404     GST_ELEMENT_ERROR (obj->element, RESOURCE, READ,
1405         (_("Error reading %d bytes from device '%s'."),
1406             toread, obj->videodev), GST_ERROR_SYSTEM);
1407     res = GST_FLOW_ERROR;
1408     goto cleanup;
1409   }
1410 cleanup:
1411   {
1412     gst_buffer_unmap (buf, &map);
1413     gst_buffer_resize (buf, 0, 0);
1414     return res;
1415   }
1416 }
1417
1418 /**
1419  * gst_v4l2_buffer_pool_process:
1420  * @bpool: a #GstBufferPool
1421  * @buf: a #GstBuffer
1422  *
1423  * Process @buf in @bpool. For capture devices, this functions fills @buf with
1424  * data from the device. For output devices, this functions send the contents of
1425  * @buf to the device for playback.
1426  *
1427  * Returns: %GST_FLOW_OK on success.
1428  */
1429 GstFlowReturn
1430 gst_v4l2_buffer_pool_process (GstV4l2BufferPool * pool, GstBuffer * buf)
1431 {
1432   GstFlowReturn ret = GST_FLOW_OK;
1433   GstBufferPool *bpool = GST_BUFFER_POOL_CAST (pool);
1434   GstV4l2Object *obj = pool->obj;
1435
1436   GST_DEBUG_OBJECT (pool, "process buffer %p", buf);
1437
1438   switch (obj->type) {
1439     case V4L2_BUF_TYPE_VIDEO_CAPTURE:
1440     case V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE:
1441       /* capture */
1442       switch (obj->mode) {
1443         case GST_V4L2_IO_RW:
1444           /* capture into the buffer */
1445           ret = gst_v4l2_do_read (pool, buf);
1446           break;
1447
1448         case GST_V4L2_IO_MMAP:
1449         {
1450           GstBuffer *tmp;
1451
1452           if (buf->pool == bpool)
1453             /* nothing, data was inside the buffer when we did _acquire() */
1454             goto done;
1455
1456           /* buffer not from our pool, grab a frame and copy it into the target */
1457           if ((ret = gst_v4l2_buffer_pool_dqbuf (pool, &tmp)) != GST_FLOW_OK)
1458             goto done;
1459
1460           if (!gst_v4l2_object_copy (obj, buf, tmp))
1461             goto copy_failed;
1462
1463           /* an queue the buffer again after the copy */
1464           if ((ret = gst_v4l2_buffer_pool_qbuf (pool, tmp)) != GST_FLOW_OK)
1465             goto done;
1466           break;
1467         }
1468
1469         case GST_V4L2_IO_USERPTR:
1470         default:
1471           g_assert_not_reached ();
1472           break;
1473       }
1474       break;
1475
1476     case V4L2_BUF_TYPE_VIDEO_OUTPUT:
1477     case V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE:
1478       /* playback */
1479       switch (obj->mode) {
1480         case GST_V4L2_IO_RW:
1481           /* FIXME, do write() */
1482           GST_WARNING_OBJECT (pool, "implement write()");
1483           break;
1484         case GST_V4L2_IO_DMABUF:
1485         case GST_V4L2_IO_MMAP:
1486         {
1487           GstBuffer *to_queue;
1488
1489           if (buf->pool == bpool) {
1490             /* nothing, we can queue directly */
1491             to_queue = gst_buffer_ref (buf);
1492             GST_LOG_OBJECT (pool, "processing buffer from our pool");
1493           } else {
1494             GST_LOG_OBJECT (pool, "alloc buffer from our pool");
1495             if (!gst_buffer_pool_is_active (bpool)) {
1496               GstStructure *config;
1497
1498               /* this pool was not activated, configure and activate */
1499               GST_DEBUG_OBJECT (pool, "activating pool");
1500
1501               config = gst_buffer_pool_get_config (bpool);
1502               gst_buffer_pool_config_add_option (config,
1503                   GST_BUFFER_POOL_OPTION_VIDEO_META);
1504               gst_buffer_pool_set_config (bpool, config);
1505
1506               if (!gst_buffer_pool_set_active (bpool, TRUE))
1507                 goto activate_failed;
1508             }
1509
1510             /* this can block if all buffers are outstanding which would be
1511              * strange because we would expect the upstream element to have
1512              * allocated them and returned to us.. */
1513             ret = gst_buffer_pool_acquire_buffer (bpool, &to_queue, NULL);
1514             if (ret != GST_FLOW_OK)
1515               goto acquire_failed;
1516
1517             /* copy into it and queue */
1518             if (!gst_v4l2_object_copy (obj, to_queue, buf))
1519               goto copy_failed;
1520           }
1521
1522           if ((ret = gst_v4l2_buffer_pool_qbuf (pool, to_queue)) != GST_FLOW_OK)
1523             goto done;
1524
1525           /* if we are not streaming yet (this is the first buffer, start
1526            * streaming now */
1527           if (!pool->streaming)
1528             if (!start_streaming (pool))
1529               goto start_failed;
1530
1531           if (pool->num_queued == pool->num_allocated) {
1532             GstBuffer *out;
1533             /* all buffers are queued, try to dequeue one and release it back
1534              * into the pool so that _acquire can get to it again. */
1535             ret = gst_v4l2_buffer_pool_dqbuf (pool, &out);
1536             if (ret != GST_FLOW_OK) {
1537               gst_buffer_unref (to_queue);
1538               goto done;
1539             }
1540
1541             /* release the rendered buffer back into the pool. This wakes up any
1542              * thread waiting for a buffer in _acquire(). If the buffer still has
1543              * a pool then this will happen when the refcount reaches 0 */
1544             if (!out->pool)
1545               gst_v4l2_buffer_pool_release_buffer (bpool, out);
1546           }
1547           gst_buffer_unref (to_queue);
1548           break;
1549         }
1550
1551         case GST_V4L2_IO_USERPTR:
1552         default:
1553           g_assert_not_reached ();
1554           break;
1555       }
1556       break;
1557     default:
1558       g_assert_not_reached ();
1559       break;
1560   }
1561 done:
1562   return ret;
1563
1564   /* ERRORS */
1565 activate_failed:
1566   {
1567     GST_ERROR_OBJECT (obj->element, "failed to activate pool");
1568     return GST_FLOW_ERROR;
1569   }
1570 acquire_failed:
1571   {
1572     GST_WARNING_OBJECT (obj->element, "failed to acquire a buffer: %s",
1573         gst_flow_get_name (ret));
1574     return ret;
1575   }
1576 copy_failed:
1577   {
1578     GST_ERROR_OBJECT (obj->element, "failed to copy data");
1579     return GST_FLOW_ERROR;
1580   }
1581 start_failed:
1582   {
1583     GST_ERROR_OBJECT (obj->element, "failed to start streaming");
1584     return GST_FLOW_ERROR;
1585   }
1586 }
1587
1588
1589 /**
1590  * gst_v4l2_buffer_pool_flush:
1591  * @bpool: a #GstBufferPool
1592  *
1593  * First, set obj->poll to be flushing
1594  * Call STREAMOFF to clear QUEUED flag on every driver buffers.
1595  * Then release all buffers that are in pool->buffers array.
1596  * Finally call STREAMON if CAPTURE type
1597  * The caller is responsible to unset flushing on obj->pool
1598  * 
1599  * Returns: TRUE on success.
1600  */
1601 gboolean
1602 gst_v4l2_buffer_pool_flush (GstV4l2BufferPool * pool)
1603 {
1604   GstBufferPool *bpool = GST_BUFFER_POOL_CAST (pool);
1605   GstV4l2Object *obj = pool->obj;
1606   gint i = 0;
1607
1608   GST_DEBUG_OBJECT (pool, "flush");
1609
1610   stop_streaming (pool);
1611
1612   switch (obj->type) {
1613     case V4L2_BUF_TYPE_VIDEO_CAPTURE:
1614     case V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE:
1615     case V4L2_BUF_TYPE_VIDEO_OUTPUT:
1616     case V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE:
1617       switch (obj->mode) {
1618         case GST_V4L2_IO_RW:
1619           break;
1620         case GST_V4L2_IO_MMAP:
1621         case GST_V4L2_IO_USERPTR:
1622         case GST_V4L2_IO_DMABUF:
1623         {
1624           for (i = 0; i < pool->num_buffers; i++) {
1625             GstBuffer *buf = pool->buffers[i];
1626             if (buf) {
1627               /* it's necessary to set to NULL before to call
1628                * gst_v4l2_buffer_pool_release_buffer
1629                * otherwise it won't go back to the pool */
1630               pool->buffers[i] = NULL;
1631
1632               /* dicrease counter */
1633               pool->num_queued--;
1634
1635               /* in CAPTURE mode the pool->num_queued will be re-incremented
1636                * because the buffers are queued when released */
1637               if (buf->pool)
1638                 gst_buffer_unref (buf);
1639               else
1640                 gst_v4l2_buffer_pool_release_buffer (bpool, buf);
1641             }
1642           }
1643
1644           /* do not set pool->num_queued to 0 because
1645            * the buffers are queued when released */
1646           break;
1647         }
1648
1649         default:
1650           g_assert_not_reached ();
1651           break;
1652       }
1653       break;
1654     default:
1655       g_assert_not_reached ();
1656       break;
1657   }
1658   /* we can start capturing now, we wait for the playback
1659    * case until we queued the first buffer */
1660   if (!V4L2_TYPE_IS_OUTPUT (obj->type))
1661     if (!start_streaming (pool))
1662       goto start_failed;
1663
1664   return TRUE;
1665
1666   /* ERRORS */
1667 start_failed:
1668   {
1669     GST_ERROR_OBJECT (pool, "failed to start streaming");
1670     return FALSE;
1671   }
1672 }