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