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