v4l2bufferpool: Drop truncated frames
[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 "gstv4l2object.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 GstFlowReturn
614 gst_v4l2_buffer_pool_resurect_buffer (GstV4l2BufferPool * pool)
615 {
616   GstBufferPoolAcquireParams params = { 0 };
617   GstBuffer *buffer = NULL;
618   GstFlowReturn ret;
619
620   GST_DEBUG_OBJECT (pool, "A buffer was lost, reallocating it");
621
622   /* block recursive calls to this function */
623   g_signal_handler_block (pool->vallocator, pool->group_released_handler);
624
625   params.flags =
626       (GstBufferPoolAcquireFlags) GST_V4L2_BUFFER_POOL_ACQUIRE_FLAG_RESURRECT |
627       GST_BUFFER_POOL_ACQUIRE_FLAG_DONTWAIT;
628   ret =
629       gst_buffer_pool_acquire_buffer (GST_BUFFER_POOL (pool), &buffer, &params);
630
631   if (ret == GST_FLOW_OK)
632     gst_buffer_unref (buffer);
633
634   g_signal_handler_unblock (pool->vallocator, pool->group_released_handler);
635
636   return ret;
637 }
638
639 static gboolean
640 gst_v4l2_buffer_pool_streamon (GstV4l2BufferPool * pool)
641 {
642   GstV4l2Object *obj = pool->obj;
643
644   if (pool->streaming)
645     return TRUE;
646
647   switch (obj->mode) {
648     case GST_V4L2_IO_MMAP:
649     case GST_V4L2_IO_USERPTR:
650     case GST_V4L2_IO_DMABUF:
651     case GST_V4L2_IO_DMABUF_IMPORT:
652       if (!V4L2_TYPE_IS_OUTPUT (pool->obj->type)) {
653         /* For captures, we need to enqueue buffers before we start streaming,
654          * so the driver don't underflow immediatly. As we have put then back
655          * into the base class queue, resurect them, then releasing will queue
656          * them back. */
657         while (gst_v4l2_buffer_pool_resurect_buffer (pool) == GST_FLOW_OK)
658           continue;
659       }
660
661       if (obj->ioctl (pool->video_fd, VIDIOC_STREAMON, &obj->type) < 0)
662         goto streamon_failed;
663
664       pool->streaming = TRUE;
665
666       GST_DEBUG_OBJECT (pool, "Started streaming");
667       break;
668     default:
669       break;
670   }
671
672   return TRUE;
673
674 streamon_failed:
675   {
676     GST_ERROR_OBJECT (pool, "error with STREAMON %d (%s)", errno,
677         g_strerror (errno));
678     return FALSE;
679   }
680 }
681
682 /* Call with streamlock held, or when streaming threads are down */
683 static void
684 gst_v4l2_buffer_pool_streamoff (GstV4l2BufferPool * pool)
685 {
686   GstBufferPoolClass *pclass = GST_BUFFER_POOL_CLASS (parent_class);
687   GstV4l2Object *obj = pool->obj;
688   gint i;
689
690   if (!pool->streaming)
691     return;
692
693   switch (obj->mode) {
694     case GST_V4L2_IO_MMAP:
695     case GST_V4L2_IO_USERPTR:
696     case GST_V4L2_IO_DMABUF:
697     case GST_V4L2_IO_DMABUF_IMPORT:
698
699       if (obj->ioctl (pool->video_fd, VIDIOC_STREAMOFF, &obj->type) < 0)
700         GST_WARNING_OBJECT (pool, "STREAMOFF failed with errno %d (%s)",
701             errno, g_strerror (errno));
702
703       pool->streaming = FALSE;
704
705       GST_DEBUG_OBJECT (pool, "Stopped streaming");
706
707       if (pool->vallocator)
708         gst_v4l2_allocator_flush (pool->vallocator);
709       break;
710     default:
711       break;
712   }
713
714   for (i = 0; i < VIDEO_MAX_FRAME; i++) {
715     if (pool->buffers[i]) {
716       GstBuffer *buffer = pool->buffers[i];
717       GstBufferPool *bpool = GST_BUFFER_POOL (pool);
718
719       pool->buffers[i] = NULL;
720
721       if (V4L2_TYPE_IS_OUTPUT (pool->obj->type))
722         gst_v4l2_buffer_pool_release_buffer (bpool, buffer);
723       else                      /* Don't re-enqueue capture buffer on stop */
724         pclass->release_buffer (bpool, buffer);
725
726       g_atomic_int_add (&pool->num_queued, -1);
727     }
728   }
729 }
730
731 static gboolean
732 gst_v4l2_buffer_pool_start (GstBufferPool * bpool)
733 {
734   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
735   GstBufferPoolClass *pclass = GST_BUFFER_POOL_CLASS (parent_class);
736   GstV4l2Object *obj = pool->obj;
737   GstStructure *config;
738   GstCaps *caps;
739   guint size, min_buffers, max_buffers;
740   guint max_latency, min_latency, copy_threshold = 0;
741   gboolean can_allocate = FALSE, ret = TRUE;
742
743   GST_DEBUG_OBJECT (pool, "activating pool");
744
745   config = gst_buffer_pool_get_config (bpool);
746   if (!gst_buffer_pool_config_get_params (config, &caps, &size, &min_buffers,
747           &max_buffers))
748     goto wrong_config;
749
750   min_latency = MAX (GST_V4L2_MIN_BUFFERS, obj->min_buffers);
751
752   switch (obj->mode) {
753     case GST_V4L2_IO_RW:
754       can_allocate = TRUE;
755 #ifdef HAVE_LIBV4L2
756       /* This workaround a unfixable bug in libv4l2 when RW is emulated on top
757        * of MMAP. In this case, the first read initialize the queues, but the
758        * poll before that will always fail. Doing an empty read, forces the
759        * queue to be initialized now. We only do this if we have a streaming
760        * driver. */
761       if (obj->device_caps & V4L2_CAP_STREAMING)
762         obj->read (obj->video_fd, NULL, 0);
763 #endif
764       break;
765     case GST_V4L2_IO_DMABUF:
766     case GST_V4L2_IO_MMAP:
767     {
768       guint count;
769
770       can_allocate = GST_V4L2_ALLOCATOR_CAN_ALLOCATE (pool->vallocator, MMAP);
771
772       /* first, lets request buffers, and see how many we can get: */
773       GST_DEBUG_OBJECT (pool, "requesting %d MMAP buffers", min_buffers);
774
775       count = gst_v4l2_allocator_start (pool->vallocator, min_buffers,
776           V4L2_MEMORY_MMAP);
777
778       if (count < GST_V4L2_MIN_BUFFERS) {
779         min_buffers = count;
780         goto no_buffers;
781       }
782
783       /* V4L2 buffer pool are often very limited in the amount of buffers it
784        * can offer. The copy_threshold will workaround this limitation by
785        * falling back to copy if the pipeline needed more buffers. This also
786        * prevent having to do REQBUFS(N)/REQBUFS(0) everytime configure is
787        * called. */
788       if (count != min_buffers || pool->enable_copy_threshold) {
789         GST_WARNING_OBJECT (pool,
790             "Uncertain or not enough buffers, enabling copy threshold");
791         min_buffers = count;
792         copy_threshold = min_latency;
793       }
794
795       break;
796     }
797     case GST_V4L2_IO_USERPTR:
798     {
799       guint count;
800
801       can_allocate =
802           GST_V4L2_ALLOCATOR_CAN_ALLOCATE (pool->vallocator, USERPTR);
803
804       GST_DEBUG_OBJECT (pool, "requesting %d USERPTR buffers", min_buffers);
805
806       count = gst_v4l2_allocator_start (pool->vallocator, min_buffers,
807           V4L2_MEMORY_USERPTR);
808
809       /* There is no rational to not get what we asked */
810       if (count < min_buffers) {
811         min_buffers = count;
812         goto no_buffers;
813       }
814
815       min_buffers = count;
816       break;
817     }
818     case GST_V4L2_IO_DMABUF_IMPORT:
819     {
820       guint count;
821
822       can_allocate = GST_V4L2_ALLOCATOR_CAN_ALLOCATE (pool->vallocator, DMABUF);
823
824       GST_DEBUG_OBJECT (pool, "requesting %d DMABUF buffers", min_buffers);
825
826       count = gst_v4l2_allocator_start (pool->vallocator, min_buffers,
827           V4L2_MEMORY_DMABUF);
828
829       /* There is no rational to not get what we asked */
830       if (count < min_buffers) {
831         min_buffers = count;
832         goto no_buffers;
833       }
834
835       min_buffers = count;
836       break;
837     }
838     default:
839       min_buffers = 0;
840       copy_threshold = 0;
841       g_assert_not_reached ();
842       break;
843   }
844
845   if (can_allocate)
846     max_latency = max_buffers;
847   else
848     max_latency = min_buffers;
849
850   pool->size = size;
851   pool->copy_threshold = copy_threshold;
852   pool->max_latency = max_latency;
853   pool->min_latency = min_latency;
854   pool->num_queued = 0;
855
856   if (max_buffers != 0 && max_buffers < min_buffers)
857     max_buffers = min_buffers;
858
859   gst_buffer_pool_config_set_params (config, caps, size, min_buffers,
860       max_buffers);
861   pclass->set_config (bpool, config);
862   gst_structure_free (config);
863
864   if (pool->other_pool)
865     if (!gst_buffer_pool_set_active (pool->other_pool, TRUE))
866       goto other_pool_failed;
867
868   /* now, allocate the buffers: */
869   if (!pclass->start (bpool))
870     goto start_failed;
871
872   if (!V4L2_TYPE_IS_OUTPUT (obj->type)) {
873     pool->group_released_handler =
874         g_signal_connect_swapped (pool->vallocator, "group-released",
875         G_CALLBACK (gst_v4l2_buffer_pool_resurect_buffer), pool);
876     ret = gst_v4l2_buffer_pool_streamon (pool);
877   }
878
879   return ret;
880
881   /* ERRORS */
882 wrong_config:
883   {
884     GST_ERROR_OBJECT (pool, "invalid config %" GST_PTR_FORMAT, config);
885     gst_structure_free (config);
886     return FALSE;
887   }
888 no_buffers:
889   {
890     GST_ERROR_OBJECT (pool,
891         "we received %d buffer from device '%s', we want at least %d",
892         min_buffers, obj->videodev, GST_V4L2_MIN_BUFFERS);
893     gst_structure_free (config);
894     return FALSE;
895   }
896 start_failed:
897   {
898     GST_ERROR_OBJECT (pool, "allocate failed");
899     return FALSE;
900   }
901 other_pool_failed:
902   {
903     GST_ERROR_OBJECT (pool, "failed to active the other pool %"
904         GST_PTR_FORMAT, pool->other_pool);
905     return FALSE;
906   }
907 }
908
909 static gboolean
910 gst_v4l2_buffer_pool_stop (GstBufferPool * bpool)
911 {
912   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
913   gboolean ret;
914
915   GST_DEBUG_OBJECT (pool, "stopping pool");
916
917   if (pool->group_released_handler > 0) {
918     g_signal_handler_disconnect (pool->vallocator,
919         pool->group_released_handler);
920     pool->group_released_handler = 0;
921   }
922
923   if (pool->other_pool) {
924     gst_buffer_pool_set_active (pool->other_pool, FALSE);
925     gst_object_unref (pool->other_pool);
926     pool->other_pool = NULL;
927   }
928
929   gst_v4l2_buffer_pool_streamoff (pool);
930
931   ret = GST_BUFFER_POOL_CLASS (parent_class)->stop (bpool);
932
933   if (ret && pool->vallocator) {
934     GstV4l2Return vret;
935
936     vret = gst_v4l2_allocator_stop (pool->vallocator);
937
938     if (vret == GST_V4L2_BUSY)
939       GST_WARNING_OBJECT (pool, "some buffers are still outstanding");
940
941     ret = (vret == GST_V4L2_OK);
942   }
943
944   return ret;
945 }
946
947 static void
948 gst_v4l2_buffer_pool_flush_start (GstBufferPool * bpool)
949 {
950   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
951
952   GST_DEBUG_OBJECT (pool, "start flushing");
953
954   gst_poll_set_flushing (pool->poll, TRUE);
955
956   GST_OBJECT_LOCK (pool);
957   pool->empty = FALSE;
958   g_cond_broadcast (&pool->empty_cond);
959   GST_OBJECT_UNLOCK (pool);
960
961   if (pool->other_pool)
962     gst_buffer_pool_set_flushing (pool->other_pool, TRUE);
963 }
964
965 static void
966 gst_v4l2_buffer_pool_flush_stop (GstBufferPool * bpool)
967 {
968   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
969
970   GST_DEBUG_OBJECT (pool, "stop flushing");
971
972   if (pool->other_pool)
973     gst_buffer_pool_set_flushing (pool->other_pool, FALSE);
974
975   gst_poll_set_flushing (pool->poll, FALSE);
976 }
977
978 static GstFlowReturn
979 gst_v4l2_buffer_pool_poll (GstV4l2BufferPool * pool, gboolean wait)
980 {
981   gint ret;
982   GstClockTime timeout;
983
984   if (wait)
985     timeout = GST_CLOCK_TIME_NONE;
986   else
987     timeout = 0;
988
989   /* In RW mode there is no queue, hence no need to wait while the queue is
990    * empty */
991   if (pool->obj->mode != GST_V4L2_IO_RW) {
992     GST_OBJECT_LOCK (pool);
993
994     if (!wait && pool->empty) {
995       GST_OBJECT_UNLOCK (pool);
996       goto no_buffers;
997     }
998
999     while (pool->empty)
1000       g_cond_wait (&pool->empty_cond, GST_OBJECT_GET_LOCK (pool));
1001
1002     GST_OBJECT_UNLOCK (pool);
1003   }
1004
1005   if (!pool->can_poll_device) {
1006     if (wait)
1007       goto done;
1008     else
1009       goto no_buffers;
1010   }
1011
1012   GST_LOG_OBJECT (pool, "polling device");
1013
1014 again:
1015   ret = gst_poll_wait (pool->poll, timeout);
1016   if (G_UNLIKELY (ret < 0)) {
1017     switch (errno) {
1018       case EBUSY:
1019         goto stopped;
1020       case EAGAIN:
1021       case EINTR:
1022         goto again;
1023       case ENXIO:
1024         GST_WARNING_OBJECT (pool,
1025             "v4l2 device doesn't support polling. Disabling"
1026             " using libv4l2 in this case may cause deadlocks");
1027         pool->can_poll_device = FALSE;
1028         goto done;
1029       default:
1030         goto select_error;
1031     }
1032   }
1033
1034   if (gst_poll_fd_has_error (pool->poll, &pool->pollfd))
1035     goto select_error;
1036
1037   if (ret == 0)
1038     goto no_buffers;
1039
1040 done:
1041   return GST_FLOW_OK;
1042
1043   /* ERRORS */
1044 stopped:
1045   {
1046     GST_DEBUG_OBJECT (pool, "stop called");
1047     return GST_FLOW_FLUSHING;
1048   }
1049 select_error:
1050   {
1051     GST_ELEMENT_ERROR (pool->obj->element, RESOURCE, READ, (NULL),
1052         ("poll error %d: %s (%d)", ret, g_strerror (errno), errno));
1053     return GST_FLOW_ERROR;
1054   }
1055 no_buffers:
1056   return GST_FLOW_CUSTOM_SUCCESS;
1057 }
1058
1059 static GstFlowReturn
1060 gst_v4l2_buffer_pool_qbuf (GstV4l2BufferPool * pool, GstBuffer * buf)
1061 {
1062   GstV4l2MemoryGroup *group = NULL;
1063   const GstV4l2Object *obj = pool->obj;
1064   GstClockTime timestamp;
1065   gint index;
1066
1067   if (!gst_v4l2_is_buffer_valid (buf, &group)) {
1068     GST_ERROR_OBJECT (pool, "invalid buffer %p", buf);
1069     return GST_FLOW_ERROR;
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   if (V4L2_TYPE_IS_OUTPUT (obj->type)) {
1080     enum v4l2_field field;
1081
1082     /* Except when field is set to alternate, buffer field is the same as
1083      * the one defined in format */
1084     if (V4L2_TYPE_IS_MULTIPLANAR (obj->type))
1085       field = obj->format.fmt.pix_mp.field;
1086     else
1087       field = obj->format.fmt.pix.field;
1088
1089     /* NB: At this moment, we can't have alternate mode because it not handled
1090      * yet */
1091     if (field == V4L2_FIELD_ALTERNATE) {
1092       if (GST_BUFFER_FLAG_IS_SET (buf, GST_VIDEO_FRAME_FLAG_TFF))
1093         field = V4L2_FIELD_TOP;
1094       else
1095         field = V4L2_FIELD_BOTTOM;
1096     }
1097
1098     group->buffer.field = field;
1099   }
1100
1101   if (GST_BUFFER_TIMESTAMP_IS_VALID (buf)) {
1102     timestamp = GST_BUFFER_TIMESTAMP (buf);
1103     GST_TIME_TO_TIMEVAL (timestamp, group->buffer.timestamp);
1104   }
1105
1106   GST_OBJECT_LOCK (pool);
1107   g_atomic_int_inc (&pool->num_queued);
1108   pool->buffers[index] = buf;
1109
1110   if (!gst_v4l2_allocator_qbuf (pool->vallocator, group))
1111     goto queue_failed;
1112
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     GST_OBJECT_UNLOCK (pool);
1132     return GST_FLOW_ERROR;
1133   }
1134 }
1135
1136 static GstFlowReturn
1137 gst_v4l2_buffer_pool_dqbuf (GstV4l2BufferPool * pool, GstBuffer ** buffer,
1138     gboolean wait)
1139 {
1140   GstFlowReturn res;
1141   GstBuffer *outbuf = NULL;
1142   GstV4l2Object *obj = pool->obj;
1143   GstClockTime timestamp;
1144   GstV4l2MemoryGroup *group;
1145   GstVideoMeta *vmeta;
1146   gsize size;
1147   gint i;
1148
1149   if ((res = gst_v4l2_buffer_pool_poll (pool, wait)) < GST_FLOW_OK)
1150     goto poll_failed;
1151
1152   if (res == GST_FLOW_CUSTOM_SUCCESS) {
1153     GST_LOG_OBJECT (pool, "nothing to dequeue");
1154     goto done;
1155   }
1156
1157   GST_LOG_OBJECT (pool, "dequeueing a buffer");
1158
1159   res = gst_v4l2_allocator_dqbuf (pool->vallocator, &group);
1160   if (res == GST_FLOW_EOS)
1161     goto eos;
1162   if (res != GST_FLOW_OK)
1163     goto dqbuf_failed;
1164
1165   /* get our GstBuffer with that index from the pool, if the buffer was
1166    * outstanding we have a serious problem.
1167    */
1168   outbuf = pool->buffers[group->buffer.index];
1169   if (outbuf == NULL)
1170     goto no_buffer;
1171
1172   /* mark the buffer outstanding */
1173   pool->buffers[group->buffer.index] = NULL;
1174   if (g_atomic_int_dec_and_test (&pool->num_queued)) {
1175     GST_OBJECT_LOCK (pool);
1176     pool->empty = TRUE;
1177     GST_OBJECT_UNLOCK (pool);
1178   }
1179
1180   timestamp = GST_TIMEVAL_TO_TIME (group->buffer.timestamp);
1181
1182   size = 0;
1183   vmeta = gst_buffer_get_video_meta (outbuf);
1184   for (i = 0; i < group->n_mem; i++) {
1185     GST_LOG_OBJECT (pool,
1186         "dequeued buffer %p seq:%d (ix=%d), mem %p used %d, plane=%d, flags %08x, ts %"
1187         GST_TIME_FORMAT ", pool-queued=%d, buffer=%p", outbuf,
1188         group->buffer.sequence, group->buffer.index, group->mem[i],
1189         group->planes[i].bytesused, i, group->buffer.flags,
1190         GST_TIME_ARGS (timestamp), pool->num_queued, outbuf);
1191
1192     if (vmeta) {
1193       vmeta->offset[i] = size;
1194       size += gst_memory_get_sizes (group->mem[i], NULL, NULL);
1195     }
1196   }
1197
1198   /* Ignore timestamp and field for OUTPUT device */
1199   if (V4L2_TYPE_IS_OUTPUT (obj->type))
1200     goto done;
1201
1202   /* Check for driver bug in reporting feild */
1203   if (group->buffer.field == V4L2_FIELD_ANY) {
1204     /* Only warn once to avoid the spamming */
1205 #ifndef GST_DISABLE_GST_DEBUG
1206     if (!pool->has_warned_on_buggy_field) {
1207       pool->has_warned_on_buggy_field = TRUE;
1208       GST_WARNING_OBJECT (pool,
1209           "Driver should never set v4l2_buffer.field to ANY");
1210     }
1211 #endif
1212
1213     /* Use the value from the format (works for UVC bug) */
1214     group->buffer.field = obj->format.fmt.pix.field;
1215
1216     /* If driver also has buggy S_FMT, assume progressive */
1217     if (group->buffer.field == V4L2_FIELD_ANY) {
1218 #ifndef GST_DISABLE_GST_DEBUG
1219       if (!pool->has_warned_on_buggy_field) {
1220         pool->has_warned_on_buggy_field = TRUE;
1221         GST_WARNING_OBJECT (pool,
1222             "Driver should never set v4l2_format.pix.field to ANY");
1223       }
1224 #endif
1225
1226       group->buffer.field = V4L2_FIELD_NONE;
1227     }
1228   }
1229
1230   /* set top/bottom field first if v4l2_buffer has the information */
1231   switch (group->buffer.field) {
1232     case V4L2_FIELD_NONE:
1233       GST_BUFFER_FLAG_UNSET (outbuf, GST_VIDEO_BUFFER_FLAG_INTERLACED);
1234       GST_BUFFER_FLAG_UNSET (outbuf, GST_VIDEO_BUFFER_FLAG_TFF);
1235       break;
1236     case V4L2_FIELD_INTERLACED_TB:
1237       GST_BUFFER_FLAG_SET (outbuf, GST_VIDEO_BUFFER_FLAG_INTERLACED);
1238       GST_BUFFER_FLAG_SET (outbuf, GST_VIDEO_BUFFER_FLAG_TFF);
1239       break;
1240     case V4L2_FIELD_INTERLACED_BT:
1241       GST_BUFFER_FLAG_SET (outbuf, GST_VIDEO_BUFFER_FLAG_INTERLACED);
1242       GST_BUFFER_FLAG_UNSET (outbuf, GST_VIDEO_BUFFER_FLAG_TFF);
1243       break;
1244     case V4L2_FIELD_INTERLACED:
1245       GST_BUFFER_FLAG_SET (outbuf, GST_VIDEO_BUFFER_FLAG_INTERLACED);
1246       if (obj->tv_norm == V4L2_STD_NTSC_M ||
1247           obj->tv_norm == V4L2_STD_NTSC_M_JP ||
1248           obj->tv_norm == V4L2_STD_NTSC_M_KR) {
1249         GST_BUFFER_FLAG_UNSET (outbuf, GST_VIDEO_BUFFER_FLAG_TFF);
1250       } else {
1251         GST_BUFFER_FLAG_SET (outbuf, GST_VIDEO_BUFFER_FLAG_TFF);
1252       }
1253       break;
1254     default:
1255       GST_BUFFER_FLAG_UNSET (outbuf, GST_VIDEO_BUFFER_FLAG_INTERLACED);
1256       GST_BUFFER_FLAG_UNSET (outbuf, GST_VIDEO_BUFFER_FLAG_TFF);
1257       GST_FIXME_OBJECT (pool,
1258           "Unhandled enum v4l2_field %d - treating as progressive",
1259           group->buffer.field);
1260       break;
1261   }
1262
1263   if (GST_VIDEO_INFO_FORMAT (&obj->info) == GST_VIDEO_FORMAT_ENCODED) {
1264     if ((group->buffer.flags & V4L2_BUF_FLAG_KEYFRAME) ||
1265         GST_V4L2_PIXELFORMAT (obj) == V4L2_PIX_FMT_MJPEG ||
1266         GST_V4L2_PIXELFORMAT (obj) == V4L2_PIX_FMT_JPEG ||
1267         GST_V4L2_PIXELFORMAT (obj) == V4L2_PIX_FMT_PJPG)
1268       GST_BUFFER_FLAG_UNSET (outbuf, GST_BUFFER_FLAG_DELTA_UNIT);
1269     else
1270       GST_BUFFER_FLAG_SET (outbuf, GST_BUFFER_FLAG_DELTA_UNIT);
1271   }
1272
1273   if (group->buffer.flags & V4L2_BUF_FLAG_ERROR)
1274     GST_BUFFER_FLAG_SET (outbuf, GST_BUFFER_FLAG_CORRUPTED);
1275
1276   GST_BUFFER_TIMESTAMP (outbuf) = timestamp;
1277   GST_BUFFER_OFFSET (outbuf) = group->buffer.sequence;
1278   GST_BUFFER_OFFSET_END (outbuf) = group->buffer.sequence + 1;
1279
1280 done:
1281   *buffer = outbuf;
1282
1283   return res;
1284
1285   /* ERRORS */
1286 poll_failed:
1287   {
1288     GST_DEBUG_OBJECT (pool, "poll error %s", gst_flow_get_name (res));
1289     return res;
1290   }
1291 eos:
1292   {
1293     return GST_FLOW_EOS;
1294   }
1295 dqbuf_failed:
1296   {
1297     return GST_FLOW_ERROR;
1298   }
1299 no_buffer:
1300   {
1301     GST_ERROR_OBJECT (pool, "No free buffer found in the pool at index %d.",
1302         group->buffer.index);
1303     return GST_FLOW_ERROR;
1304   }
1305 }
1306
1307 static GstFlowReturn
1308 gst_v4l2_buffer_pool_acquire_buffer (GstBufferPool * bpool, GstBuffer ** buffer,
1309     GstBufferPoolAcquireParams * params)
1310 {
1311   GstFlowReturn ret;
1312   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
1313   GstBufferPoolClass *pclass = GST_BUFFER_POOL_CLASS (parent_class);
1314   GstV4l2Object *obj = pool->obj;
1315
1316   GST_DEBUG_OBJECT (pool, "acquire");
1317
1318   /* If this is being called to resurect a lost buffer */
1319   if (params && params->flags & GST_V4L2_BUFFER_POOL_ACQUIRE_FLAG_RESURRECT) {
1320     ret = pclass->acquire_buffer (bpool, buffer, params);
1321     goto done;
1322   }
1323
1324   switch (obj->type) {
1325     case V4L2_BUF_TYPE_VIDEO_CAPTURE:
1326     case V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE:
1327       /* capture, This function should return a buffer with new captured data */
1328       switch (obj->mode) {
1329         case GST_V4L2_IO_RW:
1330         {
1331           /* take empty buffer from the pool */
1332           ret = pclass->acquire_buffer (bpool, buffer, params);
1333           break;
1334         }
1335         case GST_V4L2_IO_DMABUF:
1336         case GST_V4L2_IO_MMAP:
1337         case GST_V4L2_IO_USERPTR:
1338         case GST_V4L2_IO_DMABUF_IMPORT:
1339         {
1340           /* just dequeue a buffer, we basically use the queue of v4l2 as the
1341            * storage for our buffers. This function does poll first so we can
1342            * interrupt it fine. */
1343           ret = gst_v4l2_buffer_pool_dqbuf (pool, buffer, TRUE);
1344           break;
1345         }
1346         default:
1347           ret = GST_FLOW_ERROR;
1348           g_assert_not_reached ();
1349           break;
1350       }
1351       break;
1352
1353
1354     case V4L2_BUF_TYPE_VIDEO_OUTPUT:
1355     case V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE:
1356       /* playback, This function should return an empty buffer */
1357       switch (obj->mode) {
1358         case GST_V4L2_IO_RW:
1359           /* get an empty buffer */
1360           ret = pclass->acquire_buffer (bpool, buffer, params);
1361           break;
1362
1363         case GST_V4L2_IO_MMAP:
1364         case GST_V4L2_IO_DMABUF:
1365         case GST_V4L2_IO_USERPTR:
1366         case GST_V4L2_IO_DMABUF_IMPORT:
1367           /* get a free unqueued buffer */
1368           ret = pclass->acquire_buffer (bpool, buffer, params);
1369           break;
1370
1371         default:
1372           ret = GST_FLOW_ERROR;
1373           g_assert_not_reached ();
1374           break;
1375       }
1376       break;
1377
1378     default:
1379       ret = GST_FLOW_ERROR;
1380       g_assert_not_reached ();
1381       break;
1382   }
1383 done:
1384   return ret;
1385 }
1386
1387 static void
1388 gst_v4l2_buffer_pool_release_buffer (GstBufferPool * bpool, GstBuffer * buffer)
1389 {
1390   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
1391   GstBufferPoolClass *pclass = GST_BUFFER_POOL_CLASS (parent_class);
1392   GstV4l2Object *obj = pool->obj;
1393
1394   GST_DEBUG_OBJECT (pool, "release buffer %p", buffer);
1395
1396   switch (obj->type) {
1397     case V4L2_BUF_TYPE_VIDEO_CAPTURE:
1398     case V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE:
1399       /* capture, put the buffer back in the queue so that we can refill it
1400        * later. */
1401       switch (obj->mode) {
1402         case GST_V4L2_IO_RW:
1403           /* release back in the pool */
1404           pclass->release_buffer (bpool, buffer);
1405           break;
1406
1407         case GST_V4L2_IO_DMABUF:
1408         case GST_V4L2_IO_MMAP:
1409         case GST_V4L2_IO_USERPTR:
1410         case GST_V4L2_IO_DMABUF_IMPORT:
1411         {
1412           GstV4l2MemoryGroup *group;
1413           if (gst_v4l2_is_buffer_valid (buffer, &group)) {
1414             gst_v4l2_allocator_reset_group (pool->vallocator, group);
1415             /* queue back in the device */
1416             if (pool->other_pool)
1417               gst_v4l2_buffer_pool_prepare_buffer (pool, buffer, NULL);
1418             if (gst_v4l2_buffer_pool_qbuf (pool, buffer) != GST_FLOW_OK)
1419               pclass->release_buffer (bpool, buffer);
1420           } else {
1421             /* Simply release invalide/modified buffer, the allocator will
1422              * give it back later */
1423             GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_TAG_MEMORY);
1424             pclass->release_buffer (bpool, buffer);
1425           }
1426           break;
1427         }
1428         default:
1429           g_assert_not_reached ();
1430           break;
1431       }
1432       break;
1433
1434     case V4L2_BUF_TYPE_VIDEO_OUTPUT:
1435     case V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE:
1436       switch (obj->mode) {
1437         case GST_V4L2_IO_RW:
1438           /* release back in the pool */
1439           pclass->release_buffer (bpool, buffer);
1440           break;
1441
1442         case GST_V4L2_IO_MMAP:
1443         case GST_V4L2_IO_DMABUF:
1444         case GST_V4L2_IO_USERPTR:
1445         case GST_V4L2_IO_DMABUF_IMPORT:
1446         {
1447           GstV4l2MemoryGroup *group;
1448           guint index;
1449
1450           if (!gst_v4l2_is_buffer_valid (buffer, &group)) {
1451             /* Simply release invalide/modified buffer, the allocator will
1452              * give it back later */
1453             GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_TAG_MEMORY);
1454             pclass->release_buffer (bpool, buffer);
1455             break;
1456           }
1457
1458           index = group->buffer.index;
1459
1460           if (pool->buffers[index] == NULL) {
1461             GST_LOG_OBJECT (pool, "buffer %u not queued, putting on free list",
1462                 index);
1463
1464             /* Remove qdata, this will unmap any map data in userptr */
1465             gst_mini_object_set_qdata (GST_MINI_OBJECT (buffer),
1466                 GST_V4L2_IMPORT_QUARK, NULL, NULL);
1467
1468             /* reset to default size */
1469             gst_v4l2_allocator_reset_group (pool->vallocator, group);
1470
1471             /* playback, put the buffer back in the queue to refill later. */
1472             pclass->release_buffer (bpool, buffer);
1473           } else {
1474             /* the buffer is queued in the device but maybe not played yet. We just
1475              * leave it there and not make it available for future calls to acquire
1476              * for now. The buffer will be dequeued and reused later. */
1477             GST_LOG_OBJECT (pool, "buffer %u is queued", index);
1478           }
1479           break;
1480         }
1481
1482         default:
1483           g_assert_not_reached ();
1484           break;
1485       }
1486       break;
1487
1488     default:
1489       g_assert_not_reached ();
1490       break;
1491   }
1492 }
1493
1494 static void
1495 gst_v4l2_buffer_pool_dispose (GObject * object)
1496 {
1497   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (object);
1498
1499   if (pool->vallocator)
1500     gst_object_unref (pool->vallocator);
1501   pool->vallocator = NULL;
1502
1503   if (pool->allocator)
1504     gst_object_unref (pool->allocator);
1505   pool->allocator = NULL;
1506
1507   if (pool->other_pool)
1508     gst_object_unref (pool->other_pool);
1509   pool->other_pool = NULL;
1510
1511   G_OBJECT_CLASS (parent_class)->dispose (object);
1512 }
1513
1514 static void
1515 gst_v4l2_buffer_pool_finalize (GObject * object)
1516 {
1517   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (object);
1518
1519   if (pool->video_fd >= 0)
1520     pool->obj->close (pool->video_fd);
1521
1522   gst_poll_free (pool->poll);
1523
1524   /* This can't be done in dispose method because we must not set pointer
1525    * to NULL as it is part of the v4l2object and dispose could be called
1526    * multiple times */
1527   gst_object_unref (pool->obj->element);
1528
1529   g_cond_clear (&pool->empty_cond);
1530
1531   /* FIXME have we done enough here ? */
1532
1533   G_OBJECT_CLASS (parent_class)->finalize (object);
1534 }
1535
1536 static void
1537 gst_v4l2_buffer_pool_init (GstV4l2BufferPool * pool)
1538 {
1539   pool->poll = gst_poll_new (TRUE);
1540   pool->can_poll_device = TRUE;
1541   g_cond_init (&pool->empty_cond);
1542   pool->empty = TRUE;
1543 }
1544
1545 static void
1546 gst_v4l2_buffer_pool_class_init (GstV4l2BufferPoolClass * klass)
1547 {
1548   GObjectClass *object_class = G_OBJECT_CLASS (klass);
1549   GstBufferPoolClass *bufferpool_class = GST_BUFFER_POOL_CLASS (klass);
1550
1551   object_class->dispose = gst_v4l2_buffer_pool_dispose;
1552   object_class->finalize = gst_v4l2_buffer_pool_finalize;
1553
1554   bufferpool_class->start = gst_v4l2_buffer_pool_start;
1555   bufferpool_class->stop = gst_v4l2_buffer_pool_stop;
1556   bufferpool_class->set_config = gst_v4l2_buffer_pool_set_config;
1557   bufferpool_class->alloc_buffer = gst_v4l2_buffer_pool_alloc_buffer;
1558   bufferpool_class->acquire_buffer = gst_v4l2_buffer_pool_acquire_buffer;
1559   bufferpool_class->release_buffer = gst_v4l2_buffer_pool_release_buffer;
1560   bufferpool_class->flush_start = gst_v4l2_buffer_pool_flush_start;
1561   bufferpool_class->flush_stop = gst_v4l2_buffer_pool_flush_stop;
1562
1563   GST_DEBUG_CATEGORY_INIT (v4l2bufferpool_debug, "v4l2bufferpool", 0,
1564       "V4L2 Buffer Pool");
1565   GST_DEBUG_CATEGORY_GET (CAT_PERFORMANCE, "GST_PERFORMANCE");
1566 }
1567
1568 /**
1569  * gst_v4l2_buffer_pool_new:
1570  * @obj:  the v4l2 object owning the pool
1571  *
1572  * Construct a new buffer pool.
1573  *
1574  * Returns: the new pool, use gst_object_unref() to free resources
1575  */
1576 GstBufferPool *
1577 gst_v4l2_buffer_pool_new (GstV4l2Object * obj, GstCaps * caps)
1578 {
1579   GstV4l2BufferPool *pool;
1580   GstStructure *config;
1581   gchar *name, *parent_name;
1582   gint fd;
1583
1584   fd = obj->dup (obj->video_fd);
1585   if (fd < 0)
1586     goto dup_failed;
1587
1588   /* setting a significant unique name */
1589   parent_name = gst_object_get_name (GST_OBJECT (obj->element));
1590   name = g_strconcat (parent_name, ":", "pool:",
1591       V4L2_TYPE_IS_OUTPUT (obj->type) ? "sink" : "src", NULL);
1592   g_free (parent_name);
1593
1594   pool = (GstV4l2BufferPool *) g_object_new (GST_TYPE_V4L2_BUFFER_POOL,
1595       "name", name, NULL);
1596   g_object_ref_sink (pool);
1597   g_free (name);
1598
1599   gst_poll_fd_init (&pool->pollfd);
1600   pool->pollfd.fd = fd;
1601   gst_poll_add_fd (pool->poll, &pool->pollfd);
1602   if (V4L2_TYPE_IS_OUTPUT (obj->type))
1603     gst_poll_fd_ctl_write (pool->poll, &pool->pollfd, TRUE);
1604   else
1605     gst_poll_fd_ctl_read (pool->poll, &pool->pollfd, TRUE);
1606
1607   pool->video_fd = fd;
1608   pool->obj = obj;
1609   pool->can_poll_device = TRUE;
1610
1611   pool->vallocator = gst_v4l2_allocator_new (GST_OBJECT (pool), obj);
1612   if (pool->vallocator == NULL)
1613     goto allocator_failed;
1614
1615   gst_object_ref (obj->element);
1616
1617   config = gst_buffer_pool_get_config (GST_BUFFER_POOL_CAST (pool));
1618   gst_buffer_pool_config_set_params (config, caps, obj->info.size, 0, 0);
1619   /* This will simply set a default config, but will not configure the pool
1620    * because min and max are not valid */
1621   gst_buffer_pool_set_config (GST_BUFFER_POOL_CAST (pool), config);
1622
1623   return GST_BUFFER_POOL (pool);
1624
1625   /* ERRORS */
1626 dup_failed:
1627   {
1628     GST_ERROR ("failed to dup fd %d (%s)", errno, g_strerror (errno));
1629     return NULL;
1630   }
1631 allocator_failed:
1632   {
1633     GST_ERROR_OBJECT (pool, "Failed to create V4L2 allocator");
1634     gst_object_unref (pool);
1635     return NULL;
1636   }
1637 }
1638
1639 static GstFlowReturn
1640 gst_v4l2_do_read (GstV4l2BufferPool * pool, GstBuffer * buf)
1641 {
1642   GstFlowReturn res;
1643   GstV4l2Object *obj = pool->obj;
1644   gint amount;
1645   GstMapInfo map;
1646   gint toread;
1647
1648   toread = obj->info.size;
1649
1650   GST_LOG_OBJECT (pool, "reading %d bytes into buffer %p", toread, buf);
1651
1652   gst_buffer_map (buf, &map, GST_MAP_WRITE);
1653
1654   do {
1655     if ((res = gst_v4l2_buffer_pool_poll (pool, TRUE)) != GST_FLOW_OK)
1656       goto poll_error;
1657
1658     amount = obj->read (obj->video_fd, map.data, toread);
1659
1660     if (amount == toread) {
1661       break;
1662     } else if (amount == -1) {
1663       if (errno == EAGAIN || errno == EINTR) {
1664         continue;
1665       } else
1666         goto read_error;
1667     } else {
1668       /* short reads can happen if a signal interrupts the read */
1669       continue;
1670     }
1671   } while (TRUE);
1672
1673   GST_LOG_OBJECT (pool, "read %d bytes", amount);
1674   gst_buffer_unmap (buf, &map);
1675   gst_buffer_resize (buf, 0, amount);
1676
1677   return GST_FLOW_OK;
1678
1679   /* ERRORS */
1680 poll_error:
1681   {
1682     GST_DEBUG ("poll error %s", gst_flow_get_name (res));
1683     goto cleanup;
1684   }
1685 read_error:
1686   {
1687     GST_ELEMENT_ERROR (obj->element, RESOURCE, READ,
1688         (_("Error reading %d bytes from device '%s'."),
1689             toread, obj->videodev), GST_ERROR_SYSTEM);
1690     res = GST_FLOW_ERROR;
1691     goto cleanup;
1692   }
1693 cleanup:
1694   {
1695     gst_buffer_unmap (buf, &map);
1696     gst_buffer_resize (buf, 0, 0);
1697     return res;
1698   }
1699 }
1700
1701 /**
1702  * gst_v4l2_buffer_pool_process:
1703  * @bpool: a #GstBufferPool
1704  * @buf: a #GstBuffer, maybe be replaced
1705  *
1706  * Process @buf in @bpool. For capture devices, this functions fills @buf with
1707  * data from the device. For output devices, this functions send the contents of
1708  * @buf to the device for playback.
1709  *
1710  * Returns: %GST_FLOW_OK on success.
1711  */
1712 GstFlowReturn
1713 gst_v4l2_buffer_pool_process (GstV4l2BufferPool * pool, GstBuffer ** buf)
1714 {
1715   GstFlowReturn ret = GST_FLOW_OK;
1716   GstBufferPool *bpool = GST_BUFFER_POOL_CAST (pool);
1717   GstV4l2Object *obj = pool->obj;
1718
1719   GST_DEBUG_OBJECT (pool, "process buffer %p", buf);
1720
1721   if (GST_BUFFER_POOL_IS_FLUSHING (pool))
1722     return GST_FLOW_FLUSHING;
1723
1724   switch (obj->type) {
1725     case V4L2_BUF_TYPE_VIDEO_CAPTURE:
1726     case V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE:
1727       /* capture */
1728       switch (obj->mode) {
1729         case GST_V4L2_IO_RW:
1730           /* capture into the buffer */
1731           ret = gst_v4l2_do_read (pool, *buf);
1732           break;
1733
1734         case GST_V4L2_IO_MMAP:
1735         case GST_V4L2_IO_DMABUF:
1736         {
1737           GstBuffer *tmp;
1738
1739           if ((*buf)->pool == bpool) {
1740             guint num_queued;
1741             gsize size = gst_buffer_get_size (*buf);
1742
1743             if (size == 0) {
1744               if (GST_BUFFER_FLAG_IS_SET (*buf, GST_BUFFER_FLAG_CORRUPTED))
1745                 goto buffer_corrupted;
1746               else
1747                 goto eos;
1748             }
1749
1750             if (GST_VIDEO_INFO_FORMAT (&pool->caps_info) !=
1751                 GST_VIDEO_FORMAT_ENCODED && size < pool->size)
1752               goto buffer_truncated;
1753
1754             num_queued = g_atomic_int_get (&pool->num_queued);
1755             GST_TRACE_OBJECT (pool, "Only %i buffer left in the capture queue.",
1756                 num_queued);
1757
1758             /* If we have no more buffer, and can allocate it time to do so */
1759             if (num_queued == 0) {
1760               if (GST_V4L2_ALLOCATOR_CAN_ALLOCATE (pool->vallocator, MMAP)) {
1761                 ret = gst_v4l2_buffer_pool_resurect_buffer (pool);
1762                 if (ret == GST_FLOW_OK)
1763                   goto done;
1764               }
1765             }
1766
1767             /* start copying buffers when we are running low on buffers */
1768             if (num_queued < pool->copy_threshold) {
1769               GstBuffer *copy;
1770
1771               if (GST_V4L2_ALLOCATOR_CAN_ALLOCATE (pool->vallocator, MMAP)) {
1772                 ret = gst_v4l2_buffer_pool_resurect_buffer (pool);
1773                 if (ret == GST_FLOW_OK)
1774                   goto done;
1775               }
1776
1777               /* copy the buffer */
1778               copy = gst_buffer_copy_region (*buf,
1779                   GST_BUFFER_COPY_ALL | GST_BUFFER_COPY_DEEP, 0, -1);
1780               GST_LOG_OBJECT (pool, "copy buffer %p->%p", *buf, copy);
1781
1782               /* and requeue so that we can continue capturing */
1783               gst_buffer_unref (*buf);
1784               *buf = copy;
1785             }
1786
1787             ret = GST_FLOW_OK;
1788             /* nothing, data was inside the buffer when we did _acquire() */
1789             goto done;
1790           }
1791
1792           /* buffer not from our pool, grab a frame and copy it into the target */
1793           if ((ret = gst_v4l2_buffer_pool_dqbuf (pool, &tmp, TRUE))
1794               != 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           GstBuffer *tmp;
1824
1825           /* Replace our buffer with downstream allocated buffer */
1826           data = gst_mini_object_steal_qdata (GST_MINI_OBJECT (*buf),
1827               GST_V4L2_IMPORT_QUARK);
1828           tmp = gst_buffer_ref (data->buffer);
1829           _unmap_userptr_frame (data);
1830
1831           /* Now tmp is writable, copy the flags and timestamp */
1832           gst_buffer_copy_into (tmp, *buf,
1833               GST_BUFFER_COPY_FLAGS | GST_BUFFER_COPY_TIMESTAMPS, 0, -1);
1834
1835           gst_buffer_replace (buf, tmp);
1836           gst_buffer_unref (tmp);
1837           break;
1838         }
1839
1840         case GST_V4L2_IO_DMABUF_IMPORT:
1841         {
1842           GstBuffer *tmp;
1843
1844           /* Replace our buffer with downstream allocated buffer */
1845           tmp = gst_mini_object_steal_qdata (GST_MINI_OBJECT (*buf),
1846               GST_V4L2_IMPORT_QUARK);
1847
1848           gst_buffer_copy_into (tmp, *buf,
1849               GST_BUFFER_COPY_FLAGS | GST_BUFFER_COPY_TIMESTAMPS, 0, -1);
1850
1851           gst_buffer_replace (buf, tmp);
1852           gst_buffer_unref (tmp);
1853           break;
1854         }
1855
1856         default:
1857           g_assert_not_reached ();
1858           break;
1859       }
1860       break;
1861
1862     case V4L2_BUF_TYPE_VIDEO_OUTPUT:
1863     case V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE:
1864       /* playback */
1865       switch (obj->mode) {
1866         case GST_V4L2_IO_RW:
1867           /* FIXME, do write() */
1868           GST_WARNING_OBJECT (pool, "implement write()");
1869           break;
1870
1871         case GST_V4L2_IO_USERPTR:
1872         case GST_V4L2_IO_DMABUF_IMPORT:
1873         case GST_V4L2_IO_DMABUF:
1874         case GST_V4L2_IO_MMAP:
1875         {
1876           GstBuffer *to_queue = NULL;
1877           GstBuffer *buffer;
1878           GstV4l2MemoryGroup *group;
1879           gint index;
1880
1881           if ((*buf)->pool != bpool)
1882             goto copying;
1883
1884           if (!gst_v4l2_is_buffer_valid (*buf, &group))
1885             goto copying;
1886
1887           index = group->buffer.index;
1888
1889           GST_LOG_OBJECT (pool, "processing buffer %i from our pool", index);
1890
1891           if (pool->buffers[index] != NULL) {
1892             GST_LOG_OBJECT (pool, "buffer %i already queued, copying", index);
1893             goto copying;
1894           }
1895
1896           /* we can queue directly */
1897           to_queue = gst_buffer_ref (*buf);
1898
1899         copying:
1900           if (to_queue == NULL) {
1901             GstBufferPoolAcquireParams params = { 0 };
1902
1903             GST_LOG_OBJECT (pool, "alloc buffer from our pool");
1904
1905             /* this can return EOS if all buffers are outstanding which would
1906              * be strange because we would expect the upstream element to have
1907              * allocated them and returned to us.. */
1908             params.flags = GST_BUFFER_POOL_ACQUIRE_FLAG_DONTWAIT;
1909             ret = gst_buffer_pool_acquire_buffer (bpool, &to_queue, &params);
1910             if (ret != GST_FLOW_OK)
1911               goto acquire_failed;
1912
1913             ret = gst_v4l2_buffer_pool_prepare_buffer (pool, to_queue, *buf);
1914             if (ret != GST_FLOW_OK) {
1915               gst_buffer_unref (to_queue);
1916               goto prepare_failed;
1917             }
1918           }
1919
1920           if ((ret = gst_v4l2_buffer_pool_qbuf (pool, to_queue)) != GST_FLOW_OK)
1921             goto queue_failed;
1922
1923           /* if we are not streaming yet (this is the first buffer, start
1924            * streaming now */
1925           if (!gst_v4l2_buffer_pool_streamon (pool)) {
1926             /* don't check return value because qbuf would have failed */
1927             gst_v4l2_is_buffer_valid (to_queue, &group);
1928
1929             /* qbuf has stored to_queue buffer but we are not in
1930              * streaming state, so the flush logic won't be performed.
1931              * To avoid leaks, flush the allocator and restore the queued
1932              * buffer as non-queued */
1933             gst_v4l2_allocator_flush (pool->vallocator);
1934
1935             pool->buffers[group->buffer.index] = NULL;
1936
1937             gst_mini_object_set_qdata (GST_MINI_OBJECT (to_queue),
1938                 GST_V4L2_IMPORT_QUARK, NULL, NULL);
1939             gst_buffer_unref (to_queue);
1940             g_atomic_int_add (&pool->num_queued, -1);
1941             goto start_failed;
1942           }
1943
1944           /* Remove our ref, we will still hold this buffer in acquire as needed,
1945            * otherwise the pool will think it is outstanding and will refuse to stop. */
1946           gst_buffer_unref (to_queue);
1947
1948           /* release as many buffer as possible */
1949           while (gst_v4l2_buffer_pool_dqbuf (pool, &buffer, FALSE) ==
1950               GST_FLOW_OK) {
1951             if (buffer->pool == NULL)
1952               gst_v4l2_buffer_pool_release_buffer (bpool, buffer);
1953           }
1954
1955           if (g_atomic_int_get (&pool->num_queued) >= pool->min_latency) {
1956             /* all buffers are queued, try to dequeue one and release it back
1957              * into the pool so that _acquire can get to it again. */
1958             ret = gst_v4l2_buffer_pool_dqbuf (pool, &buffer, TRUE);
1959             if (ret == GST_FLOW_OK && buffer->pool == NULL)
1960               /* release the rendered buffer back into the pool. This wakes up any
1961                * thread waiting for a buffer in _acquire(). */
1962               gst_v4l2_buffer_pool_release_buffer (bpool, buffer);
1963           }
1964           break;
1965         }
1966         default:
1967           g_assert_not_reached ();
1968           break;
1969       }
1970       break;
1971     default:
1972       g_assert_not_reached ();
1973       break;
1974   }
1975 done:
1976   return ret;
1977
1978   /* ERRORS */
1979 copy_failed:
1980   {
1981     GST_ERROR_OBJECT (pool, "failed to copy buffer");
1982     return ret;
1983   }
1984 buffer_corrupted:
1985   {
1986     GST_WARNING_OBJECT (pool, "Dropping corrupted buffer without payload");
1987     gst_buffer_unref (*buf);
1988     *buf = NULL;
1989     return GST_V4L2_FLOW_CORRUPTED_BUFFER;
1990   }
1991 buffer_truncated:
1992   {
1993     GST_WARNING_OBJECT (pool,
1994         "Dropping truncated buffer, this is likely a driver bug.");
1995     gst_buffer_unref (*buf);
1996     *buf = NULL;
1997     return GST_V4L2_FLOW_CORRUPTED_BUFFER;
1998   }
1999 eos:
2000   {
2001     GST_DEBUG_OBJECT (pool, "end of stream reached");
2002     gst_buffer_unref (*buf);
2003     *buf = NULL;
2004     return GST_V4L2_FLOW_LAST_BUFFER;
2005   }
2006 acquire_failed:
2007   {
2008     if (ret == GST_FLOW_FLUSHING)
2009       GST_DEBUG_OBJECT (pool, "flushing");
2010     else
2011       GST_WARNING_OBJECT (pool, "failed to acquire a buffer: %s",
2012           gst_flow_get_name (ret));
2013     return ret;
2014   }
2015 prepare_failed:
2016   {
2017     GST_ERROR_OBJECT (pool, "failed to prepare data");
2018     return ret;
2019   }
2020 queue_failed:
2021   {
2022     GST_ERROR_OBJECT (pool, "failed to queue buffer");
2023     return ret;
2024   }
2025 start_failed:
2026   {
2027     GST_ERROR_OBJECT (pool, "failed to start streaming");
2028     return GST_FLOW_ERROR;
2029   }
2030 }
2031
2032 void
2033 gst_v4l2_buffer_pool_set_other_pool (GstV4l2BufferPool * pool,
2034     GstBufferPool * other_pool)
2035 {
2036   g_return_if_fail (!gst_buffer_pool_is_active (GST_BUFFER_POOL (pool)));
2037
2038   if (pool->other_pool)
2039     gst_object_unref (pool->other_pool);
2040   pool->other_pool = gst_object_ref (other_pool);
2041 }
2042
2043 void
2044 gst_v4l2_buffer_pool_copy_at_threshold (GstV4l2BufferPool * pool, gboolean copy)
2045 {
2046   GST_OBJECT_LOCK (pool);
2047   pool->enable_copy_threshold = copy;
2048   GST_OBJECT_UNLOCK (pool);
2049 }
2050
2051 gboolean
2052 gst_v4l2_buffer_pool_flush (GstBufferPool * bpool)
2053 {
2054   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
2055   gboolean ret = TRUE;
2056
2057   gst_v4l2_buffer_pool_streamoff (pool);
2058
2059   if (!V4L2_TYPE_IS_OUTPUT (pool->obj->type))
2060     ret = gst_v4l2_buffer_pool_streamon (pool);
2061
2062   return ret;
2063 }