v4l2: More work on bufferpools
[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
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   return TRUE;
249
250 wrong_config:
251   {
252     GST_WARNING_OBJECT (pool, "invalid config %" GST_PTR_FORMAT, config);
253     return FALSE;
254   }
255 }
256
257 static gboolean
258 start_streaming (GstBufferPool * bpool)
259 {
260   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
261   GstV4l2Object *obj = pool->obj;
262
263   switch (obj->mode) {
264     case GST_V4L2_IO_RW:
265       break;
266     case GST_V4L2_IO_MMAP:
267     case GST_V4L2_IO_USERPTR:
268       GST_DEBUG_OBJECT (pool, "STREAMON");
269       if (v4l2_ioctl (pool->video_fd, VIDIOC_STREAMON, &obj->type) < 0)
270         goto start_failed;
271       break;
272     default:
273       g_assert_not_reached ();
274       break;
275   }
276
277   pool->streaming = TRUE;
278
279   return TRUE;
280
281   /* ERRORS */
282 start_failed:
283   {
284     GST_ERROR_OBJECT (pool, "error with STREAMON %d (%s)", errno,
285         g_strerror (errno));
286     return FALSE;
287   }
288 }
289
290 static gboolean
291 gst_v4l2_buffer_pool_start (GstBufferPool * bpool)
292 {
293   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
294   GstV4l2Object *obj = pool->obj;
295   gint n;
296   struct v4l2_requestbuffers breq;
297   gint num_buffers;
298
299   num_buffers = pool->min_buffers;
300
301   switch (obj->mode) {
302     case GST_V4L2_IO_RW:
303     {
304       break;
305     }
306     case GST_V4L2_IO_MMAP:
307     {
308       /* first, lets request buffers, and see how many we can get: */
309       GST_DEBUG_OBJECT (pool, "starting, requesting %d MMAP buffers",
310           num_buffers);
311
312       memset (&breq, 0, sizeof (struct v4l2_requestbuffers));
313       breq.type = obj->type;
314       breq.count = num_buffers;
315       breq.memory = V4L2_MEMORY_MMAP;
316
317       if (v4l2_ioctl (pool->video_fd, VIDIOC_REQBUFS, &breq) < 0)
318         goto reqbufs_failed;
319
320       GST_LOG_OBJECT (pool, " count:  %u", breq.count);
321       GST_LOG_OBJECT (pool, " type:   %d", breq.type);
322       GST_LOG_OBJECT (pool, " memory: %d", breq.memory);
323
324       if (breq.count < GST_V4L2_MIN_BUFFERS)
325         goto no_buffers;
326
327       if (num_buffers != breq.count) {
328         GST_WARNING_OBJECT (pool, "using %u buffers instead", breq.count);
329         num_buffers = breq.count;
330       }
331       break;
332     }
333     case GST_V4L2_IO_USERPTR:
334     default:
335       g_assert_not_reached ();
336       break;
337   }
338
339   pool->obj = obj;
340   pool->num_buffers = num_buffers;
341   pool->buffers = g_new0 (GstBuffer *, num_buffers);
342   pool->index = 0;
343
344   /* now, allocate the buffers: */
345   for (n = 0; n < num_buffers; n++) {
346     GstBuffer *buffer;
347
348     if (gst_v4l2_buffer_pool_alloc_buffer (bpool, &buffer, NULL) != GST_FLOW_OK)
349       goto buffer_new_failed;
350
351     gst_v4l2_buffer_pool_release_buffer (bpool, buffer);
352   }
353
354   /* we can start capturing now, we wait for the playback case until we queued
355    * the first buffer */
356   if (obj->type == V4L2_BUF_TYPE_VIDEO_CAPTURE)
357     if (!start_streaming (bpool))
358       goto start_failed;
359
360   return TRUE;
361
362   /* ERRORS */
363 reqbufs_failed:
364   {
365     GST_ERROR_OBJECT (pool,
366         "error requesting %d buffers: %s", num_buffers, g_strerror (errno));
367     return FALSE;
368   }
369 no_buffers:
370   {
371     GST_ERROR_OBJECT (pool,
372         "we received %d from device '%s', we want at least %d",
373         breq.count, obj->videodev, GST_V4L2_MIN_BUFFERS);
374     return FALSE;
375   }
376 buffer_new_failed:
377   {
378     GST_ERROR_OBJECT (pool, "failed to create a buffer");
379     return FALSE;
380   }
381 start_failed:
382   {
383     GST_ERROR_OBJECT (pool, "failed to start streaming");
384     return FALSE;
385   }
386 }
387
388 static gboolean
389 gst_v4l2_buffer_pool_stop (GstBufferPool * bpool)
390 {
391   gboolean ret;
392   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
393   GstV4l2Object *obj = pool->obj;
394   guint n;
395
396   GST_DEBUG_OBJECT (pool, "stopping pool");
397
398   switch (obj->mode) {
399     case GST_V4L2_IO_RW:
400       break;
401     case GST_V4L2_IO_MMAP:
402     case GST_V4L2_IO_USERPTR:
403       /* we actually need to sync on all queued buffers but not
404        * on the non-queued ones */
405       GST_DEBUG_OBJECT (pool, "STREAMOFF");
406       if (v4l2_ioctl (pool->video_fd, VIDIOC_STREAMOFF, &obj->type) < 0)
407         goto stop_failed;
408       break;
409     default:
410       g_assert_not_reached ();
411       break;
412   }
413
414   pool->streaming = FALSE;
415
416   /* first free the buffers in the queue */
417   ret = GST_BUFFER_POOL_CLASS (parent_class)->stop (bpool);
418
419   /* then free the remaining buffers */
420   for (n = 0; n < pool->num_buffers; n++) {
421     if (pool->buffers[n])
422       gst_v4l2_buffer_pool_free_buffer (bpool, pool->buffers[n]);
423   }
424   return ret;
425
426   /* ERRORS */
427 stop_failed:
428   {
429     GST_ERROR_OBJECT (pool, "error with STREAMOFF %d (%s)", errno,
430         g_strerror (errno));
431     return FALSE;
432   }
433 }
434
435 static GstFlowReturn
436 gst_v4l2_object_poll (GstV4l2Object * v4l2object)
437 {
438   gint ret;
439
440   if (v4l2object->can_poll_device) {
441     ret = gst_poll_wait (v4l2object->poll, GST_CLOCK_TIME_NONE);
442     if (G_UNLIKELY (ret < 0)) {
443       if (errno == EBUSY)
444         goto stopped;
445       if (errno == ENXIO) {
446         GST_DEBUG_OBJECT (v4l2object->element,
447             "v4l2 device doesn't support polling. Disabling");
448         v4l2object->can_poll_device = FALSE;
449       } else {
450         if (errno != EAGAIN && errno != EINTR)
451           goto select_error;
452       }
453     }
454   }
455   return GST_FLOW_OK;
456
457   /* ERRORS */
458 stopped:
459   {
460     GST_DEBUG ("stop called");
461     return GST_FLOW_WRONG_STATE;
462   }
463 select_error:
464   {
465     GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, READ, (NULL),
466         ("poll error %d: %s (%d)", ret, g_strerror (errno), errno));
467     return GST_FLOW_ERROR;
468   }
469 }
470
471 static GstFlowReturn
472 gst_v4l2_buffer_pool_qbuf (GstBufferPool * bpool, GstBuffer * buf)
473 {
474   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
475   GstMetaV4l2 *meta;
476   gint index;
477
478   meta = GST_META_V4L2_GET (buf);
479   g_assert (meta != NULL);
480
481   index = meta->vbuffer.index;
482
483   GST_LOG_OBJECT (pool, "enqueue pool buffer %d, queued: %d", index,
484       pool->num_queued);
485
486   if (pool->buffers[index] != NULL)
487     goto already_queued;
488
489   if (v4l2_ioctl (pool->video_fd, VIDIOC_QBUF, &meta->vbuffer) < 0)
490     goto queue_failed;
491
492   pool->buffers[index] = buf;
493
494   pool->num_queued++;
495
496   return GST_FLOW_OK;
497
498   /* ERRORS */
499 already_queued:
500   {
501     GST_WARNING_OBJECT (pool, "the buffer was already queued");
502     return GST_FLOW_ERROR;
503   }
504 queue_failed:
505   {
506     GST_WARNING_OBJECT (pool, "could not queue a buffer");
507     return GST_FLOW_ERROR;
508   }
509 }
510
511 static GstFlowReturn
512 gst_v4l2_buffer_pool_dqbuf (GstBufferPool * bpool, GstBuffer ** buffer)
513 {
514   GstFlowReturn res;
515   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
516   GstBuffer *outbuf;
517   struct v4l2_buffer vbuffer;
518   GstV4l2Object *obj = pool->obj;
519
520   if ((res = gst_v4l2_object_poll (obj)) != GST_FLOW_OK)
521     goto poll_error;
522
523   memset (&vbuffer, 0x00, sizeof (vbuffer));
524   vbuffer.type = obj->type;
525   vbuffer.memory = V4L2_MEMORY_MMAP;
526
527   if (v4l2_ioctl (pool->video_fd, VIDIOC_DQBUF, &vbuffer) < 0)
528     goto error;
529
530   /* get our GstBuffer with that index from the pool, if the buffer was
531    * outstanding we have a serious problem.
532    */
533   outbuf = pool->buffers[vbuffer.index];
534   if (outbuf == NULL)
535     goto no_buffers;
536
537   /* mark the buffer outstanding */
538   pool->buffers[vbuffer.index] = NULL;
539   pool->num_queued--;
540
541   GST_LOG_OBJECT (pool,
542       "dequeued frame %d (ix=%d), used %d, flags %08x, pool-queued=%d, buffer=%p",
543       vbuffer.sequence, vbuffer.index, vbuffer.bytesused, vbuffer.flags,
544       pool->num_queued, outbuf);
545
546   /* set top/bottom field first if v4l2_buffer has the information */
547   if (vbuffer.field == V4L2_FIELD_INTERLACED_TB)
548     GST_BUFFER_FLAG_SET (outbuf, GST_VIDEO_BUFFER_TFF);
549   if (vbuffer.field == V4L2_FIELD_INTERLACED_BT)
550     GST_BUFFER_FLAG_UNSET (outbuf, GST_VIDEO_BUFFER_TFF);
551
552   /* this can change at every frame, esp. with jpeg */
553   if (obj->type == V4L2_BUF_TYPE_VIDEO_CAPTURE)
554     gst_buffer_resize (outbuf, 0, vbuffer.bytesused);
555   else
556     gst_buffer_resize (outbuf, 0, vbuffer.length);
557
558   *buffer = outbuf;
559
560   return GST_FLOW_OK;
561
562   /* ERRORS */
563 poll_error:
564   {
565     GST_DEBUG ("poll error %s", gst_flow_get_name (res));
566     return res;
567   }
568 error:
569   {
570     GST_WARNING_OBJECT (pool,
571         "problem dequeuing frame %d (ix=%d), pool-ct=%d, buf.flags=%d",
572         vbuffer.sequence, vbuffer.index,
573         GST_MINI_OBJECT_REFCOUNT (pool), vbuffer.flags);
574
575     switch (errno) {
576       case EAGAIN:
577         GST_WARNING_OBJECT (pool,
578             "Non-blocking I/O has been selected using O_NONBLOCK and"
579             " no buffer was in the outgoing queue. device %s", obj->videodev);
580         break;
581       case EINVAL:
582         GST_ERROR_OBJECT (pool,
583             "The buffer type is not supported, or the index is out of bounds, "
584             "or no buffers have been allocated yet, or the userptr "
585             "or length are invalid. device %s", obj->videodev);
586         break;
587       case ENOMEM:
588         GST_ERROR_OBJECT (pool,
589             "insufficient memory to enqueue a user pointer buffer");
590         break;
591       case EIO:
592         GST_INFO_OBJECT (pool,
593             "VIDIOC_DQBUF failed due to an internal error."
594             " Can also indicate temporary problems like signal loss."
595             " Note the driver might dequeue an (empty) buffer despite"
596             " returning an error, or even stop capturing."
597             " device %s", obj->videodev);
598         /* have we de-queued a buffer ? */
599         if (!(vbuffer.flags & (V4L2_BUF_FLAG_QUEUED | V4L2_BUF_FLAG_DONE))) {
600           GST_DEBUG_OBJECT (pool, "reenqueing buffer");
601           /* FIXME ... should we do something here? */
602         }
603         break;
604       case EINTR:
605         GST_WARNING_OBJECT (pool,
606             "could not sync on a buffer on device %s", obj->videodev);
607         break;
608       default:
609         GST_WARNING_OBJECT (pool,
610             "Grabbing frame got interrupted on %s unexpectedly. %d: %s.",
611             obj->videodev, errno, g_strerror (errno));
612         break;
613     }
614     return GST_FLOW_ERROR;
615   }
616 no_buffers:
617   {
618     GST_ERROR_OBJECT (pool, "No free buffers found in the pool at index %d.",
619         vbuffer.index);
620     return GST_FLOW_ERROR;
621   }
622 }
623
624 static GstFlowReturn
625 gst_v4l2_buffer_pool_acquire_buffer (GstBufferPool * bpool, GstBuffer ** buffer,
626     GstBufferPoolParams * params)
627 {
628   GstFlowReturn ret;
629   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
630   GstV4l2Object *obj = pool->obj;
631
632   GST_DEBUG_OBJECT (pool, "acquire");
633
634   if (GST_BUFFER_POOL_IS_FLUSHING (bpool))
635     goto flushing;
636
637   switch (obj->type) {
638     case V4L2_BUF_TYPE_VIDEO_CAPTURE:
639       /* capture, This function should return a buffer with new captured data */
640       switch (obj->mode) {
641         case GST_V4L2_IO_RW:
642           /* take empty buffer from the pool */
643           ret = GST_BUFFER_POOL_CLASS (parent_class)->acquire_buffer (bpool,
644               buffer, params);
645           break;
646
647         case GST_V4L2_IO_MMAP:
648           /* just dequeue a buffer, we basically use the queue of v4l2 as the
649            * storage for our buffers. */
650           ret = gst_v4l2_buffer_pool_dqbuf (bpool, buffer);
651           break;
652
653         case GST_V4L2_IO_USERPTR:
654         default:
655           g_assert_not_reached ();
656           break;
657       }
658       break;
659
660     case V4L2_BUF_TYPE_VIDEO_OUTPUT:
661       /* playback, This function should return an empty buffer */
662       switch (obj->mode) {
663         case GST_V4L2_IO_RW:
664           /* get an empty buffer */
665           ret = GST_BUFFER_POOL_CLASS (parent_class)->acquire_buffer (bpool,
666               buffer, params);
667           break;
668
669         case GST_V4L2_IO_MMAP:
670           /* first try to get a free unqueued buffer */
671           ret = GST_BUFFER_POOL_CLASS (parent_class)->acquire_buffer (bpool,
672               buffer, params);
673           if (ret == GST_FLOW_UNEXPECTED) {
674             /* all buffers are queued, try to dequeue one */
675             ret = gst_v4l2_buffer_pool_dqbuf (bpool, buffer);
676           }
677           break;
678
679         case GST_V4L2_IO_USERPTR:
680         default:
681           g_assert_not_reached ();
682           break;
683       }
684       break;
685
686     default:
687       g_assert_not_reached ();
688       break;
689   }
690   return ret;
691
692   /* ERRORS */
693 flushing:
694   {
695     GST_DEBUG_OBJECT (bpool, "We are flushing");
696     return GST_FLOW_WRONG_STATE;
697   }
698 }
699
700 static void
701 gst_v4l2_buffer_pool_release_buffer (GstBufferPool * bpool, GstBuffer * buffer)
702 {
703   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
704   GstV4l2Object *obj = pool->obj;
705
706   GST_DEBUG_OBJECT (pool, "release");
707
708   switch (obj->type) {
709     case V4L2_BUF_TYPE_VIDEO_CAPTURE:
710       /* capture, put the buffer back in the queue so that we can refill it
711        * later. */
712       switch (obj->mode) {
713         case GST_V4L2_IO_RW:
714           /* release back in the pool */
715           GST_BUFFER_POOL_CLASS (parent_class)->release_buffer (bpool, buffer);
716           break;
717
718         case GST_V4L2_IO_MMAP:
719           /* queue back in the device */
720           gst_v4l2_buffer_pool_qbuf (bpool, buffer);
721           break;
722
723         case GST_V4L2_IO_USERPTR:
724         default:
725           g_assert_not_reached ();
726           break;
727       }
728       break;
729
730     case V4L2_BUF_TYPE_VIDEO_OUTPUT:
731       /* playback, put the buffer back in the queue to refill later. */
732       GST_BUFFER_POOL_CLASS (parent_class)->release_buffer (bpool, buffer);
733       break;
734
735     default:
736       g_assert_not_reached ();
737       break;
738   }
739 }
740
741 static void
742 gst_v4l2_buffer_pool_finalize (GObject * object)
743 {
744   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (object);
745
746   if (pool->video_fd >= 0)
747     v4l2_close (pool->video_fd);
748
749   if (pool->buffers) {
750     g_free (pool->buffers);
751     pool->buffers = NULL;
752   }
753
754   G_OBJECT_CLASS (parent_class)->finalize (object);
755 }
756
757 static void
758 gst_v4l2_buffer_pool_init (GstV4l2BufferPool * pool)
759 {
760 }
761
762 static void
763 gst_v4l2_buffer_pool_class_init (GstV4l2BufferPoolClass * klass)
764 {
765   GObjectClass *object_class = G_OBJECT_CLASS (klass);
766   GstBufferPoolClass *bufferpool_class = GST_BUFFER_POOL_CLASS (klass);
767
768   object_class->finalize = gst_v4l2_buffer_pool_finalize;
769
770   bufferpool_class->start = gst_v4l2_buffer_pool_start;
771   bufferpool_class->stop = gst_v4l2_buffer_pool_stop;
772   bufferpool_class->set_config = gst_v4l2_buffer_pool_set_config;
773   bufferpool_class->alloc_buffer = gst_v4l2_buffer_pool_alloc_buffer;
774   bufferpool_class->acquire_buffer = gst_v4l2_buffer_pool_acquire_buffer;
775   bufferpool_class->release_buffer = gst_v4l2_buffer_pool_release_buffer;
776   bufferpool_class->free_buffer = gst_v4l2_buffer_pool_free_buffer;
777 }
778
779 /**
780  * gst_v4l2_buffer_pool_new:
781  * @obj:  the v4l2 object owning the pool
782  * @num_buffers:  the requested number of buffers in the pool
783  * @requeuebuf: if %TRUE, and if the pool is still in the running state, a
784  *  buffer with no remaining references is immediately passed back to v4l2
785  *  (VIDIOC_QBUF), otherwise it is returned to the pool of available buffers
786  *  (which can be accessed via gst_v4l2_buffer_pool_get().
787  *
788  * Construct a new buffer pool.
789  *
790  * Returns: the new pool, use gst_v4l2_buffer_pool_destroy() to free resources
791  */
792 GstBufferPool *
793 gst_v4l2_buffer_pool_new (GstV4l2Object * obj)
794 {
795   GstV4l2BufferPool *pool;
796   gint fd;
797
798   fd = v4l2_dup (obj->video_fd);
799   if (fd < 0)
800     goto dup_failed;
801
802   pool = (GstV4l2BufferPool *) g_object_new (GST_TYPE_V4L2_BUFFER_POOL, NULL);
803   pool->video_fd = fd;
804   pool->obj = obj;
805
806   return GST_BUFFER_POOL_CAST (pool);
807
808   /* ERRORS */
809 dup_failed:
810   {
811     GST_DEBUG ("failed to dup fd %d (%s)", errno, g_strerror (errno));
812     return NULL;
813   }
814 }
815
816 static GstFlowReturn
817 gst_v4l2_do_read (GstBufferPool * bpool, GstBuffer * buf)
818 {
819   GstFlowReturn res;
820   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
821   GstV4l2Object *obj = pool->obj;
822   gint amount;
823   gpointer data;
824   gint buffersize;
825
826   buffersize = gst_buffer_get_size (buf);
827
828   GST_LOG_OBJECT (pool, "reading %d bytes into buffer %p", buffersize, buf);
829
830   data = gst_buffer_map (buf, NULL, NULL, GST_MAP_WRITE);
831
832   do {
833     if ((res = gst_v4l2_object_poll (obj)) != GST_FLOW_OK)
834       goto poll_error;
835
836     amount = v4l2_read (obj->video_fd, data, buffersize);
837
838     if (amount == buffersize) {
839       break;
840     } else if (amount == -1) {
841       if (errno == EAGAIN || errno == EINTR) {
842         continue;
843       } else
844         goto read_error;
845     } else {
846       /* short reads can happen if a signal interrupts the read */
847       continue;
848     }
849   } while (TRUE);
850
851   GST_LOG_OBJECT (pool, "read %d bytes", amount);
852   gst_buffer_unmap (buf, data, amount);
853
854   return GST_FLOW_OK;
855
856   /* ERRORS */
857 poll_error:
858   {
859     GST_DEBUG ("poll error %s", gst_flow_get_name (res));
860     goto cleanup;
861   }
862 read_error:
863   {
864     GST_ELEMENT_ERROR (obj->element, RESOURCE, READ,
865         (_("Error reading %d bytes from device '%s'."),
866             buffersize, obj->videodev), GST_ERROR_SYSTEM);
867     res = GST_FLOW_ERROR;
868     goto cleanup;
869   }
870 cleanup:
871   {
872     gst_buffer_unmap (buf, data, 0);
873     return res;
874   }
875 }
876
877 /**
878  * gst_v4l2_buffer_pool_process:
879  * @bpool: a #GstBufferPool
880  * @buf: a #GstBuffer
881  *
882  * Process @buf in @bpool. For capture devices, this functions fills @buf with
883  * data from the device. For output devices, this functions send the contents of
884  * @buf to the device for playback.
885  *
886  * Returns: %GST_FLOW_OK on success.
887  */
888 GstFlowReturn
889 gst_v4l2_buffer_pool_process (GstBufferPool * bpool, GstBuffer * buf)
890 {
891   GstFlowReturn ret = GST_FLOW_OK;
892   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
893   GstV4l2Object *obj = pool->obj;
894
895   switch (obj->type) {
896     case V4L2_BUF_TYPE_VIDEO_CAPTURE:
897       /* capture */
898       switch (obj->mode) {
899         case GST_V4L2_IO_RW:
900           /* capture into the buffer */
901           ret = gst_v4l2_do_read (bpool, buf);
902           break;
903
904         case GST_V4L2_IO_MMAP:
905         {
906           GstBuffer *tmp;
907
908           if (buf->pool == bpool)
909             /* nothing, data was inside the buffer when we did _acquire() */
910             goto done;
911
912           /* buffer not from our pool, grab a frame and copy it into the target */
913           if ((ret = gst_v4l2_buffer_pool_dqbuf (bpool, &tmp)) != GST_FLOW_OK)
914             goto done;
915
916           if (!gst_v4l2_object_copy (obj, buf, tmp))
917             goto copy_failed;
918
919           if ((ret = gst_v4l2_buffer_pool_qbuf (bpool, tmp)) != GST_FLOW_OK)
920             goto done;
921           break;
922         }
923
924         case GST_V4L2_IO_USERPTR:
925         default:
926           g_assert_not_reached ();
927           break;
928       }
929       break;
930
931     case V4L2_BUF_TYPE_VIDEO_OUTPUT:
932       /* playback */
933       switch (obj->mode) {
934         case GST_V4L2_IO_RW:
935           /* FIXME, do write() */
936           break;
937
938         case GST_V4L2_IO_MMAP:
939         {
940           GstBuffer *tmp;
941
942           if (buf->pool == bpool) {
943             /* nothing, we can queue directly */
944             ret = gst_v4l2_buffer_pool_qbuf (bpool, buf);
945           } else {
946             ret = GST_BUFFER_POOL_CLASS (parent_class)->acquire_buffer (bpool,
947                 &tmp, NULL);
948             if (ret == GST_FLOW_UNEXPECTED) {
949               /* all buffers are queued, try to dequeue one */
950               ret = gst_v4l2_buffer_pool_dqbuf (bpool, &tmp);
951             }
952             if (ret != GST_FLOW_OK)
953               goto done;
954
955             /* copy into it and queue */
956             if (!gst_v4l2_object_copy (obj, tmp, buf))
957               goto copy_failed;
958
959             if ((ret = gst_v4l2_buffer_pool_qbuf (bpool, tmp)) != GST_FLOW_OK)
960               goto done;
961
962             /* if we are not streaming yet (this is the first buffer, start
963              * streaming now */
964             if (!pool->streaming)
965               if (!start_streaming (bpool))
966                 goto start_failed;
967           }
968           break;
969         }
970
971         case GST_V4L2_IO_USERPTR:
972         default:
973           g_assert_not_reached ();
974           break;
975       }
976       break;
977     default:
978       g_assert_not_reached ();
979       break;
980   }
981 done:
982   return ret;
983
984   /* ERRORS */
985 copy_failed:
986   {
987     GST_ERROR_OBJECT (obj->element, "failed to copy data");
988     return GST_FLOW_ERROR;
989   }
990 start_failed:
991   {
992     GST_ERROR_OBJECT (obj->element, "failed to start streaming");
993     return GST_FLOW_ERROR;
994   }
995 }
996
997 /**
998  * gst_v4l2_buffer_pool_available_buffers:
999  * @pool: the pool
1000  *
1001  * Check the number of buffers available to the driver, ie. buffers that
1002  * have been QBUF'd but not yet DQBUF'd.
1003  *
1004  * Returns: the number of buffers available.
1005  */
1006 gint
1007 gst_v4l2_buffer_pool_available_buffers (GstBufferPool * bpool)
1008 {
1009   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
1010
1011   return pool->num_queued;
1012 }