v4l2: bufferpool: reset buffer size in release_buffer
[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 #include <sys/mman.h>
30 #include <string.h>
31 #include <unistd.h>
32 #if HAVE_DECL_V4L2_MEMORY_DMABUF
33 #include <fcntl.h>
34 #endif
35
36 #include "gst/video/video.h"
37 #include "gst/video/gstvideometa.h"
38 #include "gst/video/gstvideopool.h"
39 #include "gst/allocators/gstdmabuf.h"
40
41 #include <gstv4l2bufferpool.h>
42
43 #include "v4l2_calls.h"
44 #include "gst/gst-i18n-plugin.h"
45 #include <gst/glib-compat-private.h>
46
47 /* videodev2.h is not versioned and we can't easily check for the presence
48  * of enum values at compile time, but the V4L2_CAP_VIDEO_OUTPUT_OVERLAY define
49  * was added in the same commit as V4L2_FIELD_INTERLACED_{TB,BT} (b2787845) */
50 #ifndef V4L2_CAP_VIDEO_OUTPUT_OVERLAY
51 #define V4L2_FIELD_INTERLACED_TB 8
52 #define V4L2_FIELD_INTERLACED_BT 9
53 #endif
54
55
56 GST_DEBUG_CATEGORY_EXTERN (v4l2_debug);
57 #define GST_CAT_DEFAULT v4l2_debug
58
59 /*
60  * GstV4l2Buffer:
61  */
62 GType
63 gst_v4l2_meta_api_get_type (void)
64 {
65   static volatile GType type;
66   static const gchar *tags[] = { "memory", NULL };
67
68   if (g_once_init_enter (&type)) {
69     GType _type = gst_meta_api_type_register ("GstV4l2MetaAPI", tags);
70     g_once_init_leave (&type, _type);
71   }
72   return type;
73 }
74
75 const GstMetaInfo *
76 gst_v4l2_meta_get_info (void)
77 {
78   static const GstMetaInfo *meta_info = NULL;
79
80   if (g_once_init_enter (&meta_info)) {
81     const GstMetaInfo *meta =
82         gst_meta_register (gst_v4l2_meta_api_get_type (), "GstV4l2Meta",
83         sizeof (GstV4l2Meta), (GstMetaInitFunction) NULL,
84         (GstMetaFreeFunction) NULL, (GstMetaTransformFunction) NULL);
85     g_once_init_leave (&meta_info, meta);
86   }
87   return meta_info;
88 }
89
90 /*
91  * GstV4l2BufferPool:
92  */
93 #define gst_v4l2_buffer_pool_parent_class parent_class
94 G_DEFINE_TYPE (GstV4l2BufferPool, gst_v4l2_buffer_pool, GST_TYPE_BUFFER_POOL);
95
96 static void gst_v4l2_buffer_pool_release_buffer (GstBufferPool * bpool,
97     GstBuffer * buffer);
98
99 static void
100 gst_v4l2_buffer_pool_free_buffer (GstBufferPool * bpool, GstBuffer * buffer)
101 {
102   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
103   GstV4l2Object *obj;
104
105   obj = pool->obj;
106
107   switch (obj->mode) {
108     case GST_V4L2_IO_RW:
109     case GST_V4L2_IO_DMABUF:
110       break;
111     case GST_V4L2_IO_MMAP:
112     {
113       GstV4l2Meta *meta;
114       gint index;
115
116       meta = GST_V4L2_META_GET (buffer);
117       g_assert (meta != NULL);
118
119       index = meta->vbuffer.index;
120       GST_LOG_OBJECT (pool,
121           "unmap buffer %p idx %d (data %p, len %u)", buffer,
122           index, meta->mem, meta->vbuffer.length);
123
124       v4l2_munmap (meta->mem, meta->vbuffer.length);
125       pool->buffers[index] = NULL;
126       break;
127     }
128     case GST_V4L2_IO_USERPTR:
129     default:
130       g_assert_not_reached ();
131       break;
132   }
133   gst_buffer_unref (buffer);
134 }
135
136 static GstFlowReturn
137 gst_v4l2_buffer_pool_alloc_buffer (GstBufferPool * bpool, GstBuffer ** buffer,
138     GstBufferPoolAcquireParams * params)
139 {
140   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
141   GstBuffer *newbuf;
142   GstV4l2Meta *meta;
143   GstV4l2Object *obj;
144   GstVideoInfo *info;
145   guint index;
146
147   obj = pool->obj;
148   info = &obj->info;
149
150   switch (obj->mode) {
151     case GST_V4L2_IO_RW:
152     {
153       newbuf =
154           gst_buffer_new_allocate (pool->allocator, pool->size, &pool->params);
155       break;
156     }
157     case GST_V4L2_IO_MMAP:
158     case GST_V4L2_IO_DMABUF:
159     {
160       newbuf = gst_buffer_new ();
161       meta = GST_V4L2_META_ADD (newbuf);
162
163       index = pool->num_allocated;
164
165       GST_LOG_OBJECT (pool, "creating buffer %u, %p", index, newbuf);
166
167       meta->vbuffer.index = index;
168       meta->vbuffer.type = obj->type;
169       meta->vbuffer.memory = V4L2_MEMORY_MMAP;
170
171       if (v4l2_ioctl (pool->video_fd, VIDIOC_QUERYBUF, &meta->vbuffer) < 0)
172         goto querybuf_failed;
173
174       GST_LOG_OBJECT (pool, "  index:     %u", meta->vbuffer.index);
175       GST_LOG_OBJECT (pool, "  type:      %d", meta->vbuffer.type);
176       GST_LOG_OBJECT (pool, "  bytesused: %u", meta->vbuffer.bytesused);
177       GST_LOG_OBJECT (pool, "  flags:     %08x", meta->vbuffer.flags);
178       GST_LOG_OBJECT (pool, "  field:     %d", meta->vbuffer.field);
179       GST_LOG_OBJECT (pool, "  memory:    %d", meta->vbuffer.memory);
180       if (meta->vbuffer.memory == V4L2_MEMORY_MMAP)
181         GST_LOG_OBJECT (pool, "  MMAP offset:  %u", meta->vbuffer.m.offset);
182
183       if (obj->mode == GST_V4L2_IO_MMAP) {
184         meta->mem = v4l2_mmap (0, meta->vbuffer.length,
185             PROT_READ | PROT_WRITE, MAP_SHARED, pool->video_fd,
186             meta->vbuffer.m.offset);
187         if (meta->mem == MAP_FAILED)
188           goto mmap_failed;
189
190         gst_buffer_append_memory (newbuf,
191             gst_memory_new_wrapped (GST_MEMORY_FLAG_NO_SHARE,
192                 meta->mem, meta->vbuffer.length, 0, meta->vbuffer.length, NULL,
193                 NULL));
194       }
195 #if HAVE_DECL_V4L2_MEMORY_DMABUF
196       if (obj->mode == GST_V4L2_IO_DMABUF) {
197         struct v4l2_exportbuffer expbuf;
198
199         expbuf.type = meta->vbuffer.type;
200         expbuf.index = meta->vbuffer.index;
201         expbuf.flags = O_CLOEXEC;
202         if (v4l2_ioctl (pool->video_fd, VIDIOC_EXPBUF, &expbuf) < 0)
203           goto mmap_failed;
204
205         meta->vbuffer.memory = V4L2_MEMORY_DMABUF;
206         gst_buffer_append_memory (newbuf,
207             gst_dmabuf_allocator_alloc (pool->allocator, expbuf.fd,
208                 meta->vbuffer.length));
209       }
210 #endif
211       /* add metadata to raw video buffers */
212       if (pool->add_videometa && info->finfo) {
213         const GstVideoFormatInfo *finfo = info->finfo;
214         gsize offset[GST_VIDEO_MAX_PLANES];
215         gint width, height, n_planes, offs, i, stride[GST_VIDEO_MAX_PLANES];
216
217         width = GST_VIDEO_INFO_WIDTH (info);
218         height = GST_VIDEO_INFO_HEIGHT (info);
219         n_planes = GST_VIDEO_INFO_N_PLANES (info);
220
221         GST_DEBUG_OBJECT (pool, "adding video meta, bytesperline %d",
222             obj->bytesperline);
223
224         offs = 0;
225         for (i = 0; i < n_planes; i++) {
226           offset[i] = offs;
227           stride[i] =
228               GST_VIDEO_FORMAT_INFO_SCALE_WIDTH (finfo, i, obj->bytesperline);
229
230           offs +=
231               stride[i] * GST_VIDEO_FORMAT_INFO_SCALE_HEIGHT (finfo, i, height);
232         }
233         gst_buffer_add_video_meta_full (newbuf, GST_VIDEO_FRAME_FLAG_NONE,
234             GST_VIDEO_INFO_FORMAT (info), width, height, n_planes,
235             offset, stride);
236       }
237       break;
238     }
239     case GST_V4L2_IO_USERPTR:
240     default:
241       newbuf = NULL;
242       g_assert_not_reached ();
243   }
244
245   pool->num_allocated++;
246
247   *buffer = newbuf;
248
249   return GST_FLOW_OK;
250
251   /* ERRORS */
252 querybuf_failed:
253   {
254     gint errnosave = errno;
255
256     GST_WARNING ("Failed QUERYBUF: %s", g_strerror (errnosave));
257     gst_buffer_unref (newbuf);
258     errno = errnosave;
259     return GST_FLOW_ERROR;
260   }
261 mmap_failed:
262   {
263     gint errnosave = errno;
264
265     GST_WARNING ("Failed to mmap: %s", g_strerror (errnosave));
266     gst_buffer_unref (newbuf);
267     errno = errnosave;
268     return GST_FLOW_ERROR;
269   }
270 }
271
272 static gboolean
273 gst_v4l2_buffer_pool_set_config (GstBufferPool * bpool, GstStructure * config)
274 {
275   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
276   GstV4l2Object *obj = pool->obj;
277   GstCaps *caps;
278   guint size, min_buffers, max_buffers, num_buffers, copy_threshold;
279   GstAllocator *allocator;
280   GstAllocationParams params;
281   struct v4l2_requestbuffers breq;
282
283   GST_DEBUG_OBJECT (pool, "set config");
284
285   pool->add_videometa =
286       gst_buffer_pool_config_has_option (config,
287       GST_BUFFER_POOL_OPTION_VIDEO_META);
288
289   if (!pool->add_videometa &&
290       GST_VIDEO_INFO_FORMAT (&obj->info) != GST_VIDEO_FORMAT_ENCODED) {
291     gint stride;
292
293     /* we don't have video metadata, and we are not dealing with raw video,
294      * see if the strides are compatible */
295     stride = GST_VIDEO_INFO_PLANE_STRIDE (&obj->info, 0);
296
297     GST_DEBUG_OBJECT (pool, "no videometadata, checking strides %d and %u",
298         stride, obj->bytesperline);
299
300     if (stride != obj->bytesperline)
301       goto missing_video_api;
302   }
303
304   /* parse the config and keep around */
305   if (!gst_buffer_pool_config_get_params (config, &caps, &size, &min_buffers,
306           &max_buffers))
307     goto wrong_config;
308
309   if (!gst_buffer_pool_config_get_allocator (config, &allocator, &params))
310     goto wrong_config;
311
312   GST_DEBUG_OBJECT (pool, "config %" GST_PTR_FORMAT, config);
313
314   switch (obj->mode) {
315     case GST_V4L2_IO_RW:
316       /* we preallocate 1 buffer, this value also instructs the latency
317        * calculation to have 1 frame latency max */
318       num_buffers = 1;
319       copy_threshold = 0;
320       break;
321     case GST_V4L2_IO_DMABUF:
322     case GST_V4L2_IO_MMAP:
323     {
324       /* request a reasonable number of buffers when no max specified. We will
325        * copy when we run out of buffers */
326       if (max_buffers == 0)
327         num_buffers = 4;
328       else
329         num_buffers = max_buffers;
330
331       /* first, lets request buffers, and see how many we can get: */
332       GST_DEBUG_OBJECT (pool, "starting, requesting %d MMAP buffers",
333           num_buffers);
334
335       memset (&breq, 0, sizeof (struct v4l2_requestbuffers));
336       breq.type = obj->type;
337       breq.count = num_buffers;
338       breq.memory = V4L2_MEMORY_MMAP;
339
340       if (v4l2_ioctl (pool->video_fd, VIDIOC_REQBUFS, &breq) < 0)
341         goto reqbufs_failed;
342
343       GST_LOG_OBJECT (pool, " count:  %u", breq.count);
344       GST_LOG_OBJECT (pool, " type:   %d", breq.type);
345       GST_LOG_OBJECT (pool, " memory: %d", breq.memory);
346
347       if (breq.count < GST_V4L2_MIN_BUFFERS)
348         goto no_buffers;
349
350       if (num_buffers != breq.count) {
351         GST_WARNING_OBJECT (pool, "using %u buffers instead", breq.count);
352         num_buffers = breq.count;
353       }
354       /* update min buffers with the amount of buffers we just reserved. We need
355        * to configure this value in the bufferpool so that the default start
356        * implementation calls our allocate function */
357       min_buffers = breq.count;
358
359       if (max_buffers == 0 || num_buffers < max_buffers) {
360         /* if we are asked to provide more buffers than we have allocated, start
361          * copying buffers when we only have 2 buffers left in the pool */
362         copy_threshold = 2;
363       } else {
364         /* we are certain that we have enough buffers so we don't need to
365          * copy */
366         copy_threshold = 0;
367       }
368       break;
369     }
370     case GST_V4L2_IO_USERPTR:
371     default:
372       num_buffers = 0;
373       copy_threshold = 0;
374       g_assert_not_reached ();
375       break;
376   }
377
378   pool->size = size;
379   pool->num_buffers = num_buffers;
380   pool->copy_threshold = copy_threshold;
381
382   if (obj->mode == GST_V4L2_IO_DMABUF)
383     allocator = gst_dmabuf_allocator_obtain ();
384
385   if (pool->allocator)
386     gst_object_unref (pool->allocator);
387   if ((pool->allocator = allocator))
388     gst_object_ref (allocator);
389   pool->params = params;
390
391   gst_buffer_pool_config_set_params (config, caps, size, min_buffers,
392       max_buffers);
393
394   return GST_BUFFER_POOL_CLASS (parent_class)->set_config (bpool, config);
395
396   /* ERRORS */
397 missing_video_api:
398   {
399     GST_ERROR_OBJECT (pool, "missing GstMetaVideo API in config, "
400         "default stride: %d, wanted stride %u",
401         GST_VIDEO_INFO_PLANE_STRIDE (&obj->info, 0), obj->bytesperline);
402     return FALSE;
403   }
404 wrong_config:
405   {
406     GST_ERROR_OBJECT (pool, "invalid config %" GST_PTR_FORMAT, config);
407     return FALSE;
408   }
409 reqbufs_failed:
410   {
411     GST_ERROR_OBJECT (pool,
412         "error requesting %d buffers: %s", num_buffers, g_strerror (errno));
413     return FALSE;
414   }
415 no_buffers:
416   {
417     GST_ERROR_OBJECT (pool,
418         "we received %d from device '%s', we want at least %d",
419         breq.count, obj->videodev, GST_V4L2_MIN_BUFFERS);
420     return FALSE;
421   }
422 }
423
424 static gboolean
425 start_streaming (GstV4l2BufferPool * pool)
426 {
427   GstV4l2Object *obj = pool->obj;
428
429   switch (obj->mode) {
430     case GST_V4L2_IO_RW:
431       break;
432     case GST_V4L2_IO_MMAP:
433     case GST_V4L2_IO_USERPTR:
434     case GST_V4L2_IO_DMABUF:
435       GST_DEBUG_OBJECT (pool, "STREAMON");
436       if (v4l2_ioctl (pool->video_fd, VIDIOC_STREAMON, &obj->type) < 0)
437         goto start_failed;
438       break;
439     default:
440       g_assert_not_reached ();
441       break;
442   }
443
444   pool->streaming = TRUE;
445
446   return TRUE;
447
448   /* ERRORS */
449 start_failed:
450   {
451     GST_ERROR_OBJECT (pool, "error with STREAMON %d (%s)", errno,
452         g_strerror (errno));
453     return FALSE;
454   }
455 }
456
457 static gboolean
458 gst_v4l2_buffer_pool_start (GstBufferPool * bpool)
459 {
460   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
461   GstV4l2Object *obj = pool->obj;
462
463   pool->obj = obj;
464   pool->buffers = g_new0 (GstBuffer *, pool->num_buffers);
465   pool->num_allocated = 0;
466
467   /* now, allocate the buffers: */
468   if (!GST_BUFFER_POOL_CLASS (parent_class)->start (bpool))
469     goto start_failed;
470
471   /* we can start capturing now, we wait for the playback case until we queued
472    * the first buffer */
473   if (obj->type == V4L2_BUF_TYPE_VIDEO_CAPTURE)
474     if (!start_streaming (pool))
475       goto start_failed;
476
477   gst_poll_set_flushing (obj->poll, FALSE);
478
479   return TRUE;
480
481   /* ERRORS */
482 start_failed:
483   {
484     GST_ERROR_OBJECT (pool, "failed to start streaming");
485     return FALSE;
486   }
487 }
488
489 static gboolean
490 gst_v4l2_buffer_pool_stop (GstBufferPool * bpool)
491 {
492   gboolean ret;
493   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
494   GstV4l2Object *obj = pool->obj;
495   guint n;
496
497   GST_DEBUG_OBJECT (pool, "stopping pool");
498
499   gst_poll_set_flushing (obj->poll, TRUE);
500
501   if (pool->streaming) {
502     switch (obj->mode) {
503       case GST_V4L2_IO_RW:
504         break;
505       case GST_V4L2_IO_MMAP:
506       case GST_V4L2_IO_USERPTR:
507       case GST_V4L2_IO_DMABUF:
508         /* we actually need to sync on all queued buffers but not
509          * on the non-queued ones */
510         GST_DEBUG_OBJECT (pool, "STREAMOFF");
511         if (v4l2_ioctl (pool->video_fd, VIDIOC_STREAMOFF, &obj->type) < 0)
512           goto stop_failed;
513         break;
514       default:
515         g_assert_not_reached ();
516         break;
517     }
518     pool->streaming = FALSE;
519   }
520
521   /* first free the buffers in the queue */
522   ret = GST_BUFFER_POOL_CLASS (parent_class)->stop (bpool);
523
524   /* then free the remaining buffers */
525   for (n = 0; n < pool->num_buffers; n++) {
526     if (pool->buffers[n])
527       gst_v4l2_buffer_pool_free_buffer (bpool, pool->buffers[n]);
528   }
529   pool->num_queued = 0;
530   g_free (pool->buffers);
531   pool->buffers = NULL;
532
533   return ret;
534
535   /* ERRORS */
536 stop_failed:
537   {
538     GST_ERROR_OBJECT (pool, "error with STREAMOFF %d (%s)", errno,
539         g_strerror (errno));
540     return FALSE;
541   }
542 }
543
544 static GstFlowReturn
545 gst_v4l2_object_poll (GstV4l2Object * v4l2object)
546 {
547   gint ret;
548
549   if (v4l2object->can_poll_device) {
550     GST_LOG_OBJECT (v4l2object->element, "polling device");
551     ret = gst_poll_wait (v4l2object->poll, GST_CLOCK_TIME_NONE);
552     if (G_UNLIKELY (ret < 0)) {
553       if (errno == EBUSY)
554         goto stopped;
555       if (errno == ENXIO) {
556         GST_WARNING_OBJECT (v4l2object->element,
557             "v4l2 device doesn't support polling. Disabling");
558         v4l2object->can_poll_device = FALSE;
559       } else {
560         if (errno != EAGAIN && errno != EINTR)
561           goto select_error;
562       }
563     }
564   }
565   return GST_FLOW_OK;
566
567   /* ERRORS */
568 stopped:
569   {
570     GST_DEBUG ("stop called");
571     return GST_FLOW_FLUSHING;
572   }
573 select_error:
574   {
575     GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, READ, (NULL),
576         ("poll error %d: %s (%d)", ret, g_strerror (errno), errno));
577     return GST_FLOW_ERROR;
578   }
579 }
580
581 static GstFlowReturn
582 gst_v4l2_buffer_pool_qbuf (GstV4l2BufferPool * pool, GstBuffer * buf)
583 {
584   GstV4l2Meta *meta;
585   gint index;
586
587   meta = GST_V4L2_META_GET (buf);
588   if (meta == NULL) {
589     GST_LOG_OBJECT (pool, "unref copied buffer %p", buf);
590     /* no meta, it was a copied buffer that we can unref */
591     gst_buffer_unref (buf);
592     return GST_FLOW_OK;
593   }
594
595   index = meta->vbuffer.index;
596
597   GST_LOG_OBJECT (pool, "enqueue buffer %p, index:%d, queued:%d, flags:%08x",
598       buf, index, pool->num_queued, meta->vbuffer.flags);
599
600   if (pool->buffers[index] != NULL)
601     goto already_queued;
602
603   GST_LOG_OBJECT (pool, "doing QBUF");
604   if (v4l2_ioctl (pool->video_fd, VIDIOC_QBUF, &meta->vbuffer) < 0)
605     goto queue_failed;
606
607   pool->buffers[index] = buf;
608   pool->num_queued++;
609
610   return GST_FLOW_OK;
611
612   /* ERRORS */
613 already_queued:
614   {
615     GST_WARNING_OBJECT (pool, "the buffer was already queued");
616     return GST_FLOW_ERROR;
617   }
618 queue_failed:
619   {
620     GST_WARNING_OBJECT (pool, "could not queue a buffer %d (%s)", errno,
621         g_strerror (errno));
622     return GST_FLOW_ERROR;
623   }
624 }
625
626 static GstFlowReturn
627 gst_v4l2_buffer_pool_dqbuf (GstV4l2BufferPool * pool, GstBuffer ** buffer)
628 {
629   GstFlowReturn res;
630   GstBuffer *outbuf;
631   struct v4l2_buffer vbuffer;
632   GstV4l2Object *obj = pool->obj;
633   GstClockTime timestamp;
634
635   if (obj->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) {
636     /* select works for input devices when data is available. According to the
637      * specs we can also poll to find out when a frame has been displayed but
638      * that just seems to lock up here */
639     if ((res = gst_v4l2_object_poll (obj)) != GST_FLOW_OK)
640       goto poll_error;
641   }
642
643   memset (&vbuffer, 0x00, sizeof (vbuffer));
644   vbuffer.type = obj->type;
645 #if HAVE_DECL_V4L2_MEMORY_DMABUF
646   if (obj->mode == GST_V4L2_IO_DMABUF)
647     vbuffer.memory = V4L2_MEMORY_DMABUF;
648   else
649 #endif
650     vbuffer.memory = V4L2_MEMORY_MMAP;
651
652   GST_LOG_OBJECT (pool, "doing DQBUF");
653   if (v4l2_ioctl (pool->video_fd, VIDIOC_DQBUF, &vbuffer) < 0)
654     goto error;
655
656   /* get our GstBuffer with that index from the pool, if the buffer was
657    * outstanding we have a serious problem.
658    */
659   outbuf = pool->buffers[vbuffer.index];
660   if (outbuf == NULL)
661     goto no_buffer;
662
663   /* mark the buffer outstanding */
664   pool->buffers[vbuffer.index] = NULL;
665   pool->num_queued--;
666
667   timestamp = GST_TIMEVAL_TO_TIME (vbuffer.timestamp);
668
669   GST_LOG_OBJECT (pool,
670       "dequeued buffer %p seq:%d (ix=%d), used %d, flags %08x, ts %"
671       GST_TIME_FORMAT ", pool-queued=%d, buffer=%p", outbuf, vbuffer.sequence,
672       vbuffer.index, vbuffer.bytesused, vbuffer.flags,
673       GST_TIME_ARGS (timestamp), pool->num_queued, outbuf);
674
675   /* set top/bottom field first if v4l2_buffer has the information */
676   if (vbuffer.field == V4L2_FIELD_INTERLACED_TB) {
677     GST_BUFFER_FLAG_SET (outbuf, GST_VIDEO_BUFFER_FLAG_TFF);
678   }
679   if (vbuffer.field == V4L2_FIELD_INTERLACED_BT) {
680     GST_BUFFER_FLAG_UNSET (outbuf, GST_VIDEO_BUFFER_FLAG_TFF);
681   }
682
683   /* this can change at every frame, esp. with jpeg */
684   if (obj->type == V4L2_BUF_TYPE_VIDEO_CAPTURE)
685     gst_buffer_resize (outbuf, 0, vbuffer.bytesused);
686
687   GST_BUFFER_TIMESTAMP (outbuf) = timestamp;
688
689   *buffer = outbuf;
690
691   return GST_FLOW_OK;
692
693   /* ERRORS */
694 poll_error:
695   {
696     GST_DEBUG_OBJECT (pool, "poll error %s", gst_flow_get_name (res));
697     return res;
698   }
699 error:
700   {
701     GST_WARNING_OBJECT (pool,
702         "problem dequeuing frame %d (ix=%d), pool-ct=%d, buf.flags=%d",
703         vbuffer.sequence, vbuffer.index,
704         GST_MINI_OBJECT_REFCOUNT (pool), vbuffer.flags);
705
706     switch (errno) {
707       case EAGAIN:
708         GST_WARNING_OBJECT (pool,
709             "Non-blocking I/O has been selected using O_NONBLOCK and"
710             " no buffer was in the outgoing queue. device %s", obj->videodev);
711         break;
712       case EINVAL:
713         GST_ERROR_OBJECT (pool,
714             "The buffer type is not supported, or the index is out of bounds, "
715             "or no buffers have been allocated yet, or the userptr "
716             "or length are invalid. device %s", obj->videodev);
717         break;
718       case ENOMEM:
719         GST_ERROR_OBJECT (pool,
720             "insufficient memory to enqueue a user pointer buffer");
721         break;
722       case EIO:
723         GST_INFO_OBJECT (pool,
724             "VIDIOC_DQBUF failed due to an internal error."
725             " Can also indicate temporary problems like signal loss."
726             " Note the driver might dequeue an (empty) buffer despite"
727             " returning an error, or even stop capturing."
728             " device %s", obj->videodev);
729         /* have we de-queued a buffer ? */
730         if (!(vbuffer.flags & (V4L2_BUF_FLAG_QUEUED | V4L2_BUF_FLAG_DONE))) {
731           GST_DEBUG_OBJECT (pool, "reenqueing buffer");
732           /* FIXME ... should we do something here? */
733         }
734         break;
735       case EINTR:
736         GST_WARNING_OBJECT (pool,
737             "could not sync on a buffer on device %s", obj->videodev);
738         break;
739       default:
740         GST_WARNING_OBJECT (pool,
741             "Grabbing frame got interrupted on %s unexpectedly. %d: %s.",
742             obj->videodev, errno, g_strerror (errno));
743         break;
744     }
745     return GST_FLOW_ERROR;
746   }
747 no_buffer:
748   {
749     GST_ERROR_OBJECT (pool, "No free buffer found in the pool at index %d.",
750         vbuffer.index);
751     return GST_FLOW_ERROR;
752   }
753 }
754
755 static GstFlowReturn
756 gst_v4l2_buffer_pool_acquire_buffer (GstBufferPool * bpool, GstBuffer ** buffer,
757     GstBufferPoolAcquireParams * params)
758 {
759   GstFlowReturn ret;
760   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
761   GstV4l2Object *obj = pool->obj;
762
763   GST_DEBUG_OBJECT (pool, "acquire");
764
765   if (GST_BUFFER_POOL_IS_FLUSHING (bpool))
766     goto flushing;
767
768   switch (obj->type) {
769     case V4L2_BUF_TYPE_VIDEO_CAPTURE:
770       /* capture, This function should return a buffer with new captured data */
771       switch (obj->mode) {
772         case GST_V4L2_IO_RW:
773           /* take empty buffer from the pool */
774           ret = GST_BUFFER_POOL_CLASS (parent_class)->acquire_buffer (bpool,
775               buffer, params);
776           break;
777         case GST_V4L2_IO_DMABUF:
778         case GST_V4L2_IO_MMAP:
779           /* just dequeue a buffer, we basically use the queue of v4l2 as the
780            * storage for our buffers. This function does poll first so we can
781            * interrupt it fine. */
782           ret = gst_v4l2_buffer_pool_dqbuf (pool, buffer);
783           if (G_UNLIKELY (ret != GST_FLOW_OK))
784             goto done;
785
786           /* start copying buffers when we are running low on buffers */
787           if (pool->num_queued < pool->copy_threshold) {
788             GstBuffer *copy;
789
790             /* copy the memory */
791             copy = gst_buffer_copy (*buffer);
792             GST_LOG_OBJECT (pool, "copy buffer %p->%p", *buffer, copy);
793
794             /* and requeue so that we can continue capturing */
795             ret = gst_v4l2_buffer_pool_qbuf (pool, *buffer);
796             *buffer = copy;
797           }
798           break;
799
800         case GST_V4L2_IO_USERPTR:
801         default:
802           ret = GST_FLOW_ERROR;
803           g_assert_not_reached ();
804           break;
805       }
806       break;
807
808     case V4L2_BUF_TYPE_VIDEO_OUTPUT:
809       /* playback, This function should return an empty buffer */
810       switch (obj->mode) {
811         case GST_V4L2_IO_RW:
812           /* get an empty buffer */
813           ret = GST_BUFFER_POOL_CLASS (parent_class)->acquire_buffer (bpool,
814               buffer, params);
815           break;
816
817         case GST_V4L2_IO_MMAP:
818           /* get a free unqueued buffer */
819           ret = GST_BUFFER_POOL_CLASS (parent_class)->acquire_buffer (bpool,
820               buffer, params);
821           break;
822
823         case GST_V4L2_IO_USERPTR:
824         default:
825           ret = GST_FLOW_ERROR;
826           g_assert_not_reached ();
827           break;
828       }
829       break;
830
831     default:
832       ret = GST_FLOW_ERROR;
833       g_assert_not_reached ();
834       break;
835   }
836 done:
837   return ret;
838
839   /* ERRORS */
840 flushing:
841   {
842     GST_DEBUG_OBJECT (pool, "We are flushing");
843     return GST_FLOW_FLUSHING;
844   }
845 }
846
847 static void
848 gst_v4l2_buffer_pool_release_buffer (GstBufferPool * bpool, GstBuffer * buffer)
849 {
850   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
851   GstV4l2Object *obj = pool->obj;
852
853   GST_DEBUG_OBJECT (pool, "release buffer %p", buffer);
854
855   switch (obj->type) {
856     case V4L2_BUF_TYPE_VIDEO_CAPTURE:
857       /* capture, put the buffer back in the queue so that we can refill it
858        * later. */
859       switch (obj->mode) {
860         case GST_V4L2_IO_RW:
861           /* release back in the pool */
862           GST_BUFFER_POOL_CLASS (parent_class)->release_buffer (bpool, buffer);
863           break;
864
865         case GST_V4L2_IO_DMABUF:
866         case GST_V4L2_IO_MMAP:
867           /* queue back in the device */
868           gst_v4l2_buffer_pool_qbuf (pool, buffer);
869           break;
870
871         case GST_V4L2_IO_USERPTR:
872         default:
873           g_assert_not_reached ();
874           break;
875       }
876       break;
877
878     case V4L2_BUF_TYPE_VIDEO_OUTPUT:
879       switch (obj->mode) {
880         case GST_V4L2_IO_RW:
881           /* release back in the pool */
882           GST_BUFFER_POOL_CLASS (parent_class)->release_buffer (bpool, buffer);
883           break;
884
885         case GST_V4L2_IO_MMAP:
886         {
887           GstV4l2Meta *meta;
888           guint index;
889
890           meta = GST_V4L2_META_GET (buffer);
891           g_assert (meta != NULL);
892
893           index = meta->vbuffer.index;
894
895           if (pool->buffers[index] == NULL) {
896             GST_LOG_OBJECT (pool, "buffer %u not queued, putting on free list",
897                 index);
898
899             /* reset to the full length, in case it was changed */
900             gst_buffer_resize (buffer, 0, meta->vbuffer.length);
901
902             /* playback, put the buffer back in the queue to refill later. */
903             GST_BUFFER_POOL_CLASS (parent_class)->release_buffer (bpool,
904                 buffer);
905           } else {
906             /* the buffer is queued in the device but maybe not played yet. We just
907              * leave it there and not make it available for future calls to acquire
908              * for now. The buffer will be dequeued and reused later. */
909             GST_LOG_OBJECT (pool, "buffer %u is queued", index);
910           }
911           break;
912         }
913
914         case GST_V4L2_IO_USERPTR:
915         default:
916           g_assert_not_reached ();
917           break;
918       }
919       break;
920
921     default:
922       g_assert_not_reached ();
923       break;
924   }
925 }
926
927 static void
928 gst_v4l2_buffer_pool_finalize (GObject * object)
929 {
930   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (object);
931
932   if (pool->video_fd >= 0)
933     v4l2_close (pool->video_fd);
934   if (pool->allocator)
935     gst_object_unref (pool->allocator);
936   g_free (pool->buffers);
937
938   G_OBJECT_CLASS (parent_class)->finalize (object);
939 }
940
941 static void
942 gst_v4l2_buffer_pool_init (GstV4l2BufferPool * pool)
943 {
944 }
945
946 static void
947 gst_v4l2_buffer_pool_class_init (GstV4l2BufferPoolClass * klass)
948 {
949   GObjectClass *object_class = G_OBJECT_CLASS (klass);
950   GstBufferPoolClass *bufferpool_class = GST_BUFFER_POOL_CLASS (klass);
951
952   object_class->finalize = gst_v4l2_buffer_pool_finalize;
953
954   bufferpool_class->start = gst_v4l2_buffer_pool_start;
955   bufferpool_class->stop = gst_v4l2_buffer_pool_stop;
956   bufferpool_class->set_config = gst_v4l2_buffer_pool_set_config;
957   bufferpool_class->alloc_buffer = gst_v4l2_buffer_pool_alloc_buffer;
958   bufferpool_class->acquire_buffer = gst_v4l2_buffer_pool_acquire_buffer;
959   bufferpool_class->release_buffer = gst_v4l2_buffer_pool_release_buffer;
960   bufferpool_class->free_buffer = gst_v4l2_buffer_pool_free_buffer;
961 }
962
963 /**
964  * gst_v4l2_buffer_pool_new:
965  * @obj:  the v4l2 object owning the pool
966  *
967  * Construct a new buffer pool.
968  *
969  * Returns: the new pool, use gst_object_unref() to free resources
970  */
971 GstBufferPool *
972 gst_v4l2_buffer_pool_new (GstV4l2Object * obj, GstCaps * caps)
973 {
974   GstV4l2BufferPool *pool;
975   GstStructure *s;
976   gint fd;
977
978   fd = v4l2_dup (obj->video_fd);
979   if (fd < 0)
980     goto dup_failed;
981
982   pool = (GstV4l2BufferPool *) g_object_new (GST_TYPE_V4L2_BUFFER_POOL, NULL);
983   pool->video_fd = fd;
984   pool->obj = obj;
985
986   s = gst_buffer_pool_get_config (GST_BUFFER_POOL_CAST (pool));
987   gst_buffer_pool_config_set_params (s, caps, obj->sizeimage, 2, 0);
988   gst_buffer_pool_set_config (GST_BUFFER_POOL_CAST (pool), s);
989
990   return GST_BUFFER_POOL (pool);
991
992   /* ERRORS */
993 dup_failed:
994   {
995     GST_DEBUG ("failed to dup fd %d (%s)", errno, g_strerror (errno));
996     return NULL;
997   }
998 }
999
1000 static GstFlowReturn
1001 gst_v4l2_do_read (GstV4l2BufferPool * pool, GstBuffer * buf)
1002 {
1003   GstFlowReturn res;
1004   GstV4l2Object *obj = pool->obj;
1005   gint amount;
1006   GstMapInfo map;
1007   gint toread;
1008
1009   toread = obj->sizeimage;
1010
1011   GST_LOG_OBJECT (pool, "reading %d bytes into buffer %p", toread, buf);
1012
1013   gst_buffer_map (buf, &map, GST_MAP_WRITE);
1014
1015   do {
1016     if ((res = gst_v4l2_object_poll (obj)) != GST_FLOW_OK)
1017       goto poll_error;
1018
1019     amount = v4l2_read (obj->video_fd, map.data, toread);
1020
1021     if (amount == toread) {
1022       break;
1023     } else if (amount == -1) {
1024       if (errno == EAGAIN || errno == EINTR) {
1025         continue;
1026       } else
1027         goto read_error;
1028     } else {
1029       /* short reads can happen if a signal interrupts the read */
1030       continue;
1031     }
1032   } while (TRUE);
1033
1034   GST_LOG_OBJECT (pool, "read %d bytes", amount);
1035   gst_buffer_unmap (buf, &map);
1036   gst_buffer_resize (buf, 0, amount);
1037
1038   return GST_FLOW_OK;
1039
1040   /* ERRORS */
1041 poll_error:
1042   {
1043     GST_DEBUG ("poll error %s", gst_flow_get_name (res));
1044     goto cleanup;
1045   }
1046 read_error:
1047   {
1048     GST_ELEMENT_ERROR (obj->element, RESOURCE, READ,
1049         (_("Error reading %d bytes from device '%s'."),
1050             toread, obj->videodev), GST_ERROR_SYSTEM);
1051     res = GST_FLOW_ERROR;
1052     goto cleanup;
1053   }
1054 cleanup:
1055   {
1056     gst_buffer_unmap (buf, &map);
1057     gst_buffer_resize (buf, 0, 0);
1058     return res;
1059   }
1060 }
1061
1062 /**
1063  * gst_v4l2_buffer_pool_process:
1064  * @bpool: a #GstBufferPool
1065  * @buf: a #GstBuffer
1066  *
1067  * Process @buf in @bpool. For capture devices, this functions fills @buf with
1068  * data from the device. For output devices, this functions send the contents of
1069  * @buf to the device for playback.
1070  *
1071  * Returns: %GST_FLOW_OK on success.
1072  */
1073 GstFlowReturn
1074 gst_v4l2_buffer_pool_process (GstV4l2BufferPool * pool, GstBuffer * buf)
1075 {
1076   GstFlowReturn ret = GST_FLOW_OK;
1077   GstBufferPool *bpool = GST_BUFFER_POOL_CAST (pool);
1078   GstV4l2Object *obj = pool->obj;
1079
1080   GST_DEBUG_OBJECT (pool, "process buffer %p", buf);
1081
1082   switch (obj->type) {
1083     case V4L2_BUF_TYPE_VIDEO_CAPTURE:
1084       /* capture */
1085       switch (obj->mode) {
1086         case GST_V4L2_IO_RW:
1087           /* capture into the buffer */
1088           ret = gst_v4l2_do_read (pool, buf);
1089           break;
1090
1091         case GST_V4L2_IO_MMAP:
1092         {
1093           GstBuffer *tmp;
1094
1095           if (buf->pool == bpool)
1096             /* nothing, data was inside the buffer when we did _acquire() */
1097             goto done;
1098
1099           /* buffer not from our pool, grab a frame and copy it into the target */
1100           if ((ret = gst_v4l2_buffer_pool_dqbuf (pool, &tmp)) != GST_FLOW_OK)
1101             goto done;
1102
1103           if (!gst_v4l2_object_copy (obj, buf, tmp))
1104             goto copy_failed;
1105
1106           /* an queue the buffer again after the copy */
1107           if ((ret = gst_v4l2_buffer_pool_qbuf (pool, tmp)) != GST_FLOW_OK)
1108             goto done;
1109           break;
1110         }
1111
1112         case GST_V4L2_IO_USERPTR:
1113         default:
1114           g_assert_not_reached ();
1115           break;
1116       }
1117       break;
1118
1119     case V4L2_BUF_TYPE_VIDEO_OUTPUT:
1120       /* playback */
1121       switch (obj->mode) {
1122         case GST_V4L2_IO_RW:
1123           /* FIXME, do write() */
1124           GST_WARNING_OBJECT (pool, "implement write()");
1125           break;
1126         case GST_V4L2_IO_DMABUF:
1127         case GST_V4L2_IO_MMAP:
1128         {
1129           GstBuffer *to_queue;
1130
1131           if (buf->pool == bpool) {
1132             /* nothing, we can queue directly */
1133             to_queue = buf;
1134             GST_LOG_OBJECT (pool, "processing buffer from our pool");
1135           } else {
1136             GST_LOG_OBJECT (pool, "alloc buffer from our pool");
1137             if (!gst_buffer_pool_is_active (bpool)) {
1138               GstStructure *config;
1139
1140               /* this pool was not activated, configure and activate */
1141               GST_DEBUG_OBJECT (pool, "activating pool");
1142
1143               config = gst_buffer_pool_get_config (bpool);
1144               gst_buffer_pool_config_add_option (config,
1145                   GST_BUFFER_POOL_OPTION_VIDEO_META);
1146               gst_buffer_pool_set_config (bpool, config);
1147
1148               if (!gst_buffer_pool_set_active (bpool, TRUE))
1149                 goto activate_failed;
1150             }
1151
1152             /* this can block if all buffers are outstanding which would be
1153              * strange because we would expect the upstream element to have
1154              * allocated them and returned to us.. */
1155             ret = GST_BUFFER_POOL_CLASS (parent_class)->acquire_buffer (bpool,
1156                 &to_queue, NULL);
1157             if (ret != GST_FLOW_OK)
1158               goto acquire_failed;
1159
1160             /* copy into it and queue */
1161             if (!gst_v4l2_object_copy (obj, to_queue, buf))
1162               goto copy_failed;
1163           }
1164
1165           if ((ret = gst_v4l2_buffer_pool_qbuf (pool, to_queue)) != GST_FLOW_OK)
1166             goto done;
1167
1168           /* if we are not streaming yet (this is the first buffer, start
1169            * streaming now */
1170           if (!pool->streaming)
1171             if (!start_streaming (pool))
1172               goto start_failed;
1173
1174           if (pool->num_queued == pool->num_allocated) {
1175             /* all buffers are queued, try to dequeue one and release it back
1176              * into the pool so that _acquire can get to it again. */
1177             ret = gst_v4l2_buffer_pool_dqbuf (pool, &to_queue);
1178             if (ret != GST_FLOW_OK)
1179               goto done;
1180
1181             /* release the rendered buffer back into the pool. This wakes up any
1182              * thread waiting for a buffer in _acquire() */
1183             gst_v4l2_buffer_pool_release_buffer (bpool, to_queue);
1184           }
1185           break;
1186         }
1187
1188         case GST_V4L2_IO_USERPTR:
1189         default:
1190           g_assert_not_reached ();
1191           break;
1192       }
1193       break;
1194     default:
1195       g_assert_not_reached ();
1196       break;
1197   }
1198 done:
1199   return ret;
1200
1201   /* ERRORS */
1202 activate_failed:
1203   {
1204     GST_ERROR_OBJECT (obj->element, "failed to activate pool");
1205     return GST_FLOW_ERROR;
1206   }
1207 acquire_failed:
1208   {
1209     GST_WARNING_OBJECT (obj->element, "failed to acquire a buffer: %s",
1210         gst_flow_get_name (ret));
1211     return ret;
1212   }
1213 copy_failed:
1214   {
1215     GST_ERROR_OBJECT (obj->element, "failed to copy data");
1216     return GST_FLOW_ERROR;
1217   }
1218 start_failed:
1219   {
1220     GST_ERROR_OBJECT (obj->element, "failed to start streaming");
1221     return GST_FLOW_ERROR;
1222   }
1223 }