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