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