v4l2: bufferpool: remove unused includes
[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   else
687     gst_buffer_resize (outbuf, 0, vbuffer.length);
688
689   GST_BUFFER_TIMESTAMP (outbuf) = timestamp;
690
691   *buffer = outbuf;
692
693   return GST_FLOW_OK;
694
695   /* ERRORS */
696 poll_error:
697   {
698     GST_DEBUG_OBJECT (pool, "poll error %s", gst_flow_get_name (res));
699     return res;
700   }
701 error:
702   {
703     GST_WARNING_OBJECT (pool,
704         "problem dequeuing frame %d (ix=%d), pool-ct=%d, buf.flags=%d",
705         vbuffer.sequence, vbuffer.index,
706         GST_MINI_OBJECT_REFCOUNT (pool), vbuffer.flags);
707
708     switch (errno) {
709       case EAGAIN:
710         GST_WARNING_OBJECT (pool,
711             "Non-blocking I/O has been selected using O_NONBLOCK and"
712             " no buffer was in the outgoing queue. device %s", obj->videodev);
713         break;
714       case EINVAL:
715         GST_ERROR_OBJECT (pool,
716             "The buffer type is not supported, or the index is out of bounds, "
717             "or no buffers have been allocated yet, or the userptr "
718             "or length are invalid. device %s", obj->videodev);
719         break;
720       case ENOMEM:
721         GST_ERROR_OBJECT (pool,
722             "insufficient memory to enqueue a user pointer buffer");
723         break;
724       case EIO:
725         GST_INFO_OBJECT (pool,
726             "VIDIOC_DQBUF failed due to an internal error."
727             " Can also indicate temporary problems like signal loss."
728             " Note the driver might dequeue an (empty) buffer despite"
729             " returning an error, or even stop capturing."
730             " device %s", obj->videodev);
731         /* have we de-queued a buffer ? */
732         if (!(vbuffer.flags & (V4L2_BUF_FLAG_QUEUED | V4L2_BUF_FLAG_DONE))) {
733           GST_DEBUG_OBJECT (pool, "reenqueing buffer");
734           /* FIXME ... should we do something here? */
735         }
736         break;
737       case EINTR:
738         GST_WARNING_OBJECT (pool,
739             "could not sync on a buffer on device %s", obj->videodev);
740         break;
741       default:
742         GST_WARNING_OBJECT (pool,
743             "Grabbing frame got interrupted on %s unexpectedly. %d: %s.",
744             obj->videodev, errno, g_strerror (errno));
745         break;
746     }
747     return GST_FLOW_ERROR;
748   }
749 no_buffer:
750   {
751     GST_ERROR_OBJECT (pool, "No free buffer found in the pool at index %d.",
752         vbuffer.index);
753     return GST_FLOW_ERROR;
754   }
755 }
756
757 static GstFlowReturn
758 gst_v4l2_buffer_pool_acquire_buffer (GstBufferPool * bpool, GstBuffer ** buffer,
759     GstBufferPoolAcquireParams * params)
760 {
761   GstFlowReturn ret;
762   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
763   GstV4l2Object *obj = pool->obj;
764
765   GST_DEBUG_OBJECT (pool, "acquire");
766
767   if (GST_BUFFER_POOL_IS_FLUSHING (bpool))
768     goto flushing;
769
770   switch (obj->type) {
771     case V4L2_BUF_TYPE_VIDEO_CAPTURE:
772       /* capture, This function should return a buffer with new captured data */
773       switch (obj->mode) {
774         case GST_V4L2_IO_RW:
775           /* take empty buffer from the pool */
776           ret = GST_BUFFER_POOL_CLASS (parent_class)->acquire_buffer (bpool,
777               buffer, params);
778           break;
779         case GST_V4L2_IO_DMABUF:
780         case GST_V4L2_IO_MMAP:
781           /* just dequeue a buffer, we basically use the queue of v4l2 as the
782            * storage for our buffers. This function does poll first so we can
783            * interrupt it fine. */
784           ret = gst_v4l2_buffer_pool_dqbuf (pool, buffer);
785           if (G_UNLIKELY (ret != GST_FLOW_OK))
786             goto done;
787
788           /* start copying buffers when we are running low on buffers */
789           if (pool->num_queued < pool->copy_threshold) {
790             GstBuffer *copy;
791
792             /* copy the memory */
793             copy = gst_buffer_copy (*buffer);
794             GST_LOG_OBJECT (pool, "copy buffer %p->%p", *buffer, copy);
795
796             /* and requeue so that we can continue capturing */
797             ret = gst_v4l2_buffer_pool_qbuf (pool, *buffer);
798             *buffer = copy;
799           }
800           break;
801
802         case GST_V4L2_IO_USERPTR:
803         default:
804           ret = GST_FLOW_ERROR;
805           g_assert_not_reached ();
806           break;
807       }
808       break;
809
810     case V4L2_BUF_TYPE_VIDEO_OUTPUT:
811       /* playback, This function should return an empty buffer */
812       switch (obj->mode) {
813         case GST_V4L2_IO_RW:
814           /* get an empty buffer */
815           ret = GST_BUFFER_POOL_CLASS (parent_class)->acquire_buffer (bpool,
816               buffer, params);
817           break;
818
819         case GST_V4L2_IO_MMAP:
820           /* get a free unqueued buffer */
821           ret = GST_BUFFER_POOL_CLASS (parent_class)->acquire_buffer (bpool,
822               buffer, params);
823           break;
824
825         case GST_V4L2_IO_USERPTR:
826         default:
827           ret = GST_FLOW_ERROR;
828           g_assert_not_reached ();
829           break;
830       }
831       break;
832
833     default:
834       ret = GST_FLOW_ERROR;
835       g_assert_not_reached ();
836       break;
837   }
838 done:
839   return ret;
840
841   /* ERRORS */
842 flushing:
843   {
844     GST_DEBUG_OBJECT (pool, "We are flushing");
845     return GST_FLOW_FLUSHING;
846   }
847 }
848
849 static void
850 gst_v4l2_buffer_pool_release_buffer (GstBufferPool * bpool, GstBuffer * buffer)
851 {
852   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
853   GstV4l2Object *obj = pool->obj;
854
855   GST_DEBUG_OBJECT (pool, "release buffer %p", buffer);
856
857   switch (obj->type) {
858     case V4L2_BUF_TYPE_VIDEO_CAPTURE:
859       /* capture, put the buffer back in the queue so that we can refill it
860        * later. */
861       switch (obj->mode) {
862         case GST_V4L2_IO_RW:
863           /* release back in the pool */
864           GST_BUFFER_POOL_CLASS (parent_class)->release_buffer (bpool, buffer);
865           break;
866
867         case GST_V4L2_IO_DMABUF:
868         case GST_V4L2_IO_MMAP:
869           /* queue back in the device */
870           gst_v4l2_buffer_pool_qbuf (pool, buffer);
871           break;
872
873         case GST_V4L2_IO_USERPTR:
874         default:
875           g_assert_not_reached ();
876           break;
877       }
878       break;
879
880     case V4L2_BUF_TYPE_VIDEO_OUTPUT:
881       switch (obj->mode) {
882         case GST_V4L2_IO_RW:
883           /* release back in the pool */
884           GST_BUFFER_POOL_CLASS (parent_class)->release_buffer (bpool, buffer);
885           break;
886
887         case GST_V4L2_IO_MMAP:
888         {
889           GstV4l2Meta *meta;
890           guint index;
891
892           meta = GST_V4L2_META_GET (buffer);
893           g_assert (meta != NULL);
894
895           index = meta->vbuffer.index;
896
897           if (pool->buffers[index] == NULL) {
898             GST_LOG_OBJECT (pool, "buffer %u not queued, putting on free list",
899                 index);
900             /* playback, put the buffer back in the queue to refill later. */
901             GST_BUFFER_POOL_CLASS (parent_class)->release_buffer (bpool,
902                 buffer);
903           } else {
904             /* the buffer is queued in the device but maybe not played yet. We just
905              * leave it there and not make it available for future calls to acquire
906              * for now. The buffer will be dequeued and reused later. */
907             GST_LOG_OBJECT (pool, "buffer %u is queued", index);
908           }
909           break;
910         }
911
912         case GST_V4L2_IO_USERPTR:
913         default:
914           g_assert_not_reached ();
915           break;
916       }
917       break;
918
919     default:
920       g_assert_not_reached ();
921       break;
922   }
923 }
924
925 static void
926 gst_v4l2_buffer_pool_finalize (GObject * object)
927 {
928   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (object);
929
930   if (pool->video_fd >= 0)
931     v4l2_close (pool->video_fd);
932   if (pool->allocator)
933     gst_object_unref (pool->allocator);
934   g_free (pool->buffers);
935
936   G_OBJECT_CLASS (parent_class)->finalize (object);
937 }
938
939 static void
940 gst_v4l2_buffer_pool_init (GstV4l2BufferPool * pool)
941 {
942 }
943
944 static void
945 gst_v4l2_buffer_pool_class_init (GstV4l2BufferPoolClass * klass)
946 {
947   GObjectClass *object_class = G_OBJECT_CLASS (klass);
948   GstBufferPoolClass *bufferpool_class = GST_BUFFER_POOL_CLASS (klass);
949
950   object_class->finalize = gst_v4l2_buffer_pool_finalize;
951
952   bufferpool_class->start = gst_v4l2_buffer_pool_start;
953   bufferpool_class->stop = gst_v4l2_buffer_pool_stop;
954   bufferpool_class->set_config = gst_v4l2_buffer_pool_set_config;
955   bufferpool_class->alloc_buffer = gst_v4l2_buffer_pool_alloc_buffer;
956   bufferpool_class->acquire_buffer = gst_v4l2_buffer_pool_acquire_buffer;
957   bufferpool_class->release_buffer = gst_v4l2_buffer_pool_release_buffer;
958   bufferpool_class->free_buffer = gst_v4l2_buffer_pool_free_buffer;
959 }
960
961 /**
962  * gst_v4l2_buffer_pool_new:
963  * @obj:  the v4l2 object owning the pool
964  *
965  * Construct a new buffer pool.
966  *
967  * Returns: the new pool, use gst_object_unref() to free resources
968  */
969 GstBufferPool *
970 gst_v4l2_buffer_pool_new (GstV4l2Object * obj, GstCaps * caps)
971 {
972   GstV4l2BufferPool *pool;
973   GstStructure *s;
974   gint fd;
975
976   fd = v4l2_dup (obj->video_fd);
977   if (fd < 0)
978     goto dup_failed;
979
980   pool = (GstV4l2BufferPool *) g_object_new (GST_TYPE_V4L2_BUFFER_POOL, NULL);
981   pool->video_fd = fd;
982   pool->obj = obj;
983
984   s = gst_buffer_pool_get_config (GST_BUFFER_POOL_CAST (pool));
985   gst_buffer_pool_config_set_params (s, caps, obj->sizeimage, 2, 0);
986   gst_buffer_pool_set_config (GST_BUFFER_POOL_CAST (pool), s);
987
988   return GST_BUFFER_POOL (pool);
989
990   /* ERRORS */
991 dup_failed:
992   {
993     GST_DEBUG ("failed to dup fd %d (%s)", errno, g_strerror (errno));
994     return NULL;
995   }
996 }
997
998 static GstFlowReturn
999 gst_v4l2_do_read (GstV4l2BufferPool * pool, GstBuffer * buf)
1000 {
1001   GstFlowReturn res;
1002   GstV4l2Object *obj = pool->obj;
1003   gint amount;
1004   GstMapInfo map;
1005   gint toread;
1006
1007   toread = obj->sizeimage;
1008
1009   GST_LOG_OBJECT (pool, "reading %d bytes into buffer %p", toread, buf);
1010
1011   gst_buffer_map (buf, &map, GST_MAP_WRITE);
1012
1013   do {
1014     if ((res = gst_v4l2_object_poll (obj)) != GST_FLOW_OK)
1015       goto poll_error;
1016
1017     amount = v4l2_read (obj->video_fd, map.data, toread);
1018
1019     if (amount == toread) {
1020       break;
1021     } else if (amount == -1) {
1022       if (errno == EAGAIN || errno == EINTR) {
1023         continue;
1024       } else
1025         goto read_error;
1026     } else {
1027       /* short reads can happen if a signal interrupts the read */
1028       continue;
1029     }
1030   } while (TRUE);
1031
1032   GST_LOG_OBJECT (pool, "read %d bytes", amount);
1033   gst_buffer_unmap (buf, &map);
1034   gst_buffer_resize (buf, 0, amount);
1035
1036   return GST_FLOW_OK;
1037
1038   /* ERRORS */
1039 poll_error:
1040   {
1041     GST_DEBUG ("poll error %s", gst_flow_get_name (res));
1042     goto cleanup;
1043   }
1044 read_error:
1045   {
1046     GST_ELEMENT_ERROR (obj->element, RESOURCE, READ,
1047         (_("Error reading %d bytes from device '%s'."),
1048             toread, obj->videodev), GST_ERROR_SYSTEM);
1049     res = GST_FLOW_ERROR;
1050     goto cleanup;
1051   }
1052 cleanup:
1053   {
1054     gst_buffer_unmap (buf, &map);
1055     gst_buffer_resize (buf, 0, 0);
1056     return res;
1057   }
1058 }
1059
1060 /**
1061  * gst_v4l2_buffer_pool_process:
1062  * @bpool: a #GstBufferPool
1063  * @buf: a #GstBuffer
1064  *
1065  * Process @buf in @bpool. For capture devices, this functions fills @buf with
1066  * data from the device. For output devices, this functions send the contents of
1067  * @buf to the device for playback.
1068  *
1069  * Returns: %GST_FLOW_OK on success.
1070  */
1071 GstFlowReturn
1072 gst_v4l2_buffer_pool_process (GstV4l2BufferPool * pool, GstBuffer * buf)
1073 {
1074   GstFlowReturn ret = GST_FLOW_OK;
1075   GstBufferPool *bpool = GST_BUFFER_POOL_CAST (pool);
1076   GstV4l2Object *obj = pool->obj;
1077
1078   GST_DEBUG_OBJECT (pool, "process buffer %p", buf);
1079
1080   switch (obj->type) {
1081     case V4L2_BUF_TYPE_VIDEO_CAPTURE:
1082       /* capture */
1083       switch (obj->mode) {
1084         case GST_V4L2_IO_RW:
1085           /* capture into the buffer */
1086           ret = gst_v4l2_do_read (pool, buf);
1087           break;
1088
1089         case GST_V4L2_IO_MMAP:
1090         {
1091           GstBuffer *tmp;
1092
1093           if (buf->pool == bpool)
1094             /* nothing, data was inside the buffer when we did _acquire() */
1095             goto done;
1096
1097           /* buffer not from our pool, grab a frame and copy it into the target */
1098           if ((ret = gst_v4l2_buffer_pool_dqbuf (pool, &tmp)) != GST_FLOW_OK)
1099             goto done;
1100
1101           if (!gst_v4l2_object_copy (obj, buf, tmp))
1102             goto copy_failed;
1103
1104           /* an queue the buffer again after the copy */
1105           if ((ret = gst_v4l2_buffer_pool_qbuf (pool, tmp)) != GST_FLOW_OK)
1106             goto done;
1107           break;
1108         }
1109
1110         case GST_V4L2_IO_USERPTR:
1111         default:
1112           g_assert_not_reached ();
1113           break;
1114       }
1115       break;
1116
1117     case V4L2_BUF_TYPE_VIDEO_OUTPUT:
1118       /* playback */
1119       switch (obj->mode) {
1120         case GST_V4L2_IO_RW:
1121           /* FIXME, do write() */
1122           GST_WARNING_OBJECT (pool, "implement write()");
1123           break;
1124         case GST_V4L2_IO_DMABUF:
1125         case GST_V4L2_IO_MMAP:
1126         {
1127           GstBuffer *to_queue;
1128
1129           if (buf->pool == bpool) {
1130             /* nothing, we can queue directly */
1131             to_queue = buf;
1132             GST_LOG_OBJECT (pool, "processing buffer from our pool");
1133           } else {
1134             GST_LOG_OBJECT (pool, "alloc buffer from our pool");
1135             if (!gst_buffer_pool_is_active (bpool)) {
1136               GstStructure *config;
1137
1138               /* this pool was not activated, configure and activate */
1139               GST_DEBUG_OBJECT (pool, "activating pool");
1140
1141               config = gst_buffer_pool_get_config (bpool);
1142               gst_buffer_pool_config_add_option (config,
1143                   GST_BUFFER_POOL_OPTION_VIDEO_META);
1144               gst_buffer_pool_set_config (bpool, config);
1145
1146               if (!gst_buffer_pool_set_active (bpool, TRUE))
1147                 goto activate_failed;
1148             }
1149
1150             /* this can block if all buffers are outstanding which would be
1151              * strange because we would expect the upstream element to have
1152              * allocated them and returned to us.. */
1153             ret = GST_BUFFER_POOL_CLASS (parent_class)->acquire_buffer (bpool,
1154                 &to_queue, NULL);
1155             if (ret != GST_FLOW_OK)
1156               goto acquire_failed;
1157
1158             /* copy into it and queue */
1159             if (!gst_v4l2_object_copy (obj, to_queue, buf))
1160               goto copy_failed;
1161           }
1162
1163           if ((ret = gst_v4l2_buffer_pool_qbuf (pool, to_queue)) != GST_FLOW_OK)
1164             goto done;
1165
1166           /* if we are not streaming yet (this is the first buffer, start
1167            * streaming now */
1168           if (!pool->streaming)
1169             if (!start_streaming (pool))
1170               goto start_failed;
1171
1172           if (pool->num_queued == pool->num_allocated) {
1173             /* all buffers are queued, try to dequeue one and release it back
1174              * into the pool so that _acquire can get to it again. */
1175             ret = gst_v4l2_buffer_pool_dqbuf (pool, &to_queue);
1176             if (ret != GST_FLOW_OK)
1177               goto done;
1178
1179             /* release the rendered buffer back into the pool. This wakes up any
1180              * thread waiting for a buffer in _acquire() */
1181             gst_v4l2_buffer_pool_release_buffer (bpool, to_queue);
1182           }
1183           break;
1184         }
1185
1186         case GST_V4L2_IO_USERPTR:
1187         default:
1188           g_assert_not_reached ();
1189           break;
1190       }
1191       break;
1192     default:
1193       g_assert_not_reached ();
1194       break;
1195   }
1196 done:
1197   return ret;
1198
1199   /* ERRORS */
1200 activate_failed:
1201   {
1202     GST_ERROR_OBJECT (obj->element, "failed to activate pool");
1203     return GST_FLOW_ERROR;
1204   }
1205 acquire_failed:
1206   {
1207     GST_WARNING_OBJECT (obj->element, "failed to acquire a buffer: %s",
1208         gst_flow_get_name (ret));
1209     return ret;
1210   }
1211 copy_failed:
1212   {
1213     GST_ERROR_OBJECT (obj->element, "failed to copy data");
1214     return GST_FLOW_ERROR;
1215   }
1216 start_failed:
1217   {
1218     GST_ERROR_OBJECT (obj->element, "failed to start streaming");
1219     return GST_FLOW_ERROR;
1220   }
1221 }