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