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