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