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