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