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