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