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