v4l2: use driver timestamps
[platform/upstream/gst-plugins-good.git] / sys / v4l2 / gstv4l2bufferpool.c
index 7b2ee76..9798770 100644 (file)
@@ -40,6 +40,7 @@
 #include "gstv4l2sink.h"
 #include "v4l2_calls.h"
 #include "gst/gst-i18n-plugin.h"
+#include <gst/glib-compat-private.h>
 
 /* videodev2.h is not versioned and we can't easily check for the presence
  * of enum values at compile time, but the V4L2_CAP_VIDEO_OUTPUT_OVERLAY define
@@ -56,6 +57,19 @@ GST_DEBUG_CATEGORY_EXTERN (v4l2_debug);
 /*
  * GstV4l2Buffer:
  */
+GType
+gst_v4l2_meta_api_get_type (void)
+{
+  static volatile GType type;
+  static const gchar *tags[] = { "memory", NULL };
+
+  if (g_once_init_enter (&type)) {
+    GType _type = gst_meta_api_type_register ("GstV4l2MetaAPI", tags);
+    g_once_init_leave (&type, _type);
+  }
+  return type;
+}
+
 const GstMetaInfo *
 gst_v4l2_meta_get_info (void)
 {
@@ -63,10 +77,9 @@ gst_v4l2_meta_get_info (void)
 
   if (meta_info == NULL) {
     meta_info =
-        gst_meta_register ("GstV4l2Meta", "GstV4l2Meta",
+        gst_meta_register (gst_v4l2_meta_api_get_type (), "GstV4l2Meta",
         sizeof (GstV4l2Meta), (GstMetaInitFunction) NULL,
-        (GstMetaFreeFunction) NULL, (GstMetaCopyFunction) NULL,
-        (GstMetaTransformFunction) NULL);
+        (GstMetaFreeFunction) NULL, (GstMetaTransformFunction) NULL);
   }
   return meta_info;
 }
@@ -118,7 +131,7 @@ gst_v4l2_buffer_pool_free_buffer (GstBufferPool * bpool, GstBuffer * buffer)
 
 static GstFlowReturn
 gst_v4l2_buffer_pool_alloc_buffer (GstBufferPool * bpool, GstBuffer ** buffer,
-    GstBufferPoolParams * params)
+    GstBufferPoolAcquireParams * params)
 {
   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
   GstBuffer *newbuf;
@@ -134,7 +147,7 @@ gst_v4l2_buffer_pool_alloc_buffer (GstBufferPool * bpool, GstBuffer ** buffer,
     case GST_V4L2_IO_RW:
     {
       newbuf =
-          gst_buffer_new_allocate (pool->allocator, pool->size, pool->align);
+          gst_buffer_new_allocate (pool->allocator, pool->size, &pool->params);
       break;
     }
     case GST_V4L2_IO_MMAP:
@@ -144,7 +157,7 @@ gst_v4l2_buffer_pool_alloc_buffer (GstBufferPool * bpool, GstBuffer ** buffer,
 
       index = pool->num_allocated;
 
-      GST_LOG_OBJECT (pool, "creating buffer %u, %p", index, newbuf, pool);
+      GST_LOG_OBJECT (pool, "creating buffer %u, %p", index, newbuf);
 
       meta->vbuffer.index = index;
       meta->vbuffer.type = obj->type;
@@ -170,9 +183,10 @@ gst_v4l2_buffer_pool_alloc_buffer (GstBufferPool * bpool, GstBuffer ** buffer,
       if (meta->mem == MAP_FAILED)
         goto mmap_failed;
 
-      gst_buffer_take_memory (newbuf, -1,
-          gst_memory_new_wrapped (0,
-              meta->mem, NULL, meta->vbuffer.length, 0, meta->vbuffer.length));
+      gst_buffer_append_memory (newbuf,
+          gst_memory_new_wrapped (GST_MEMORY_FLAG_NO_SHARE,
+              meta->mem, meta->vbuffer.length, 0, meta->vbuffer.length, NULL,
+              NULL));
 
       /* add metadata to raw video buffers */
       if (pool->add_videometa && info->finfo) {
@@ -183,7 +197,7 @@ gst_v4l2_buffer_pool_alloc_buffer (GstBufferPool * bpool, GstBuffer ** buffer,
         stride[0] = obj->bytesperline;
 
         GST_DEBUG_OBJECT (pool, "adding video meta, stride %d", stride[0]);
-        gst_buffer_add_video_meta_full (newbuf, info->flags,
+        gst_buffer_add_video_meta_full (newbuf, GST_VIDEO_FRAME_FLAG_NONE,
             GST_VIDEO_INFO_FORMAT (info), GST_VIDEO_INFO_WIDTH (info),
             GST_VIDEO_INFO_HEIGHT (info), GST_VIDEO_INFO_N_PLANES (info),
             offset, stride);
@@ -228,9 +242,11 @@ gst_v4l2_buffer_pool_set_config (GstBufferPool * bpool, GstStructure * config)
 {
   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
   GstV4l2Object *obj = pool->obj;
-  const GstCaps *caps;
-  guint size, min_buffers, max_buffers;
-  guint prefix, align;
+  GstCaps *caps;
+  guint size, min_buffers, max_buffers, num_buffers, copy_threshold;
+  GstAllocator *allocator;
+  GstAllocationParams params;
+  struct v4l2_requestbuffers breq;
 
   GST_DEBUG_OBJECT (pool, "set config");
 
@@ -252,20 +268,89 @@ gst_v4l2_buffer_pool_set_config (GstBufferPool * bpool, GstStructure * config)
   }
 
   /* parse the config and keep around */
-  if (!gst_buffer_pool_config_get (config, &caps, &size, &min_buffers,
-          &max_buffers, &prefix, &align))
+  if (!gst_buffer_pool_config_get_params (config, &caps, &size, &min_buffers,
+          &max_buffers))
+    goto wrong_config;
+
+  if (!gst_buffer_pool_config_get_allocator (config, &allocator, &params))
     goto wrong_config;
 
   GST_DEBUG_OBJECT (pool, "config %" GST_PTR_FORMAT, config);
 
+  switch (obj->mode) {
+    case GST_V4L2_IO_RW:
+      /* we preallocate 1 buffer, this value also instructs the latency
+       * calculation to have 1 frame latency max */
+      num_buffers = 1;
+      copy_threshold = 0;
+      break;
+    case GST_V4L2_IO_MMAP:
+    {
+      /* request a reasonable number of buffers when no max specified. We will
+       * copy when we run out of buffers */
+      if (max_buffers == 0)
+        num_buffers = 4;
+      else
+        num_buffers = max_buffers;
+
+      /* first, lets request buffers, and see how many we can get: */
+      GST_DEBUG_OBJECT (pool, "starting, requesting %d MMAP buffers",
+          num_buffers);
+
+      memset (&breq, 0, sizeof (struct v4l2_requestbuffers));
+      breq.type = obj->type;
+      breq.count = num_buffers;
+      breq.memory = V4L2_MEMORY_MMAP;
+
+      if (v4l2_ioctl (pool->video_fd, VIDIOC_REQBUFS, &breq) < 0)
+        goto reqbufs_failed;
+
+      GST_LOG_OBJECT (pool, " count:  %u", breq.count);
+      GST_LOG_OBJECT (pool, " type:   %d", breq.type);
+      GST_LOG_OBJECT (pool, " memory: %d", breq.memory);
+
+      if (breq.count < GST_V4L2_MIN_BUFFERS)
+        goto no_buffers;
+
+      if (num_buffers != breq.count) {
+        GST_WARNING_OBJECT (pool, "using %u buffers instead", breq.count);
+        num_buffers = breq.count;
+      }
+      /* update min buffers with the amount of buffers we just reserved. We need
+       * to configure this value in the bufferpool so that the default start
+       * implementation calls our allocate function */
+      min_buffers = breq.count;
+
+      if (max_buffers == 0 || num_buffers < max_buffers) {
+        /* if we are asked to provide more buffers than we have allocated, start
+         * copying buffers when we only have 2 buffers left in the pool */
+        copy_threshold = 2;
+      } else {
+        /* we are certain that we have enough buffers so we don't need to
+         * copy */
+        copy_threshold = 0;
+      }
+      break;
+    }
+    case GST_V4L2_IO_USERPTR:
+    default:
+      num_buffers = 0;
+      copy_threshold = 0;
+      g_assert_not_reached ();
+      break;
+  }
+
   pool->size = size;
-  pool->max_buffers = MAX (min_buffers, max_buffers);
-  pool->min_buffers = MIN (pool->max_buffers, min_buffers);
-  pool->prefix = prefix;
-  pool->align = align;
+  pool->num_buffers = num_buffers;
+  pool->copy_threshold = copy_threshold;
+  if (pool->allocator)
+    gst_allocator_unref (pool->allocator);
+  if ((pool->allocator = allocator))
+    gst_allocator_ref (allocator);
+  pool->params = params;
 
-  gst_buffer_pool_config_set (config, caps, size, min_buffers,
-      max_buffers, prefix, align);
+  gst_buffer_pool_config_set_params (config, caps, size, min_buffers,
+      max_buffers);
 
   return GST_BUFFER_POOL_CLASS (parent_class)->set_config (bpool, config);
 
@@ -282,6 +367,19 @@ wrong_config:
     GST_ERROR_OBJECT (pool, "invalid config %" GST_PTR_FORMAT, config);
     return FALSE;
   }
+reqbufs_failed:
+  {
+    GST_ERROR_OBJECT (pool,
+        "error requesting %d buffers: %s", num_buffers, g_strerror (errno));
+    return FALSE;
+  }
+no_buffers:
+  {
+    GST_ERROR_OBJECT (pool,
+        "we received %d from device '%s', we want at least %d",
+        breq.count, obj->videodev, GST_V4L2_MIN_BUFFERS);
+    return FALSE;
+  }
 }
 
 static gboolean
@@ -321,68 +419,14 @@ gst_v4l2_buffer_pool_start (GstBufferPool * bpool)
 {
   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
   GstV4l2Object *obj = pool->obj;
-  gint n;
-  struct v4l2_requestbuffers breq;
-  gint min_buffers, max_buffers;
-
-  min_buffers = pool->min_buffers;
-  max_buffers = pool->max_buffers;
-
-  switch (obj->mode) {
-    case GST_V4L2_IO_RW:
-    {
-      break;
-    }
-    case GST_V4L2_IO_MMAP:
-    {
-      /* first, lets request buffers, and see how many we can get: */
-      GST_DEBUG_OBJECT (pool, "starting, requesting %d MMAP buffers",
-          max_buffers);
-
-      if (max_buffers == 0)
-        max_buffers = 4;
-
-      memset (&breq, 0, sizeof (struct v4l2_requestbuffers));
-      breq.type = obj->type;
-      breq.count = max_buffers;
-      breq.memory = V4L2_MEMORY_MMAP;
-
-      if (v4l2_ioctl (pool->video_fd, VIDIOC_REQBUFS, &breq) < 0)
-        goto reqbufs_failed;
-
-      GST_LOG_OBJECT (pool, " count:  %u", breq.count);
-      GST_LOG_OBJECT (pool, " type:   %d", breq.type);
-      GST_LOG_OBJECT (pool, " memory: %d", breq.memory);
-
-      if (breq.count < GST_V4L2_MIN_BUFFERS)
-        goto no_buffers;
-
-      if (max_buffers != breq.count) {
-        GST_WARNING_OBJECT (pool, "using %u buffers instead", breq.count);
-        max_buffers = breq.count;
-      }
-      break;
-    }
-    case GST_V4L2_IO_USERPTR:
-    default:
-      g_assert_not_reached ();
-      break;
-  }
 
   pool->obj = obj;
-  pool->max_buffers = max_buffers;
-  pool->buffers = g_new0 (GstBuffer *, max_buffers);
+  pool->buffers = g_new0 (GstBuffer *, pool->num_buffers);
   pool->num_allocated = 0;
 
   /* now, allocate the buffers: */
-  for (n = 0; n < min_buffers; n++) {
-    GstBuffer *buffer;
-
-    if (gst_v4l2_buffer_pool_alloc_buffer (bpool, &buffer, NULL) != GST_FLOW_OK)
-      goto buffer_new_failed;
-
-    gst_v4l2_buffer_pool_release_buffer (bpool, buffer);
-  }
+  if (!GST_BUFFER_POOL_CLASS (parent_class)->start (bpool))
+    goto start_failed;
 
   /* we can start capturing now, we wait for the playback case until we queued
    * the first buffer */
@@ -395,24 +439,6 @@ gst_v4l2_buffer_pool_start (GstBufferPool * bpool)
   return TRUE;
 
   /* ERRORS */
-reqbufs_failed:
-  {
-    GST_ERROR_OBJECT (pool,
-        "error requesting %d buffers: %s", max_buffers, g_strerror (errno));
-    return FALSE;
-  }
-no_buffers:
-  {
-    GST_ERROR_OBJECT (pool,
-        "we received %d from device '%s', we want at least %d",
-        breq.count, obj->videodev, GST_V4L2_MIN_BUFFERS);
-    return FALSE;
-  }
-buffer_new_failed:
-  {
-    GST_ERROR_OBJECT (pool, "failed to create a buffer");
-    return FALSE;
-  }
 start_failed:
   {
     GST_ERROR_OBJECT (pool, "failed to start streaming");
@@ -455,9 +481,8 @@ gst_v4l2_buffer_pool_stop (GstBufferPool * bpool)
   ret = GST_BUFFER_POOL_CLASS (parent_class)->stop (bpool);
 
   /* then free the remaining buffers */
-  for (n = 0; n < pool->num_allocated; n++) {
-    if (pool->buffers[n])
-      gst_v4l2_buffer_pool_free_buffer (bpool, pool->buffers[n]);
+  for (n = 0; n < pool->num_queued; n++) {
+    gst_v4l2_buffer_pool_free_buffer (bpool, pool->buffers[n]);
   }
   g_free (pool->buffers);
   pool->buffers = NULL;
@@ -500,7 +525,7 @@ gst_v4l2_object_poll (GstV4l2Object * v4l2object)
 stopped:
   {
     GST_DEBUG ("stop called");
-    return GST_FLOW_WRONG_STATE;
+    return GST_FLOW_FLUSHING;
   }
 select_error:
   {
@@ -517,16 +542,22 @@ gst_v4l2_buffer_pool_qbuf (GstV4l2BufferPool * pool, GstBuffer * buf)
   gint index;
 
   meta = GST_V4L2_META_GET (buf);
-  g_assert (meta != NULL);
+  if (meta == NULL) {
+    GST_LOG_OBJECT (pool, "unref copied buffer %p", buf);
+    /* no meta, it was a copied buffer that we can unref */
+    gst_buffer_unref (buf);
+    return GST_FLOW_OK;
+  }
 
   index = meta->vbuffer.index;
 
-  GST_LOG_OBJECT (pool, "enqueue buffer %p, index:%d, queued:%d", buf,
-      index, pool->num_queued);
+  GST_LOG_OBJECT (pool, "enqueue buffer %p, index:%d, queued:%d, flags:%08x",
+      buf, index, pool->num_queued, meta->vbuffer.flags);
 
   if (pool->buffers[index] != NULL)
     goto already_queued;
 
+  GST_LOG_OBJECT (pool, "doing QBUF");
   if (v4l2_ioctl (pool->video_fd, VIDIOC_QBUF, &meta->vbuffer) < 0)
     goto queue_failed;
 
@@ -556,6 +587,7 @@ gst_v4l2_buffer_pool_dqbuf (GstV4l2BufferPool * pool, GstBuffer ** buffer)
   GstBuffer *outbuf;
   struct v4l2_buffer vbuffer;
   GstV4l2Object *obj = pool->obj;
+  GstClockTime timestamp;
 
   if (obj->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) {
     /* select works for input devices when data is available. According to the
@@ -584,16 +616,21 @@ gst_v4l2_buffer_pool_dqbuf (GstV4l2BufferPool * pool, GstBuffer ** buffer)
   pool->buffers[vbuffer.index] = NULL;
   pool->num_queued--;
 
+  timestamp = GST_TIMEVAL_TO_TIME (vbuffer.timestamp);
+
   GST_LOG_OBJECT (pool,
-      "dequeued buffer %p seq:%d (ix=%d), used %d, flags %08x, pool-queued=%d, buffer=%p",
-      outbuf, vbuffer.sequence, vbuffer.index, vbuffer.bytesused, vbuffer.flags,
-      pool->num_queued, outbuf);
+      "dequeued buffer %p seq:%d (ix=%d), used %d, flags %08x, ts %"
+      GST_TIME_FORMAT ", pool-queued=%d, buffer=%p", outbuf, vbuffer.sequence,
+      vbuffer.index, vbuffer.bytesused, vbuffer.flags,
+      GST_TIME_ARGS (timestamp), pool->num_queued, outbuf);
 
   /* set top/bottom field first if v4l2_buffer has the information */
-  if (vbuffer.field == V4L2_FIELD_INTERLACED_TB)
+  if (vbuffer.field == V4L2_FIELD_INTERLACED_TB) {
     GST_BUFFER_FLAG_SET (outbuf, GST_VIDEO_BUFFER_FLAG_TFF);
-  if (vbuffer.field == V4L2_FIELD_INTERLACED_BT)
+  }
+  if (vbuffer.field == V4L2_FIELD_INTERLACED_BT) {
     GST_BUFFER_FLAG_UNSET (outbuf, GST_VIDEO_BUFFER_FLAG_TFF);
+  }
 
   /* this can change at every frame, esp. with jpeg */
   if (obj->type == V4L2_BUF_TYPE_VIDEO_CAPTURE)
@@ -601,6 +638,8 @@ gst_v4l2_buffer_pool_dqbuf (GstV4l2BufferPool * pool, GstBuffer ** buffer)
   else
     gst_buffer_resize (outbuf, 0, vbuffer.length);
 
+  GST_BUFFER_TIMESTAMP (outbuf) = timestamp;
+
   *buffer = outbuf;
 
   return GST_FLOW_OK;
@@ -669,7 +708,7 @@ no_buffer:
 
 static GstFlowReturn
 gst_v4l2_buffer_pool_acquire_buffer (GstBufferPool * bpool, GstBuffer ** buffer,
-    GstBufferPoolParams * params)
+    GstBufferPoolAcquireParams * params)
 {
   GstFlowReturn ret;
   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
@@ -695,6 +734,21 @@ gst_v4l2_buffer_pool_acquire_buffer (GstBufferPool * bpool, GstBuffer ** buffer,
            * storage for our buffers. This function does poll first so we can
            * interrupt it fine. */
           ret = gst_v4l2_buffer_pool_dqbuf (pool, buffer);
+          if (G_UNLIKELY (ret != GST_FLOW_OK))
+            goto done;
+
+          /* start copying buffers when we are running low on buffers */
+          if (pool->num_queued < pool->copy_threshold) {
+            GstBuffer *copy;
+
+            /* copy the memory */
+            copy = gst_buffer_copy (*buffer);
+            GST_LOG_OBJECT (pool, "copy buffer %p->%p", *buffer, copy);
+
+            /* and requeue so that we can continue capturing */
+            ret = gst_v4l2_buffer_pool_qbuf (pool, *buffer);
+            *buffer = copy;
+          }
           break;
 
         case GST_V4L2_IO_USERPTR:
@@ -730,13 +784,14 @@ gst_v4l2_buffer_pool_acquire_buffer (GstBufferPool * bpool, GstBuffer ** buffer,
       g_assert_not_reached ();
       break;
   }
+done:
   return ret;
 
   /* ERRORS */
 flushing:
   {
     GST_DEBUG_OBJECT (pool, "We are flushing");
-    return GST_FLOW_WRONG_STATE;
+    return GST_FLOW_FLUSHING;
   }
 }
 
@@ -818,7 +873,8 @@ gst_v4l2_buffer_pool_finalize (GObject * object)
 
   if (pool->video_fd >= 0)
     v4l2_close (pool->video_fd);
-
+  if (pool->allocator)
+    gst_allocator_unref (pool->allocator);
   g_free (pool->buffers);
 
   G_OBJECT_CLASS (parent_class)->finalize (object);
@@ -858,6 +914,7 @@ GstBufferPool *
 gst_v4l2_buffer_pool_new (GstV4l2Object * obj, GstCaps * caps)
 {
   GstV4l2BufferPool *pool;
+  GstStructure *s;
   gint fd;
 
   fd = v4l2_dup (obj->video_fd);
@@ -868,8 +925,9 @@ gst_v4l2_buffer_pool_new (GstV4l2Object * obj, GstCaps * caps)
   pool->video_fd = fd;
   pool->obj = obj;
 
-  gst_buffer_pool_config_set (GST_BUFFER_POOL_CAST (pool)->config, caps,
-      obj->sizeimage, 2, 0, 0, 0);
+  s = gst_buffer_pool_get_config (GST_BUFFER_POOL_CAST (pool));
+  gst_buffer_pool_config_set_params (s, caps, obj->sizeimage, 2, 0);
+  gst_buffer_pool_set_config (GST_BUFFER_POOL_CAST (pool), s);
 
   return GST_BUFFER_POOL (pool);
 
@@ -887,20 +945,20 @@ gst_v4l2_do_read (GstV4l2BufferPool * pool, GstBuffer * buf)
   GstFlowReturn res;
   GstV4l2Object *obj = pool->obj;
   gint amount;
-  gpointer data;
+  GstMapInfo map;
   gint toread;
 
   toread = obj->sizeimage;
 
   GST_LOG_OBJECT (pool, "reading %d bytes into buffer %p", toread, buf);
 
-  data = gst_buffer_map (buf, NULL, NULL, GST_MAP_WRITE);
+  gst_buffer_map (buf, &map, GST_MAP_WRITE);
 
   do {
     if ((res = gst_v4l2_object_poll (obj)) != GST_FLOW_OK)
       goto poll_error;
 
-    amount = v4l2_read (obj->video_fd, data, toread);
+    amount = v4l2_read (obj->video_fd, map.data, toread);
 
     if (amount == toread) {
       break;
@@ -916,7 +974,8 @@ gst_v4l2_do_read (GstV4l2BufferPool * pool, GstBuffer * buf)
   } while (TRUE);
 
   GST_LOG_OBJECT (pool, "read %d bytes", amount);
-  gst_buffer_unmap (buf, data, amount);
+  gst_buffer_unmap (buf, &map);
+  gst_buffer_resize (buf, 0, amount);
 
   return GST_FLOW_OK;
 
@@ -936,7 +995,8 @@ read_error:
   }
 cleanup:
   {
-    gst_buffer_unmap (buf, data, 0);
+    gst_buffer_unmap (buf, &map);
+    gst_buffer_resize (buf, 0, 0);
     return res;
   }
 }