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