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