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