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