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