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