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