v4l2: use driver timestamps
[platform/upstream/gst-plugins-good.git] / sys / v4l2 / gstv4l2bufferpool.c
index 72940c8..9798770 100644 (file)
@@ -31,7 +31,8 @@
 #include <unistd.h>
 
 #include "gst/video/video.h"
-#include "gst/video/gstmetavideo.h"
+#include "gst/video/gstvideometa.h"
+#include "gst/video/gstvideopool.h"
 
 #include <gstv4l2bufferpool.h>
 
@@ -39,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
@@ -55,17 +57,29 @@ 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_meta_v4l2_get_info (void)
+gst_v4l2_meta_get_info (void)
 {
   static const GstMetaInfo *meta_info = NULL;
 
   if (meta_info == NULL) {
     meta_info =
-        gst_meta_register ("GstMetaV4l2", "GstMetaV4l2",
-        sizeof (GstMetaV4l2), (GstMetaInitFunction) NULL,
-        (GstMetaFreeFunction) NULL, (GstMetaCopyFunction) NULL,
-        (GstMetaTransformFunction) NULL);
+        gst_meta_register (gst_v4l2_meta_api_get_type (), "GstV4l2Meta",
+        sizeof (GstV4l2Meta), (GstMetaInitFunction) NULL,
+        (GstMetaFreeFunction) NULL, (GstMetaTransformFunction) NULL);
   }
   return meta_info;
 }
@@ -92,10 +106,10 @@ gst_v4l2_buffer_pool_free_buffer (GstBufferPool * bpool, GstBuffer * buffer)
       break;
     case GST_V4L2_IO_MMAP:
     {
-      GstMetaV4l2 *meta;
+      GstV4l2Meta *meta;
       gint index;
 
-      meta = GST_META_V4L2_GET (buffer);
+      meta = GST_V4L2_META_GET (buffer);
       g_assert (meta != NULL);
 
       index = meta->vbuffer.index;
@@ -117,11 +131,11 @@ 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;
-  GstMetaV4l2 *meta;
+  GstV4l2Meta *meta;
   GstV4l2Object *obj;
   GstVideoInfo *info;
   guint index;
@@ -133,17 +147,17 @@ 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:
     {
       newbuf = gst_buffer_new ();
-      meta = GST_META_V4L2_ADD (newbuf);
+      meta = GST_V4L2_META_ADD (newbuf);
 
-      index = pool->index;
+      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;
@@ -169,12 +183,13 @@ 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 (info->finfo) {
+      if (pool->add_videometa && info->finfo) {
         gsize offset[GST_VIDEO_MAX_PLANES];
         gint stride[GST_VIDEO_MAX_PLANES];
 
@@ -182,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_meta_video_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);
@@ -195,7 +210,7 @@ gst_v4l2_buffer_pool_alloc_buffer (GstBufferPool * bpool, GstBuffer ** buffer,
       break;
   }
 
-  pool->index++;
+  pool->num_allocated++;
 
   *buffer = newbuf;
 
@@ -226,33 +241,143 @@ static gboolean
 gst_v4l2_buffer_pool_set_config (GstBufferPool * bpool, GstStructure * config)
 {
   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
-  const GstCaps *caps;
-  guint size, min_buffers, max_buffers;
-  guint prefix, align;
+  GstV4l2Object *obj = pool->obj;
+  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");
 
+  pool->add_videometa =
+      gst_buffer_pool_config_has_option (config,
+      GST_BUFFER_POOL_OPTION_VIDEO_META);
+
+  if (!pool->add_videometa) {
+    gint stride;
+
+    /* we don't have video metadata, see if the strides are compatible */
+    stride = GST_VIDEO_INFO_PLANE_STRIDE (&obj->info, 0);
+
+    GST_DEBUG_OBJECT (pool, "no videometadata, checking strides %d and %u",
+        stride, obj->bytesperline);
+
+    if (stride != obj->bytesperline)
+      goto missing_video_api;
+  }
+
   /* 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->min_buffers = min_buffers;
-  pool->max_buffers = max_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);
 
+  /* ERRORS */
+missing_video_api:
+  {
+    GST_ERROR_OBJECT (pool, "missing GstMetaVideo API in config, "
+        "default stride: %d, wanted stride %u",
+        GST_VIDEO_INFO_PLANE_STRIDE (&obj->info, 0), obj->bytesperline);
+    return FALSE;
+  }
 wrong_config:
   {
-    GST_WARNING_OBJECT (pool, "invalid config %" GST_PTR_FORMAT, 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;
   }
 }
@@ -294,65 +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);
-
-      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->index = 0;
+  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 */
@@ -360,27 +434,11 @@ gst_v4l2_buffer_pool_start (GstBufferPool * bpool)
     if (!start_streaming (pool))
       goto start_failed;
 
+  gst_poll_set_flushing (obj->poll, FALSE);
+
   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");
@@ -398,6 +456,8 @@ gst_v4l2_buffer_pool_stop (GstBufferPool * bpool)
 
   GST_DEBUG_OBJECT (pool, "stopping pool");
 
+  gst_poll_set_flushing (obj->poll, TRUE);
+
   if (pool->streaming) {
     switch (obj->mode) {
       case GST_V4L2_IO_RW:
@@ -421,10 +481,12 @@ 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_buffers; 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;
+
   return ret;
 
   /* ERRORS */
@@ -463,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:
   {
@@ -476,20 +538,26 @@ select_error:
 static GstFlowReturn
 gst_v4l2_buffer_pool_qbuf (GstV4l2BufferPool * pool, GstBuffer * buf)
 {
-  GstMetaV4l2 *meta;
+  GstV4l2Meta *meta;
   gint index;
 
-  meta = GST_META_V4L2_GET (buf);
-  g_assert (meta != NULL);
+  meta = GST_V4L2_META_GET (buf);
+  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;
 
@@ -519,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
@@ -547,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)
-    GST_BUFFER_FLAG_SET (outbuf, GST_VIDEO_BUFFER_TFF);
-  if (vbuffer.field == V4L2_FIELD_INTERLACED_BT)
-    GST_BUFFER_FLAG_UNSET (outbuf, GST_VIDEO_BUFFER_TFF);
+  if (vbuffer.field == V4L2_FIELD_INTERLACED_TB) {
+    GST_BUFFER_FLAG_SET (outbuf, GST_VIDEO_BUFFER_FLAG_TFF);
+  }
+  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)
@@ -564,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;
@@ -632,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);
@@ -655,8 +731,24 @@ gst_v4l2_buffer_pool_acquire_buffer (GstBufferPool * bpool, GstBuffer ** buffer,
 
         case GST_V4L2_IO_MMAP:
           /* just dequeue a buffer, we basically use the queue of v4l2 as the
-           * storage for our buffers. */
+           * 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:
@@ -676,24 +768,10 @@ gst_v4l2_buffer_pool_acquire_buffer (GstBufferPool * bpool, GstBuffer ** buffer,
           break;
 
         case GST_V4L2_IO_MMAP:
-        {
-          GstBufferPoolParams tparams = { 0, };
-
-          if (params)
-            tparams = *params;
-
-          tparams.flags |= GST_BUFFER_POOL_FLAG_DONTWAIT;
-
-          /* first try to get a free unqueued buffer */
+          /* get a free unqueued buffer */
           ret = GST_BUFFER_POOL_CLASS (parent_class)->acquire_buffer (bpool,
-              buffer, &tparams);
-          if (ret == GST_FLOW_UNEXPECTED) {
-            GST_DEBUG_OBJECT (pool, "pool empty, try to dequeue a buffer");
-            /* all buffers are queued, try to dequeue one */
-            ret = gst_v4l2_buffer_pool_dqbuf (pool, buffer);
-          }
+              buffer, params);
           break;
-        }
 
         case GST_V4L2_IO_USERPTR:
         default:
@@ -706,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;
   }
 }
 
@@ -747,21 +826,39 @@ gst_v4l2_buffer_pool_release_buffer (GstBufferPool * bpool, GstBuffer * buffer)
       break;
 
     case V4L2_BUF_TYPE_VIDEO_OUTPUT:
-    {
-      GstMetaV4l2 *meta;
+      switch (obj->mode) {
+        case GST_V4L2_IO_RW:
+          /* release back in the pool */
+          GST_BUFFER_POOL_CLASS (parent_class)->release_buffer (bpool, buffer);
+          break;
 
-      meta = GST_META_V4L2_GET (buffer);
-      g_assert (meta != NULL);
+        case GST_V4L2_IO_MMAP:
+        {
+          GstV4l2Meta *meta;
 
-      if (pool->buffers[meta->vbuffer.index] == NULL) {
-        GST_LOG_OBJECT (pool, "buffer not queued, putting on free list");
-        /* playback, put the buffer back in the queue to refill later. */
-        GST_BUFFER_POOL_CLASS (parent_class)->release_buffer (bpool, buffer);
-      } else {
-        GST_LOG_OBJECT (pool, "buffer is queued");
+          meta = GST_V4L2_META_GET (buffer);
+          g_assert (meta != NULL);
+
+          if (pool->buffers[meta->vbuffer.index] == NULL) {
+            GST_LOG_OBJECT (pool, "buffer not queued, putting on free list");
+            /* playback, put the buffer back in the queue to refill later. */
+            GST_BUFFER_POOL_CLASS (parent_class)->release_buffer (bpool,
+                buffer);
+          } else {
+            /* the buffer is queued in the device but maybe not played yet. We just
+             * leave it there and not make it available for future calls to acquire
+             * for now. The buffer will be dequeued and reused later. */
+            GST_LOG_OBJECT (pool, "buffer is queued");
+          }
+          break;
+        }
+
+        case GST_V4L2_IO_USERPTR:
+        default:
+          g_assert_not_reached ();
+          break;
       }
       break;
-    }
 
     default:
       g_assert_not_reached ();
@@ -776,11 +873,9 @@ gst_v4l2_buffer_pool_finalize (GObject * object)
 
   if (pool->video_fd >= 0)
     v4l2_close (pool->video_fd);
-
-  if (pool->buffers) {
-    g_free (pool->buffers);
-    pool->buffers = NULL;
-  }
+  if (pool->allocator)
+    gst_allocator_unref (pool->allocator);
+  g_free (pool->buffers);
 
   G_OBJECT_CLASS (parent_class)->finalize (object);
 }
@@ -810,20 +905,16 @@ gst_v4l2_buffer_pool_class_init (GstV4l2BufferPoolClass * klass)
 /**
  * gst_v4l2_buffer_pool_new:
  * @obj:  the v4l2 object owning the pool
- * @num_buffers:  the requested number of buffers in the pool
- * @requeuebuf: if %TRUE, and if the pool is still in the running state, a
- *  buffer with no remaining references is immediately passed back to v4l2
- *  (VIDIOC_QBUF), otherwise it is returned to the pool of available buffers
- *  (which can be accessed via gst_v4l2_buffer_pool_get().
  *
  * Construct a new buffer pool.
  *
- * Returns: the new pool, use gst_v4l2_buffer_pool_destroy() to free resources
+ * Returns: the new pool, use gst_object_unref() to free resources
  */
 GstBufferPool *
-gst_v4l2_buffer_pool_new (GstV4l2Object * obj)
+gst_v4l2_buffer_pool_new (GstV4l2Object * obj, GstCaps * caps)
 {
   GstV4l2BufferPool *pool;
+  GstStructure *s;
   gint fd;
 
   fd = v4l2_dup (obj->video_fd);
@@ -834,7 +925,11 @@ gst_v4l2_buffer_pool_new (GstV4l2Object * obj)
   pool->video_fd = fd;
   pool->obj = obj;
 
-  return GST_BUFFER_POOL_CAST (pool);
+  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);
 
   /* ERRORS */
 dup_failed:
@@ -850,22 +945,22 @@ gst_v4l2_do_read (GstV4l2BufferPool * pool, GstBuffer * buf)
   GstFlowReturn res;
   GstV4l2Object *obj = pool->obj;
   gint amount;
-  gpointer data;
-  gint buffersize;
+  GstMapInfo map;
+  gint toread;
 
-  buffersize = gst_buffer_get_size (buf);
+  toread = obj->sizeimage;
 
-  GST_LOG_OBJECT (pool, "reading %d bytes into buffer %p", buffersize, buf);
+  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, buffersize);
+    amount = v4l2_read (obj->video_fd, map.data, toread);
 
-    if (amount == buffersize) {
+    if (amount == toread) {
       break;
     } else if (amount == -1) {
       if (errno == EAGAIN || errno == EINTR) {
@@ -879,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;
 
@@ -893,13 +989,14 @@ read_error:
   {
     GST_ELEMENT_ERROR (obj->element, RESOURCE, READ,
         (_("Error reading %d bytes from device '%s'."),
-            buffersize, obj->videodev), GST_ERROR_SYSTEM);
+            toread, obj->videodev), GST_ERROR_SYSTEM);
     res = GST_FLOW_ERROR;
     goto cleanup;
   }
 cleanup:
   {
-    gst_buffer_unmap (buf, data, 0);
+    gst_buffer_unmap (buf, &map);
+    gst_buffer_resize (buf, 0, 0);
     return res;
   }
 }
@@ -916,10 +1013,10 @@ cleanup:
  * Returns: %GST_FLOW_OK on success.
  */
 GstFlowReturn
-gst_v4l2_buffer_pool_process (GstBufferPool * bpool, GstBuffer * buf)
+gst_v4l2_buffer_pool_process (GstV4l2BufferPool * pool, GstBuffer * buf)
 {
   GstFlowReturn ret = GST_FLOW_OK;
-  GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
+  GstBufferPool *bpool = GST_BUFFER_POOL_CAST (pool);
   GstV4l2Object *obj = pool->obj;
 
   GST_DEBUG_OBJECT (pool, "process buffer %p", buf);
@@ -966,6 +1063,7 @@ gst_v4l2_buffer_pool_process (GstBufferPool * bpool, GstBuffer * buf)
       switch (obj->mode) {
         case GST_V4L2_IO_RW:
           /* FIXME, do write() */
+          GST_WARNING_OBJECT (pool, "implement write()");
           break;
 
         case GST_V4L2_IO_MMAP:
@@ -975,16 +1073,31 @@ gst_v4l2_buffer_pool_process (GstBufferPool * bpool, GstBuffer * buf)
           if (buf->pool == bpool) {
             /* nothing, we can queue directly */
             to_queue = buf;
+            GST_LOG_OBJECT (pool, "processing buffer from our pool");
           } else {
+            GST_LOG_OBJECT (pool, "alloc buffer from our pool");
+            if (!gst_buffer_pool_is_active (bpool)) {
+              GstStructure *config;
+
+              /* this pool was not activated, configure and activate */
+              GST_DEBUG_OBJECT (pool, "activating pool");
+
+              config = gst_buffer_pool_get_config (bpool);
+              gst_buffer_pool_config_add_option (config,
+                  GST_BUFFER_POOL_OPTION_VIDEO_META);
+              gst_buffer_pool_set_config (bpool, config);
+
+              if (!gst_buffer_pool_set_active (bpool, TRUE))
+                goto activate_failed;
+            }
+
+            /* this can block if all buffers are outstanding which would be
+             * strange because we would expect the upstream element to have
+             * allocated them and returned to us.. */
             ret = GST_BUFFER_POOL_CLASS (parent_class)->acquire_buffer (bpool,
                 &to_queue, NULL);
-            if (ret == GST_FLOW_UNEXPECTED) {
-              GST_DEBUG_OBJECT (pool, "pool empty, try to dequeue a buffer");
-              /* all buffers are queued, try to dequeue one */
-              ret = gst_v4l2_buffer_pool_dqbuf (pool, &to_queue);
-            }
             if (ret != GST_FLOW_OK)
-              goto done;
+              goto acquire_failed;
 
             /* copy into it and queue */
             if (!gst_v4l2_object_copy (obj, to_queue, buf))
@@ -999,6 +1112,18 @@ gst_v4l2_buffer_pool_process (GstBufferPool * bpool, GstBuffer * buf)
           if (!pool->streaming)
             if (!start_streaming (pool))
               goto start_failed;
+
+          if (pool->num_queued == pool->num_allocated) {
+            /* all buffers are queued, try to dequeue one and release it back
+             * into the pool so that _acquire can get to it again. */
+            ret = gst_v4l2_buffer_pool_dqbuf (pool, &to_queue);
+            if (ret != GST_FLOW_OK)
+              goto done;
+
+            /* release the rendered buffer back into the pool. This wakes up any
+             * thread waiting for a buffer in _acquire() */
+            gst_v4l2_buffer_pool_release_buffer (bpool, to_queue);
+          }
           break;
         }
 
@@ -1016,6 +1141,17 @@ done:
   return ret;
 
   /* ERRORS */
+activate_failed:
+  {
+    GST_ERROR_OBJECT (obj->element, "failed to activate pool");
+    return GST_FLOW_ERROR;
+  }
+acquire_failed:
+  {
+    GST_WARNING_OBJECT (obj->element, "failed to acquire a buffer: %s",
+        gst_flow_get_name (ret));
+    return ret;
+  }
 copy_failed:
   {
     GST_ERROR_OBJECT (obj->element, "failed to copy data");
@@ -1027,20 +1163,3 @@ start_failed:
     return GST_FLOW_ERROR;
   }
 }
-
-/**
- * gst_v4l2_buffer_pool_available_buffers:
- * @pool: the pool
- *
- * Check the number of buffers available to the driver, ie. buffers that
- * have been QBUF'd but not yet DQBUF'd.
- *
- * Returns: the number of buffers available.
- */
-gint
-gst_v4l2_buffer_pool_available_buffers (GstBufferPool * bpool)
-{
-  GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
-
-  return pool->num_queued;
-}