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