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