f5e3bbc267e44f1ed973b5e2d7650f2b02431418
[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_POOL_ACQUIRE_FLAG_RESURECT = GST_BUFFER_POOL_ACQUIRE_FLAG_LAST,
65   GST_V4L2_BUFFER_POOL_ACQUIRE_FAG_LAST
66 };
67
68 static void gst_v4l2_buffer_pool_release_buffer (GstBufferPool * bpool,
69     GstBuffer * buffer);
70
71 static gboolean
72 gst_v4l2_is_buffer_valid (GstBuffer * buffer, GstV4l2MemoryGroup ** group)
73 {
74   GstMemory *mem = gst_buffer_peek_memory (buffer, 0);
75   gboolean valid = FALSE;
76
77   if (GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_TAG_MEMORY))
78     goto done;
79
80   if (gst_is_dmabuf_memory (mem))
81     mem = mem->parent;
82
83   if (gst_is_v4l2_memory (mem)) {
84     GstV4l2Memory *vmem = (GstV4l2Memory *) mem;
85     valid = TRUE;
86     if (group)
87       *group = vmem->group;
88   }
89
90 done:
91   return valid;
92 }
93
94 static GstFlowReturn
95 gst_v4l2_buffer_pool_copy_buffer (GstV4l2BufferPool * pool, GstBuffer * dest,
96     GstBuffer * src)
97 {
98   const GstVideoFormatInfo *finfo = pool->caps_info.finfo;
99
100   GST_LOG_OBJECT (pool, "copying buffer");
101
102   if (finfo && (finfo->format != GST_VIDEO_FORMAT_UNKNOWN &&
103           finfo->format != GST_VIDEO_FORMAT_ENCODED)) {
104     GstVideoFrame src_frame, dest_frame;
105
106     GST_DEBUG_OBJECT (pool, "copy video frame");
107
108     /* we have raw video, use videoframe copy to get strides right */
109     if (!gst_video_frame_map (&src_frame, &pool->caps_info, src, GST_MAP_READ))
110       goto invalid_buffer;
111
112     if (!gst_video_frame_map (&dest_frame, &pool->caps_info, dest,
113             GST_MAP_WRITE)) {
114       gst_video_frame_unmap (&src_frame);
115       goto invalid_buffer;
116     }
117
118     gst_video_frame_copy (&dest_frame, &src_frame);
119
120     gst_video_frame_unmap (&src_frame);
121     gst_video_frame_unmap (&dest_frame);
122   } else {
123     GstMapInfo map;
124
125     GST_DEBUG_OBJECT (pool, "copy raw bytes");
126
127     if (!gst_buffer_map (src, &map, GST_MAP_READ))
128       goto invalid_buffer;
129
130     gst_buffer_fill (dest, 0, map.data, gst_buffer_get_size (src));
131
132     gst_buffer_unmap (src, &map);
133     gst_buffer_resize (dest, 0, gst_buffer_get_size (src));
134   }
135
136   GST_CAT_LOG_OBJECT (GST_CAT_PERFORMANCE, pool, "slow copy into buffer %p",
137       dest);
138
139   return GST_FLOW_OK;
140
141 invalid_buffer:
142   {
143     GST_ERROR_OBJECT (pool, "could not map buffer");
144     return GST_FLOW_ERROR;
145   }
146 }
147
148 struct UserPtrData
149 {
150   GstBuffer *buffer;
151   gboolean is_frame;
152   GstVideoFrame frame;
153   GstMapInfo map;
154 };
155
156 static GQuark
157 gst_v4l2_buffer_pool_import_quark (void)
158 {
159   static GQuark quark = 0;
160
161   if (quark == 0)
162     quark = g_quark_from_string ("GstV4l2BufferPoolUsePtrData");
163
164   return quark;
165 }
166
167 static void
168 _unmap_userptr_frame (struct UserPtrData *data)
169 {
170   if (data->is_frame)
171     gst_video_frame_unmap (&data->frame);
172   else
173     gst_buffer_unmap (data->buffer, &data->map);
174
175   if (data->buffer)
176     gst_buffer_unref (data->buffer);
177
178   g_slice_free (struct UserPtrData, data);
179 }
180
181 static GstFlowReturn
182 gst_v4l2_buffer_pool_import_userptr (GstV4l2BufferPool * pool,
183     GstBuffer * dest, GstBuffer * src)
184 {
185   GstFlowReturn ret = GST_FLOW_OK;
186   GstV4l2MemoryGroup *group = NULL;
187   GstMapFlags flags;
188   const GstVideoFormatInfo *finfo = pool->caps_info.finfo;
189   struct UserPtrData *data = NULL;
190
191   GST_LOG_OBJECT (pool, "importing userptr");
192
193   /* get the group */
194   if (!gst_v4l2_is_buffer_valid (dest, &group))
195     goto not_our_buffer;
196
197   if (V4L2_TYPE_IS_OUTPUT (pool->obj->type))
198     flags = GST_MAP_READ;
199   else
200     flags = GST_MAP_WRITE;
201
202   data = g_slice_new0 (struct UserPtrData);
203
204   if (finfo && (finfo->format != GST_VIDEO_FORMAT_UNKNOWN &&
205           finfo->format != GST_VIDEO_FORMAT_ENCODED)) {
206     data->is_frame = TRUE;
207
208     if (!gst_video_frame_map (&data->frame, &pool->caps_info, src, flags))
209       goto invalid_buffer;
210
211     if (!gst_v4l2_allocator_import_userptr (pool->vallocator, group,
212             data->frame.info.size, finfo->n_planes, data->frame.data,
213             data->frame.info.offset))
214       goto import_failed;
215   } else {
216     gsize offset[1] = { 0 };
217     gpointer ptr[1];
218
219     data->is_frame = FALSE;
220
221     if (!gst_buffer_map (src, &data->map, flags))
222       goto invalid_buffer;
223
224     ptr[0] = data->map.data;
225
226     if (!gst_v4l2_allocator_import_userptr (pool->vallocator, group,
227             data->map.size, 1, ptr, offset))
228       goto import_failed;
229   }
230
231   data->buffer = gst_buffer_ref (src);
232
233   gst_mini_object_set_qdata (GST_MINI_OBJECT (dest), GST_V4L2_IMPORT_QUARK,
234       data, (GDestroyNotify) _unmap_userptr_frame);
235
236   return ret;
237
238 not_our_buffer:
239   {
240     GST_ERROR_OBJECT (pool, "destination buffer invalid or not from our pool");
241     return GST_FLOW_ERROR;
242   }
243 invalid_buffer:
244   {
245     GST_ERROR_OBJECT (pool, "could not map buffer");
246     g_slice_free (struct UserPtrData, data);
247     return GST_FLOW_ERROR;
248   }
249 import_failed:
250   {
251     GST_ERROR_OBJECT (pool, "failed to import data");
252     _unmap_userptr_frame (data);
253     return GST_FLOW_ERROR;
254   }
255 }
256
257 static GstFlowReturn
258 gst_v4l2_buffer_pool_import_dmabuf (GstV4l2BufferPool * pool,
259     GstBuffer * dest, GstBuffer * src)
260 {
261   GstV4l2MemoryGroup *group = NULL;
262   GstMemory *dma_mem[GST_VIDEO_MAX_PLANES] = { 0 };
263   guint n_mem = gst_buffer_n_memory (src);
264   gint i;
265
266   GST_LOG_OBJECT (pool, "importing dmabuf");
267
268   if (!gst_v4l2_is_buffer_valid (dest, &group))
269     goto not_our_buffer;
270
271   if (n_mem > GST_VIDEO_MAX_PLANES)
272     goto too_many_mems;
273
274   for (i = 0; i < n_mem; i++)
275     dma_mem[i] = gst_buffer_peek_memory (src, i);
276
277   if (!gst_v4l2_allocator_import_dmabuf (pool->vallocator, group, n_mem,
278           dma_mem))
279     goto import_failed;
280
281   gst_mini_object_set_qdata (GST_MINI_OBJECT (dest), GST_V4L2_IMPORT_QUARK,
282       gst_buffer_ref (src), (GDestroyNotify) gst_buffer_unref);
283
284   return GST_FLOW_OK;
285
286 not_our_buffer:
287   {
288     GST_ERROR_OBJECT (pool, "destination buffer invalid or not from our pool");
289     return GST_FLOW_ERROR;
290   }
291 too_many_mems:
292   {
293     GST_ERROR_OBJECT (pool, "could not map buffer");
294     return GST_FLOW_ERROR;
295   }
296 import_failed:
297   {
298     GST_ERROR_OBJECT (pool, "failed to import dmabuf");
299     return GST_FLOW_ERROR;
300   }
301 }
302
303 static GstFlowReturn
304 gst_v4l2_buffer_pool_prepare_buffer (GstV4l2BufferPool * pool,
305     GstBuffer * dest, GstBuffer * src)
306 {
307   GstFlowReturn ret = GST_FLOW_OK;
308   gboolean own_src = FALSE;
309
310   if (src == NULL) {
311     if (pool->other_pool == NULL) {
312       GST_ERROR_OBJECT (pool, "can't prepare buffer, source buffer missing");
313       return GST_FLOW_ERROR;
314     }
315
316     ret = gst_buffer_pool_acquire_buffer (pool->other_pool, &src, NULL);
317     if (ret != GST_FLOW_OK) {
318       GST_ERROR_OBJECT (pool, "failed to acquire buffer from downstream pool");
319       goto done;
320     }
321
322     own_src = TRUE;
323   }
324
325   switch (pool->obj->mode) {
326     case GST_V4L2_IO_MMAP:
327     case GST_V4L2_IO_DMABUF:
328       ret = gst_v4l2_buffer_pool_copy_buffer (pool, dest, src);
329       break;
330     case GST_V4L2_IO_USERPTR:
331       ret = gst_v4l2_buffer_pool_import_userptr (pool, dest, src);
332       break;
333     case GST_V4L2_IO_DMABUF_IMPORT:
334       ret = gst_v4l2_buffer_pool_import_dmabuf (pool, dest, src);
335       break;
336     default:
337       break;
338   }
339
340   if (own_src)
341     gst_buffer_unref (src);
342
343 done:
344   return ret;
345 }
346
347 static GstFlowReturn
348 gst_v4l2_buffer_pool_alloc_buffer (GstBufferPool * bpool, GstBuffer ** buffer,
349     GstBufferPoolAcquireParams * params)
350 {
351   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
352   GstV4l2MemoryGroup *group = NULL;
353   GstBuffer *newbuf = NULL;
354   GstV4l2Object *obj;
355   GstVideoInfo *info;
356
357   obj = pool->obj;
358   info = &obj->info;
359
360   switch (obj->mode) {
361     case GST_V4L2_IO_RW:
362       newbuf =
363           gst_buffer_new_allocate (pool->allocator, pool->size, &pool->params);
364       break;
365     case GST_V4L2_IO_MMAP:
366       group = gst_v4l2_allocator_alloc_mmap (pool->vallocator);
367       break;
368     case GST_V4L2_IO_DMABUF:
369       group = gst_v4l2_allocator_alloc_dmabuf (pool->vallocator,
370           pool->allocator);
371       break;
372     case GST_V4L2_IO_USERPTR:
373       group = gst_v4l2_allocator_alloc_userptr (pool->vallocator);
374       break;
375     case GST_V4L2_IO_DMABUF_IMPORT:
376       group = gst_v4l2_allocator_alloc_dmabufin (pool->vallocator);
377       break;
378     default:
379       newbuf = NULL;
380       g_assert_not_reached ();
381       break;
382   }
383
384   if (group != NULL) {
385     gint i;
386     newbuf = gst_buffer_new ();
387
388     for (i = 0; i < group->n_mem; i++)
389       gst_buffer_append_memory (newbuf, group->mem[i]);
390   } else if (newbuf == NULL) {
391     goto allocation_failed;
392   }
393
394   /* add metadata to raw video buffers */
395   if (pool->add_videometa)
396     gst_buffer_add_video_meta_full (newbuf, GST_VIDEO_FRAME_FLAG_NONE,
397         GST_VIDEO_INFO_FORMAT (info), GST_VIDEO_INFO_WIDTH (info),
398         GST_VIDEO_INFO_HEIGHT (info), GST_VIDEO_INFO_N_PLANES (info),
399         info->offset, info->stride);
400
401   *buffer = newbuf;
402
403   return GST_FLOW_OK;
404
405   /* ERRORS */
406 allocation_failed:
407   {
408     GST_ERROR_OBJECT (pool, "failed to allocate buffer");
409     return GST_FLOW_ERROR;
410   }
411 }
412
413 static gboolean
414 gst_v4l2_buffer_pool_set_config (GstBufferPool * bpool, GstStructure * config)
415 {
416   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
417   GstV4l2Object *obj = pool->obj;
418   GstCaps *caps;
419   guint size, min_buffers, max_buffers;
420   GstAllocator *allocator;
421   GstAllocationParams params;
422   gboolean can_allocate = FALSE;
423   gboolean updated = FALSE;
424   gboolean ret;
425
426   pool->add_videometa =
427       gst_buffer_pool_config_has_option (config,
428       GST_BUFFER_POOL_OPTION_VIDEO_META);
429
430   /* parse the config and keep around */
431   if (!gst_buffer_pool_config_get_params (config, &caps, &size, &min_buffers,
432           &max_buffers))
433     goto wrong_config;
434
435   if (!gst_buffer_pool_config_get_allocator (config, &allocator, &params))
436     goto wrong_config;
437
438   GST_DEBUG_OBJECT (pool, "config %" GST_PTR_FORMAT, config);
439
440   if (pool->allocator)
441     gst_object_unref (pool->allocator);
442   pool->allocator = NULL;
443
444   switch (obj->mode) {
445     case GST_V4L2_IO_DMABUF:
446       pool->allocator = gst_dmabuf_allocator_new ();
447       can_allocate = GST_V4L2_ALLOCATOR_CAN_ALLOCATE (pool->vallocator, MMAP);
448       break;
449     case GST_V4L2_IO_MMAP:
450       can_allocate = GST_V4L2_ALLOCATOR_CAN_ALLOCATE (pool->vallocator, MMAP);
451       break;
452     case GST_V4L2_IO_USERPTR:
453       can_allocate =
454           GST_V4L2_ALLOCATOR_CAN_ALLOCATE (pool->vallocator, USERPTR);
455       break;
456     case GST_V4L2_IO_DMABUF_IMPORT:
457       can_allocate = GST_V4L2_ALLOCATOR_CAN_ALLOCATE (pool->vallocator, DMABUF);
458       break;
459     case GST_V4L2_IO_RW:
460       pool->allocator = g_object_ref (allocator);
461       pool->params = params;
462       /* No need to change the configuration */
463       goto done;
464       break;
465     default:
466       g_assert_not_reached ();
467       break;
468   }
469
470   if (min_buffers < GST_V4L2_MIN_BUFFERS) {
471     updated = TRUE;
472     min_buffers = GST_V4L2_MIN_BUFFERS;
473     GST_INFO_OBJECT (pool, "increasing minimum buffers to %u", min_buffers);
474   }
475
476   if (max_buffers > VIDEO_MAX_FRAME || max_buffers == 0) {
477     updated = TRUE;
478     max_buffers = VIDEO_MAX_FRAME;
479     GST_INFO_OBJECT (pool, "reducing maximum buffers to %u", max_buffers);
480   }
481
482   if (min_buffers > max_buffers) {
483     updated = TRUE;
484     min_buffers = max_buffers;
485     GST_INFO_OBJECT (pool, "reducing minimum buffers to %u", min_buffers);
486   } else if (min_buffers != max_buffers) {
487     if (!can_allocate) {
488       updated = TRUE;
489       max_buffers = min_buffers;
490       GST_INFO_OBJECT (pool, "can't allocate, setting maximum to minimum");
491     }
492   }
493
494   if (!pool->add_videometa && obj->need_video_meta) {
495     GST_INFO_OBJECT (pool, "adding needed video meta");
496     updated = TRUE;
497     gst_buffer_pool_config_add_option (config,
498         GST_BUFFER_POOL_OPTION_VIDEO_META);
499   }
500
501   if (updated)
502     gst_buffer_pool_config_set_params (config, caps, size, min_buffers,
503         max_buffers);
504
505   /* keep a GstVideoInfo with defaults for the when we need to copy */
506   gst_video_info_from_caps (&pool->caps_info, caps);
507
508 done:
509   ret = GST_BUFFER_POOL_CLASS (parent_class)->set_config (bpool, config);
510
511   /* If anything was changed documentation recommand to return FALSE */
512   return !updated && ret;
513
514   /* ERRORS */
515 wrong_config:
516   {
517     GST_ERROR_OBJECT (pool, "invalid config %" GST_PTR_FORMAT, config);
518     return FALSE;
519   }
520 }
521
522 static gboolean
523 gst_v4l2_buffer_pool_streamon (GstV4l2BufferPool * pool)
524 {
525   GstV4l2Object *obj = pool->obj;
526
527   switch (obj->mode) {
528     case GST_V4L2_IO_MMAP:
529     case GST_V4L2_IO_USERPTR:
530     case GST_V4L2_IO_DMABUF:
531     case GST_V4L2_IO_DMABUF_IMPORT:
532       if (!pool->streaming) {
533         if (v4l2_ioctl (pool->video_fd, VIDIOC_STREAMON, &obj->type) < 0)
534           goto streamon_failed;
535
536         pool->streaming = TRUE;
537
538         GST_DEBUG_OBJECT (pool, "Started streaming");
539       }
540       break;
541     default:
542       break;
543   }
544
545   return TRUE;
546
547 streamon_failed:
548   {
549     GST_ERROR_OBJECT (pool, "error with STREAMON %d (%s)", errno,
550         g_strerror (errno));
551     return FALSE;
552   }
553 }
554
555 static gboolean
556 gst_v4l2_buffer_pool_streamoff (GstV4l2BufferPool * pool)
557 {
558   GstV4l2Object *obj = pool->obj;
559
560   switch (obj->mode) {
561     case GST_V4L2_IO_MMAP:
562     case GST_V4L2_IO_USERPTR:
563     case GST_V4L2_IO_DMABUF:
564     case GST_V4L2_IO_DMABUF_IMPORT:
565       if (pool->streaming) {
566         if (v4l2_ioctl (pool->video_fd, VIDIOC_STREAMOFF, &obj->type) < 0)
567           goto streamoff_failed;
568
569         pool->streaming = FALSE;
570
571         GST_DEBUG_OBJECT (pool, "Stopped streaming");
572       }
573       break;
574     default:
575       break;
576   }
577
578   return TRUE;
579
580 streamoff_failed:
581   {
582     GST_ERROR_OBJECT (pool, "error with STREAMOFF %d (%s)", errno,
583         g_strerror (errno));
584     return FALSE;
585   }
586 }
587
588 static void
589 gst_v4l2_buffer_pool_group_released (GstV4l2BufferPool * pool)
590 {
591   GstBufferPoolAcquireParams params = { 0 };
592   GstBuffer *buffer = NULL;
593   GstFlowReturn ret;
594
595   GST_DEBUG_OBJECT (pool, "A buffer was lost, reallocating it");
596
597   params.flags =
598       (GstBufferPoolAcquireFlags) GST_V4L2_POOL_ACQUIRE_FLAG_RESURECT;
599   ret =
600       gst_buffer_pool_acquire_buffer (GST_BUFFER_POOL (pool), &buffer, &params);
601
602   if (ret == GST_FLOW_OK)
603     gst_buffer_unref (buffer);
604 }
605
606 static gboolean
607 gst_v4l2_buffer_pool_start (GstBufferPool * bpool)
608 {
609   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
610   GstBufferPoolClass *pclass = GST_BUFFER_POOL_CLASS (parent_class);
611   GstV4l2Object *obj = pool->obj;
612   GstStructure *config;
613   GstCaps *caps;
614   guint size, min_buffers, max_buffers;
615   guint max_latency, min_latency, copy_threshold = 0;
616   gboolean can_allocate = FALSE;
617
618   GST_DEBUG_OBJECT (pool, "activating pool");
619
620   config = gst_buffer_pool_get_config (bpool);
621   if (!gst_buffer_pool_config_get_params (config, &caps, &size, &min_buffers,
622           &max_buffers))
623     goto wrong_config;
624
625   /* TODO Also consider min_buffers_for_output when implemented */
626   min_latency = MAX (GST_V4L2_MIN_BUFFERS, obj->min_buffers_for_capture);
627
628   switch (obj->mode) {
629     case GST_V4L2_IO_RW:
630       can_allocate = TRUE;
631       break;
632     case GST_V4L2_IO_DMABUF:
633     case GST_V4L2_IO_MMAP:
634     {
635       guint count;
636
637       can_allocate = GST_V4L2_ALLOCATOR_CAN_ALLOCATE (pool->vallocator, MMAP);
638
639       /* first, lets request buffers, and see how many we can get: */
640       GST_DEBUG_OBJECT (pool, "requesting %d MMAP buffers", min_buffers);
641
642       count = gst_v4l2_allocator_start (pool->vallocator, min_buffers,
643           V4L2_MEMORY_MMAP);
644
645       if (count < GST_V4L2_MIN_BUFFERS) {
646         min_buffers = count;
647         goto no_buffers;
648       }
649
650       /* V4L2 buffer pool are often very limited in the amount of buffers it
651        * can offer. The copy_threshold will workaround this limitation by
652        * falling back to copy if the pipeline needed more buffers. This also
653        * prevent having to do REQBUFS(N)/REQBUFS(0) everytime configure is
654        * called. */
655       if (count != min_buffers) {
656         GST_WARNING_OBJECT (pool, "using %u buffers instead of %u",
657             count, min_buffers);
658         min_buffers = count;
659         copy_threshold = min_latency;
660
661         /* The initial minimum could be provide either by GstBufferPool or
662          * driver needs. */
663         min_buffers = count;
664       }
665
666       break;
667     }
668     case GST_V4L2_IO_USERPTR:
669     {
670       guint count;
671
672       can_allocate =
673           GST_V4L2_ALLOCATOR_CAN_ALLOCATE (pool->vallocator, USERPTR);
674
675       GST_DEBUG_OBJECT (pool, "requesting %d USERPTR buffers", min_buffers);
676
677       count = gst_v4l2_allocator_start (pool->vallocator, min_buffers,
678           V4L2_MEMORY_USERPTR);
679
680       /* There is no rational to not get what we asked */
681       if (count < min_buffers) {
682         min_buffers = count;
683         goto no_buffers;
684       }
685
686       min_buffers = count;
687       break;
688     }
689     case GST_V4L2_IO_DMABUF_IMPORT:
690     {
691       guint count;
692
693       can_allocate = GST_V4L2_ALLOCATOR_CAN_ALLOCATE (pool->vallocator, DMABUF);
694
695       GST_DEBUG_OBJECT (pool, "requesting %d DMABUF buffers", min_buffers);
696
697       count = gst_v4l2_allocator_start (pool->vallocator, min_buffers,
698           V4L2_MEMORY_DMABUF);
699
700       /* There is no rational to not get what we asked */
701       if (count < min_buffers) {
702         min_buffers = count;
703         goto no_buffers;
704       }
705
706       min_buffers = count;
707       break;
708     }
709     default:
710       min_buffers = 0;
711       copy_threshold = 0;
712       g_assert_not_reached ();
713       break;
714   }
715
716   if (can_allocate)
717     max_latency = max_buffers;
718   else
719     max_latency = min_buffers;
720
721   /* FIXME Encoder don't negotiate amount of buffers. If we can't grow the
722    * pool, or the minimum is at V4L2 maximum, enabled copy on threshold
723    * https://bugzilla.gnome.org/show_bug.cgi?id=732288 */
724   if (!can_allocate || min_buffers == VIDEO_MAX_FRAME)
725     copy_threshold = min_latency;
726
727   pool->size = size;
728   pool->copy_threshold = copy_threshold;
729   pool->max_latency = max_latency;
730   pool->min_latency = min_latency;
731   pool->num_queued = 0;
732
733   if (max_buffers < min_buffers)
734     max_buffers = min_buffers;
735
736   gst_buffer_pool_config_set_params (config, caps, size, min_buffers,
737       max_buffers);
738   pclass->set_config (bpool, config);
739   gst_structure_free (config);
740
741   if (pool->other_pool)
742     if (!gst_buffer_pool_set_active (pool->other_pool, TRUE))
743       goto other_pool_failed;
744
745   /* now, allocate the buffers: */
746   if (!pclass->start (bpool))
747     goto start_failed;
748
749   if (!V4L2_TYPE_IS_OUTPUT (obj->type))
750     pool->group_released_handler =
751         g_signal_connect_swapped (pool->vallocator, "group-released",
752         G_CALLBACK (gst_v4l2_buffer_pool_group_released), pool);
753
754   return TRUE;
755
756   /* ERRORS */
757 wrong_config:
758   {
759     GST_ERROR_OBJECT (pool, "invalid config %" GST_PTR_FORMAT, config);
760     gst_structure_free (config);
761     return FALSE;
762   }
763 no_buffers:
764   {
765     GST_ERROR_OBJECT (pool,
766         "we received %d buffer from device '%s', we want at least %d",
767         min_buffers, obj->videodev, GST_V4L2_MIN_BUFFERS);
768     gst_structure_free (config);
769     return FALSE;
770   }
771 start_failed:
772   {
773     GST_ERROR_OBJECT (pool, "failed to start streaming");
774     return FALSE;
775   }
776 other_pool_failed:
777   {
778     GST_ERROR_OBJECT (pool, "failed to active the other pool %"
779         GST_PTR_FORMAT, pool->other_pool);
780     return FALSE;
781   }
782 }
783
784 static gboolean
785 gst_v4l2_buffer_pool_stop (GstBufferPool * bpool)
786 {
787   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
788   GstBufferPoolClass *pclass = GST_BUFFER_POOL_CLASS (parent_class);
789   gboolean ret;
790   gint i;
791
792   GST_DEBUG_OBJECT (pool, "stopping pool");
793
794   if (pool->group_released_handler > 0) {
795     g_signal_handler_disconnect (pool->vallocator,
796         pool->group_released_handler);
797     pool->group_released_handler = 0;
798   }
799
800   if (pool->other_pool) {
801     gst_object_unref (pool->other_pool);
802     pool->other_pool = NULL;
803   }
804
805   if (!gst_v4l2_buffer_pool_streamoff (pool))
806     goto streamoff_failed;
807
808   gst_v4l2_allocator_flush (pool->vallocator);
809
810   for (i = 0; i < VIDEO_MAX_FRAME; i++) {
811     if (pool->buffers[i]) {
812       GstBuffer *buffer = pool->buffers[i];
813
814       pool->buffers[i] = NULL;
815
816       if (V4L2_TYPE_IS_OUTPUT (pool->obj->type))
817         gst_buffer_unref (buffer);
818       else
819         pclass->release_buffer (bpool, buffer);
820
821       g_atomic_int_add (&pool->num_queued, -1);
822     }
823   }
824
825   ret = GST_BUFFER_POOL_CLASS (parent_class)->stop (bpool);
826
827   if (ret) {
828     GstV4l2Return vret;
829
830     vret = gst_v4l2_allocator_stop (pool->vallocator);
831
832     if (vret == GST_V4L2_BUSY)
833       GST_WARNING_OBJECT (pool, "some buffers are still outstanding");
834
835     ret = (vret == GST_V4L2_OK);
836   }
837
838   return ret;
839
840   /* ERRORS */
841 streamoff_failed:
842   GST_ERROR_OBJECT (pool, "device refused to stop streaming");
843   return FALSE;
844 }
845
846 static void
847 gst_v4l2_buffer_pool_flush_start (GstBufferPool * bpool)
848 {
849   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
850
851   GST_DEBUG_OBJECT (pool, "start flushing");
852
853   gst_poll_set_flushing (pool->poll, TRUE);
854
855   GST_OBJECT_LOCK (pool);
856   pool->empty = FALSE;
857   g_cond_broadcast (&pool->empty_cond);
858   GST_OBJECT_UNLOCK (pool);
859
860   if (pool->other_pool)
861     gst_buffer_pool_set_flushing (pool->other_pool, TRUE);
862 }
863
864 static void
865 gst_v4l2_buffer_pool_flush_stop (GstBufferPool * bpool)
866 {
867   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
868   GstV4l2Object *obj = pool->obj;
869   gint i;
870
871   GST_DEBUG_OBJECT (pool, "stop flushing");
872
873   /* If we haven't started streaming yet, simply call streamon */
874   if (!pool->streaming)
875     goto streamon;
876
877   if (pool->other_pool)
878     gst_buffer_pool_set_flushing (pool->other_pool, FALSE);
879
880   if (!gst_v4l2_buffer_pool_streamoff (pool))
881     goto stop_failed;
882
883   gst_v4l2_allocator_flush (pool->vallocator);
884
885   /* Reset our state */
886   switch (obj->mode) {
887     case GST_V4L2_IO_RW:
888       break;
889     case GST_V4L2_IO_MMAP:
890     case GST_V4L2_IO_USERPTR:
891     case GST_V4L2_IO_DMABUF:
892     case GST_V4L2_IO_DMABUF_IMPORT:
893     {
894       gsize num_allocated;
895
896       num_allocated = gst_v4l2_allocator_num_allocated (pool->vallocator);
897
898       for (i = 0; i < num_allocated; i++) {
899         /* Re-enqueue buffers */
900         if (pool->buffers[i]) {
901           GstBufferPool *bpool = (GstBufferPool *) pool;
902           GstBuffer *buffer = pool->buffers[i];
903
904           pool->buffers[i] = NULL;
905
906           /* Remove qdata, this will unmap any map data in
907            * userptr/dmabuf-import */
908           gst_mini_object_set_qdata (GST_MINI_OBJECT (buffer),
909               GST_V4L2_IMPORT_QUARK, NULL, NULL);
910
911           if (V4L2_TYPE_IS_OUTPUT (obj->type))
912             gst_buffer_unref (buffer);
913           else
914             gst_v4l2_buffer_pool_release_buffer (bpool, buffer);
915
916           g_atomic_int_add (&pool->num_queued, -1);
917         }
918       }
919
920       break;
921     }
922     default:
923       g_assert_not_reached ();
924       break;
925   }
926
927 streamon:
928   /* Start streaming on capture device only */
929   if (!V4L2_TYPE_IS_OUTPUT (obj->type))
930     gst_v4l2_buffer_pool_streamon (pool);
931
932   gst_poll_set_flushing (pool->poll, FALSE);
933
934   return;
935
936   /* ERRORS */
937 stop_failed:
938   {
939     GST_ERROR_OBJECT (pool, "device refused to flush");
940   }
941 }
942
943 static GstFlowReturn
944 gst_v4l2_buffer_pool_poll (GstV4l2BufferPool * pool)
945 {
946   gint ret;
947
948   GST_OBJECT_LOCK (pool);
949   while (pool->empty)
950     g_cond_wait (&pool->empty_cond, GST_OBJECT_GET_LOCK (pool));
951   GST_OBJECT_UNLOCK (pool);
952
953   if (!pool->can_poll_device)
954     goto done;
955
956   GST_LOG_OBJECT (pool, "polling device");
957
958 again:
959   ret = gst_poll_wait (pool->poll, GST_CLOCK_TIME_NONE);
960   if (G_UNLIKELY (ret < 0)) {
961     switch (errno) {
962       case EBUSY:
963         goto stopped;
964       case EAGAIN:
965       case EINTR:
966         goto again;
967       case ENXIO:
968         GST_WARNING_OBJECT (pool,
969             "v4l2 device doesn't support polling. Disabling"
970             " using libv4l2 in this case may cause deadlocks");
971         pool->can_poll_device = FALSE;
972         goto done;
973       default:
974         goto select_error;
975     }
976   }
977
978   if (gst_poll_fd_has_error (pool->poll, &pool->pollfd))
979     goto select_error;
980
981 done:
982   return GST_FLOW_OK;
983
984   /* ERRORS */
985 stopped:
986   {
987     GST_DEBUG_OBJECT (pool, "stop called");
988     return GST_FLOW_FLUSHING;
989   }
990 select_error:
991   {
992     GST_ELEMENT_ERROR (pool->obj->element, RESOURCE, READ, (NULL),
993         ("poll error %d: %s (%d)", ret, g_strerror (errno), errno));
994     return GST_FLOW_ERROR;
995   }
996 }
997
998 static GstFlowReturn
999 gst_v4l2_buffer_pool_qbuf (GstV4l2BufferPool * pool, GstBuffer * buf)
1000 {
1001   GstV4l2MemoryGroup *group = NULL;
1002   gint index;
1003
1004   if (!gst_v4l2_is_buffer_valid (buf, &group)) {
1005     GST_LOG_OBJECT (pool, "unref copied/invalid buffer %p", buf);
1006     gst_buffer_unref (buf);
1007     return GST_FLOW_OK;
1008   }
1009
1010   index = group->buffer.index;
1011
1012   if (pool->buffers[index] != NULL)
1013     goto already_queued;
1014
1015   GST_LOG_OBJECT (pool, "queuing buffer %i", index);
1016
1017   g_atomic_int_inc (&pool->num_queued);
1018   pool->buffers[index] = buf;
1019
1020   if (!gst_v4l2_allocator_qbuf (pool->vallocator, group))
1021     goto queue_failed;
1022
1023   GST_OBJECT_LOCK (pool);
1024   pool->empty = FALSE;
1025   g_cond_signal (&pool->empty_cond);
1026   GST_OBJECT_UNLOCK (pool);
1027
1028   return GST_FLOW_OK;
1029
1030 already_queued:
1031   {
1032     GST_ERROR_OBJECT (pool, "the buffer %i was already queued", index);
1033     return GST_FLOW_ERROR;
1034   }
1035 queue_failed:
1036   {
1037     GST_ERROR_OBJECT (pool, "could not queue a buffer %i", index);
1038     /* Mark broken buffer to the allocator */
1039     GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_TAG_MEMORY);
1040     g_atomic_int_add (&pool->num_queued, -1);
1041     pool->buffers[index] = NULL;
1042     return GST_FLOW_ERROR;
1043   }
1044 }
1045
1046 static GstFlowReturn
1047 gst_v4l2_buffer_pool_dqbuf (GstV4l2BufferPool * pool, GstBuffer ** buffer)
1048 {
1049   GstFlowReturn res;
1050   GstBuffer *outbuf;
1051   GstV4l2Object *obj = pool->obj;
1052   GstClockTime timestamp;
1053   GstV4l2MemoryGroup *group;
1054   gint i;
1055
1056   if ((res = gst_v4l2_buffer_pool_poll (pool)) != GST_FLOW_OK)
1057     goto poll_failed;
1058
1059   GST_LOG_OBJECT (pool, "dequeueing a buffer");
1060
1061   group = gst_v4l2_allocator_dqbuf (pool->vallocator);
1062   if (group == NULL)
1063     goto dqbuf_failed;
1064
1065   /* get our GstBuffer with that index from the pool, if the buffer was
1066    * outstanding we have a serious problem.
1067    */
1068   outbuf = pool->buffers[group->buffer.index];
1069   if (outbuf == NULL)
1070     goto no_buffer;
1071
1072   /* mark the buffer outstanding */
1073   pool->buffers[group->buffer.index] = NULL;
1074   if (g_atomic_int_dec_and_test (&pool->num_queued)) {
1075     GST_OBJECT_LOCK (pool);
1076     pool->empty = TRUE;
1077     GST_OBJECT_UNLOCK (pool);
1078   }
1079
1080   timestamp = GST_TIMEVAL_TO_TIME (group->buffer.timestamp);
1081
1082 #ifndef GST_DISABLE_GST_DEBUG
1083   for (i = 0; i < group->n_mem; i++) {
1084     GST_LOG_OBJECT (pool,
1085         "dequeued buffer %p seq:%d (ix=%d), mem %p used %d, plane=%d, flags %08x, ts %"
1086         GST_TIME_FORMAT ", pool-queued=%d, buffer=%p", outbuf,
1087         group->buffer.sequence, group->buffer.index, group->mem[i],
1088         group->planes[i].bytesused, i, group->buffer.flags,
1089         GST_TIME_ARGS (timestamp), pool->num_queued, outbuf);
1090   }
1091 #endif
1092
1093   /* set top/bottom field first if v4l2_buffer has the information */
1094   if (group->buffer.field == V4L2_FIELD_INTERLACED_TB) {
1095     GST_BUFFER_FLAG_SET (outbuf, GST_VIDEO_BUFFER_FLAG_INTERLACED);
1096     GST_BUFFER_FLAG_SET (outbuf, GST_VIDEO_BUFFER_FLAG_TFF);
1097   } else if (group->buffer.field == V4L2_FIELD_INTERLACED_BT) {
1098     GST_BUFFER_FLAG_SET (outbuf, GST_VIDEO_BUFFER_FLAG_INTERLACED);
1099     GST_BUFFER_FLAG_UNSET (outbuf, GST_VIDEO_BUFFER_FLAG_TFF);
1100   } else {
1101     GST_BUFFER_FLAG_UNSET (outbuf, GST_VIDEO_BUFFER_FLAG_INTERLACED);
1102     GST_BUFFER_FLAG_UNSET (outbuf, GST_VIDEO_BUFFER_FLAG_TFF);
1103   }
1104
1105   if (GST_VIDEO_INFO_FORMAT (&obj->info) == GST_VIDEO_FORMAT_ENCODED) {
1106     if (group->buffer.flags & V4L2_BUF_FLAG_KEYFRAME)
1107       GST_BUFFER_FLAG_UNSET (outbuf, GST_BUFFER_FLAG_DELTA_UNIT);
1108     else
1109       GST_BUFFER_FLAG_SET (outbuf, GST_BUFFER_FLAG_DELTA_UNIT);
1110   }
1111
1112   GST_BUFFER_TIMESTAMP (outbuf) = timestamp;
1113
1114   *buffer = outbuf;
1115
1116   return GST_FLOW_OK;
1117
1118   /* ERRORS */
1119 poll_failed:
1120   {
1121     GST_DEBUG_OBJECT (pool, "poll error %s", gst_flow_get_name (res));
1122     return res;
1123   }
1124 dqbuf_failed:
1125   {
1126     return GST_FLOW_ERROR;
1127   }
1128 no_buffer:
1129   {
1130     GST_ERROR_OBJECT (pool, "No free buffer found in the pool at index %d.",
1131         group->buffer.index);
1132     return GST_FLOW_ERROR;
1133   }
1134 }
1135
1136 static GstFlowReturn
1137 gst_v4l2_buffer_pool_acquire_buffer (GstBufferPool * bpool, GstBuffer ** buffer,
1138     GstBufferPoolAcquireParams * params)
1139 {
1140   GstFlowReturn ret;
1141   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
1142   GstBufferPoolClass *pclass = GST_BUFFER_POOL_CLASS (parent_class);
1143   GstV4l2Object *obj = pool->obj;
1144
1145   GST_DEBUG_OBJECT (pool, "acquire");
1146
1147   /* If this is being called to resurect a lost buffer */
1148   if (params && params->flags & GST_V4L2_POOL_ACQUIRE_FLAG_RESURECT) {
1149     ret = pclass->acquire_buffer (bpool, buffer, params);
1150     goto done;
1151   }
1152
1153   switch (obj->type) {
1154     case V4L2_BUF_TYPE_VIDEO_CAPTURE:
1155     case V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE:
1156       /* capture, This function should return a buffer with new captured data */
1157       switch (obj->mode) {
1158         case GST_V4L2_IO_RW:
1159         {
1160           /* take empty buffer from the pool */
1161           ret = pclass->acquire_buffer (bpool, buffer, params);
1162           break;
1163         }
1164         case GST_V4L2_IO_DMABUF:
1165         case GST_V4L2_IO_MMAP:
1166         {
1167           /* just dequeue a buffer, we basically use the queue of v4l2 as the
1168            * storage for our buffers. This function does poll first so we can
1169            * interrupt it fine. */
1170           ret = gst_v4l2_buffer_pool_dqbuf (pool, buffer);
1171           if (G_UNLIKELY (ret != GST_FLOW_OK))
1172             goto done;
1173
1174           /* start copying buffers when we are running low on buffers */
1175           if (g_atomic_int_get (&pool->num_queued) < pool->copy_threshold) {
1176             GstBuffer *copy;
1177
1178             if (GST_V4L2_ALLOCATOR_CAN_ALLOCATE (pool->vallocator, MMAP)) {
1179               if (pclass->acquire_buffer (bpool, &copy, params) == GST_FLOW_OK) {
1180                 gst_v4l2_buffer_pool_release_buffer (bpool, copy);
1181                 break;
1182               }
1183             }
1184
1185             /* copy the buffer */
1186             copy = gst_buffer_copy_region (*buffer,
1187                 GST_BUFFER_COPY_ALL | GST_BUFFER_COPY_DEEP, 0, -1);
1188             GST_LOG_OBJECT (pool, "copy buffer %p->%p", *buffer, copy);
1189
1190             /* and requeue so that we can continue capturing */
1191             gst_v4l2_buffer_pool_release_buffer (bpool, *buffer);
1192             *buffer = copy;
1193           }
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_finalize (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->video_fd >= 0)
1359     v4l2_close (pool->video_fd);
1360
1361   gst_poll_free (pool->poll);
1362
1363   if (pool->vallocator)
1364     gst_object_unref (pool->vallocator);
1365
1366   if (pool->allocator)
1367     gst_object_unref (pool->allocator);
1368
1369   if (pool->other_pool)
1370     gst_object_unref (pool->other_pool);
1371
1372   /* FIXME Is this required to keep around ? */
1373   gst_object_unref (pool->obj->element);
1374
1375   /* FIXME have we done enough here ? */
1376
1377   G_OBJECT_CLASS (parent_class)->finalize (object);
1378 }
1379
1380 static void
1381 gst_v4l2_buffer_pool_init (GstV4l2BufferPool * pool)
1382 {
1383   pool->poll = gst_poll_new (TRUE);
1384   pool->can_poll_device = TRUE;
1385   g_cond_init (&pool->empty_cond);
1386   pool->empty = TRUE;
1387 }
1388
1389 static void
1390 gst_v4l2_buffer_pool_class_init (GstV4l2BufferPoolClass * klass)
1391 {
1392   GObjectClass *object_class = G_OBJECT_CLASS (klass);
1393   GstBufferPoolClass *bufferpool_class = GST_BUFFER_POOL_CLASS (klass);
1394
1395   object_class->finalize = gst_v4l2_buffer_pool_finalize;
1396
1397   bufferpool_class->start = gst_v4l2_buffer_pool_start;
1398   bufferpool_class->stop = gst_v4l2_buffer_pool_stop;
1399   bufferpool_class->set_config = gst_v4l2_buffer_pool_set_config;
1400   bufferpool_class->alloc_buffer = gst_v4l2_buffer_pool_alloc_buffer;
1401   bufferpool_class->acquire_buffer = gst_v4l2_buffer_pool_acquire_buffer;
1402   bufferpool_class->release_buffer = gst_v4l2_buffer_pool_release_buffer;
1403   bufferpool_class->flush_start = gst_v4l2_buffer_pool_flush_start;
1404   bufferpool_class->flush_stop = gst_v4l2_buffer_pool_flush_stop;
1405 }
1406
1407 /**
1408  * gst_v4l2_buffer_pool_new:
1409  * @obj:  the v4l2 object owning the pool
1410  *
1411  * Construct a new buffer pool.
1412  *
1413  * Returns: the new pool, use gst_object_unref() to free resources
1414  */
1415 GstBufferPool *
1416 gst_v4l2_buffer_pool_new (GstV4l2Object * obj, GstCaps * caps)
1417 {
1418   GstV4l2BufferPool *pool;
1419   GstStructure *config;
1420   gchar *name, *parent_name;
1421   gint fd;
1422
1423   fd = v4l2_dup (obj->video_fd);
1424   if (fd < 0)
1425     goto dup_failed;
1426
1427   /* setting a significant unique name */
1428   parent_name = gst_object_get_name (GST_OBJECT (obj->element));
1429   name = g_strconcat (parent_name, ":", "pool:",
1430       V4L2_TYPE_IS_OUTPUT (obj->type) ? "sink" : "src", NULL);
1431   g_free (parent_name);
1432
1433   pool = (GstV4l2BufferPool *) g_object_new (GST_TYPE_V4L2_BUFFER_POOL,
1434       "name", name, NULL);
1435   g_free (name);
1436
1437   gst_poll_fd_init (&pool->pollfd);
1438   pool->pollfd.fd = fd;
1439   gst_poll_add_fd (pool->poll, &pool->pollfd);
1440   if (V4L2_TYPE_IS_OUTPUT (obj->type))
1441     gst_poll_fd_ctl_write (pool->poll, &pool->pollfd, TRUE);
1442   else
1443     gst_poll_fd_ctl_read (pool->poll, &pool->pollfd, TRUE);
1444
1445   pool->video_fd = fd;
1446   pool->obj = obj;
1447   pool->can_poll_device = TRUE;
1448
1449   pool->vallocator =
1450       gst_v4l2_allocator_new (GST_OBJECT (pool), obj->video_fd, &obj->format);
1451   if (pool->vallocator == NULL)
1452     goto allocator_failed;
1453
1454   gst_object_ref (obj->element);
1455
1456   config = gst_buffer_pool_get_config (GST_BUFFER_POOL_CAST (pool));
1457   gst_buffer_pool_config_set_params (config, caps, obj->info.size, 0, 0);
1458   /* This will simply set a default config, but will not configure the pool
1459    * because min and max are not valid */
1460   gst_buffer_pool_set_config (GST_BUFFER_POOL_CAST (pool), config);
1461
1462   return GST_BUFFER_POOL (pool);
1463
1464   /* ERRORS */
1465 dup_failed:
1466   {
1467     GST_ERROR ("failed to dup fd %d (%s)", errno, g_strerror (errno));
1468     return NULL;
1469   }
1470 allocator_failed:
1471   {
1472     GST_ERROR_OBJECT (pool, "Failed to create V4L2 allocator");
1473     return NULL;
1474   }
1475 }
1476
1477 static GstFlowReturn
1478 gst_v4l2_do_read (GstV4l2BufferPool * pool, GstBuffer * buf)
1479 {
1480   GstFlowReturn res;
1481   GstV4l2Object *obj = pool->obj;
1482   gint amount;
1483   GstMapInfo map;
1484   gint toread;
1485
1486   toread = obj->info.size;
1487
1488   GST_LOG_OBJECT (pool, "reading %d bytes into buffer %p", toread, buf);
1489
1490   gst_buffer_map (buf, &map, GST_MAP_WRITE);
1491
1492   do {
1493     if ((res = gst_v4l2_buffer_pool_poll (pool)) != GST_FLOW_OK)
1494       goto poll_error;
1495
1496     amount = v4l2_read (obj->video_fd, map.data, toread);
1497
1498     if (amount == toread) {
1499       break;
1500     } else if (amount == -1) {
1501       if (errno == EAGAIN || errno == EINTR) {
1502         continue;
1503       } else
1504         goto read_error;
1505     } else {
1506       /* short reads can happen if a signal interrupts the read */
1507       continue;
1508     }
1509   } while (TRUE);
1510
1511   GST_LOG_OBJECT (pool, "read %d bytes", amount);
1512   gst_buffer_unmap (buf, &map);
1513   gst_buffer_resize (buf, 0, amount);
1514
1515   return GST_FLOW_OK;
1516
1517   /* ERRORS */
1518 poll_error:
1519   {
1520     GST_DEBUG ("poll error %s", gst_flow_get_name (res));
1521     goto cleanup;
1522   }
1523 read_error:
1524   {
1525     GST_ELEMENT_ERROR (obj->element, RESOURCE, READ,
1526         (_("Error reading %d bytes from device '%s'."),
1527             toread, obj->videodev), GST_ERROR_SYSTEM);
1528     res = GST_FLOW_ERROR;
1529     goto cleanup;
1530   }
1531 cleanup:
1532   {
1533     gst_buffer_unmap (buf, &map);
1534     gst_buffer_resize (buf, 0, 0);
1535     return res;
1536   }
1537 }
1538
1539 /**
1540  * gst_v4l2_buffer_pool_process:
1541  * @bpool: a #GstBufferPool
1542  * @buf: a #GstBuffer, maybe be replaced
1543  *
1544  * Process @buf in @bpool. For capture devices, this functions fills @buf with
1545  * data from the device. For output devices, this functions send the contents of
1546  * @buf to the device for playback.
1547  *
1548  * Returns: %GST_FLOW_OK on success.
1549  */
1550 GstFlowReturn
1551 gst_v4l2_buffer_pool_process (GstV4l2BufferPool * pool, GstBuffer ** buf)
1552 {
1553   GstFlowReturn ret = GST_FLOW_OK;
1554   GstBufferPool *bpool = GST_BUFFER_POOL_CAST (pool);
1555   GstV4l2Object *obj = pool->obj;
1556
1557   GST_DEBUG_OBJECT (pool, "process buffer %p", buf);
1558
1559   g_return_val_if_fail (gst_buffer_pool_is_active (bpool), GST_FLOW_ERROR);
1560
1561   if (GST_BUFFER_POOL_IS_FLUSHING (pool))
1562     return GST_FLOW_FLUSHING;
1563
1564   switch (obj->type) {
1565     case V4L2_BUF_TYPE_VIDEO_CAPTURE:
1566     case V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE:
1567       /* capture */
1568       switch (obj->mode) {
1569         case GST_V4L2_IO_RW:
1570           /* capture into the buffer */
1571           ret = gst_v4l2_do_read (pool, *buf);
1572           break;
1573
1574         case GST_V4L2_IO_MMAP:
1575         case GST_V4L2_IO_DMABUF:
1576         {
1577           GstBuffer *tmp;
1578
1579           if ((*buf)->pool == bpool) {
1580             if (gst_buffer_get_size (*buf) == 0)
1581               goto eos;
1582             else
1583               /* nothing, data was inside the buffer when we did _acquire() */
1584               goto done;
1585           }
1586
1587           /* buffer not from our pool, grab a frame and copy it into the target */
1588           if ((ret = gst_v4l2_buffer_pool_dqbuf (pool, &tmp)) != GST_FLOW_OK)
1589             goto done;
1590
1591           /* An empty buffer on capture indicates the end of stream */
1592           if (gst_buffer_get_size (tmp) == 0) {
1593             gst_v4l2_buffer_pool_release_buffer (bpool, tmp);
1594             goto eos;
1595           }
1596
1597           ret = gst_v4l2_buffer_pool_copy_buffer (pool, *buf, tmp);
1598
1599           /* an queue the buffer again after the copy */
1600           gst_v4l2_buffer_pool_release_buffer (bpool, tmp);
1601
1602           if (ret != GST_FLOW_OK)
1603             goto copy_failed;
1604           break;
1605         }
1606
1607         case GST_V4L2_IO_USERPTR:
1608         {
1609           struct UserPtrData *data;
1610
1611           /* Replace our buffer with downstream allocated buffer */
1612           data = gst_mini_object_steal_qdata (GST_MINI_OBJECT (*buf),
1613               GST_V4L2_IMPORT_QUARK);
1614           gst_buffer_replace (buf, data->buffer);
1615           _unmap_userptr_frame (data);
1616           break;
1617         }
1618
1619         case GST_V4L2_IO_DMABUF_IMPORT:
1620         {
1621           GstBuffer *tmp;
1622
1623           /* Replace our buffer with downstream allocated buffer */
1624           tmp = gst_mini_object_steal_qdata (GST_MINI_OBJECT (*buf),
1625               GST_V4L2_IMPORT_QUARK);
1626           gst_buffer_replace (buf, tmp);
1627           gst_buffer_unref (tmp);
1628           break;
1629         }
1630
1631         default:
1632           g_assert_not_reached ();
1633           break;
1634       }
1635       break;
1636
1637     case V4L2_BUF_TYPE_VIDEO_OUTPUT:
1638     case V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE:
1639       /* playback */
1640       switch (obj->mode) {
1641         case GST_V4L2_IO_RW:
1642           /* FIXME, do write() */
1643           GST_WARNING_OBJECT (pool, "implement write()");
1644           break;
1645
1646         case GST_V4L2_IO_USERPTR:
1647         case GST_V4L2_IO_DMABUF_IMPORT:
1648         case GST_V4L2_IO_DMABUF:
1649         case GST_V4L2_IO_MMAP:
1650         {
1651           GstBuffer *to_queue = NULL;
1652           GstV4l2MemoryGroup *group;
1653           gint index;
1654
1655           if ((*buf)->pool != bpool)
1656             goto copying;
1657
1658           if (!gst_v4l2_is_buffer_valid (*buf, &group))
1659             goto copying;
1660
1661           index = group->buffer.index;
1662
1663           GST_LOG_OBJECT (pool, "processing buffer %i from our pool", index);
1664
1665           index = group->buffer.index;
1666           if (pool->buffers[index] != NULL) {
1667             GST_LOG_OBJECT (pool, "buffer %i already queued, copying", index);
1668             goto copying;
1669           }
1670
1671           /* we can queue directly */
1672           to_queue = gst_buffer_ref (*buf);
1673
1674         copying:
1675           if (to_queue == NULL) {
1676             GstBufferPoolAcquireParams params = { 0 };
1677
1678             GST_LOG_OBJECT (pool, "alloc buffer from our pool");
1679
1680             /* this can return EOS if all buffers are outstanding which would
1681              * be strange because we would expect the upstream element to have
1682              * allocated them and returned to us.. */
1683             params.flags = GST_BUFFER_POOL_ACQUIRE_FLAG_DONTWAIT;
1684             ret = gst_buffer_pool_acquire_buffer (bpool, &to_queue, &params);
1685             if (ret != GST_FLOW_OK)
1686               goto acquire_failed;
1687
1688             ret = gst_v4l2_buffer_pool_prepare_buffer (pool, to_queue, *buf);
1689             if (ret != GST_FLOW_OK) {
1690               gst_buffer_unref (to_queue);
1691               goto prepare_failed;
1692             }
1693           }
1694
1695           if ((ret = gst_v4l2_buffer_pool_qbuf (pool, to_queue)) != GST_FLOW_OK)
1696             goto queue_failed;
1697
1698           /* if we are not streaming yet (this is the first buffer, start
1699            * streaming now */
1700           if (!gst_v4l2_buffer_pool_streamon (pool)) {
1701             gst_buffer_unref (to_queue);
1702             goto start_failed;
1703           }
1704
1705           if (g_atomic_int_get (&pool->num_queued) >= pool->min_latency) {
1706             GstBuffer *out;
1707             /* all buffers are queued, try to dequeue one and release it back
1708              * into the pool so that _acquire can get to it again. */
1709             ret = gst_v4l2_buffer_pool_dqbuf (pool, &out);
1710             if (ret == GST_FLOW_OK)
1711               /* release the rendered buffer back into the pool. This wakes up any
1712                * thread waiting for a buffer in _acquire(). */
1713               gst_buffer_unref (out);
1714           }
1715           break;
1716         }
1717         default:
1718           g_assert_not_reached ();
1719           break;
1720       }
1721       break;
1722     default:
1723       g_assert_not_reached ();
1724       break;
1725   }
1726 done:
1727   return ret;
1728
1729   /* ERRORS */
1730 copy_failed:
1731   {
1732     GST_ERROR_OBJECT (pool, "failed to copy buffer");
1733     return ret;
1734   }
1735 eos:
1736   {
1737     GST_DEBUG_OBJECT (pool, "end of stream reached");
1738     return GST_FLOW_EOS;
1739   }
1740 acquire_failed:
1741   {
1742     if (ret == GST_FLOW_FLUSHING)
1743       GST_DEBUG_OBJECT (pool, "flushing");
1744     else
1745       GST_WARNING_OBJECT (pool, "failed to acquire a buffer: %s",
1746           gst_flow_get_name (ret));
1747     return ret;
1748   }
1749 prepare_failed:
1750   {
1751     GST_ERROR_OBJECT (pool, "failed to prepare data");
1752     return ret;
1753   }
1754 queue_failed:
1755   {
1756     GST_ERROR_OBJECT (pool, "failed to queue buffer");
1757     return ret;
1758   }
1759 start_failed:
1760   {
1761     GST_ERROR_OBJECT (pool, "failed to start streaming");
1762     return GST_FLOW_ERROR;
1763   }
1764 }
1765
1766 void
1767 gst_v4l2_buffer_pool_set_other_pool (GstV4l2BufferPool * pool,
1768     GstBufferPool * other_pool)
1769 {
1770   g_return_if_fail (!gst_buffer_pool_is_active (GST_BUFFER_POOL (pool)));
1771
1772   if (pool->other_pool)
1773     gst_object_unref (pool->other_pool);
1774   pool->other_pool = gst_object_ref (other_pool);
1775 }