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