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