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