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