v4l2: Don't use allocator size to iterate
[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 #ifndef _GNU_SOURCE
30 # define _GNU_SOURCE            /* O_CLOEXEC */
31 #endif
32 #include <fcntl.h>
33
34 #include <sys/mman.h>
35 #include <string.h>
36 #include <unistd.h>
37
38 #include "gst/video/video.h"
39 #include "gst/video/gstvideometa.h"
40 #include "gst/video/gstvideopool.h"
41 #include "gst/allocators/gstdmabuf.h"
42
43 #include <gstv4l2bufferpool.h>
44
45 #include "v4l2_calls.h"
46 #include "gst/gst-i18n-plugin.h"
47 #include <gst/glib-compat-private.h>
48
49 GST_DEBUG_CATEGORY_EXTERN (v4l2_debug);
50 GST_DEBUG_CATEGORY_EXTERN (GST_CAT_PERFORMANCE);
51 #define GST_CAT_DEFAULT v4l2_debug
52
53 #define GST_V4L2_IMPORT_QUARK gst_v4l2_buffer_pool_import_quark ()
54
55
56 /*
57  * GstV4l2BufferPool:
58  */
59 #define gst_v4l2_buffer_pool_parent_class parent_class
60 G_DEFINE_TYPE (GstV4l2BufferPool, gst_v4l2_buffer_pool, GST_TYPE_BUFFER_POOL);
61
62 enum _GstV4l2BufferPoolAcquireFlags
63 {
64   GST_V4L2_BUFFER_POOL_ACQUIRE_FLAG_RESURRECT =
65       GST_BUFFER_POOL_ACQUIRE_FLAG_LAST,
66   GST_V4L2_BUFFER_POOL_ACQUIRE_FLAG_LAST
67 };
68
69 static void gst_v4l2_buffer_pool_release_buffer (GstBufferPool * bpool,
70     GstBuffer * buffer);
71
72 static gboolean
73 gst_v4l2_is_buffer_valid (GstBuffer * buffer, GstV4l2MemoryGroup ** out_group)
74 {
75   GstMemory *mem = gst_buffer_peek_memory (buffer, 0);
76   gboolean valid = FALSE;
77
78   if (GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_TAG_MEMORY))
79     goto done;
80
81   if (gst_is_dmabuf_memory (mem))
82     mem = gst_mini_object_get_qdata (GST_MINI_OBJECT (mem),
83         GST_V4L2_MEMORY_QUARK);
84
85   if (mem && gst_is_v4l2_memory (mem)) {
86     GstV4l2Memory *vmem = (GstV4l2Memory *) mem;
87     GstV4l2MemoryGroup *group = vmem->group;
88     gint i;
89
90     if (group->n_mem != gst_buffer_n_memory (buffer))
91       goto done;
92
93     for (i = 0; i < group->n_mem; i++) {
94       if (group->mem[i] != gst_buffer_peek_memory (buffer, i))
95         goto done;
96
97       if (!gst_memory_is_writable (group->mem[i]))
98         goto done;
99     }
100
101     valid = TRUE;
102     if (out_group)
103       *out_group = group;
104   }
105
106 done:
107   return valid;
108 }
109
110 static GstFlowReturn
111 gst_v4l2_buffer_pool_copy_buffer (GstV4l2BufferPool * pool, GstBuffer * dest,
112     GstBuffer * src)
113 {
114   const GstVideoFormatInfo *finfo = pool->caps_info.finfo;
115
116   GST_LOG_OBJECT (pool, "copying buffer");
117
118   if (finfo && (finfo->format != GST_VIDEO_FORMAT_UNKNOWN &&
119           finfo->format != GST_VIDEO_FORMAT_ENCODED)) {
120     GstVideoFrame src_frame, dest_frame;
121
122     GST_DEBUG_OBJECT (pool, "copy video frame");
123
124     /* we have raw video, use videoframe copy to get strides right */
125     if (!gst_video_frame_map (&src_frame, &pool->caps_info, src, GST_MAP_READ))
126       goto invalid_buffer;
127
128     if (!gst_video_frame_map (&dest_frame, &pool->caps_info, dest,
129             GST_MAP_WRITE)) {
130       gst_video_frame_unmap (&src_frame);
131       goto invalid_buffer;
132     }
133
134     gst_video_frame_copy (&dest_frame, &src_frame);
135
136     gst_video_frame_unmap (&src_frame);
137     gst_video_frame_unmap (&dest_frame);
138   } else {
139     GstMapInfo map;
140
141     GST_DEBUG_OBJECT (pool, "copy raw bytes");
142
143     if (!gst_buffer_map (src, &map, GST_MAP_READ))
144       goto invalid_buffer;
145
146     gst_buffer_fill (dest, 0, map.data, gst_buffer_get_size (src));
147
148     gst_buffer_unmap (src, &map);
149     gst_buffer_resize (dest, 0, gst_buffer_get_size (src));
150   }
151
152   GST_CAT_LOG_OBJECT (GST_CAT_PERFORMANCE, pool, "slow copy into buffer %p",
153       dest);
154
155   return GST_FLOW_OK;
156
157 invalid_buffer:
158   {
159     GST_ERROR_OBJECT (pool, "could not map buffer");
160     return GST_FLOW_ERROR;
161   }
162 }
163
164 struct UserPtrData
165 {
166   GstBuffer *buffer;
167   gboolean is_frame;
168   GstVideoFrame frame;
169   GstMapInfo map;
170 };
171
172 static GQuark
173 gst_v4l2_buffer_pool_import_quark (void)
174 {
175   static GQuark quark = 0;
176
177   if (quark == 0)
178     quark = g_quark_from_string ("GstV4l2BufferPoolUsePtrData");
179
180   return quark;
181 }
182
183 static void
184 _unmap_userptr_frame (struct UserPtrData *data)
185 {
186   if (data->is_frame)
187     gst_video_frame_unmap (&data->frame);
188   else
189     gst_buffer_unmap (data->buffer, &data->map);
190
191   if (data->buffer)
192     gst_buffer_unref (data->buffer);
193
194   g_slice_free (struct UserPtrData, data);
195 }
196
197 static GstFlowReturn
198 gst_v4l2_buffer_pool_import_userptr (GstV4l2BufferPool * pool,
199     GstBuffer * dest, GstBuffer * src)
200 {
201   GstFlowReturn ret = GST_FLOW_OK;
202   GstV4l2MemoryGroup *group = NULL;
203   GstMapFlags flags;
204   const GstVideoFormatInfo *finfo = pool->caps_info.finfo;
205   struct UserPtrData *data = NULL;
206
207   GST_LOG_OBJECT (pool, "importing userptr");
208
209   /* get the group */
210   if (!gst_v4l2_is_buffer_valid (dest, &group))
211     goto not_our_buffer;
212
213   if (V4L2_TYPE_IS_OUTPUT (pool->obj->type))
214     flags = GST_MAP_READ;
215   else
216     flags = GST_MAP_WRITE;
217
218   data = g_slice_new0 (struct UserPtrData);
219
220   if (finfo && (finfo->format != GST_VIDEO_FORMAT_UNKNOWN &&
221           finfo->format != GST_VIDEO_FORMAT_ENCODED)) {
222     data->is_frame = TRUE;
223
224     if (!gst_video_frame_map (&data->frame, &pool->caps_info, src, flags))
225       goto invalid_buffer;
226
227     if (!gst_v4l2_allocator_import_userptr (pool->vallocator, group,
228             data->frame.info.size, finfo->n_planes, data->frame.data,
229             data->frame.info.offset))
230       goto import_failed;
231   } else {
232     gsize offset[1] = { 0 };
233     gpointer ptr[1];
234
235     data->is_frame = FALSE;
236
237     if (!gst_buffer_map (src, &data->map, flags))
238       goto invalid_buffer;
239
240     ptr[0] = data->map.data;
241
242     if (!gst_v4l2_allocator_import_userptr (pool->vallocator, group,
243             data->map.size, 1, ptr, offset))
244       goto import_failed;
245   }
246
247   data->buffer = gst_buffer_ref (src);
248
249   gst_mini_object_set_qdata (GST_MINI_OBJECT (dest), GST_V4L2_IMPORT_QUARK,
250       data, (GDestroyNotify) _unmap_userptr_frame);
251
252   return ret;
253
254 not_our_buffer:
255   {
256     GST_ERROR_OBJECT (pool, "destination buffer invalid or not from our pool");
257     return GST_FLOW_ERROR;
258   }
259 invalid_buffer:
260   {
261     GST_ERROR_OBJECT (pool, "could not map buffer");
262     g_slice_free (struct UserPtrData, data);
263     return GST_FLOW_ERROR;
264   }
265 import_failed:
266   {
267     GST_ERROR_OBJECT (pool, "failed to import data");
268     _unmap_userptr_frame (data);
269     return GST_FLOW_ERROR;
270   }
271 }
272
273 static GstFlowReturn
274 gst_v4l2_buffer_pool_import_dmabuf (GstV4l2BufferPool * pool,
275     GstBuffer * dest, GstBuffer * src)
276 {
277   GstV4l2MemoryGroup *group = NULL;
278   GstMemory *dma_mem[GST_VIDEO_MAX_PLANES] = { 0 };
279   guint n_mem = gst_buffer_n_memory (src);
280   gint i;
281
282   GST_LOG_OBJECT (pool, "importing dmabuf");
283
284   if (!gst_v4l2_is_buffer_valid (dest, &group))
285     goto not_our_buffer;
286
287   if (n_mem > GST_VIDEO_MAX_PLANES)
288     goto too_many_mems;
289
290   for (i = 0; i < n_mem; i++)
291     dma_mem[i] = gst_buffer_peek_memory (src, i);
292
293   if (!gst_v4l2_allocator_import_dmabuf (pool->vallocator, group, n_mem,
294           dma_mem))
295     goto import_failed;
296
297   gst_mini_object_set_qdata (GST_MINI_OBJECT (dest), GST_V4L2_IMPORT_QUARK,
298       gst_buffer_ref (src), (GDestroyNotify) gst_buffer_unref);
299
300   return GST_FLOW_OK;
301
302 not_our_buffer:
303   {
304     GST_ERROR_OBJECT (pool, "destination buffer invalid or not from our pool");
305     return GST_FLOW_ERROR;
306   }
307 too_many_mems:
308   {
309     GST_ERROR_OBJECT (pool, "could not map buffer");
310     return GST_FLOW_ERROR;
311   }
312 import_failed:
313   {
314     GST_ERROR_OBJECT (pool, "failed to import dmabuf");
315     return GST_FLOW_ERROR;
316   }
317 }
318
319 static GstFlowReturn
320 gst_v4l2_buffer_pool_prepare_buffer (GstV4l2BufferPool * pool,
321     GstBuffer * dest, GstBuffer * src)
322 {
323   GstFlowReturn ret = GST_FLOW_OK;
324   gboolean own_src = FALSE;
325
326   if (src == NULL) {
327     if (pool->other_pool == NULL) {
328       GST_ERROR_OBJECT (pool, "can't prepare buffer, source buffer missing");
329       return GST_FLOW_ERROR;
330     }
331
332     ret = gst_buffer_pool_acquire_buffer (pool->other_pool, &src, NULL);
333     if (ret != GST_FLOW_OK) {
334       GST_ERROR_OBJECT (pool, "failed to acquire buffer from downstream pool");
335       goto done;
336     }
337
338     own_src = TRUE;
339   }
340
341   switch (pool->obj->mode) {
342     case GST_V4L2_IO_MMAP:
343     case GST_V4L2_IO_DMABUF:
344       ret = gst_v4l2_buffer_pool_copy_buffer (pool, dest, src);
345       break;
346     case GST_V4L2_IO_USERPTR:
347       ret = gst_v4l2_buffer_pool_import_userptr (pool, dest, src);
348       break;
349     case GST_V4L2_IO_DMABUF_IMPORT:
350       ret = gst_v4l2_buffer_pool_import_dmabuf (pool, dest, src);
351       break;
352     default:
353       break;
354   }
355
356   if (own_src)
357     gst_buffer_unref (src);
358
359 done:
360   return ret;
361 }
362
363 static GstFlowReturn
364 gst_v4l2_buffer_pool_alloc_buffer (GstBufferPool * bpool, GstBuffer ** buffer,
365     GstBufferPoolAcquireParams * params)
366 {
367   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
368   GstV4l2MemoryGroup *group = NULL;
369   GstBuffer *newbuf = NULL;
370   GstV4l2Object *obj;
371   GstVideoInfo *info;
372
373   obj = pool->obj;
374   info = &obj->info;
375
376   switch (obj->mode) {
377     case GST_V4L2_IO_RW:
378       newbuf =
379           gst_buffer_new_allocate (pool->allocator, pool->size, &pool->params);
380       break;
381     case GST_V4L2_IO_MMAP:
382       group = gst_v4l2_allocator_alloc_mmap (pool->vallocator);
383       break;
384     case GST_V4L2_IO_DMABUF:
385       group = gst_v4l2_allocator_alloc_dmabuf (pool->vallocator,
386           pool->allocator);
387       break;
388     case GST_V4L2_IO_USERPTR:
389       group = gst_v4l2_allocator_alloc_userptr (pool->vallocator);
390       break;
391     case GST_V4L2_IO_DMABUF_IMPORT:
392       group = gst_v4l2_allocator_alloc_dmabufin (pool->vallocator);
393       break;
394     default:
395       newbuf = NULL;
396       g_assert_not_reached ();
397       break;
398   }
399
400   if (group != NULL) {
401     gint i;
402     newbuf = gst_buffer_new ();
403
404     for (i = 0; i < group->n_mem; i++)
405       gst_buffer_append_memory (newbuf, group->mem[i]);
406   } else if (newbuf == NULL) {
407     goto allocation_failed;
408   }
409
410   /* add metadata to raw video buffers */
411   if (pool->add_videometa)
412     gst_buffer_add_video_meta_full (newbuf, GST_VIDEO_FRAME_FLAG_NONE,
413         GST_VIDEO_INFO_FORMAT (info), GST_VIDEO_INFO_WIDTH (info),
414         GST_VIDEO_INFO_HEIGHT (info), GST_VIDEO_INFO_N_PLANES (info),
415         info->offset, info->stride);
416
417   *buffer = newbuf;
418
419   return GST_FLOW_OK;
420
421   /* ERRORS */
422 allocation_failed:
423   {
424     GST_ERROR_OBJECT (pool, "failed to allocate buffer");
425     return GST_FLOW_ERROR;
426   }
427 }
428
429 static gboolean
430 gst_v4l2_buffer_pool_set_config (GstBufferPool * bpool, GstStructure * config)
431 {
432   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
433   GstV4l2Object *obj = pool->obj;
434   GstCaps *caps;
435   guint size, min_buffers, max_buffers;
436   GstAllocator *allocator;
437   GstAllocationParams params;
438   gboolean can_allocate = FALSE;
439   gboolean updated = FALSE;
440   gboolean ret;
441
442   pool->add_videometa =
443       gst_buffer_pool_config_has_option (config,
444       GST_BUFFER_POOL_OPTION_VIDEO_META);
445
446   /* parse the config and keep around */
447   if (!gst_buffer_pool_config_get_params (config, &caps, &size, &min_buffers,
448           &max_buffers))
449     goto wrong_config;
450
451   if (!gst_buffer_pool_config_get_allocator (config, &allocator, &params))
452     goto wrong_config;
453
454   GST_DEBUG_OBJECT (pool, "config %" GST_PTR_FORMAT, config);
455
456   if (pool->allocator)
457     gst_object_unref (pool->allocator);
458   pool->allocator = NULL;
459
460   switch (obj->mode) {
461     case GST_V4L2_IO_DMABUF:
462       pool->allocator = gst_dmabuf_allocator_new ();
463       can_allocate = GST_V4L2_ALLOCATOR_CAN_ALLOCATE (pool->vallocator, MMAP);
464       break;
465     case GST_V4L2_IO_MMAP:
466       can_allocate = GST_V4L2_ALLOCATOR_CAN_ALLOCATE (pool->vallocator, MMAP);
467       break;
468     case GST_V4L2_IO_USERPTR:
469       can_allocate =
470           GST_V4L2_ALLOCATOR_CAN_ALLOCATE (pool->vallocator, USERPTR);
471       break;
472     case GST_V4L2_IO_DMABUF_IMPORT:
473       can_allocate = GST_V4L2_ALLOCATOR_CAN_ALLOCATE (pool->vallocator, DMABUF);
474       break;
475     case GST_V4L2_IO_RW:
476       if (allocator)
477         pool->allocator = g_object_ref (allocator);
478       pool->params = params;
479       /* No need to change the configuration */
480       goto done;
481       break;
482     default:
483       g_assert_not_reached ();
484       break;
485   }
486
487   /* libv4l2 conversion code does not handle CREATE_BUFS, and may lead to
488    * instability and crash, disable it for now */
489   if (can_allocate && obj->fmtdesc->flags & V4L2_FMT_FLAG_EMULATED) {
490     GST_WARNING_OBJECT (pool,
491         "libv4l2 converter detected, disabling CREATE_BUFS");
492     can_allocate = FALSE;
493   }
494
495   if (min_buffers < GST_V4L2_MIN_BUFFERS) {
496     updated = TRUE;
497     min_buffers = GST_V4L2_MIN_BUFFERS;
498     GST_INFO_OBJECT (pool, "increasing minimum buffers to %u", min_buffers);
499   }
500
501   if (max_buffers > VIDEO_MAX_FRAME || max_buffers == 0) {
502     updated = TRUE;
503     max_buffers = VIDEO_MAX_FRAME;
504     GST_INFO_OBJECT (pool, "reducing maximum buffers to %u", max_buffers);
505   }
506
507   if (min_buffers > max_buffers) {
508     updated = TRUE;
509     min_buffers = max_buffers;
510     GST_INFO_OBJECT (pool, "reducing minimum buffers to %u", min_buffers);
511   } else if (min_buffers != max_buffers) {
512     if (!can_allocate) {
513       updated = TRUE;
514       max_buffers = min_buffers;
515       GST_INFO_OBJECT (pool, "can't allocate, setting maximum to minimum");
516     }
517   }
518
519   if (!pool->add_videometa && obj->need_video_meta) {
520     GST_INFO_OBJECT (pool, "adding needed video meta");
521     updated = TRUE;
522     gst_buffer_pool_config_add_option (config,
523         GST_BUFFER_POOL_OPTION_VIDEO_META);
524   }
525
526   /* Always update the config to ensure the configured size matches */
527   gst_buffer_pool_config_set_params (config, caps, obj->info.size, min_buffers,
528       max_buffers);
529
530   /* keep a GstVideoInfo with defaults for the when we need to copy */
531   gst_video_info_from_caps (&pool->caps_info, caps);
532
533 done:
534   ret = GST_BUFFER_POOL_CLASS (parent_class)->set_config (bpool, config);
535
536   /* If anything was changed documentation recommand to return FALSE */
537   return !updated && ret;
538
539   /* ERRORS */
540 wrong_config:
541   {
542     GST_ERROR_OBJECT (pool, "invalid config %" GST_PTR_FORMAT, config);
543     return FALSE;
544   }
545 }
546
547 static gboolean
548 gst_v4l2_buffer_pool_streamon (GstV4l2BufferPool * pool)
549 {
550   GstV4l2Object *obj = pool->obj;
551
552   switch (obj->mode) {
553     case GST_V4L2_IO_MMAP:
554     case GST_V4L2_IO_USERPTR:
555     case GST_V4L2_IO_DMABUF:
556     case GST_V4L2_IO_DMABUF_IMPORT:
557       if (!pool->streaming) {
558         if (v4l2_ioctl (pool->video_fd, VIDIOC_STREAMON, &obj->type) < 0)
559           goto streamon_failed;
560
561         pool->streaming = TRUE;
562
563         GST_DEBUG_OBJECT (pool, "Started streaming");
564       }
565       break;
566     default:
567       break;
568   }
569
570   return TRUE;
571
572 streamon_failed:
573   {
574     GST_ERROR_OBJECT (pool, "error with STREAMON %d (%s)", errno,
575         g_strerror (errno));
576     return FALSE;
577   }
578 }
579
580 static void
581 gst_v4l2_buffer_pool_streamoff (GstV4l2BufferPool * pool)
582 {
583   GstV4l2Object *obj = pool->obj;
584
585   switch (obj->mode) {
586     case GST_V4L2_IO_MMAP:
587     case GST_V4L2_IO_USERPTR:
588     case GST_V4L2_IO_DMABUF:
589     case GST_V4L2_IO_DMABUF_IMPORT:
590       if (pool->streaming) {
591         if (v4l2_ioctl (pool->video_fd, VIDIOC_STREAMOFF, &obj->type) < 0)
592           GST_WARNING_OBJECT (pool, "STREAMOFF failed with errno %d (%s)",
593               errno, g_strerror (errno));
594
595         pool->streaming = FALSE;
596
597         GST_DEBUG_OBJECT (pool, "Stopped streaming");
598
599         if (pool->vallocator)
600           gst_v4l2_allocator_flush (pool->vallocator);
601       }
602       break;
603     default:
604       break;
605   }
606 }
607
608 static GstFlowReturn
609 gst_v4l2_buffer_pool_resurect_buffer (GstV4l2BufferPool * pool)
610 {
611   GstBufferPoolAcquireParams params = { 0 };
612   GstBuffer *buffer = NULL;
613   GstFlowReturn ret;
614
615   GST_DEBUG_OBJECT (pool, "A buffer was lost, reallocating it");
616
617   params.flags =
618       (GstBufferPoolAcquireFlags) GST_V4L2_BUFFER_POOL_ACQUIRE_FLAG_RESURRECT;
619   ret =
620       gst_buffer_pool_acquire_buffer (GST_BUFFER_POOL (pool), &buffer, &params);
621
622   if (ret == GST_FLOW_OK)
623     gst_buffer_unref (buffer);
624
625   return ret;
626 }
627
628 static gboolean
629 gst_v4l2_buffer_pool_start (GstBufferPool * bpool)
630 {
631   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
632   GstBufferPoolClass *pclass = GST_BUFFER_POOL_CLASS (parent_class);
633   GstV4l2Object *obj = pool->obj;
634   GstStructure *config;
635   GstCaps *caps;
636   guint size, min_buffers, max_buffers;
637   guint max_latency, min_latency, copy_threshold = 0;
638   gboolean can_allocate = FALSE;
639
640   GST_DEBUG_OBJECT (pool, "activating pool");
641
642   config = gst_buffer_pool_get_config (bpool);
643   if (!gst_buffer_pool_config_get_params (config, &caps, &size, &min_buffers,
644           &max_buffers))
645     goto wrong_config;
646
647   min_latency = MAX (GST_V4L2_MIN_BUFFERS, obj->min_buffers);
648
649   switch (obj->mode) {
650     case GST_V4L2_IO_RW:
651       can_allocate = TRUE;
652 #ifdef HAVE_LIBV4L2
653       /* This workaround a unfixable bug in libv4l2 when RW is emulated on top
654        * of MMAP. In this case, the first read initialize the queues, but the
655        * poll before that will always fail. Doing an empty read, forces the
656        * queue to be initialized now. We only do this if we have a streaming
657        * driver. */
658       if (obj->vcap.capabilities & V4L2_CAP_STREAMING)
659         v4l2_read (obj->video_fd, NULL, 0);
660 #endif
661       break;
662     case GST_V4L2_IO_DMABUF:
663     case GST_V4L2_IO_MMAP:
664     {
665       guint count;
666
667       can_allocate = GST_V4L2_ALLOCATOR_CAN_ALLOCATE (pool->vallocator, MMAP);
668
669       /* first, lets request buffers, and see how many we can get: */
670       GST_DEBUG_OBJECT (pool, "requesting %d MMAP buffers", min_buffers);
671
672       count = gst_v4l2_allocator_start (pool->vallocator, min_buffers,
673           V4L2_MEMORY_MMAP);
674
675       if (count < GST_V4L2_MIN_BUFFERS) {
676         min_buffers = count;
677         goto no_buffers;
678       }
679
680       /* V4L2 buffer pool are often very limited in the amount of buffers it
681        * can offer. The copy_threshold will workaround this limitation by
682        * falling back to copy if the pipeline needed more buffers. This also
683        * prevent having to do REQBUFS(N)/REQBUFS(0) everytime configure is
684        * called. */
685       if (count != min_buffers) {
686         GST_WARNING_OBJECT (pool, "using %u buffers instead of %u",
687             count, min_buffers);
688         min_buffers = count;
689         copy_threshold = min_latency;
690
691         /* The initial minimum could be provide either by GstBufferPool or
692          * driver needs. */
693         min_buffers = count;
694       }
695
696       break;
697     }
698     case GST_V4L2_IO_USERPTR:
699     {
700       guint count;
701
702       can_allocate =
703           GST_V4L2_ALLOCATOR_CAN_ALLOCATE (pool->vallocator, USERPTR);
704
705       GST_DEBUG_OBJECT (pool, "requesting %d USERPTR buffers", min_buffers);
706
707       count = gst_v4l2_allocator_start (pool->vallocator, min_buffers,
708           V4L2_MEMORY_USERPTR);
709
710       /* There is no rational to not get what we asked */
711       if (count < min_buffers) {
712         min_buffers = count;
713         goto no_buffers;
714       }
715
716       min_buffers = count;
717       break;
718     }
719     case GST_V4L2_IO_DMABUF_IMPORT:
720     {
721       guint count;
722
723       can_allocate = GST_V4L2_ALLOCATOR_CAN_ALLOCATE (pool->vallocator, DMABUF);
724
725       GST_DEBUG_OBJECT (pool, "requesting %d DMABUF buffers", min_buffers);
726
727       count = gst_v4l2_allocator_start (pool->vallocator, min_buffers,
728           V4L2_MEMORY_DMABUF);
729
730       /* There is no rational to not get what we asked */
731       if (count < min_buffers) {
732         min_buffers = count;
733         goto no_buffers;
734       }
735
736       min_buffers = count;
737       break;
738     }
739     default:
740       min_buffers = 0;
741       copy_threshold = 0;
742       g_assert_not_reached ();
743       break;
744   }
745
746   if (can_allocate)
747     max_latency = max_buffers;
748   else
749     max_latency = min_buffers;
750
751   pool->size = size;
752   pool->copy_threshold = copy_threshold;
753   pool->max_latency = max_latency;
754   pool->min_latency = min_latency;
755   pool->num_queued = 0;
756
757   if (max_buffers != 0 && max_buffers < min_buffers)
758     max_buffers = min_buffers;
759
760   gst_buffer_pool_config_set_params (config, caps, size, min_buffers,
761       max_buffers);
762   pclass->set_config (bpool, config);
763   gst_structure_free (config);
764
765   if (pool->other_pool)
766     if (!gst_buffer_pool_set_active (pool->other_pool, TRUE))
767       goto other_pool_failed;
768
769   /* now, allocate the buffers: */
770   if (!pclass->start (bpool))
771     goto start_failed;
772
773   if (!V4L2_TYPE_IS_OUTPUT (obj->type))
774     pool->group_released_handler =
775         g_signal_connect_swapped (pool->vallocator, "group-released",
776         G_CALLBACK (gst_v4l2_buffer_pool_resurect_buffer), pool);
777
778   return TRUE;
779
780   /* ERRORS */
781 wrong_config:
782   {
783     GST_ERROR_OBJECT (pool, "invalid config %" GST_PTR_FORMAT, config);
784     gst_structure_free (config);
785     return FALSE;
786   }
787 no_buffers:
788   {
789     GST_ERROR_OBJECT (pool,
790         "we received %d buffer from device '%s', we want at least %d",
791         min_buffers, obj->videodev, GST_V4L2_MIN_BUFFERS);
792     gst_structure_free (config);
793     return FALSE;
794   }
795 start_failed:
796   {
797     GST_ERROR_OBJECT (pool, "failed to start streaming");
798     return FALSE;
799   }
800 other_pool_failed:
801   {
802     GST_ERROR_OBJECT (pool, "failed to active the other pool %"
803         GST_PTR_FORMAT, pool->other_pool);
804     return FALSE;
805   }
806 }
807
808 static gboolean
809 gst_v4l2_buffer_pool_stop (GstBufferPool * bpool)
810 {
811   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
812   GstBufferPoolClass *pclass = GST_BUFFER_POOL_CLASS (parent_class);
813   gboolean ret;
814   gint i;
815
816   GST_DEBUG_OBJECT (pool, "stopping pool");
817
818   if (pool->group_released_handler > 0) {
819     g_signal_handler_disconnect (pool->vallocator,
820         pool->group_released_handler);
821     pool->group_released_handler = 0;
822   }
823
824   if (pool->other_pool) {
825     gst_object_unref (pool->other_pool);
826     pool->other_pool = NULL;
827   }
828
829   gst_v4l2_buffer_pool_streamoff (pool);
830
831   for (i = 0; i < VIDEO_MAX_FRAME; i++) {
832     if (pool->buffers[i]) {
833       GstBuffer *buffer = pool->buffers[i];
834
835       pool->buffers[i] = NULL;
836
837       if (V4L2_TYPE_IS_OUTPUT (pool->obj->type))
838         gst_v4l2_buffer_pool_release_buffer (bpool, buffer);
839       else                      /* Don't re-enqueue capture buffer on stop */
840         pclass->release_buffer (bpool, buffer);
841
842       g_atomic_int_add (&pool->num_queued, -1);
843     }
844   }
845
846   ret = GST_BUFFER_POOL_CLASS (parent_class)->stop (bpool);
847
848   if (ret && pool->vallocator) {
849     GstV4l2Return vret;
850
851     vret = gst_v4l2_allocator_stop (pool->vallocator);
852
853     if (vret == GST_V4L2_BUSY)
854       GST_WARNING_OBJECT (pool, "some buffers are still outstanding");
855
856     ret = (vret == GST_V4L2_OK);
857   }
858
859   return ret;
860 }
861
862 static void
863 gst_v4l2_buffer_pool_flush_start (GstBufferPool * bpool)
864 {
865   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
866
867   GST_DEBUG_OBJECT (pool, "start flushing");
868
869   gst_poll_set_flushing (pool->poll, TRUE);
870
871   GST_OBJECT_LOCK (pool);
872   pool->empty = FALSE;
873   g_cond_broadcast (&pool->empty_cond);
874   GST_OBJECT_UNLOCK (pool);
875
876   if (pool->other_pool)
877     gst_buffer_pool_set_flushing (pool->other_pool, TRUE);
878 }
879
880 static void
881 gst_v4l2_buffer_pool_flush_stop (GstBufferPool * bpool)
882 {
883   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
884   GstV4l2Object *obj = pool->obj;
885   gint i;
886
887   GST_DEBUG_OBJECT (pool, "stop flushing");
888
889   /* If we haven't started streaming yet, simply call streamon */
890   if (!pool->streaming)
891     goto streamon;
892
893   if (pool->other_pool)
894     gst_buffer_pool_set_flushing (pool->other_pool, FALSE);
895
896   gst_v4l2_buffer_pool_streamoff (pool);
897
898   /* Reset our state */
899   switch (obj->mode) {
900     case GST_V4L2_IO_RW:
901       break;
902     case GST_V4L2_IO_MMAP:
903     case GST_V4L2_IO_USERPTR:
904     case GST_V4L2_IO_DMABUF:
905     case GST_V4L2_IO_DMABUF_IMPORT:
906     {
907       for (i = 0; i < VIDEO_MAX_FRAME; i++) {
908         /* Re-enqueue buffers */
909         if (pool->buffers[i]) {
910           GstBufferPool *bpool = (GstBufferPool *) pool;
911           GstBuffer *buffer = pool->buffers[i];
912
913           pool->buffers[i] = NULL;
914
915           /* Remove qdata, this will unmap any map data in
916            * userptr/dmabuf-import */
917           gst_mini_object_set_qdata (GST_MINI_OBJECT (buffer),
918               GST_V4L2_IMPORT_QUARK, NULL, NULL);
919
920           if (buffer->pool == NULL)
921             gst_v4l2_buffer_pool_release_buffer (bpool, buffer);
922
923           g_atomic_int_add (&pool->num_queued, -1);
924         }
925       }
926
927       break;
928     }
929     default:
930       g_assert_not_reached ();
931       break;
932   }
933
934 streamon:
935   /* Start streaming on capture device only */
936   if (!V4L2_TYPE_IS_OUTPUT (obj->type))
937     gst_v4l2_buffer_pool_streamon (pool);
938
939   gst_poll_set_flushing (pool->poll, FALSE);
940 }
941
942 static GstFlowReturn
943 gst_v4l2_buffer_pool_poll (GstV4l2BufferPool * pool)
944 {
945   gint ret;
946
947   /* In RW mode there is no queue, hence no need to wait while the queue is
948    * empty */
949   if (pool->obj->mode != GST_V4L2_IO_RW) {
950     GST_OBJECT_LOCK (pool);
951     while (pool->empty)
952       g_cond_wait (&pool->empty_cond, GST_OBJECT_GET_LOCK (pool));
953     GST_OBJECT_UNLOCK (pool);
954   }
955
956   if (!pool->can_poll_device)
957     goto done;
958
959   GST_LOG_OBJECT (pool, "polling device");
960
961 again:
962   ret = gst_poll_wait (pool->poll, GST_CLOCK_TIME_NONE);
963   if (G_UNLIKELY (ret < 0)) {
964     switch (errno) {
965       case EBUSY:
966         goto stopped;
967       case EAGAIN:
968       case EINTR:
969         goto again;
970       case ENXIO:
971         GST_WARNING_OBJECT (pool,
972             "v4l2 device doesn't support polling. Disabling"
973             " using libv4l2 in this case may cause deadlocks");
974         pool->can_poll_device = FALSE;
975         goto done;
976       default:
977         goto select_error;
978     }
979   }
980
981   if (gst_poll_fd_has_error (pool->poll, &pool->pollfd))
982     goto select_error;
983
984 done:
985   return GST_FLOW_OK;
986
987   /* ERRORS */
988 stopped:
989   {
990     GST_DEBUG_OBJECT (pool, "stop called");
991     return GST_FLOW_FLUSHING;
992   }
993 select_error:
994   {
995     GST_ELEMENT_ERROR (pool->obj->element, RESOURCE, READ, (NULL),
996         ("poll error %d: %s (%d)", ret, g_strerror (errno), errno));
997     return GST_FLOW_ERROR;
998   }
999 }
1000
1001 static GstFlowReturn
1002 gst_v4l2_buffer_pool_qbuf (GstV4l2BufferPool * pool, GstBuffer * buf)
1003 {
1004   GstV4l2MemoryGroup *group = NULL;
1005   gint index;
1006
1007   if (!gst_v4l2_is_buffer_valid (buf, &group)) {
1008     GST_LOG_OBJECT (pool, "unref copied/invalid buffer %p", buf);
1009     gst_buffer_unref (buf);
1010     return GST_FLOW_OK;
1011   }
1012
1013   index = group->buffer.index;
1014
1015   if (pool->buffers[index] != NULL)
1016     goto already_queued;
1017
1018   GST_LOG_OBJECT (pool, "queuing buffer %i", index);
1019
1020   g_atomic_int_inc (&pool->num_queued);
1021   pool->buffers[index] = buf;
1022
1023   if (!gst_v4l2_allocator_qbuf (pool->vallocator, group))
1024     goto queue_failed;
1025
1026   GST_OBJECT_LOCK (pool);
1027   pool->empty = FALSE;
1028   g_cond_signal (&pool->empty_cond);
1029   GST_OBJECT_UNLOCK (pool);
1030
1031   return GST_FLOW_OK;
1032
1033 already_queued:
1034   {
1035     GST_ERROR_OBJECT (pool, "the buffer %i was already queued", index);
1036     return GST_FLOW_ERROR;
1037   }
1038 queue_failed:
1039   {
1040     GST_ERROR_OBJECT (pool, "could not queue a buffer %i", index);
1041     /* Mark broken buffer to the allocator */
1042     GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_TAG_MEMORY);
1043     g_atomic_int_add (&pool->num_queued, -1);
1044     pool->buffers[index] = NULL;
1045     return GST_FLOW_ERROR;
1046   }
1047 }
1048
1049 static GstFlowReturn
1050 gst_v4l2_buffer_pool_dqbuf (GstV4l2BufferPool * pool, GstBuffer ** buffer)
1051 {
1052   GstFlowReturn res;
1053   GstBuffer *outbuf;
1054   GstV4l2Object *obj = pool->obj;
1055   GstClockTime timestamp;
1056   GstV4l2MemoryGroup *group;
1057   gint i;
1058
1059   if ((res = gst_v4l2_buffer_pool_poll (pool)) != GST_FLOW_OK)
1060     goto poll_failed;
1061
1062   GST_LOG_OBJECT (pool, "dequeueing a buffer");
1063
1064   group = gst_v4l2_allocator_dqbuf (pool->vallocator);
1065   if (group == NULL)
1066     goto dqbuf_failed;
1067
1068   /* get our GstBuffer with that index from the pool, if the buffer was
1069    * outstanding we have a serious problem.
1070    */
1071   outbuf = pool->buffers[group->buffer.index];
1072   if (outbuf == NULL)
1073     goto no_buffer;
1074
1075   /* mark the buffer outstanding */
1076   pool->buffers[group->buffer.index] = NULL;
1077   if (g_atomic_int_dec_and_test (&pool->num_queued)) {
1078     GST_OBJECT_LOCK (pool);
1079     pool->empty = TRUE;
1080     GST_OBJECT_UNLOCK (pool);
1081   }
1082
1083   timestamp = GST_TIMEVAL_TO_TIME (group->buffer.timestamp);
1084
1085 #ifndef GST_DISABLE_GST_DEBUG
1086   for (i = 0; i < group->n_mem; i++) {
1087     GST_LOG_OBJECT (pool,
1088         "dequeued buffer %p seq:%d (ix=%d), mem %p used %d, plane=%d, flags %08x, ts %"
1089         GST_TIME_FORMAT ", pool-queued=%d, buffer=%p", outbuf,
1090         group->buffer.sequence, group->buffer.index, group->mem[i],
1091         group->planes[i].bytesused, i, group->buffer.flags,
1092         GST_TIME_ARGS (timestamp), pool->num_queued, outbuf);
1093   }
1094 #endif
1095
1096   /* set top/bottom field first if v4l2_buffer has the information */
1097   switch (group->buffer.field) {
1098     case V4L2_FIELD_NONE:
1099       GST_BUFFER_FLAG_UNSET (outbuf, GST_VIDEO_BUFFER_FLAG_INTERLACED);
1100       GST_BUFFER_FLAG_UNSET (outbuf, GST_VIDEO_BUFFER_FLAG_TFF);
1101       break;
1102     case V4L2_FIELD_INTERLACED_TB:
1103       GST_BUFFER_FLAG_SET (outbuf, GST_VIDEO_BUFFER_FLAG_INTERLACED);
1104       GST_BUFFER_FLAG_SET (outbuf, GST_VIDEO_BUFFER_FLAG_TFF);
1105       break;
1106     case V4L2_FIELD_INTERLACED_BT:
1107       GST_BUFFER_FLAG_SET (outbuf, GST_VIDEO_BUFFER_FLAG_INTERLACED);
1108       GST_BUFFER_FLAG_UNSET (outbuf, GST_VIDEO_BUFFER_FLAG_TFF);
1109       break;
1110     case V4L2_FIELD_INTERLACED:
1111       GST_BUFFER_FLAG_SET (outbuf, GST_VIDEO_BUFFER_FLAG_INTERLACED);
1112       if (obj->tv_norm == V4L2_STD_NTSC_M ||
1113           obj->tv_norm == V4L2_STD_NTSC_M_JP ||
1114           obj->tv_norm == V4L2_STD_NTSC_M_KR) {
1115         GST_BUFFER_FLAG_UNSET (outbuf, GST_VIDEO_BUFFER_FLAG_TFF);
1116       } else {
1117         GST_BUFFER_FLAG_SET (outbuf, GST_VIDEO_BUFFER_FLAG_TFF);
1118       }
1119       break;
1120     default:
1121       GST_BUFFER_FLAG_UNSET (outbuf, GST_VIDEO_BUFFER_FLAG_INTERLACED);
1122       GST_BUFFER_FLAG_UNSET (outbuf, GST_VIDEO_BUFFER_FLAG_TFF);
1123       GST_FIXME_OBJECT (pool,
1124           "Unhandled enum v4l2_field %d - treating as progressive",
1125           group->buffer.field);
1126   }
1127
1128   if (GST_VIDEO_INFO_FORMAT (&obj->info) == GST_VIDEO_FORMAT_ENCODED) {
1129     if (group->buffer.flags & V4L2_BUF_FLAG_KEYFRAME)
1130       GST_BUFFER_FLAG_UNSET (outbuf, GST_BUFFER_FLAG_DELTA_UNIT);
1131     else
1132       GST_BUFFER_FLAG_SET (outbuf, GST_BUFFER_FLAG_DELTA_UNIT);
1133   }
1134
1135   if (group->buffer.flags & V4L2_BUF_FLAG_ERROR)
1136     GST_BUFFER_FLAG_SET (outbuf, GST_BUFFER_FLAG_CORRUPTED);
1137
1138   GST_BUFFER_TIMESTAMP (outbuf) = timestamp;
1139
1140   *buffer = outbuf;
1141
1142   return GST_FLOW_OK;
1143
1144   /* ERRORS */
1145 poll_failed:
1146   {
1147     GST_DEBUG_OBJECT (pool, "poll error %s", gst_flow_get_name (res));
1148     return res;
1149   }
1150 dqbuf_failed:
1151   {
1152     return GST_FLOW_ERROR;
1153   }
1154 no_buffer:
1155   {
1156     GST_ERROR_OBJECT (pool, "No free buffer found in the pool at index %d.",
1157         group->buffer.index);
1158     return GST_FLOW_ERROR;
1159   }
1160 }
1161
1162 static GstFlowReturn
1163 gst_v4l2_buffer_pool_acquire_buffer (GstBufferPool * bpool, GstBuffer ** buffer,
1164     GstBufferPoolAcquireParams * params)
1165 {
1166   GstFlowReturn ret;
1167   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
1168   GstBufferPoolClass *pclass = GST_BUFFER_POOL_CLASS (parent_class);
1169   GstV4l2Object *obj = pool->obj;
1170
1171   GST_DEBUG_OBJECT (pool, "acquire");
1172
1173   /* If this is being called to resurect a lost buffer */
1174   if (params && params->flags & GST_V4L2_BUFFER_POOL_ACQUIRE_FLAG_RESURRECT) {
1175     ret = pclass->acquire_buffer (bpool, buffer, params);
1176     goto done;
1177   }
1178
1179   switch (obj->type) {
1180     case V4L2_BUF_TYPE_VIDEO_CAPTURE:
1181     case V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE:
1182       /* capture, This function should return a buffer with new captured data */
1183       switch (obj->mode) {
1184         case GST_V4L2_IO_RW:
1185         {
1186           /* take empty buffer from the pool */
1187           ret = pclass->acquire_buffer (bpool, buffer, params);
1188           break;
1189         }
1190         case GST_V4L2_IO_DMABUF:
1191         case GST_V4L2_IO_MMAP:
1192         case GST_V4L2_IO_USERPTR:
1193         case GST_V4L2_IO_DMABUF_IMPORT:
1194         {
1195           /* just dequeue a buffer, we basically use the queue of v4l2 as the
1196            * storage for our buffers. This function does poll first so we can
1197            * interrupt it fine. */
1198           ret = gst_v4l2_buffer_pool_dqbuf (pool, buffer);
1199           break;
1200         }
1201         default:
1202           ret = GST_FLOW_ERROR;
1203           g_assert_not_reached ();
1204           break;
1205       }
1206       break;
1207
1208
1209     case V4L2_BUF_TYPE_VIDEO_OUTPUT:
1210     case V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE:
1211       /* playback, This function should return an empty buffer */
1212       switch (obj->mode) {
1213         case GST_V4L2_IO_RW:
1214           /* get an empty buffer */
1215           ret = pclass->acquire_buffer (bpool, buffer, params);
1216           break;
1217
1218         case GST_V4L2_IO_MMAP:
1219         case GST_V4L2_IO_DMABUF:
1220         case GST_V4L2_IO_USERPTR:
1221         case GST_V4L2_IO_DMABUF_IMPORT:
1222           /* get a free unqueued buffer */
1223           ret = pclass->acquire_buffer (bpool, buffer, params);
1224           break;
1225
1226         default:
1227           ret = GST_FLOW_ERROR;
1228           g_assert_not_reached ();
1229           break;
1230       }
1231       break;
1232
1233     default:
1234       ret = GST_FLOW_ERROR;
1235       g_assert_not_reached ();
1236       break;
1237   }
1238 done:
1239   return ret;
1240 }
1241
1242 static void
1243 gst_v4l2_buffer_pool_release_buffer (GstBufferPool * bpool, GstBuffer * buffer)
1244 {
1245   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
1246   GstBufferPoolClass *pclass = GST_BUFFER_POOL_CLASS (parent_class);
1247   GstV4l2Object *obj = pool->obj;
1248
1249   GST_DEBUG_OBJECT (pool, "release buffer %p", buffer);
1250
1251   switch (obj->type) {
1252     case V4L2_BUF_TYPE_VIDEO_CAPTURE:
1253     case V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE:
1254       /* capture, put the buffer back in the queue so that we can refill it
1255        * later. */
1256       switch (obj->mode) {
1257         case GST_V4L2_IO_RW:
1258           /* release back in the pool */
1259           pclass->release_buffer (bpool, buffer);
1260           break;
1261
1262         case GST_V4L2_IO_DMABUF:
1263         case GST_V4L2_IO_MMAP:
1264         case GST_V4L2_IO_USERPTR:
1265         case GST_V4L2_IO_DMABUF_IMPORT:
1266         {
1267           if (gst_v4l2_is_buffer_valid (buffer, NULL)) {
1268             /* queue back in the device */
1269             if (pool->other_pool)
1270               gst_v4l2_buffer_pool_prepare_buffer (pool, buffer, NULL);
1271             if (gst_v4l2_buffer_pool_qbuf (pool, buffer) != GST_FLOW_OK)
1272               pclass->release_buffer (bpool, buffer);
1273           } else {
1274             /* Simply release invalide/modified buffer, the allocator will
1275              * give it back later */
1276             GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_TAG_MEMORY);
1277             pclass->release_buffer (bpool, buffer);
1278           }
1279           break;
1280         }
1281         default:
1282           g_assert_not_reached ();
1283           break;
1284       }
1285       break;
1286
1287     case V4L2_BUF_TYPE_VIDEO_OUTPUT:
1288     case V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE:
1289       switch (obj->mode) {
1290         case GST_V4L2_IO_RW:
1291           /* release back in the pool */
1292           pclass->release_buffer (bpool, buffer);
1293           break;
1294
1295         case GST_V4L2_IO_MMAP:
1296         case GST_V4L2_IO_DMABUF:
1297         case GST_V4L2_IO_USERPTR:
1298         case GST_V4L2_IO_DMABUF_IMPORT:
1299         {
1300           GstV4l2MemoryGroup *group;
1301           guint index;
1302
1303           if (!gst_v4l2_is_buffer_valid (buffer, &group)) {
1304             /* Simply release invalide/modified buffer, the allocator will
1305              * give it back later */
1306             GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_TAG_MEMORY);
1307             pclass->release_buffer (bpool, buffer);
1308             break;
1309           }
1310
1311           index = group->buffer.index;
1312
1313           if (pool->buffers[index] == NULL) {
1314             GST_LOG_OBJECT (pool, "buffer %u not queued, putting on free list",
1315                 index);
1316
1317             /* Remove qdata, this will unmap any map data in userptr */
1318             gst_mini_object_set_qdata (GST_MINI_OBJECT (buffer),
1319                 GST_V4L2_IMPORT_QUARK, NULL, NULL);
1320
1321             /* reset to default size */
1322             gst_v4l2_allocator_reset_group (pool->vallocator, group);
1323
1324             /* playback, put the buffer back in the queue to refill later. */
1325             pclass->release_buffer (bpool, buffer);
1326           } else {
1327             /* the buffer is queued in the device but maybe not played yet. We just
1328              * leave it there and not make it available for future calls to acquire
1329              * for now. The buffer will be dequeued and reused later. */
1330             GST_LOG_OBJECT (pool, "buffer %u is queued", index);
1331           }
1332           break;
1333         }
1334
1335         default:
1336           g_assert_not_reached ();
1337           break;
1338       }
1339       break;
1340
1341     default:
1342       g_assert_not_reached ();
1343       break;
1344   }
1345 }
1346
1347 static void
1348 gst_v4l2_buffer_pool_dispose (GObject * object)
1349 {
1350   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (object);
1351
1352   if (pool->vallocator)
1353     gst_object_unref (pool->vallocator);
1354   pool->vallocator = NULL;
1355
1356   if (pool->allocator)
1357     gst_object_unref (pool->allocator);
1358   pool->allocator = NULL;
1359
1360   if (pool->other_pool)
1361     gst_object_unref (pool->other_pool);
1362   pool->other_pool = NULL;
1363
1364   G_OBJECT_CLASS (parent_class)->dispose (object);
1365 }
1366
1367 static void
1368 gst_v4l2_buffer_pool_finalize (GObject * object)
1369 {
1370   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (object);
1371
1372   if (pool->video_fd >= 0)
1373     v4l2_close (pool->video_fd);
1374
1375   gst_poll_free (pool->poll);
1376
1377   /* FIXME Is this required to keep around ?
1378    * This can't be done in dispose method because we must not set pointer
1379    * to NULL as it is part of the v4l2object and dispose could be called
1380    * multiple times */
1381   gst_object_unref (pool->obj->element);
1382
1383   g_cond_clear (&pool->empty_cond);
1384
1385   /* FIXME have we done enough here ? */
1386
1387   G_OBJECT_CLASS (parent_class)->finalize (object);
1388 }
1389
1390 static void
1391 gst_v4l2_buffer_pool_init (GstV4l2BufferPool * pool)
1392 {
1393   pool->poll = gst_poll_new (TRUE);
1394   pool->can_poll_device = TRUE;
1395   g_cond_init (&pool->empty_cond);
1396   pool->empty = TRUE;
1397 }
1398
1399 static void
1400 gst_v4l2_buffer_pool_class_init (GstV4l2BufferPoolClass * klass)
1401 {
1402   GObjectClass *object_class = G_OBJECT_CLASS (klass);
1403   GstBufferPoolClass *bufferpool_class = GST_BUFFER_POOL_CLASS (klass);
1404
1405   object_class->dispose = gst_v4l2_buffer_pool_dispose;
1406   object_class->finalize = gst_v4l2_buffer_pool_finalize;
1407
1408   bufferpool_class->start = gst_v4l2_buffer_pool_start;
1409   bufferpool_class->stop = gst_v4l2_buffer_pool_stop;
1410   bufferpool_class->set_config = gst_v4l2_buffer_pool_set_config;
1411   bufferpool_class->alloc_buffer = gst_v4l2_buffer_pool_alloc_buffer;
1412   bufferpool_class->acquire_buffer = gst_v4l2_buffer_pool_acquire_buffer;
1413   bufferpool_class->release_buffer = gst_v4l2_buffer_pool_release_buffer;
1414   bufferpool_class->flush_start = gst_v4l2_buffer_pool_flush_start;
1415   bufferpool_class->flush_stop = gst_v4l2_buffer_pool_flush_stop;
1416 }
1417
1418 /**
1419  * gst_v4l2_buffer_pool_new:
1420  * @obj:  the v4l2 object owning the pool
1421  *
1422  * Construct a new buffer pool.
1423  *
1424  * Returns: the new pool, use gst_object_unref() to free resources
1425  */
1426 GstBufferPool *
1427 gst_v4l2_buffer_pool_new (GstV4l2Object * obj, GstCaps * caps)
1428 {
1429   GstV4l2BufferPool *pool;
1430   GstStructure *config;
1431   gchar *name, *parent_name;
1432   gint fd;
1433
1434   fd = v4l2_dup (obj->video_fd);
1435   if (fd < 0)
1436     goto dup_failed;
1437
1438   /* setting a significant unique name */
1439   parent_name = gst_object_get_name (GST_OBJECT (obj->element));
1440   name = g_strconcat (parent_name, ":", "pool:",
1441       V4L2_TYPE_IS_OUTPUT (obj->type) ? "sink" : "src", NULL);
1442   g_free (parent_name);
1443
1444   pool = (GstV4l2BufferPool *) g_object_new (GST_TYPE_V4L2_BUFFER_POOL,
1445       "name", name, NULL);
1446   g_free (name);
1447
1448   gst_poll_fd_init (&pool->pollfd);
1449   pool->pollfd.fd = fd;
1450   gst_poll_add_fd (pool->poll, &pool->pollfd);
1451   if (V4L2_TYPE_IS_OUTPUT (obj->type))
1452     gst_poll_fd_ctl_write (pool->poll, &pool->pollfd, TRUE);
1453   else
1454     gst_poll_fd_ctl_read (pool->poll, &pool->pollfd, TRUE);
1455
1456   pool->video_fd = fd;
1457   pool->obj = obj;
1458   pool->can_poll_device = TRUE;
1459
1460   pool->vallocator =
1461       gst_v4l2_allocator_new (GST_OBJECT (pool), obj->video_fd, &obj->format);
1462   if (pool->vallocator == NULL)
1463     goto allocator_failed;
1464
1465   gst_object_ref (obj->element);
1466
1467   config = gst_buffer_pool_get_config (GST_BUFFER_POOL_CAST (pool));
1468   gst_buffer_pool_config_set_params (config, caps, obj->info.size, 0, 0);
1469   /* This will simply set a default config, but will not configure the pool
1470    * because min and max are not valid */
1471   gst_buffer_pool_set_config (GST_BUFFER_POOL_CAST (pool), config);
1472
1473   return GST_BUFFER_POOL (pool);
1474
1475   /* ERRORS */
1476 dup_failed:
1477   {
1478     GST_ERROR ("failed to dup fd %d (%s)", errno, g_strerror (errno));
1479     return NULL;
1480   }
1481 allocator_failed:
1482   {
1483     GST_ERROR_OBJECT (pool, "Failed to create V4L2 allocator");
1484     gst_object_unref (pool);
1485     return NULL;
1486   }
1487 }
1488
1489 static GstFlowReturn
1490 gst_v4l2_do_read (GstV4l2BufferPool * pool, GstBuffer * buf)
1491 {
1492   GstFlowReturn res;
1493   GstV4l2Object *obj = pool->obj;
1494   gint amount;
1495   GstMapInfo map;
1496   gint toread;
1497
1498   toread = obj->info.size;
1499
1500   GST_LOG_OBJECT (pool, "reading %d bytes into buffer %p", toread, buf);
1501
1502   gst_buffer_map (buf, &map, GST_MAP_WRITE);
1503
1504   do {
1505     if ((res = gst_v4l2_buffer_pool_poll (pool)) != GST_FLOW_OK)
1506       goto poll_error;
1507
1508     amount = v4l2_read (obj->video_fd, map.data, toread);
1509
1510     if (amount == toread) {
1511       break;
1512     } else if (amount == -1) {
1513       if (errno == EAGAIN || errno == EINTR) {
1514         continue;
1515       } else
1516         goto read_error;
1517     } else {
1518       /* short reads can happen if a signal interrupts the read */
1519       continue;
1520     }
1521   } while (TRUE);
1522
1523   GST_LOG_OBJECT (pool, "read %d bytes", amount);
1524   gst_buffer_unmap (buf, &map);
1525   gst_buffer_resize (buf, 0, amount);
1526
1527   return GST_FLOW_OK;
1528
1529   /* ERRORS */
1530 poll_error:
1531   {
1532     GST_DEBUG ("poll error %s", gst_flow_get_name (res));
1533     goto cleanup;
1534   }
1535 read_error:
1536   {
1537     GST_ELEMENT_ERROR (obj->element, RESOURCE, READ,
1538         (_("Error reading %d bytes from device '%s'."),
1539             toread, obj->videodev), GST_ERROR_SYSTEM);
1540     res = GST_FLOW_ERROR;
1541     goto cleanup;
1542   }
1543 cleanup:
1544   {
1545     gst_buffer_unmap (buf, &map);
1546     gst_buffer_resize (buf, 0, 0);
1547     return res;
1548   }
1549 }
1550
1551 /**
1552  * gst_v4l2_buffer_pool_process:
1553  * @bpool: a #GstBufferPool
1554  * @buf: a #GstBuffer, maybe be replaced
1555  *
1556  * Process @buf in @bpool. For capture devices, this functions fills @buf with
1557  * data from the device. For output devices, this functions send the contents of
1558  * @buf to the device for playback.
1559  *
1560  * Returns: %GST_FLOW_OK on success.
1561  */
1562 GstFlowReturn
1563 gst_v4l2_buffer_pool_process (GstV4l2BufferPool * pool, GstBuffer ** buf)
1564 {
1565   GstFlowReturn ret = GST_FLOW_OK;
1566   GstBufferPool *bpool = GST_BUFFER_POOL_CAST (pool);
1567   GstV4l2Object *obj = pool->obj;
1568
1569   GST_DEBUG_OBJECT (pool, "process buffer %p", buf);
1570
1571   g_return_val_if_fail (gst_buffer_pool_is_active (bpool), GST_FLOW_ERROR);
1572
1573   if (GST_BUFFER_POOL_IS_FLUSHING (pool))
1574     return GST_FLOW_FLUSHING;
1575
1576   switch (obj->type) {
1577     case V4L2_BUF_TYPE_VIDEO_CAPTURE:
1578     case V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE:
1579       /* capture */
1580       switch (obj->mode) {
1581         case GST_V4L2_IO_RW:
1582           /* capture into the buffer */
1583           ret = gst_v4l2_do_read (pool, *buf);
1584           break;
1585
1586         case GST_V4L2_IO_MMAP:
1587         case GST_V4L2_IO_DMABUF:
1588         {
1589           GstBuffer *tmp;
1590
1591           if ((*buf)->pool == bpool) {
1592             guint num_queued;
1593
1594             if (gst_buffer_get_size (*buf) == 0) {
1595               if (GST_BUFFER_FLAG_IS_SET (*buf, GST_BUFFER_FLAG_CORRUPTED))
1596                 goto buffer_corrupted;
1597               else
1598                 goto eos;
1599             }
1600
1601             num_queued = g_atomic_int_get (&pool->num_queued);
1602             GST_TRACE_OBJECT (pool, "Only %i buffer left in the capture queue.",
1603                 num_queued);
1604
1605             /* If we have no more buffer, and can allocate it time to do so */
1606             if (num_queued == 0) {
1607               if (GST_V4L2_ALLOCATOR_CAN_ALLOCATE (pool->vallocator, MMAP)) {
1608                 ret = gst_v4l2_buffer_pool_resurect_buffer (pool);
1609                 if (ret == GST_FLOW_OK)
1610                   goto done;
1611               }
1612             }
1613
1614             /* start copying buffers when we are running low on buffers */
1615             if (num_queued < pool->copy_threshold) {
1616               GstBuffer *copy;
1617
1618               if (GST_V4L2_ALLOCATOR_CAN_ALLOCATE (pool->vallocator, MMAP)) {
1619                 ret = gst_v4l2_buffer_pool_resurect_buffer (pool);
1620                 if (ret == GST_FLOW_OK)
1621                   goto done;
1622               }
1623
1624               /* copy the buffer */
1625               copy = gst_buffer_copy_region (*buf,
1626                   GST_BUFFER_COPY_ALL | GST_BUFFER_COPY_DEEP, 0, -1);
1627               GST_LOG_OBJECT (pool, "copy buffer %p->%p", *buf, copy);
1628
1629               /* and requeue so that we can continue capturing */
1630               gst_buffer_unref (*buf);
1631               *buf = copy;
1632             }
1633
1634             /* nothing, data was inside the buffer when we did _acquire() */
1635             goto done;
1636           }
1637
1638           /* buffer not from our pool, grab a frame and copy it into the target */
1639           if ((ret = gst_v4l2_buffer_pool_dqbuf (pool, &tmp)) != GST_FLOW_OK)
1640             goto done;
1641
1642           /* An empty buffer on capture indicates the end of stream */
1643           if (gst_buffer_get_size (tmp) == 0) {
1644             gst_v4l2_buffer_pool_release_buffer (bpool, tmp);
1645
1646             if (GST_BUFFER_FLAG_IS_SET (*buf, GST_BUFFER_FLAG_CORRUPTED))
1647               goto buffer_corrupted;
1648             else
1649               goto eos;
1650           }
1651
1652           ret = gst_v4l2_buffer_pool_copy_buffer (pool, *buf, tmp);
1653
1654           /* an queue the buffer again after the copy */
1655           gst_v4l2_buffer_pool_release_buffer (bpool, tmp);
1656
1657           if (ret != GST_FLOW_OK)
1658             goto copy_failed;
1659           break;
1660         }
1661
1662         case GST_V4L2_IO_USERPTR:
1663         {
1664           struct UserPtrData *data;
1665
1666           /* Replace our buffer with downstream allocated buffer */
1667           data = gst_mini_object_steal_qdata (GST_MINI_OBJECT (*buf),
1668               GST_V4L2_IMPORT_QUARK);
1669           gst_buffer_replace (buf, data->buffer);
1670           _unmap_userptr_frame (data);
1671           break;
1672         }
1673
1674         case GST_V4L2_IO_DMABUF_IMPORT:
1675         {
1676           GstBuffer *tmp;
1677
1678           /* Replace our buffer with downstream allocated buffer */
1679           tmp = gst_mini_object_steal_qdata (GST_MINI_OBJECT (*buf),
1680               GST_V4L2_IMPORT_QUARK);
1681           gst_buffer_replace (buf, tmp);
1682           gst_buffer_unref (tmp);
1683           break;
1684         }
1685
1686         default:
1687           g_assert_not_reached ();
1688           break;
1689       }
1690       break;
1691
1692     case V4L2_BUF_TYPE_VIDEO_OUTPUT:
1693     case V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE:
1694       /* playback */
1695       switch (obj->mode) {
1696         case GST_V4L2_IO_RW:
1697           /* FIXME, do write() */
1698           GST_WARNING_OBJECT (pool, "implement write()");
1699           break;
1700
1701         case GST_V4L2_IO_USERPTR:
1702         case GST_V4L2_IO_DMABUF_IMPORT:
1703         case GST_V4L2_IO_DMABUF:
1704         case GST_V4L2_IO_MMAP:
1705         {
1706           GstBuffer *to_queue = NULL;
1707           GstV4l2MemoryGroup *group;
1708           gint index;
1709
1710           if ((*buf)->pool != bpool)
1711             goto copying;
1712
1713           if (!gst_v4l2_is_buffer_valid (*buf, &group))
1714             goto copying;
1715
1716           index = group->buffer.index;
1717
1718           GST_LOG_OBJECT (pool, "processing buffer %i from our pool", index);
1719
1720           index = group->buffer.index;
1721           if (pool->buffers[index] != NULL) {
1722             GST_LOG_OBJECT (pool, "buffer %i already queued, copying", index);
1723             goto copying;
1724           }
1725
1726           /* we can queue directly */
1727           to_queue = gst_buffer_ref (*buf);
1728
1729         copying:
1730           if (to_queue == NULL) {
1731             GstBufferPoolAcquireParams params = { 0 };
1732
1733             GST_LOG_OBJECT (pool, "alloc buffer from our pool");
1734
1735             /* this can return EOS if all buffers are outstanding which would
1736              * be strange because we would expect the upstream element to have
1737              * allocated them and returned to us.. */
1738             params.flags = GST_BUFFER_POOL_ACQUIRE_FLAG_DONTWAIT;
1739             ret = gst_buffer_pool_acquire_buffer (bpool, &to_queue, &params);
1740             if (ret != GST_FLOW_OK)
1741               goto acquire_failed;
1742
1743             ret = gst_v4l2_buffer_pool_prepare_buffer (pool, to_queue, *buf);
1744             if (ret != GST_FLOW_OK) {
1745               gst_buffer_unref (to_queue);
1746               goto prepare_failed;
1747             }
1748           }
1749
1750           if ((ret = gst_v4l2_buffer_pool_qbuf (pool, to_queue)) != GST_FLOW_OK)
1751             goto queue_failed;
1752
1753           /* if we are not streaming yet (this is the first buffer, start
1754            * streaming now */
1755           if (!gst_v4l2_buffer_pool_streamon (pool)) {
1756             /* don't check return value because qbuf would have failed */
1757             gst_v4l2_is_buffer_valid (to_queue, &group);
1758
1759             /* qbuf has stored to_queue buffer but we are not in
1760              * streaming state, so the flush logic won't be performed.
1761              * To avoid leaks, flush the allocator and restore the queued
1762              * buffer as non-queued */
1763             gst_v4l2_allocator_flush (pool->vallocator);
1764
1765             pool->buffers[group->buffer.index] = NULL;
1766
1767             gst_mini_object_set_qdata (GST_MINI_OBJECT (to_queue),
1768                 GST_V4L2_IMPORT_QUARK, NULL, NULL);
1769             gst_buffer_unref (to_queue);
1770             g_atomic_int_add (&pool->num_queued, -1);
1771             goto start_failed;
1772           }
1773
1774           /* Remove our ref, we will still hold this buffer in acquire as needed,
1775            * otherwise the pool will think it is outstanding and will refuse to stop. */
1776           gst_buffer_unref (to_queue);
1777
1778           if (g_atomic_int_get (&pool->num_queued) >= pool->min_latency) {
1779             GstBuffer *out;
1780             /* all buffers are queued, try to dequeue one and release it back
1781              * into the pool so that _acquire can get to it again. */
1782             ret = gst_v4l2_buffer_pool_dqbuf (pool, &out);
1783             if (ret == GST_FLOW_OK && out->pool == NULL)
1784               /* release the rendered buffer back into the pool. This wakes up any
1785                * thread waiting for a buffer in _acquire(). */
1786               gst_v4l2_buffer_pool_release_buffer (bpool, out);
1787           }
1788           break;
1789         }
1790         default:
1791           g_assert_not_reached ();
1792           break;
1793       }
1794       break;
1795     default:
1796       g_assert_not_reached ();
1797       break;
1798   }
1799 done:
1800   return ret;
1801
1802   /* ERRORS */
1803 copy_failed:
1804   {
1805     GST_ERROR_OBJECT (pool, "failed to copy buffer");
1806     return ret;
1807   }
1808 buffer_corrupted:
1809   {
1810     GST_WARNING_OBJECT (pool, "Dropping corrupted buffer without payload");
1811     gst_buffer_unref (*buf);
1812     *buf = NULL;
1813     return GST_V4L2_FLOW_CORRUPTED_BUFFER;
1814   }
1815 eos:
1816   {
1817     GST_DEBUG_OBJECT (pool, "end of stream reached");
1818     gst_buffer_unref (*buf);
1819     *buf = NULL;
1820     return GST_V4L2_FLOW_LAST_BUFFER;
1821   }
1822 acquire_failed:
1823   {
1824     if (ret == GST_FLOW_FLUSHING)
1825       GST_DEBUG_OBJECT (pool, "flushing");
1826     else
1827       GST_WARNING_OBJECT (pool, "failed to acquire a buffer: %s",
1828           gst_flow_get_name (ret));
1829     return ret;
1830   }
1831 prepare_failed:
1832   {
1833     GST_ERROR_OBJECT (pool, "failed to prepare data");
1834     return ret;
1835   }
1836 queue_failed:
1837   {
1838     GST_ERROR_OBJECT (pool, "failed to queue buffer");
1839     return ret;
1840   }
1841 start_failed:
1842   {
1843     GST_ERROR_OBJECT (pool, "failed to start streaming");
1844     return GST_FLOW_ERROR;
1845   }
1846 }
1847
1848 void
1849 gst_v4l2_buffer_pool_set_other_pool (GstV4l2BufferPool * pool,
1850     GstBufferPool * other_pool)
1851 {
1852   g_return_if_fail (!gst_buffer_pool_is_active (GST_BUFFER_POOL (pool)));
1853
1854   if (pool->other_pool)
1855     gst_object_unref (pool->other_pool);
1856   pool->other_pool = gst_object_ref (other_pool);
1857 }