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