v4l2: free all queued buffers
[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 "gstv4l2src.h"
44 #include "gstv4l2sink.h"
45 #include "v4l2_calls.h"
46 #include "gst/gst-i18n-plugin.h"
47 #include <gst/glib-compat-private.h>
48
49 /* videodev2.h is not versioned and we can't easily check for the presence
50  * of enum values at compile time, but the V4L2_CAP_VIDEO_OUTPUT_OVERLAY define
51  * was added in the same commit as V4L2_FIELD_INTERLACED_{TB,BT} (b2787845) */
52 #ifndef V4L2_CAP_VIDEO_OUTPUT_OVERLAY
53 #define V4L2_FIELD_INTERLACED_TB 8
54 #define V4L2_FIELD_INTERLACED_BT 9
55 #endif
56
57
58 GST_DEBUG_CATEGORY_EXTERN (v4l2_debug);
59 #define GST_CAT_DEFAULT v4l2_debug
60
61 /*
62  * GstV4l2Buffer:
63  */
64 GType
65 gst_v4l2_meta_api_get_type (void)
66 {
67   static volatile GType type;
68   static const gchar *tags[] = { "memory", NULL };
69
70   if (g_once_init_enter (&type)) {
71     GType _type = gst_meta_api_type_register ("GstV4l2MetaAPI", tags);
72     g_once_init_leave (&type, _type);
73   }
74   return type;
75 }
76
77 const GstMetaInfo *
78 gst_v4l2_meta_get_info (void)
79 {
80   static const GstMetaInfo *meta_info = NULL;
81
82   if (g_once_init_enter (&meta_info)) {
83     const GstMetaInfo *meta =
84         gst_meta_register (gst_v4l2_meta_api_get_type (), "GstV4l2Meta",
85         sizeof (GstV4l2Meta), (GstMetaInitFunction) NULL,
86         (GstMetaFreeFunction) NULL, (GstMetaTransformFunction) NULL);
87     g_once_init_leave (&meta_info, meta);
88   }
89   return meta_info;
90 }
91
92 /*
93  * GstV4l2BufferPool:
94  */
95 #define gst_v4l2_buffer_pool_parent_class parent_class
96 G_DEFINE_TYPE (GstV4l2BufferPool, gst_v4l2_buffer_pool, GST_TYPE_BUFFER_POOL);
97
98 static void gst_v4l2_buffer_pool_release_buffer (GstBufferPool * bpool,
99     GstBuffer * buffer);
100
101 static void
102 gst_v4l2_buffer_pool_free_buffer (GstBufferPool * bpool, GstBuffer * buffer)
103 {
104   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
105   GstV4l2Object *obj;
106
107   obj = pool->obj;
108
109   switch (obj->mode) {
110     case GST_V4L2_IO_RW:
111     case GST_V4L2_IO_DMABUF:
112       break;
113     case GST_V4L2_IO_MMAP:
114     {
115       GstV4l2Meta *meta;
116       gint index;
117
118       meta = GST_V4L2_META_GET (buffer);
119       g_assert (meta != NULL);
120
121       index = meta->vbuffer.index;
122       GST_LOG_OBJECT (pool,
123           "unmap buffer %p idx %d (data %p, len %u)", buffer,
124           index, meta->mem, meta->vbuffer.length);
125
126       v4l2_munmap (meta->mem, meta->vbuffer.length);
127       pool->buffers[index] = NULL;
128       break;
129     }
130     case GST_V4L2_IO_USERPTR:
131     default:
132       g_assert_not_reached ();
133       break;
134   }
135   gst_buffer_unref (buffer);
136 }
137
138 static GstFlowReturn
139 gst_v4l2_buffer_pool_alloc_buffer (GstBufferPool * bpool, GstBuffer ** buffer,
140     GstBufferPoolAcquireParams * params)
141 {
142   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
143   GstBuffer *newbuf;
144   GstV4l2Meta *meta;
145   GstV4l2Object *obj;
146   GstVideoInfo *info;
147   guint index;
148
149   obj = pool->obj;
150   info = &obj->info;
151
152   switch (obj->mode) {
153     case GST_V4L2_IO_RW:
154     {
155       newbuf =
156           gst_buffer_new_allocate (pool->allocator, pool->size, &pool->params);
157       break;
158     }
159     case GST_V4L2_IO_MMAP:
160     case GST_V4L2_IO_DMABUF:
161     {
162       newbuf = gst_buffer_new ();
163       meta = GST_V4L2_META_ADD (newbuf);
164
165       index = pool->num_allocated;
166
167       GST_LOG_OBJECT (pool, "creating buffer %u, %p", index, newbuf);
168
169       meta->vbuffer.index = index;
170       meta->vbuffer.type = obj->type;
171       meta->vbuffer.memory = V4L2_MEMORY_MMAP;
172
173       if (v4l2_ioctl (pool->video_fd, VIDIOC_QUERYBUF, &meta->vbuffer) < 0)
174         goto querybuf_failed;
175
176       GST_LOG_OBJECT (pool, "  index:     %u", meta->vbuffer.index);
177       GST_LOG_OBJECT (pool, "  type:      %d", meta->vbuffer.type);
178       GST_LOG_OBJECT (pool, "  bytesused: %u", meta->vbuffer.bytesused);
179       GST_LOG_OBJECT (pool, "  flags:     %08x", meta->vbuffer.flags);
180       GST_LOG_OBJECT (pool, "  field:     %d", meta->vbuffer.field);
181       GST_LOG_OBJECT (pool, "  memory:    %d", meta->vbuffer.memory);
182       if (meta->vbuffer.memory == V4L2_MEMORY_MMAP)
183         GST_LOG_OBJECT (pool, "  MMAP offset:  %u", meta->vbuffer.m.offset);
184
185       if (obj->mode == GST_V4L2_IO_MMAP) {
186         meta->mem = v4l2_mmap (0, meta->vbuffer.length,
187             PROT_READ | PROT_WRITE, MAP_SHARED, pool->video_fd,
188             meta->vbuffer.m.offset);
189         if (meta->mem == MAP_FAILED)
190           goto mmap_failed;
191
192         gst_buffer_append_memory (newbuf,
193             gst_memory_new_wrapped (GST_MEMORY_FLAG_NO_SHARE,
194                 meta->mem, meta->vbuffer.length, 0, meta->vbuffer.length, NULL,
195                 NULL));
196       }
197 #if HAVE_DECL_V4L2_MEMORY_DMABUF
198       if (obj->mode == GST_V4L2_IO_DMABUF) {
199         struct v4l2_exportbuffer expbuf;
200
201         expbuf.type = meta->vbuffer.type;
202         expbuf.index = meta->vbuffer.index;
203         expbuf.flags = O_CLOEXEC;
204         if (v4l2_ioctl (pool->video_fd, VIDIOC_EXPBUF, &expbuf) < 0)
205           goto mmap_failed;
206
207         meta->vbuffer.memory = V4L2_MEMORY_DMABUF;
208         gst_buffer_append_memory (newbuf,
209             gst_dmabuf_allocator_alloc (pool->allocator, expbuf.fd,
210                 meta->vbuffer.length));
211       }
212 #endif
213       /* add metadata to raw video buffers */
214       if (pool->add_videometa && info->finfo) {
215         const GstVideoFormatInfo *finfo = info->finfo;
216         gsize offset[GST_VIDEO_MAX_PLANES];
217         gint width, height, n_planes, offs, i, stride[GST_VIDEO_MAX_PLANES];
218
219         width = GST_VIDEO_INFO_WIDTH (info);
220         height = GST_VIDEO_INFO_HEIGHT (info);
221         n_planes = GST_VIDEO_INFO_N_PLANES (info);
222
223         GST_DEBUG_OBJECT (pool, "adding video meta, bytesperline %d",
224             obj->bytesperline);
225
226         offs = 0;
227         for (i = 0; i < n_planes; i++) {
228           offset[i] = offs;
229           stride[i] =
230               GST_VIDEO_FORMAT_INFO_SCALE_WIDTH (finfo, i, obj->bytesperline);
231
232           offs +=
233               stride[i] * GST_VIDEO_FORMAT_INFO_SCALE_HEIGHT (finfo, i, height);
234         }
235         gst_buffer_add_video_meta_full (newbuf, GST_VIDEO_FRAME_FLAG_NONE,
236             GST_VIDEO_INFO_FORMAT (info), width, height, n_planes,
237             offset, stride);
238       }
239       break;
240     }
241     case GST_V4L2_IO_USERPTR:
242     default:
243       newbuf = NULL;
244       g_assert_not_reached ();
245   }
246
247   pool->num_allocated++;
248
249   *buffer = newbuf;
250
251   return GST_FLOW_OK;
252
253   /* ERRORS */
254 querybuf_failed:
255   {
256     gint errnosave = errno;
257
258     GST_WARNING ("Failed QUERYBUF: %s", g_strerror (errnosave));
259     gst_buffer_unref (newbuf);
260     errno = errnosave;
261     return GST_FLOW_ERROR;
262   }
263 mmap_failed:
264   {
265     gint errnosave = errno;
266
267     GST_WARNING ("Failed to mmap: %s", g_strerror (errnosave));
268     gst_buffer_unref (newbuf);
269     errno = errnosave;
270     return GST_FLOW_ERROR;
271   }
272 }
273
274 static gboolean
275 gst_v4l2_buffer_pool_set_config (GstBufferPool * bpool, GstStructure * config)
276 {
277   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
278   GstV4l2Object *obj = pool->obj;
279   GstCaps *caps;
280   guint size, min_buffers, max_buffers, num_buffers, copy_threshold;
281   GstAllocator *allocator;
282   GstAllocationParams params;
283   struct v4l2_requestbuffers breq;
284
285   GST_DEBUG_OBJECT (pool, "set config");
286
287   pool->add_videometa =
288       gst_buffer_pool_config_has_option (config,
289       GST_BUFFER_POOL_OPTION_VIDEO_META);
290
291   if (!pool->add_videometa &&
292       GST_VIDEO_INFO_FORMAT (&obj->info) != GST_VIDEO_FORMAT_ENCODED) {
293     gint stride;
294
295     /* we don't have video metadata, and we are not dealing with raw video,
296      * see if the strides are compatible */
297     stride = GST_VIDEO_INFO_PLANE_STRIDE (&obj->info, 0);
298
299     GST_DEBUG_OBJECT (pool, "no videometadata, checking strides %d and %u",
300         stride, obj->bytesperline);
301
302     if (stride != obj->bytesperline)
303       goto missing_video_api;
304   }
305
306   /* parse the config and keep around */
307   if (!gst_buffer_pool_config_get_params (config, &caps, &size, &min_buffers,
308           &max_buffers))
309     goto wrong_config;
310
311   if (!gst_buffer_pool_config_get_allocator (config, &allocator, &params))
312     goto wrong_config;
313
314   GST_DEBUG_OBJECT (pool, "config %" GST_PTR_FORMAT, config);
315
316   switch (obj->mode) {
317     case GST_V4L2_IO_RW:
318       /* we preallocate 1 buffer, this value also instructs the latency
319        * calculation to have 1 frame latency max */
320       num_buffers = 1;
321       copy_threshold = 0;
322       break;
323     case GST_V4L2_IO_DMABUF:
324     case GST_V4L2_IO_MMAP:
325     {
326       /* request a reasonable number of buffers when no max specified. We will
327        * copy when we run out of buffers */
328       if (max_buffers == 0)
329         num_buffers = 4;
330       else
331         num_buffers = max_buffers;
332
333       /* first, lets request buffers, and see how many we can get: */
334       GST_DEBUG_OBJECT (pool, "starting, requesting %d MMAP buffers",
335           num_buffers);
336
337       memset (&breq, 0, sizeof (struct v4l2_requestbuffers));
338       breq.type = obj->type;
339       breq.count = num_buffers;
340       breq.memory = V4L2_MEMORY_MMAP;
341
342       if (v4l2_ioctl (pool->video_fd, VIDIOC_REQBUFS, &breq) < 0)
343         goto reqbufs_failed;
344
345       GST_LOG_OBJECT (pool, " count:  %u", breq.count);
346       GST_LOG_OBJECT (pool, " type:   %d", breq.type);
347       GST_LOG_OBJECT (pool, " memory: %d", breq.memory);
348
349       if (breq.count < GST_V4L2_MIN_BUFFERS)
350         goto no_buffers;
351
352       if (num_buffers != breq.count) {
353         GST_WARNING_OBJECT (pool, "using %u buffers instead", breq.count);
354         num_buffers = breq.count;
355       }
356       /* update min buffers with the amount of buffers we just reserved. We need
357        * to configure this value in the bufferpool so that the default start
358        * implementation calls our allocate function */
359       min_buffers = breq.count;
360
361       if (max_buffers == 0 || num_buffers < max_buffers) {
362         /* if we are asked to provide more buffers than we have allocated, start
363          * copying buffers when we only have 2 buffers left in the pool */
364         copy_threshold = 2;
365       } else {
366         /* we are certain that we have enough buffers so we don't need to
367          * copy */
368         copy_threshold = 0;
369       }
370       break;
371     }
372     case GST_V4L2_IO_USERPTR:
373     default:
374       num_buffers = 0;
375       copy_threshold = 0;
376       g_assert_not_reached ();
377       break;
378   }
379
380   pool->size = size;
381   pool->num_buffers = num_buffers;
382   pool->copy_threshold = copy_threshold;
383
384   if (obj->mode == GST_V4L2_IO_DMABUF)
385     allocator = gst_dmabuf_allocator_obtain ();
386
387   if (pool->allocator)
388     gst_object_unref (pool->allocator);
389   if ((pool->allocator = allocator))
390     gst_object_ref (allocator);
391   pool->params = params;
392
393   gst_buffer_pool_config_set_params (config, caps, size, min_buffers,
394       max_buffers);
395
396   return GST_BUFFER_POOL_CLASS (parent_class)->set_config (bpool, config);
397
398   /* ERRORS */
399 missing_video_api:
400   {
401     GST_ERROR_OBJECT (pool, "missing GstMetaVideo API in config, "
402         "default stride: %d, wanted stride %u",
403         GST_VIDEO_INFO_PLANE_STRIDE (&obj->info, 0), obj->bytesperline);
404     return FALSE;
405   }
406 wrong_config:
407   {
408     GST_ERROR_OBJECT (pool, "invalid config %" GST_PTR_FORMAT, config);
409     return FALSE;
410   }
411 reqbufs_failed:
412   {
413     GST_ERROR_OBJECT (pool,
414         "error requesting %d buffers: %s", num_buffers, g_strerror (errno));
415     return FALSE;
416   }
417 no_buffers:
418   {
419     GST_ERROR_OBJECT (pool,
420         "we received %d from device '%s', we want at least %d",
421         breq.count, obj->videodev, GST_V4L2_MIN_BUFFERS);
422     return FALSE;
423   }
424 }
425
426 static gboolean
427 start_streaming (GstV4l2BufferPool * pool)
428 {
429   GstV4l2Object *obj = pool->obj;
430
431   switch (obj->mode) {
432     case GST_V4L2_IO_RW:
433       break;
434     case GST_V4L2_IO_MMAP:
435     case GST_V4L2_IO_USERPTR:
436     case GST_V4L2_IO_DMABUF:
437       GST_DEBUG_OBJECT (pool, "STREAMON");
438       if (v4l2_ioctl (pool->video_fd, VIDIOC_STREAMON, &obj->type) < 0)
439         goto start_failed;
440       break;
441     default:
442       g_assert_not_reached ();
443       break;
444   }
445
446   pool->streaming = TRUE;
447
448   return TRUE;
449
450   /* ERRORS */
451 start_failed:
452   {
453     GST_ERROR_OBJECT (pool, "error with STREAMON %d (%s)", errno,
454         g_strerror (errno));
455     return FALSE;
456   }
457 }
458
459 static gboolean
460 gst_v4l2_buffer_pool_start (GstBufferPool * bpool)
461 {
462   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
463   GstV4l2Object *obj = pool->obj;
464
465   pool->obj = obj;
466   pool->buffers = g_new0 (GstBuffer *, pool->num_buffers);
467   pool->num_allocated = 0;
468
469   /* now, allocate the buffers: */
470   if (!GST_BUFFER_POOL_CLASS (parent_class)->start (bpool))
471     goto start_failed;
472
473   /* we can start capturing now, we wait for the playback case until we queued
474    * the first buffer */
475   if (obj->type == V4L2_BUF_TYPE_VIDEO_CAPTURE)
476     if (!start_streaming (pool))
477       goto start_failed;
478
479   gst_poll_set_flushing (obj->poll, FALSE);
480
481   return TRUE;
482
483   /* ERRORS */
484 start_failed:
485   {
486     GST_ERROR_OBJECT (pool, "failed to start streaming");
487     return FALSE;
488   }
489 }
490
491 static gboolean
492 gst_v4l2_buffer_pool_stop (GstBufferPool * bpool)
493 {
494   gboolean ret;
495   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
496   GstV4l2Object *obj = pool->obj;
497   guint n;
498
499   GST_DEBUG_OBJECT (pool, "stopping pool");
500
501   gst_poll_set_flushing (obj->poll, TRUE);
502
503   if (pool->streaming) {
504     switch (obj->mode) {
505       case GST_V4L2_IO_RW:
506         break;
507       case GST_V4L2_IO_MMAP:
508       case GST_V4L2_IO_USERPTR:
509       case GST_V4L2_IO_DMABUF:
510         /* we actually need to sync on all queued buffers but not
511          * on the non-queued ones */
512         GST_DEBUG_OBJECT (pool, "STREAMOFF");
513         if (v4l2_ioctl (pool->video_fd, VIDIOC_STREAMOFF, &obj->type) < 0)
514           goto stop_failed;
515         break;
516       default:
517         g_assert_not_reached ();
518         break;
519     }
520     pool->streaming = FALSE;
521   }
522
523   /* first free the buffers in the queue */
524   ret = GST_BUFFER_POOL_CLASS (parent_class)->stop (bpool);
525
526   /* then free the remaining buffers */
527   for (n = 0; n < pool->num_buffers; n++) {
528     if (pool->buffers[n])
529       gst_v4l2_buffer_pool_free_buffer (bpool, pool->buffers[n]);
530   }
531   pool->num_queued = 0;
532   g_free (pool->buffers);
533   pool->buffers = NULL;
534
535   return ret;
536
537   /* ERRORS */
538 stop_failed:
539   {
540     GST_ERROR_OBJECT (pool, "error with STREAMOFF %d (%s)", errno,
541         g_strerror (errno));
542     return FALSE;
543   }
544 }
545
546 static GstFlowReturn
547 gst_v4l2_object_poll (GstV4l2Object * v4l2object)
548 {
549   gint ret;
550
551   if (v4l2object->can_poll_device) {
552     GST_LOG_OBJECT (v4l2object->element, "polling device");
553     ret = gst_poll_wait (v4l2object->poll, GST_CLOCK_TIME_NONE);
554     if (G_UNLIKELY (ret < 0)) {
555       if (errno == EBUSY)
556         goto stopped;
557       if (errno == ENXIO) {
558         GST_WARNING_OBJECT (v4l2object->element,
559             "v4l2 device doesn't support polling. Disabling");
560         v4l2object->can_poll_device = FALSE;
561       } else {
562         if (errno != EAGAIN && errno != EINTR)
563           goto select_error;
564       }
565     }
566   }
567   return GST_FLOW_OK;
568
569   /* ERRORS */
570 stopped:
571   {
572     GST_DEBUG ("stop called");
573     return GST_FLOW_FLUSHING;
574   }
575 select_error:
576   {
577     GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, READ, (NULL),
578         ("poll error %d: %s (%d)", ret, g_strerror (errno), errno));
579     return GST_FLOW_ERROR;
580   }
581 }
582
583 static GstFlowReturn
584 gst_v4l2_buffer_pool_qbuf (GstV4l2BufferPool * pool, GstBuffer * buf)
585 {
586   GstV4l2Meta *meta;
587   gint index;
588
589   meta = GST_V4L2_META_GET (buf);
590   if (meta == NULL) {
591     GST_LOG_OBJECT (pool, "unref copied buffer %p", buf);
592     /* no meta, it was a copied buffer that we can unref */
593     gst_buffer_unref (buf);
594     return GST_FLOW_OK;
595   }
596
597   index = meta->vbuffer.index;
598
599   GST_LOG_OBJECT (pool, "enqueue buffer %p, index:%d, queued:%d, flags:%08x",
600       buf, index, pool->num_queued, meta->vbuffer.flags);
601
602   if (pool->buffers[index] != NULL)
603     goto already_queued;
604
605   GST_LOG_OBJECT (pool, "doing QBUF");
606   if (v4l2_ioctl (pool->video_fd, VIDIOC_QBUF, &meta->vbuffer) < 0)
607     goto queue_failed;
608
609   pool->buffers[index] = buf;
610   pool->num_queued++;
611
612   return GST_FLOW_OK;
613
614   /* ERRORS */
615 already_queued:
616   {
617     GST_WARNING_OBJECT (pool, "the buffer was already queued");
618     return GST_FLOW_ERROR;
619   }
620 queue_failed:
621   {
622     GST_WARNING_OBJECT (pool, "could not queue a buffer %d (%s)", errno,
623         g_strerror (errno));
624     return GST_FLOW_ERROR;
625   }
626 }
627
628 static GstFlowReturn
629 gst_v4l2_buffer_pool_dqbuf (GstV4l2BufferPool * pool, GstBuffer ** buffer)
630 {
631   GstFlowReturn res;
632   GstBuffer *outbuf;
633   struct v4l2_buffer vbuffer;
634   GstV4l2Object *obj = pool->obj;
635   GstClockTime timestamp;
636
637   if (obj->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) {
638     /* select works for input devices when data is available. According to the
639      * specs we can also poll to find out when a frame has been displayed but
640      * that just seems to lock up here */
641     if ((res = gst_v4l2_object_poll (obj)) != GST_FLOW_OK)
642       goto poll_error;
643   }
644
645   memset (&vbuffer, 0x00, sizeof (vbuffer));
646   vbuffer.type = obj->type;
647 #if HAVE_DECL_V4L2_MEMORY_DMABUF
648   if (obj->mode == GST_V4L2_IO_DMABUF)
649     vbuffer.memory = V4L2_MEMORY_DMABUF;
650   else
651 #endif
652     vbuffer.memory = V4L2_MEMORY_MMAP;
653
654   GST_LOG_OBJECT (pool, "doing DQBUF");
655   if (v4l2_ioctl (pool->video_fd, VIDIOC_DQBUF, &vbuffer) < 0)
656     goto error;
657
658   /* get our GstBuffer with that index from the pool, if the buffer was
659    * outstanding we have a serious problem.
660    */
661   outbuf = pool->buffers[vbuffer.index];
662   if (outbuf == NULL)
663     goto no_buffer;
664
665   /* mark the buffer outstanding */
666   pool->buffers[vbuffer.index] = NULL;
667   pool->num_queued--;
668
669   timestamp = GST_TIMEVAL_TO_TIME (vbuffer.timestamp);
670
671   GST_LOG_OBJECT (pool,
672       "dequeued buffer %p seq:%d (ix=%d), used %d, flags %08x, ts %"
673       GST_TIME_FORMAT ", pool-queued=%d, buffer=%p", outbuf, vbuffer.sequence,
674       vbuffer.index, vbuffer.bytesused, vbuffer.flags,
675       GST_TIME_ARGS (timestamp), pool->num_queued, outbuf);
676
677   /* set top/bottom field first if v4l2_buffer has the information */
678   if (vbuffer.field == V4L2_FIELD_INTERLACED_TB) {
679     GST_BUFFER_FLAG_SET (outbuf, GST_VIDEO_BUFFER_FLAG_TFF);
680   }
681   if (vbuffer.field == V4L2_FIELD_INTERLACED_BT) {
682     GST_BUFFER_FLAG_UNSET (outbuf, GST_VIDEO_BUFFER_FLAG_TFF);
683   }
684
685   /* this can change at every frame, esp. with jpeg */
686   if (obj->type == V4L2_BUF_TYPE_VIDEO_CAPTURE)
687     gst_buffer_resize (outbuf, 0, vbuffer.bytesused);
688   else
689     gst_buffer_resize (outbuf, 0, vbuffer.length);
690
691   GST_BUFFER_TIMESTAMP (outbuf) = timestamp;
692
693   *buffer = outbuf;
694
695   return GST_FLOW_OK;
696
697   /* ERRORS */
698 poll_error:
699   {
700     GST_DEBUG_OBJECT (pool, "poll error %s", gst_flow_get_name (res));
701     return res;
702   }
703 error:
704   {
705     GST_WARNING_OBJECT (pool,
706         "problem dequeuing frame %d (ix=%d), pool-ct=%d, buf.flags=%d",
707         vbuffer.sequence, vbuffer.index,
708         GST_MINI_OBJECT_REFCOUNT (pool), vbuffer.flags);
709
710     switch (errno) {
711       case EAGAIN:
712         GST_WARNING_OBJECT (pool,
713             "Non-blocking I/O has been selected using O_NONBLOCK and"
714             " no buffer was in the outgoing queue. device %s", obj->videodev);
715         break;
716       case EINVAL:
717         GST_ERROR_OBJECT (pool,
718             "The buffer type is not supported, or the index is out of bounds, "
719             "or no buffers have been allocated yet, or the userptr "
720             "or length are invalid. device %s", obj->videodev);
721         break;
722       case ENOMEM:
723         GST_ERROR_OBJECT (pool,
724             "insufficient memory to enqueue a user pointer buffer");
725         break;
726       case EIO:
727         GST_INFO_OBJECT (pool,
728             "VIDIOC_DQBUF failed due to an internal error."
729             " Can also indicate temporary problems like signal loss."
730             " Note the driver might dequeue an (empty) buffer despite"
731             " returning an error, or even stop capturing."
732             " device %s", obj->videodev);
733         /* have we de-queued a buffer ? */
734         if (!(vbuffer.flags & (V4L2_BUF_FLAG_QUEUED | V4L2_BUF_FLAG_DONE))) {
735           GST_DEBUG_OBJECT (pool, "reenqueing buffer");
736           /* FIXME ... should we do something here? */
737         }
738         break;
739       case EINTR:
740         GST_WARNING_OBJECT (pool,
741             "could not sync on a buffer on device %s", obj->videodev);
742         break;
743       default:
744         GST_WARNING_OBJECT (pool,
745             "Grabbing frame got interrupted on %s unexpectedly. %d: %s.",
746             obj->videodev, errno, g_strerror (errno));
747         break;
748     }
749     return GST_FLOW_ERROR;
750   }
751 no_buffer:
752   {
753     GST_ERROR_OBJECT (pool, "No free buffer found in the pool at index %d.",
754         vbuffer.index);
755     return GST_FLOW_ERROR;
756   }
757 }
758
759 static GstFlowReturn
760 gst_v4l2_buffer_pool_acquire_buffer (GstBufferPool * bpool, GstBuffer ** buffer,
761     GstBufferPoolAcquireParams * params)
762 {
763   GstFlowReturn ret;
764   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
765   GstV4l2Object *obj = pool->obj;
766
767   GST_DEBUG_OBJECT (pool, "acquire");
768
769   if (GST_BUFFER_POOL_IS_FLUSHING (bpool))
770     goto flushing;
771
772   switch (obj->type) {
773     case V4L2_BUF_TYPE_VIDEO_CAPTURE:
774       /* capture, This function should return a buffer with new captured data */
775       switch (obj->mode) {
776         case GST_V4L2_IO_RW:
777           /* take empty buffer from the pool */
778           ret = GST_BUFFER_POOL_CLASS (parent_class)->acquire_buffer (bpool,
779               buffer, params);
780           break;
781         case GST_V4L2_IO_DMABUF:
782         case GST_V4L2_IO_MMAP:
783           /* just dequeue a buffer, we basically use the queue of v4l2 as the
784            * storage for our buffers. This function does poll first so we can
785            * interrupt it fine. */
786           ret = gst_v4l2_buffer_pool_dqbuf (pool, buffer);
787           if (G_UNLIKELY (ret != GST_FLOW_OK))
788             goto done;
789
790           /* start copying buffers when we are running low on buffers */
791           if (pool->num_queued < pool->copy_threshold) {
792             GstBuffer *copy;
793
794             /* copy the memory */
795             copy = gst_buffer_copy (*buffer);
796             GST_LOG_OBJECT (pool, "copy buffer %p->%p", *buffer, copy);
797
798             /* and requeue so that we can continue capturing */
799             ret = gst_v4l2_buffer_pool_qbuf (pool, *buffer);
800             *buffer = copy;
801           }
802           break;
803
804         case GST_V4L2_IO_USERPTR:
805         default:
806           ret = GST_FLOW_ERROR;
807           g_assert_not_reached ();
808           break;
809       }
810       break;
811
812     case V4L2_BUF_TYPE_VIDEO_OUTPUT:
813       /* playback, This function should return an empty buffer */
814       switch (obj->mode) {
815         case GST_V4L2_IO_RW:
816           /* get an empty buffer */
817           ret = GST_BUFFER_POOL_CLASS (parent_class)->acquire_buffer (bpool,
818               buffer, params);
819           break;
820
821         case GST_V4L2_IO_MMAP:
822           /* get a free unqueued buffer */
823           ret = GST_BUFFER_POOL_CLASS (parent_class)->acquire_buffer (bpool,
824               buffer, params);
825           break;
826
827         case GST_V4L2_IO_USERPTR:
828         default:
829           ret = GST_FLOW_ERROR;
830           g_assert_not_reached ();
831           break;
832       }
833       break;
834
835     default:
836       ret = GST_FLOW_ERROR;
837       g_assert_not_reached ();
838       break;
839   }
840 done:
841   return ret;
842
843   /* ERRORS */
844 flushing:
845   {
846     GST_DEBUG_OBJECT (pool, "We are flushing");
847     return GST_FLOW_FLUSHING;
848   }
849 }
850
851 static void
852 gst_v4l2_buffer_pool_release_buffer (GstBufferPool * bpool, GstBuffer * buffer)
853 {
854   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
855   GstV4l2Object *obj = pool->obj;
856
857   GST_DEBUG_OBJECT (pool, "release buffer %p", buffer);
858
859   switch (obj->type) {
860     case V4L2_BUF_TYPE_VIDEO_CAPTURE:
861       /* capture, put the buffer back in the queue so that we can refill it
862        * later. */
863       switch (obj->mode) {
864         case GST_V4L2_IO_RW:
865           /* release back in the pool */
866           GST_BUFFER_POOL_CLASS (parent_class)->release_buffer (bpool, buffer);
867           break;
868
869         case GST_V4L2_IO_DMABUF:
870         case GST_V4L2_IO_MMAP:
871           /* queue back in the device */
872           gst_v4l2_buffer_pool_qbuf (pool, buffer);
873           break;
874
875         case GST_V4L2_IO_USERPTR:
876         default:
877           g_assert_not_reached ();
878           break;
879       }
880       break;
881
882     case V4L2_BUF_TYPE_VIDEO_OUTPUT:
883       switch (obj->mode) {
884         case GST_V4L2_IO_RW:
885           /* release back in the pool */
886           GST_BUFFER_POOL_CLASS (parent_class)->release_buffer (bpool, buffer);
887           break;
888
889         case GST_V4L2_IO_MMAP:
890         {
891           GstV4l2Meta *meta;
892           guint index;
893
894           meta = GST_V4L2_META_GET (buffer);
895           g_assert (meta != NULL);
896
897           index = meta->vbuffer.index;
898
899           if (pool->buffers[index] == NULL) {
900             GST_LOG_OBJECT (pool, "buffer %u not queued, putting on free list",
901                 index);
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 }