v4l2sink: change where buffers get dequeued
[platform/upstream/gstreamer.git] / sys / v4l2 / gstv4l2bufferpool.c
1 /* GStreamer
2  *
3  * Copyright (C) 2001-2002 Ronald Bultje <rbultje@ronald.bitfreak.net>
4  *               2006 Edgard Lima <edgard.lima@indt.org.br>
5  *               2009 Texas Instruments, Inc - http://www.ti.com/
6  *
7  * gstv4l2src.h: BT8x8/V4L2 source element
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 <gstv4l2bufferpool.h>
34 #include "gstv4l2src.h"
35 #include "gstv4l2sink.h"
36 #include "v4l2_calls.h"
37 #include "gst/gst-i18n-plugin.h"
38
39
40 GST_DEBUG_CATEGORY_EXTERN (v4l2_debug);
41 #define GST_CAT_DEFAULT v4l2_debug
42
43
44 /*
45  * GstV4l2Buffer:
46  */
47
48 static GstBufferClass *v4l2buffer_parent_class = NULL;
49
50 static void
51 gst_v4l2_buffer_finalize (GstV4l2Buffer * buffer)
52 {
53   GstV4l2BufferPool *pool;
54   gboolean resuscitated = FALSE;
55   gint index;
56
57   pool = buffer->pool;
58
59   index = buffer->vbuffer.index;
60
61   GST_LOG_OBJECT (pool->v4l2elem, "finalizing buffer %p %d", buffer, index);
62
63   GST_V4L2_BUFFER_POOL_LOCK (pool);
64   if (pool->running) {
65     if (pool->requeuebuf) {
66       if (!gst_v4l2_buffer_pool_qbuf (pool, buffer)) {
67         GST_WARNING ("could not requeue buffer %p %d", buffer, index);
68       } else {
69         resuscitated = TRUE;
70       }
71     } else {
72       resuscitated = TRUE;
73       /* XXX double check this... I think it is ok to not synchronize this
74        * w.r.t. destruction of the pool, since the buffer is still live and
75        * the buffer holds a ref to the pool..
76        */
77       g_async_queue_push (pool->avail_buffers, buffer);
78     }
79   } else {
80     GST_LOG_OBJECT (pool->v4l2elem, "the pool is shutting down");
81   }
82
83   if (resuscitated) {
84     /* FIXME: check that the caps didn't change */
85     GST_LOG_OBJECT (pool->v4l2elem, "reviving buffer %p, %d", buffer, index);
86     gst_buffer_ref (GST_BUFFER (buffer));
87     GST_BUFFER_SIZE (buffer) = 0;
88     pool->buffers[index] = buffer;
89   }
90
91   GST_V4L2_BUFFER_POOL_UNLOCK (pool);
92
93   if (!resuscitated) {
94     GST_LOG_OBJECT (pool->v4l2elem, "buffer %p not recovered, unmapping",
95         buffer);
96     gst_mini_object_unref (GST_MINI_OBJECT (pool));
97     v4l2_munmap ((void *) GST_BUFFER_DATA (buffer), buffer->vbuffer.length);
98
99     GST_MINI_OBJECT_CLASS (v4l2buffer_parent_class)->finalize (GST_MINI_OBJECT
100         (buffer));
101   }
102 }
103
104 static void
105 gst_v4l2_buffer_class_init (gpointer g_class, gpointer class_data)
106 {
107   GstMiniObjectClass *mini_object_class = GST_MINI_OBJECT_CLASS (g_class);
108
109   v4l2buffer_parent_class = g_type_class_peek_parent (g_class);
110
111   mini_object_class->finalize = (GstMiniObjectFinalizeFunction)
112       gst_v4l2_buffer_finalize;
113 }
114
115 GType
116 gst_v4l2_buffer_get_type (void)
117 {
118   static GType _gst_v4l2_buffer_type;
119
120   if (G_UNLIKELY (_gst_v4l2_buffer_type == 0)) {
121     static const GTypeInfo v4l2_buffer_info = {
122       sizeof (GstBufferClass),
123       NULL,
124       NULL,
125       gst_v4l2_buffer_class_init,
126       NULL,
127       NULL,
128       sizeof (GstV4l2Buffer),
129       0,
130       NULL,
131       NULL
132     };
133     _gst_v4l2_buffer_type = g_type_register_static (GST_TYPE_BUFFER,
134         "GstV4l2Buffer", &v4l2_buffer_info, 0);
135   }
136   return _gst_v4l2_buffer_type;
137 }
138
139 static GstV4l2Buffer *
140 gst_v4l2_buffer_new (GstV4l2BufferPool * pool, guint index, GstCaps * caps)
141 {
142   GstV4l2Buffer *ret;
143   guint8 *data;
144
145   ret = (GstV4l2Buffer *) gst_mini_object_new (GST_TYPE_V4L2_BUFFER);
146
147   GST_LOG_OBJECT (pool->v4l2elem, "creating buffer %u, %p in pool %p", index,
148       ret, pool);
149
150   ret->pool =
151       (GstV4l2BufferPool *) gst_mini_object_ref (GST_MINI_OBJECT (pool));
152
153   ret->vbuffer.index = index;
154   ret->vbuffer.type = pool->type;
155   ret->vbuffer.memory = V4L2_MEMORY_MMAP;
156
157   if (v4l2_ioctl (pool->video_fd, VIDIOC_QUERYBUF, &ret->vbuffer) < 0)
158     goto querybuf_failed;
159
160   GST_LOG_OBJECT (pool->v4l2elem, "  index:     %u", ret->vbuffer.index);
161   GST_LOG_OBJECT (pool->v4l2elem, "  type:      %d", ret->vbuffer.type);
162   GST_LOG_OBJECT (pool->v4l2elem, "  bytesused: %u", ret->vbuffer.bytesused);
163   GST_LOG_OBJECT (pool->v4l2elem, "  flags:     %08x", ret->vbuffer.flags);
164   GST_LOG_OBJECT (pool->v4l2elem, "  field:     %d", ret->vbuffer.field);
165   GST_LOG_OBJECT (pool->v4l2elem, "  memory:    %d", ret->vbuffer.memory);
166   if (ret->vbuffer.memory == V4L2_MEMORY_MMAP)
167     GST_LOG_OBJECT (pool->v4l2elem, "  MMAP offset:  %u",
168         ret->vbuffer.m.offset);
169   GST_LOG_OBJECT (pool->v4l2elem, "  length:    %u", ret->vbuffer.length);
170   GST_LOG_OBJECT (pool->v4l2elem, "  input:     %u", ret->vbuffer.input);
171
172   data = (guint8 *) v4l2_mmap (0, ret->vbuffer.length,
173       PROT_READ | PROT_WRITE, MAP_SHARED, pool->video_fd,
174       ret->vbuffer.m.offset);
175
176   if (data == MAP_FAILED)
177     goto mmap_failed;
178
179   GST_BUFFER_DATA (ret) = data;
180   GST_BUFFER_SIZE (ret) = ret->vbuffer.length;
181
182   GST_BUFFER_FLAG_SET (ret, GST_BUFFER_FLAG_READONLY);
183
184   gst_buffer_set_caps (GST_BUFFER (ret), caps);
185
186   return ret;
187
188   /* ERRORS */
189 querybuf_failed:
190   {
191     gint errnosave = errno;
192
193     GST_WARNING ("Failed QUERYBUF: %s", g_strerror (errnosave));
194     gst_buffer_unref (GST_BUFFER (ret));
195     errno = errnosave;
196     return NULL;
197   }
198 mmap_failed:
199   {
200     gint errnosave = errno;
201
202     GST_WARNING ("Failed to mmap: %s", g_strerror (errnosave));
203     gst_buffer_unref (GST_BUFFER (ret));
204     errno = errnosave;
205     return NULL;
206   }
207 }
208
209
210 /*
211  * GstV4l2BufferPool:
212  */
213
214 static GstMiniObjectClass *buffer_pool_parent_class = NULL;
215
216 static void
217 gst_v4l2_buffer_pool_finalize (GstV4l2BufferPool * pool)
218 {
219   g_mutex_free (pool->lock);
220   pool->lock = NULL;
221
222   g_async_queue_unref (pool->avail_buffers);
223   pool->avail_buffers = NULL;
224
225   if (pool->video_fd >= 0)
226     v4l2_close (pool->video_fd);
227
228   if (pool->buffers) {
229     g_free (pool->buffers);
230     pool->buffers = NULL;
231   }
232
233   GST_MINI_OBJECT_CLASS (buffer_pool_parent_class)->finalize (GST_MINI_OBJECT
234       (pool));
235 }
236
237 static void
238 gst_v4l2_buffer_pool_init (GstV4l2BufferPool * pool, gpointer g_class)
239 {
240   pool->lock = g_mutex_new ();
241   pool->running = FALSE;
242   pool->num_live_buffers = 0;
243 }
244
245 static void
246 gst_v4l2_buffer_pool_class_init (gpointer g_class, gpointer class_data)
247 {
248   GstMiniObjectClass *mini_object_class = GST_MINI_OBJECT_CLASS (g_class);
249
250   buffer_pool_parent_class = g_type_class_peek_parent (g_class);
251
252   mini_object_class->finalize = (GstMiniObjectFinalizeFunction)
253       gst_v4l2_buffer_pool_finalize;
254 }
255
256 GType
257 gst_v4l2_buffer_pool_get_type (void)
258 {
259   static GType _gst_v4l2_buffer_pool_type;
260
261   if (G_UNLIKELY (_gst_v4l2_buffer_pool_type == 0)) {
262     static const GTypeInfo v4l2_buffer_pool_info = {
263       sizeof (GstBufferClass),
264       NULL,
265       NULL,
266       gst_v4l2_buffer_pool_class_init,
267       NULL,
268       NULL,
269       sizeof (GstV4l2BufferPool),
270       0,
271       (GInstanceInitFunc) gst_v4l2_buffer_pool_init,
272       NULL
273     };
274     _gst_v4l2_buffer_pool_type = g_type_register_static (GST_TYPE_MINI_OBJECT,
275         "GstV4l2BufferPool", &v4l2_buffer_pool_info, 0);
276   }
277   return _gst_v4l2_buffer_pool_type;
278 }
279
280
281 /* this is somewhat of a hack.. but better to keep the hack in
282  * one place than copy/pasting it around..
283  */
284 static GstV4l2Object *
285 get_v4l2_object (GstElement * v4l2elem)
286 {
287   GstV4l2Object *v4l2object = NULL;
288   if (GST_IS_V4L2SRC (v4l2elem)) {
289     v4l2object = (GST_V4L2SRC (v4l2elem))->v4l2object;
290   } else if (GST_IS_V4L2SINK (v4l2elem)) {
291     v4l2object = (GST_V4L2SINK (v4l2elem))->v4l2object;
292   } else {
293     GST_ERROR_OBJECT (v4l2elem, "unknown v4l2 element");
294   }
295   return v4l2object;
296 }
297
298
299
300 /**
301  * Construct a new buffer pool
302  *
303  * @v4l2elem  the v4l2 element (src or sink) that owns this pool
304  * @fd   the video device file descriptor
305  * @num_buffers  the requested number of buffers in the pool
306  * @caps  the caps to set on the buffer
307  * @requeuebuf  if <code>TRUE</code>, and if the pool is still in the
308  *   <code>running</code> state, a buffer with no remaining references
309  *   is immediately passed back to v4l2 (<code>VIDIOC_QBUF</code>),
310  *   otherwise it is returned to the pool of available buffers
311  *   (which can be accessed via <code>gst_v4l2_buffer_pool_get()</code>.
312  */
313 GstV4l2BufferPool *
314 gst_v4l2_buffer_pool_new (GstElement * v4l2elem, gint fd, gint num_buffers,
315     GstCaps * caps, gboolean requeuebuf, enum v4l2_buf_type type)
316 {
317   GstV4l2BufferPool *pool;
318   gint n;
319   struct v4l2_requestbuffers breq;
320
321   pool = (GstV4l2BufferPool *) gst_mini_object_new (GST_TYPE_V4L2_BUFFER_POOL);
322
323   pool->video_fd = v4l2_dup (fd);
324   if (pool->video_fd < 0)
325     goto dup_failed;
326
327
328   /* first, lets request buffers, and see how many we can get: */
329   GST_DEBUG_OBJECT (v4l2elem, "STREAMING, requesting %d MMAP buffers",
330       num_buffers);
331
332   memset (&breq, 0, sizeof (struct v4l2_requestbuffers));
333   breq.type = type;
334   breq.count = num_buffers;
335   breq.memory = V4L2_MEMORY_MMAP;
336
337   if (v4l2_ioctl (fd, VIDIOC_REQBUFS, &breq) < 0)
338     goto reqbufs_failed;
339
340   GST_LOG_OBJECT (v4l2elem, " count:  %u", breq.count);
341   GST_LOG_OBJECT (v4l2elem, " type:   %d", breq.type);
342   GST_LOG_OBJECT (v4l2elem, " memory: %d", breq.memory);
343
344   if (breq.count < GST_V4L2_MIN_BUFFERS)
345     goto no_buffers;
346
347   if (num_buffers != breq.count) {
348     GST_WARNING_OBJECT (v4l2elem, "using %u buffers instead", breq.count);
349     num_buffers = breq.count;
350   }
351
352   pool->v4l2elem = v4l2elem;
353   pool->requeuebuf = requeuebuf;
354   pool->type = type;
355   pool->buffer_count = num_buffers;
356   pool->buffers = g_new0 (GstV4l2Buffer *, num_buffers);
357   pool->avail_buffers = g_async_queue_new ();
358
359   /* now, map the buffers: */
360   for (n = 0; n < num_buffers; n++) {
361     pool->buffers[n] = gst_v4l2_buffer_new (pool, n, caps);
362     if (!pool->buffers[n])
363       goto buffer_new_failed;
364     pool->num_live_buffers++;
365     g_async_queue_push (pool->avail_buffers, pool->buffers[n]);
366   }
367
368   return pool;
369
370   /* ERRORS */
371 dup_failed:
372   {
373     gint errnosave = errno;
374
375     gst_mini_object_unref (GST_MINI_OBJECT (pool));
376
377     errno = errnosave;
378
379     return NULL;
380   }
381 reqbufs_failed:
382   {
383     GstV4l2Object *v4l2object = get_v4l2_object (v4l2elem);
384     GST_ELEMENT_ERROR (v4l2elem, RESOURCE, READ,
385         (_("Could not get buffers from device '%s'."),
386             v4l2object->videodev),
387         ("error requesting %d buffers: %s", num_buffers, g_strerror (errno)));
388     return NULL;
389   }
390 no_buffers:
391   {
392     GstV4l2Object *v4l2object = get_v4l2_object (v4l2elem);
393     GST_ELEMENT_ERROR (v4l2elem, RESOURCE, READ,
394         (_("Could not get enough buffers from device '%s'."),
395             v4l2object->videodev),
396         ("we received %d from device '%s', we want at least %d",
397             breq.count, v4l2object->videodev, GST_V4L2_MIN_BUFFERS));
398     return NULL;
399   }
400 buffer_new_failed:
401   {
402     gint errnosave = errno;
403
404     gst_v4l2_buffer_pool_destroy (pool);
405
406     errno = errnosave;
407
408     return NULL;
409   }
410 }
411
412
413 void
414 gst_v4l2_buffer_pool_destroy (GstV4l2BufferPool * pool)
415 {
416   gint n;
417
418   GST_V4L2_BUFFER_POOL_LOCK (pool);
419   pool->running = FALSE;
420   GST_V4L2_BUFFER_POOL_UNLOCK (pool);
421
422   GST_DEBUG_OBJECT (pool->v4l2elem, "destroy pool");
423
424   /* after this point, no more buffers will be queued or dequeued; no buffer
425    * from pool->buffers that is NULL will be set to a buffer, and no buffer that
426    * is not NULL will be pushed out. */
427
428   /* miniobjects have no dispose, so they can't break ref-cycles, as buffers ref
429    * the pool, we need to unref the buffer to properly finalize te pool */
430   for (n = 0; n < pool->buffer_count; n++) {
431     GstBuffer *buf;
432
433     GST_V4L2_BUFFER_POOL_LOCK (pool);
434     buf = GST_BUFFER (pool->buffers[n]);
435     GST_V4L2_BUFFER_POOL_UNLOCK (pool);
436
437     if (buf)
438       /* we own the ref if the buffer is in pool->buffers; drop it. */
439       gst_buffer_unref (buf);
440   }
441
442   gst_mini_object_unref (GST_MINI_OBJECT (pool));
443 }
444
445 /**
446  * Get an available buffer in the pool
447  *
448  * @pool   the "this" object
449  */
450 GstV4l2Buffer *
451 gst_v4l2_buffer_pool_get (GstV4l2BufferPool * pool)
452 {
453   GstV4l2Buffer *buf = g_async_queue_try_pop (pool->avail_buffers);
454
455   if (buf)
456     GST_BUFFER_SIZE (buf) = buf->vbuffer.length;
457
458   pool->running = TRUE;
459
460   return buf;
461 }
462
463
464 /**
465  * Queue a buffer to the driver
466  *
467  * @pool   the "this" object
468  * @buf    the buffer to queue
469  */
470 gboolean
471 gst_v4l2_buffer_pool_qbuf (GstV4l2BufferPool * pool, GstV4l2Buffer * buf)
472 {
473   GST_LOG_OBJECT (pool->v4l2elem, "enqueue pool buffer %d", buf->vbuffer.index);
474
475   if (v4l2_ioctl (pool->video_fd, VIDIOC_QBUF, &buf->vbuffer) < 0)
476     return FALSE;
477
478   pool->num_live_buffers--;
479   GST_DEBUG_OBJECT (pool->v4l2elem, "num_live_buffers--: %d",
480       pool->num_live_buffers);
481
482   return TRUE;
483 }
484
485 /**
486  * Dequeue a buffer from the driver.  Some generic error handling is done in
487  * this function, but any error handling specific to v4l2src (capture) or
488  * v4l2sink (output) can be done outside this function by checking 'errno'
489  *
490  * @pool   the "this" object
491  */
492 GstV4l2Buffer *
493 gst_v4l2_buffer_pool_dqbuf (GstV4l2BufferPool * pool)
494 {
495   GstV4l2Object *v4l2object = get_v4l2_object (pool->v4l2elem);
496   GstV4l2Buffer *pool_buffer;
497   struct v4l2_buffer buffer;
498
499   memset (&buffer, 0x00, sizeof (buffer));
500   buffer.type = pool->type;
501   buffer.memory = V4L2_MEMORY_MMAP;
502
503
504   if (v4l2_ioctl (pool->video_fd, VIDIOC_DQBUF, &buffer) >= 0) {
505
506     GST_V4L2_BUFFER_POOL_LOCK (pool);
507
508     /* get our GstBuffer with that index from the pool, if the buffer was
509      * outstanding we have a serious problem.
510      */
511     pool_buffer = pool->buffers[buffer.index];
512
513     if (pool_buffer == NULL) {
514       GST_ELEMENT_ERROR (pool->v4l2elem, RESOURCE, FAILED,
515           (_("Failed trying to get video frames from device '%s'."),
516               v4l2object->videodev),
517           (_("No free buffers found in the pool at index %d."), buffer.index));
518       GST_V4L2_BUFFER_POOL_UNLOCK (pool);
519       return NULL;
520     }
521
522     GST_LOG_OBJECT (pool->v4l2elem,
523         "grabbed frame %d (ix=%d), flags %08x, pool-ct=%d, buffer=%p",
524         buffer.sequence, buffer.index, buffer.flags, pool->num_live_buffers,
525         pool_buffer);
526
527     pool->num_live_buffers++;
528     GST_DEBUG_OBJECT (pool->v4l2elem, "num_live_buffers++: %d",
529         pool->num_live_buffers);
530
531     GST_V4L2_BUFFER_POOL_UNLOCK (pool);
532
533     /* this can change at every frame, esp. with jpeg */
534     GST_BUFFER_SIZE (pool_buffer) = buffer.bytesused;
535
536     return pool_buffer;
537   }
538
539
540   GST_WARNING_OBJECT (pool->v4l2elem,
541       "problem grabbing frame %d (ix=%d), pool-ct=%d, buf.flags=%d",
542       buffer.sequence, buffer.index,
543       GST_MINI_OBJECT_REFCOUNT (pool), buffer.flags);
544
545   switch (errno) {
546     case EAGAIN:
547       GST_WARNING_OBJECT (pool->v4l2elem,
548           "Non-blocking I/O has been selected using O_NONBLOCK and"
549           " no buffer was in the outgoing queue. device %s",
550           v4l2object->videodev);
551       break;
552     case EINVAL:
553       GST_ELEMENT_ERROR (pool->v4l2elem, RESOURCE, FAILED,
554           (_("Failed trying to get video frames from device '%s'."),
555               v4l2object->videodev),
556           (_("The buffer type is not supported, or the index is out of bounds,"
557                   " or no buffers have been allocated yet, or the userptr"
558                   " or length are invalid. device %s"), v4l2object->videodev));
559       break;
560     case ENOMEM:
561       GST_ELEMENT_ERROR (pool->v4l2elem, RESOURCE, FAILED,
562           (_("Failed trying to get video frames from device '%s'. Not enough memory."), v4l2object->videodev), (_("insufficient memory to enqueue a user pointer buffer. device %s."), v4l2object->videodev));
563       break;
564     case EIO:
565       GST_INFO_OBJECT (pool->v4l2elem,
566           "VIDIOC_DQBUF failed due to an internal error."
567           " Can also indicate temporary problems like signal loss."
568           " Note the driver might dequeue an (empty) buffer despite"
569           " returning an error, or even stop capturing."
570           " device %s", v4l2object->videodev);
571       /* have we de-queued a buffer ? */
572       if (!(buffer.flags & (V4L2_BUF_FLAG_QUEUED | V4L2_BUF_FLAG_DONE))) {
573         GST_DEBUG_OBJECT (pool->v4l2elem, "reenqueing buffer");
574         /* FIXME ... should we do something here? */
575       }
576       break;
577     case EINTR:
578       GST_WARNING_OBJECT (pool->v4l2elem,
579           "could not sync on a buffer on device %s", v4l2object->videodev);
580       break;
581     default:
582       GST_WARNING_OBJECT (pool->v4l2elem,
583           "Grabbing frame got interrupted on %s unexpectedly. %d: %s.",
584           v4l2object->videodev, errno, g_strerror (errno));
585       break;
586   }
587
588   return NULL;
589 }
590
591 /**
592  * gst_v4l2_buffer_pool_available_buffers:
593  * Returns the number of buffers available to the driver, ie. buffers that
594  * have been QBUF'd but not yet DQBUF'd.
595  */
596 gint
597 gst_v4l2_buffer_pool_available_buffers (GstV4l2BufferPool * pool)
598 {
599   return pool->buffer_count - pool->num_live_buffers;
600 }