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