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