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