v4l2: use driver timestamps
[platform/upstream/gst-plugins-good.git] / sys / v4l2 / gstv4l2bufferpool.c
index 51419ff..9798770 100644 (file)
 #include <unistd.h>
 
 #include "gst/video/video.h"
+#include "gst/video/gstvideometa.h"
+#include "gst/video/gstvideopool.h"
 
 #include <gstv4l2bufferpool.h>
+
 #include "gstv4l2src.h"
-#ifdef HAVE_EXPERIMENTAL
 #include "gstv4l2sink.h"
-#endif
 #include "v4l2_calls.h"
 #include "gst/gst-i18n-plugin.h"
 #include <gst/glib-compat-private.h>
 GST_DEBUG_CATEGORY_EXTERN (v4l2_debug);
 #define GST_CAT_DEFAULT v4l2_debug
 
-
 /*
  * GstV4l2Buffer:
  */
-
-static GstBufferClass *v4l2buffer_parent_class = NULL;
-
-static void
-gst_v4l2_buffer_finalize (GstV4l2Buffer * buffer)
+GType
+gst_v4l2_meta_api_get_type (void)
 {
-  GstV4l2BufferPool *pool;
-  gboolean resuscitated = FALSE;
-  gint index;
-
-  pool = buffer->pool;
-
-  index = buffer->vbuffer.index;
-
-  GST_LOG_OBJECT (pool->v4l2elem, "finalizing buffer %p %d", buffer, index);
-
-  GST_V4L2_BUFFER_POOL_LOCK (pool);
-  if (pool->running) {
-    if (pool->requeuebuf) {
-      if (!gst_v4l2_buffer_pool_qbuf (pool, buffer)) {
-        GST_WARNING ("could not requeue buffer %p %d", buffer, index);
-      } else {
-        resuscitated = TRUE;
-      }
-    } else {
-      resuscitated = TRUE;
-      /* XXX double check this... I think it is ok to not synchronize this
-       * w.r.t. destruction of the pool, since the buffer is still live and
-       * the buffer holds a ref to the pool..
-       */
-      g_async_queue_push (pool->avail_buffers, buffer);
-    }
-  } else {
-    GST_LOG_OBJECT (pool->v4l2elem, "the pool is shutting down");
-  }
+  static volatile GType type;
+  static const gchar *tags[] = { "memory", NULL };
 
-  if (resuscitated) {
-    /* FIXME: check that the caps didn't change */
-    GST_LOG_OBJECT (pool->v4l2elem, "reviving buffer %p, %d", buffer, index);
-    gst_buffer_ref (GST_BUFFER (buffer));
-    GST_BUFFER_SIZE (buffer) = 0;
-    pool->buffers[index] = buffer;
-  }
-
-  GST_V4L2_BUFFER_POOL_UNLOCK (pool);
-
-  if (!resuscitated) {
-    GST_LOG_OBJECT (pool->v4l2elem,
-        "buffer %p (data %p, len %u) not recovered, unmapping",
-        buffer, GST_BUFFER_DATA (buffer), buffer->mmap_length);
-    gst_mini_object_unref (GST_MINI_OBJECT (pool));
-    v4l2_munmap ((void *) GST_BUFFER_DATA (buffer), buffer->mmap_length);
-
-    GST_MINI_OBJECT_CLASS (v4l2buffer_parent_class)->finalize (GST_MINI_OBJECT
-        (buffer));
+  if (g_once_init_enter (&type)) {
+    GType _type = gst_meta_api_type_register ("GstV4l2MetaAPI", tags);
+    g_once_init_leave (&type, _type);
   }
+  return type;
 }
 
-static void
-gst_v4l2_buffer_class_init (gpointer g_class, gpointer class_data)
+const GstMetaInfo *
+gst_v4l2_meta_get_info (void)
 {
-  GstMiniObjectClass *mini_object_class = GST_MINI_OBJECT_CLASS (g_class);
+  static const GstMetaInfo *meta_info = NULL;
 
-  v4l2buffer_parent_class = g_type_class_peek_parent (g_class);
-
-  mini_object_class->finalize = (GstMiniObjectFinalizeFunction)
-      gst_v4l2_buffer_finalize;
-}
-
-GType
-gst_v4l2_buffer_get_type (void)
-{
-  static GType _gst_v4l2_buffer_type;
-
-  if (G_UNLIKELY (_gst_v4l2_buffer_type == 0)) {
-    static const GTypeInfo v4l2_buffer_info = {
-      sizeof (GstBufferClass),
-      NULL,
-      NULL,
-      gst_v4l2_buffer_class_init,
-      NULL,
-      NULL,
-      sizeof (GstV4l2Buffer),
-      0,
-      NULL,
-      NULL
-    };
-    _gst_v4l2_buffer_type = g_type_register_static (GST_TYPE_BUFFER,
-        "GstV4l2Buffer", &v4l2_buffer_info, 0);
-  }
-  return _gst_v4l2_buffer_type;
+  if (meta_info == NULL) {
+    meta_info =
+        gst_meta_register (gst_v4l2_meta_api_get_type (), "GstV4l2Meta",
+        sizeof (GstV4l2Meta), (GstMetaInitFunction) NULL,
+        (GstMetaFreeFunction) NULL, (GstMetaTransformFunction) NULL);
+  }
+  return meta_info;
 }
 
-static GstV4l2Buffer *
-gst_v4l2_buffer_new (GstV4l2BufferPool * pool, guint index, GstCaps * caps)
-{
-  GstV4l2Buffer *ret;
-  guint8 *data;
-
-  ret = (GstV4l2Buffer *) gst_mini_object_new (GST_TYPE_V4L2_BUFFER);
+/*
+ * GstV4l2BufferPool:
+ */
+#define gst_v4l2_buffer_pool_parent_class parent_class
+G_DEFINE_TYPE (GstV4l2BufferPool, gst_v4l2_buffer_pool, GST_TYPE_BUFFER_POOL);
 
-  GST_LOG_OBJECT (pool->v4l2elem, "creating buffer %u, %p in pool %p", index,
-      ret, pool);
+static void gst_v4l2_buffer_pool_release_buffer (GstBufferPool * bpool,
+    GstBuffer * buffer);
 
-  ret->pool =
-      (GstV4l2BufferPool *) gst_mini_object_ref (GST_MINI_OBJECT (pool));
+static void
+gst_v4l2_buffer_pool_free_buffer (GstBufferPool * bpool, GstBuffer * buffer)
+{
+  GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
+  GstV4l2Object *obj;
 
-  ret->vbuffer.index = index;
-  ret->vbuffer.type = pool->type;
-  ret->vbuffer.memory = V4L2_MEMORY_MMAP;
+  obj = pool->obj;
 
-  if (v4l2_ioctl (pool->video_fd, VIDIOC_QUERYBUF, &ret->vbuffer) < 0)
-    goto querybuf_failed;
+  switch (obj->mode) {
+    case GST_V4L2_IO_RW:
+      break;
+    case GST_V4L2_IO_MMAP:
+    {
+      GstV4l2Meta *meta;
+      gint index;
 
-  GST_LOG_OBJECT (pool->v4l2elem, "  index:     %u", ret->vbuffer.index);
-  GST_LOG_OBJECT (pool->v4l2elem, "  type:      %d", ret->vbuffer.type);
-  GST_LOG_OBJECT (pool->v4l2elem, "  bytesused: %u", ret->vbuffer.bytesused);
-  GST_LOG_OBJECT (pool->v4l2elem, "  flags:     %08x", ret->vbuffer.flags);
-  GST_LOG_OBJECT (pool->v4l2elem, "  field:     %d", ret->vbuffer.field);
-  GST_LOG_OBJECT (pool->v4l2elem, "  memory:    %d", ret->vbuffer.memory);
-  if (ret->vbuffer.memory == V4L2_MEMORY_MMAP)
-    GST_LOG_OBJECT (pool->v4l2elem, "  MMAP offset:  %u",
-        ret->vbuffer.m.offset);
-  GST_LOG_OBJECT (pool->v4l2elem, "  length:    %u", ret->vbuffer.length);
-  GST_LOG_OBJECT (pool->v4l2elem, "  input:     %u", ret->vbuffer.input);
+      meta = GST_V4L2_META_GET (buffer);
+      g_assert (meta != NULL);
 
-  ret->mmap_length = ret->vbuffer.length;
-  data = (guint8 *) v4l2_mmap (0, ret->vbuffer.length,
-      PROT_READ | PROT_WRITE, MAP_SHARED, pool->video_fd,
-      ret->vbuffer.m.offset);
+      index = meta->vbuffer.index;
+      GST_LOG_OBJECT (pool,
+          "mmap buffer %p idx %d (data %p, len %u) freed, unmapping", buffer,
+          index, meta->mem, meta->vbuffer.length);
 
-  if (data == MAP_FAILED)
-    goto mmap_failed;
+      v4l2_munmap (meta->mem, meta->vbuffer.length);
+      pool->buffers[index] = NULL;
+      break;
+    }
+    case GST_V4L2_IO_USERPTR:
+    default:
+      g_assert_not_reached ();
+      break;
+  }
+  gst_buffer_unref (buffer);
+}
 
-  GST_BUFFER_DATA (ret) = data;
-  GST_BUFFER_SIZE (ret) = ret->vbuffer.length;
+static GstFlowReturn
+gst_v4l2_buffer_pool_alloc_buffer (GstBufferPool * bpool, GstBuffer ** buffer,
+    GstBufferPoolAcquireParams * params)
+{
+  GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
+  GstBuffer *newbuf;
+  GstV4l2Meta *meta;
+  GstV4l2Object *obj;
+  GstVideoInfo *info;
+  guint index;
+
+  obj = pool->obj;
+  info = &obj->info;
+
+  switch (obj->mode) {
+    case GST_V4L2_IO_RW:
+    {
+      newbuf =
+          gst_buffer_new_allocate (pool->allocator, pool->size, &pool->params);
+      break;
+    }
+    case GST_V4L2_IO_MMAP:
+    {
+      newbuf = gst_buffer_new ();
+      meta = GST_V4L2_META_ADD (newbuf);
+
+      index = pool->num_allocated;
+
+      GST_LOG_OBJECT (pool, "creating buffer %u, %p", index, newbuf);
+
+      meta->vbuffer.index = index;
+      meta->vbuffer.type = obj->type;
+      meta->vbuffer.memory = V4L2_MEMORY_MMAP;
+
+      if (v4l2_ioctl (pool->video_fd, VIDIOC_QUERYBUF, &meta->vbuffer) < 0)
+        goto querybuf_failed;
+
+      GST_LOG_OBJECT (pool, "  index:     %u", meta->vbuffer.index);
+      GST_LOG_OBJECT (pool, "  type:      %d", meta->vbuffer.type);
+      GST_LOG_OBJECT (pool, "  bytesused: %u", meta->vbuffer.bytesused);
+      GST_LOG_OBJECT (pool, "  flags:     %08x", meta->vbuffer.flags);
+      GST_LOG_OBJECT (pool, "  field:     %d", meta->vbuffer.field);
+      GST_LOG_OBJECT (pool, "  memory:    %d", meta->vbuffer.memory);
+      if (meta->vbuffer.memory == V4L2_MEMORY_MMAP)
+        GST_LOG_OBJECT (pool, "  MMAP offset:  %u", meta->vbuffer.m.offset);
+      GST_LOG_OBJECT (pool, "  length:    %u", meta->vbuffer.length);
+      GST_LOG_OBJECT (pool, "  input:     %u", meta->vbuffer.input);
+
+      meta->mem = v4l2_mmap (0, meta->vbuffer.length,
+          PROT_READ | PROT_WRITE, MAP_SHARED, pool->video_fd,
+          meta->vbuffer.m.offset);
+      if (meta->mem == MAP_FAILED)
+        goto mmap_failed;
+
+      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) {
+        gsize offset[GST_VIDEO_MAX_PLANES];
+        gint stride[GST_VIDEO_MAX_PLANES];
+
+        offset[0] = 0;
+        stride[0] = obj->bytesperline;
+
+        GST_DEBUG_OBJECT (pool, "adding video meta, stride %d", stride[0]);
+        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);
+      }
+      break;
+    }
+    case GST_V4L2_IO_USERPTR:
+    default:
+      g_assert_not_reached ();
+      break;
+  }
 
-  GST_BUFFER_FLAG_SET (ret, GST_BUFFER_FLAG_READONLY);
+  pool->num_allocated++;
 
-  gst_buffer_set_caps (GST_BUFFER (ret), caps);
+  *buffer = newbuf;
 
-  return ret;
+  return GST_FLOW_OK;
 
   /* ERRORS */
 querybuf_failed:
@@ -206,448 +222,944 @@ querybuf_failed:
     gint errnosave = errno;
 
     GST_WARNING ("Failed QUERYBUF: %s", g_strerror (errnosave));
-    gst_buffer_unref (GST_BUFFER (ret));
+    gst_buffer_unref (newbuf);
     errno = errnosave;
-    return NULL;
+    return GST_FLOW_ERROR;
   }
 mmap_failed:
   {
     gint errnosave = errno;
 
     GST_WARNING ("Failed to mmap: %s", g_strerror (errnosave));
-    gst_buffer_unref (GST_BUFFER (ret));
+    gst_buffer_unref (newbuf);
     errno = errnosave;
-    return NULL;
+    return GST_FLOW_ERROR;
   }
 }
 
+static gboolean
+gst_v4l2_buffer_pool_set_config (GstBufferPool * bpool, GstStructure * config)
+{
+  GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
+  GstV4l2Object *obj = pool->obj;
+  GstCaps *caps;
+  guint size, min_buffers, max_buffers, num_buffers, copy_threshold;
+  GstAllocator *allocator;
+  GstAllocationParams params;
+  struct v4l2_requestbuffers breq;
 
-/*
- * GstV4l2BufferPool:
- */
+  GST_DEBUG_OBJECT (pool, "set config");
 
-static GstMiniObjectClass *buffer_pool_parent_class = NULL;
+  pool->add_videometa =
+      gst_buffer_pool_config_has_option (config,
+      GST_BUFFER_POOL_OPTION_VIDEO_META);
 
-static void
-gst_v4l2_buffer_pool_finalize (GstV4l2BufferPool * pool)
-{
-  g_mutex_free (pool->lock);
-  pool->lock = NULL;
+  if (!pool->add_videometa) {
+    gint stride;
 
-  g_async_queue_unref (pool->avail_buffers);
-  pool->avail_buffers = NULL;
+    /* we don't have video metadata, see if the strides are compatible */
+    stride = GST_VIDEO_INFO_PLANE_STRIDE (&obj->info, 0);
 
-  if (pool->video_fd >= 0)
-    v4l2_close (pool->video_fd);
+    GST_DEBUG_OBJECT (pool, "no videometadata, checking strides %d and %u",
+        stride, obj->bytesperline);
 
-  if (pool->buffers) {
-    g_free (pool->buffers);
-    pool->buffers = NULL;
+    if (stride != obj->bytesperline)
+      goto missing_video_api;
   }
 
-  GST_MINI_OBJECT_CLASS (buffer_pool_parent_class)->finalize (GST_MINI_OBJECT
-      (pool));
-}
+  /* parse the config and keep around */
+  if (!gst_buffer_pool_config_get_params (config, &caps, &size, &min_buffers,
+          &max_buffers))
+    goto wrong_config;
 
-static void
-gst_v4l2_buffer_pool_init (GstV4l2BufferPool * pool, gpointer g_class)
-{
-  pool->lock = g_mutex_new ();
-  pool->running = FALSE;
-  pool->num_live_buffers = 0;
-}
+  if (!gst_buffer_pool_config_get_allocator (config, &allocator, &params))
+    goto wrong_config;
 
-static void
-gst_v4l2_buffer_pool_class_init (gpointer g_class, gpointer class_data)
-{
-  GstMiniObjectClass *mini_object_class = GST_MINI_OBJECT_CLASS (g_class);
+  GST_DEBUG_OBJECT (pool, "config %" GST_PTR_FORMAT, config);
 
-  buffer_pool_parent_class = g_type_class_peek_parent (g_class);
+  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;
+  }
 
-  mini_object_class->finalize = (GstMiniObjectFinalizeFunction)
-      gst_v4l2_buffer_pool_finalize;
-}
+  pool->size = size;
+  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;
 
-GType
-gst_v4l2_buffer_pool_get_type (void)
-{
-  static GType _gst_v4l2_buffer_pool_type;
-
-  if (G_UNLIKELY (_gst_v4l2_buffer_pool_type == 0)) {
-    static const GTypeInfo v4l2_buffer_pool_info = {
-      sizeof (GstMiniObjectClass),
-      NULL,
-      NULL,
-      gst_v4l2_buffer_pool_class_init,
-      NULL,
-      NULL,
-      sizeof (GstV4l2BufferPool),
-      0,
-      (GInstanceInitFunc) gst_v4l2_buffer_pool_init,
-      NULL
-    };
-    _gst_v4l2_buffer_pool_type = g_type_register_static (GST_TYPE_MINI_OBJECT,
-        "GstV4l2BufferPool", &v4l2_buffer_pool_info, 0);
-  }
-  return _gst_v4l2_buffer_pool_type;
-}
+  gst_buffer_pool_config_set_params (config, caps, size, min_buffers,
+      max_buffers);
 
+  return GST_BUFFER_POOL_CLASS (parent_class)->set_config (bpool, config);
 
-/* this is somewhat of a hack.. but better to keep the hack in
- * one place than copy/pasting it around..
- */
-static GstV4l2Object *
-get_v4l2_object (GstElement * v4l2elem)
-{
-  GstV4l2Object *v4l2object = NULL;
-  if (GST_IS_V4L2SRC (v4l2elem)) {
-    v4l2object = (GST_V4L2SRC (v4l2elem))->v4l2object;
-#ifdef HAVE_EXPERIMENTAL
-  } else if (GST_IS_V4L2SINK (v4l2elem)) {
-    v4l2object = (GST_V4L2SINK (v4l2elem))->v4l2object;
-#endif
-  } else {
-    GST_ERROR_OBJECT (v4l2elem, "unknown v4l2 element");
+  /* 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_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;
   }
-  return v4l2object;
 }
 
+static gboolean
+start_streaming (GstV4l2BufferPool * pool)
+{
+  GstV4l2Object *obj = pool->obj;
+
+  switch (obj->mode) {
+    case GST_V4L2_IO_RW:
+      break;
+    case GST_V4L2_IO_MMAP:
+    case GST_V4L2_IO_USERPTR:
+      GST_DEBUG_OBJECT (pool, "STREAMON");
+      if (v4l2_ioctl (pool->video_fd, VIDIOC_STREAMON, &obj->type) < 0)
+        goto start_failed;
+      break;
+    default:
+      g_assert_not_reached ();
+      break;
+  }
 
+  pool->streaming = TRUE;
 
-/**
- * gst_v4l2_buffer_pool_new:
- * @v4l2elem:  the v4l2 element (src or sink) that owns this pool
- * @fd:   the video device file descriptor
- * @num_buffers:  the requested number of buffers in the pool
- * @caps:  the caps to set on the buffer
- * @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
- */
-GstV4l2BufferPool *
-gst_v4l2_buffer_pool_new (GstElement * v4l2elem, gint fd, gint num_buffers,
-    GstCaps * caps, gboolean requeuebuf, enum v4l2_buf_type type)
-{
-  GstV4l2BufferPool *pool;
-  gint n;
-  struct v4l2_requestbuffers breq;
+  return TRUE;
 
-  pool = (GstV4l2BufferPool *) gst_mini_object_new (GST_TYPE_V4L2_BUFFER_POOL);
+  /* ERRORS */
+start_failed:
+  {
+    GST_ERROR_OBJECT (pool, "error with STREAMON %d (%s)", errno,
+        g_strerror (errno));
+    return FALSE;
+  }
+}
 
-  pool->video_fd = v4l2_dup (fd);
-  if (pool->video_fd < 0)
-    goto dup_failed;
+static gboolean
+gst_v4l2_buffer_pool_start (GstBufferPool * bpool)
+{
+  GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
+  GstV4l2Object *obj = pool->obj;
 
+  pool->obj = obj;
+  pool->buffers = g_new0 (GstBuffer *, pool->num_buffers);
+  pool->num_allocated = 0;
 
-  /* first, lets request buffers, and see how many we can get: */
-  GST_DEBUG_OBJECT (v4l2elem, "STREAMING, requesting %d MMAP buffers",
-      num_buffers);
+  /* now, allocate the buffers: */
+  if (!GST_BUFFER_POOL_CLASS (parent_class)->start (bpool))
+    goto start_failed;
 
-  memset (&breq, 0, sizeof (struct v4l2_requestbuffers));
-  breq.type = type;
-  breq.count = num_buffers;
-  breq.memory = V4L2_MEMORY_MMAP;
+  /* we can start capturing now, we wait for the playback case until we queued
+   * the first buffer */
+  if (obj->type == V4L2_BUF_TYPE_VIDEO_CAPTURE)
+    if (!start_streaming (pool))
+      goto start_failed;
 
-  if (v4l2_ioctl (fd, VIDIOC_REQBUFS, &breq) < 0)
-    goto reqbufs_failed;
+  gst_poll_set_flushing (obj->poll, FALSE);
 
-  GST_LOG_OBJECT (v4l2elem, " count:  %u", breq.count);
-  GST_LOG_OBJECT (v4l2elem, " type:   %d", breq.type);
-  GST_LOG_OBJECT (v4l2elem, " memory: %d", breq.memory);
+  return TRUE;
 
-  if (breq.count < GST_V4L2_MIN_BUFFERS)
-    goto no_buffers;
+  /* ERRORS */
+start_failed:
+  {
+    GST_ERROR_OBJECT (pool, "failed to start streaming");
+    return FALSE;
+  }
+}
 
-  if (num_buffers != breq.count) {
-    GST_WARNING_OBJECT (v4l2elem, "using %u buffers instead", breq.count);
-    num_buffers = breq.count;
+static gboolean
+gst_v4l2_buffer_pool_stop (GstBufferPool * bpool)
+{
+  gboolean ret;
+  GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
+  GstV4l2Object *obj = pool->obj;
+  guint n;
+
+  GST_DEBUG_OBJECT (pool, "stopping pool");
+
+  gst_poll_set_flushing (obj->poll, TRUE);
+
+  if (pool->streaming) {
+    switch (obj->mode) {
+      case GST_V4L2_IO_RW:
+        break;
+      case GST_V4L2_IO_MMAP:
+      case GST_V4L2_IO_USERPTR:
+        /* we actually need to sync on all queued buffers but not
+         * on the non-queued ones */
+        GST_DEBUG_OBJECT (pool, "STREAMOFF");
+        if (v4l2_ioctl (pool->video_fd, VIDIOC_STREAMOFF, &obj->type) < 0)
+          goto stop_failed;
+        break;
+      default:
+        g_assert_not_reached ();
+        break;
+    }
+    pool->streaming = FALSE;
   }
 
-  pool->v4l2elem = v4l2elem;
-  pool->requeuebuf = requeuebuf;
-  pool->type = type;
-  pool->buffer_count = num_buffers;
-  pool->buffers = g_new0 (GstV4l2Buffer *, num_buffers);
-  pool->avail_buffers = g_async_queue_new ();
+  /* first free the buffers in the queue */
+  ret = GST_BUFFER_POOL_CLASS (parent_class)->stop (bpool);
 
-  /* now, map the buffers: */
-  for (n = 0; n < num_buffers; n++) {
-    pool->buffers[n] = gst_v4l2_buffer_new (pool, n, caps);
-    if (!pool->buffers[n])
-      goto buffer_new_failed;
-    pool->num_live_buffers++;
-    g_async_queue_push (pool->avail_buffers, pool->buffers[n]);
+  /* then free the remaining buffers */
+  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 pool;
+  return ret;
 
   /* ERRORS */
-dup_failed:
+stop_failed:
   {
-    gint errnosave = errno;
-
-    gst_mini_object_unref (GST_MINI_OBJECT (pool));
-
-    errno = errnosave;
+    GST_ERROR_OBJECT (pool, "error with STREAMOFF %d (%s)", errno,
+        g_strerror (errno));
+    return FALSE;
+  }
+}
 
-    return NULL;
+static GstFlowReturn
+gst_v4l2_object_poll (GstV4l2Object * v4l2object)
+{
+  gint ret;
+
+  if (v4l2object->can_poll_device) {
+    GST_LOG_OBJECT (v4l2object->element, "polling device");
+    ret = gst_poll_wait (v4l2object->poll, GST_CLOCK_TIME_NONE);
+    if (G_UNLIKELY (ret < 0)) {
+      if (errno == EBUSY)
+        goto stopped;
+      if (errno == ENXIO) {
+        GST_WARNING_OBJECT (v4l2object->element,
+            "v4l2 device doesn't support polling. Disabling");
+        v4l2object->can_poll_device = FALSE;
+      } else {
+        if (errno != EAGAIN && errno != EINTR)
+          goto select_error;
+      }
+    }
   }
-reqbufs_failed:
+  return GST_FLOW_OK;
+
+  /* ERRORS */
+stopped:
   {
-    GstV4l2Object *v4l2object = get_v4l2_object (v4l2elem);
-    GST_ELEMENT_ERROR (v4l2elem, RESOURCE, READ,
-        (_("Could not get buffers from device '%s'."),
-            v4l2object->videodev),
-        ("error requesting %d buffers: %s", num_buffers, g_strerror (errno)));
-    return NULL;
+    GST_DEBUG ("stop called");
+    return GST_FLOW_FLUSHING;
   }
-no_buffers:
+select_error:
   {
-    GstV4l2Object *v4l2object = get_v4l2_object (v4l2elem);
-    GST_ELEMENT_ERROR (v4l2elem, RESOURCE, READ,
-        (_("Could not get enough buffers from device '%s'."),
-            v4l2object->videodev),
-        ("we received %d from device '%s', we want at least %d",
-            breq.count, v4l2object->videodev, GST_V4L2_MIN_BUFFERS));
-    return NULL;
+    GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, READ, (NULL),
+        ("poll error %d: %s (%d)", ret, g_strerror (errno), errno));
+    return GST_FLOW_ERROR;
   }
-buffer_new_failed:
-  {
-    gint errnosave = errno;
+}
 
-    gst_v4l2_buffer_pool_destroy (pool);
+static GstFlowReturn
+gst_v4l2_buffer_pool_qbuf (GstV4l2BufferPool * pool, GstBuffer * buf)
+{
+  GstV4l2Meta *meta;
+  gint index;
 
-    errno = errnosave;
+  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;
+  }
 
-    return NULL;
+  index = meta->vbuffer.index;
+
+  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;
+
+  pool->buffers[index] = buf;
+  pool->num_queued++;
+
+  return GST_FLOW_OK;
+
+  /* ERRORS */
+already_queued:
+  {
+    GST_WARNING_OBJECT (pool, "the buffer was already queued");
+    return GST_FLOW_ERROR;
+  }
+queue_failed:
+  {
+    GST_WARNING_OBJECT (pool, "could not queue a buffer %d (%s)", errno,
+        g_strerror (errno));
+    return GST_FLOW_ERROR;
   }
 }
 
-/**
- * gst_v4l2_buffer_pool_destroy:
- * @pool: the pool
- *
- * Free all resources in the pool and the pool itself.
- */
-void
-gst_v4l2_buffer_pool_destroy (GstV4l2BufferPool * pool)
+static GstFlowReturn
+gst_v4l2_buffer_pool_dqbuf (GstV4l2BufferPool * pool, GstBuffer ** buffer)
 {
-  gint n;
+  GstFlowReturn res;
+  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
+     * specs we can also poll to find out when a frame has been displayed but
+     * that just seems to lock up here */
+    if ((res = gst_v4l2_object_poll (obj)) != GST_FLOW_OK)
+      goto poll_error;
+  }
+
+  memset (&vbuffer, 0x00, sizeof (vbuffer));
+  vbuffer.type = obj->type;
+  vbuffer.memory = V4L2_MEMORY_MMAP;
 
-  GST_V4L2_BUFFER_POOL_LOCK (pool);
-  pool->running = FALSE;
-  GST_V4L2_BUFFER_POOL_UNLOCK (pool);
+  GST_LOG_OBJECT (pool, "doing DQBUF");
+  if (v4l2_ioctl (pool->video_fd, VIDIOC_DQBUF, &vbuffer) < 0)
+    goto error;
 
-  GST_DEBUG_OBJECT (pool->v4l2elem, "destroy pool");
+  /* get our GstBuffer with that index from the pool, if the buffer was
+   * outstanding we have a serious problem.
+   */
+  outbuf = pool->buffers[vbuffer.index];
+  if (outbuf == NULL)
+    goto no_buffer;
 
-  /* after this point, no more buffers will be queued or dequeued; no buffer
-   * from pool->buffers that is NULL will be set to a buffer, and no buffer that
-   * is not NULL will be pushed out. */
+  /* mark the buffer outstanding */
+  pool->buffers[vbuffer.index] = NULL;
+  pool->num_queued--;
 
-  /* miniobjects have no dispose, so they can't break ref-cycles, as buffers ref
-   * the pool, we need to unref the buffer to properly finalize te pool */
-  for (n = 0; n < pool->buffer_count; n++) {
-    GstBuffer *buf;
+  timestamp = GST_TIMEVAL_TO_TIME (vbuffer.timestamp);
 
-    GST_V4L2_BUFFER_POOL_LOCK (pool);
-    buf = GST_BUFFER (pool->buffers[n]);
-    GST_V4L2_BUFFER_POOL_UNLOCK (pool);
+  GST_LOG_OBJECT (pool,
+      "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);
 
-    if (buf)
-      /* we own the ref if the buffer is in pool->buffers; drop it. */
-      gst_buffer_unref (buf);
+  /* 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_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)
+    gst_buffer_resize (outbuf, 0, vbuffer.bytesused);
+  else
+    gst_buffer_resize (outbuf, 0, vbuffer.length);
+
+  GST_BUFFER_TIMESTAMP (outbuf) = timestamp;
+
+  *buffer = outbuf;
+
+  return GST_FLOW_OK;
 
-  gst_mini_object_unref (GST_MINI_OBJECT (pool));
+  /* ERRORS */
+poll_error:
+  {
+    GST_DEBUG_OBJECT (pool, "poll error %s", gst_flow_get_name (res));
+    return res;
+  }
+error:
+  {
+    GST_WARNING_OBJECT (pool,
+        "problem dequeuing frame %d (ix=%d), pool-ct=%d, buf.flags=%d",
+        vbuffer.sequence, vbuffer.index,
+        GST_MINI_OBJECT_REFCOUNT (pool), vbuffer.flags);
+
+    switch (errno) {
+      case EAGAIN:
+        GST_WARNING_OBJECT (pool,
+            "Non-blocking I/O has been selected using O_NONBLOCK and"
+            " no buffer was in the outgoing queue. device %s", obj->videodev);
+        break;
+      case EINVAL:
+        GST_ERROR_OBJECT (pool,
+            "The buffer type is not supported, or the index is out of bounds, "
+            "or no buffers have been allocated yet, or the userptr "
+            "or length are invalid. device %s", obj->videodev);
+        break;
+      case ENOMEM:
+        GST_ERROR_OBJECT (pool,
+            "insufficient memory to enqueue a user pointer buffer");
+        break;
+      case EIO:
+        GST_INFO_OBJECT (pool,
+            "VIDIOC_DQBUF failed due to an internal error."
+            " Can also indicate temporary problems like signal loss."
+            " Note the driver might dequeue an (empty) buffer despite"
+            " returning an error, or even stop capturing."
+            " device %s", obj->videodev);
+        /* have we de-queued a buffer ? */
+        if (!(vbuffer.flags & (V4L2_BUF_FLAG_QUEUED | V4L2_BUF_FLAG_DONE))) {
+          GST_DEBUG_OBJECT (pool, "reenqueing buffer");
+          /* FIXME ... should we do something here? */
+        }
+        break;
+      case EINTR:
+        GST_WARNING_OBJECT (pool,
+            "could not sync on a buffer on device %s", obj->videodev);
+        break;
+      default:
+        GST_WARNING_OBJECT (pool,
+            "Grabbing frame got interrupted on %s unexpectedly. %d: %s.",
+            obj->videodev, errno, g_strerror (errno));
+        break;
+    }
+    return GST_FLOW_ERROR;
+  }
+no_buffer:
+  {
+    GST_ERROR_OBJECT (pool, "No free buffer found in the pool at index %d.",
+        vbuffer.index);
+    return GST_FLOW_ERROR;
+  }
 }
 
-/**
- * gst_v4l2_buffer_pool_get:
- * @pool:   the "this" object
- * @blocking:  should this call suspend until there is a buffer available
- *    in the buffer pool?
- *
- * Get an available buffer in the pool
- */
-GstV4l2Buffer *
-gst_v4l2_buffer_pool_get (GstV4l2BufferPool * pool, gboolean blocking)
+static GstFlowReturn
+gst_v4l2_buffer_pool_acquire_buffer (GstBufferPool * bpool, GstBuffer ** buffer,
+    GstBufferPoolAcquireParams * params)
 {
-  GstV4l2Buffer *buf;
+  GstFlowReturn ret;
+  GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
+  GstV4l2Object *obj = pool->obj;
+
+  GST_DEBUG_OBJECT (pool, "acquire");
+
+  if (GST_BUFFER_POOL_IS_FLUSHING (bpool))
+    goto flushing;
+
+  switch (obj->type) {
+    case V4L2_BUF_TYPE_VIDEO_CAPTURE:
+      /* capture, This function should return a buffer with new captured data */
+      switch (obj->mode) {
+        case GST_V4L2_IO_RW:
+          /* take empty buffer from the pool */
+          ret = GST_BUFFER_POOL_CLASS (parent_class)->acquire_buffer (bpool,
+              buffer, params);
+          break;
+
+        case GST_V4L2_IO_MMAP:
+          /* just dequeue a buffer, we basically use the queue of v4l2 as the
+           * 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:
+        default:
+          g_assert_not_reached ();
+          break;
+      }
+      break;
 
-  if (blocking) {
-    buf = g_async_queue_pop (pool->avail_buffers);
-  } else {
-    buf = g_async_queue_try_pop (pool->avail_buffers);
+    case V4L2_BUF_TYPE_VIDEO_OUTPUT:
+      /* playback, This function should return an empty buffer */
+      switch (obj->mode) {
+        case GST_V4L2_IO_RW:
+          /* get an empty buffer */
+          ret = GST_BUFFER_POOL_CLASS (parent_class)->acquire_buffer (bpool,
+              buffer, params);
+          break;
+
+        case GST_V4L2_IO_MMAP:
+          /* get a free unqueued buffer */
+          ret = GST_BUFFER_POOL_CLASS (parent_class)->acquire_buffer (bpool,
+              buffer, params);
+          break;
+
+        case GST_V4L2_IO_USERPTR:
+        default:
+          g_assert_not_reached ();
+          break;
+      }
+      break;
+
+    default:
+      g_assert_not_reached ();
+      break;
   }
+done:
+  return ret;
 
-  if (buf) {
-    GST_V4L2_BUFFER_POOL_LOCK (pool);
-    GST_BUFFER_SIZE (buf) = buf->vbuffer.length;
-    GST_BUFFER_FLAG_UNSET (buf, 0xffffffff);
-    GST_V4L2_BUFFER_POOL_UNLOCK (pool);
+  /* ERRORS */
+flushing:
+  {
+    GST_DEBUG_OBJECT (pool, "We are flushing");
+    return GST_FLOW_FLUSHING;
   }
+}
 
-  pool->running = TRUE;
+static void
+gst_v4l2_buffer_pool_release_buffer (GstBufferPool * bpool, GstBuffer * buffer)
+{
+  GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool);
+  GstV4l2Object *obj = pool->obj;
+
+  GST_DEBUG_OBJECT (pool, "release buffer %p", buffer);
+
+  switch (obj->type) {
+    case V4L2_BUF_TYPE_VIDEO_CAPTURE:
+      /* capture, put the buffer back in the queue so that we can refill it
+       * later. */
+      switch (obj->mode) {
+        case GST_V4L2_IO_RW:
+          /* release back in the pool */
+          GST_BUFFER_POOL_CLASS (parent_class)->release_buffer (bpool, buffer);
+          break;
+
+        case GST_V4L2_IO_MMAP:
+          /* queue back in the device */
+          gst_v4l2_buffer_pool_qbuf (pool, buffer);
+          break;
+
+        case GST_V4L2_IO_USERPTR:
+        default:
+          g_assert_not_reached ();
+          break;
+      }
+      break;
 
-  return buf;
-}
+    case V4L2_BUF_TYPE_VIDEO_OUTPUT:
+      switch (obj->mode) {
+        case GST_V4L2_IO_RW:
+          /* release back in the pool */
+          GST_BUFFER_POOL_CLASS (parent_class)->release_buffer (bpool, buffer);
+          break;
+
+        case GST_V4L2_IO_MMAP:
+        {
+          GstV4l2Meta *meta;
+
+          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 ();
+      break;
+  }
+}
 
-/**
- * gst_v4l2_buffer_pool_qbuf:
- * @pool: the pool
- * @buf: the buffer to queue
- *
- * Queue a buffer to the driver
- *
- * Returns: %TRUE for success
- */
-gboolean
-gst_v4l2_buffer_pool_qbuf (GstV4l2BufferPool * pool, GstV4l2Buffer * buf)
+static void
+gst_v4l2_buffer_pool_finalize (GObject * object)
 {
-  GST_LOG_OBJECT (pool->v4l2elem, "enqueue pool buffer %d", buf->vbuffer.index);
+  GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (object);
 
-  if (v4l2_ioctl (pool->video_fd, VIDIOC_QBUF, &buf->vbuffer) < 0)
-    return FALSE;
+  if (pool->video_fd >= 0)
+    v4l2_close (pool->video_fd);
+  if (pool->allocator)
+    gst_allocator_unref (pool->allocator);
+  g_free (pool->buffers);
 
-  pool->num_live_buffers--;
-  GST_DEBUG_OBJECT (pool->v4l2elem, "num_live_buffers--: %d",
-      pool->num_live_buffers);
+  G_OBJECT_CLASS (parent_class)->finalize (object);
+}
 
-  return TRUE;
+static void
+gst_v4l2_buffer_pool_init (GstV4l2BufferPool * pool)
+{
+}
+
+static void
+gst_v4l2_buffer_pool_class_init (GstV4l2BufferPoolClass * klass)
+{
+  GObjectClass *object_class = G_OBJECT_CLASS (klass);
+  GstBufferPoolClass *bufferpool_class = GST_BUFFER_POOL_CLASS (klass);
+
+  object_class->finalize = gst_v4l2_buffer_pool_finalize;
+
+  bufferpool_class->start = gst_v4l2_buffer_pool_start;
+  bufferpool_class->stop = gst_v4l2_buffer_pool_stop;
+  bufferpool_class->set_config = gst_v4l2_buffer_pool_set_config;
+  bufferpool_class->alloc_buffer = gst_v4l2_buffer_pool_alloc_buffer;
+  bufferpool_class->acquire_buffer = gst_v4l2_buffer_pool_acquire_buffer;
+  bufferpool_class->release_buffer = gst_v4l2_buffer_pool_release_buffer;
+  bufferpool_class->free_buffer = gst_v4l2_buffer_pool_free_buffer;
 }
 
 /**
- * gst_v4l2_buffer_pool_dqbuf:
- * @pool: the pool
+ * gst_v4l2_buffer_pool_new:
+ * @obj:  the v4l2 object owning the pool
  *
- * Dequeue a buffer from the driver.  Some generic error handling is done in
- * this function, but any error handling specific to v4l2src (capture) or
- * v4l2sink (output) can be done outside this function by checking 'errno'
+ * Construct a new buffer pool.
  *
- * Returns: a buffer
+ * Returns: the new pool, use gst_object_unref() to free resources
  */
-GstV4l2Buffer *
-gst_v4l2_buffer_pool_dqbuf (GstV4l2BufferPool * pool)
+GstBufferPool *
+gst_v4l2_buffer_pool_new (GstV4l2Object * obj, GstCaps * caps)
 {
-  GstV4l2Object *v4l2object = get_v4l2_object (pool->v4l2elem);
-  GstV4l2Buffer *pool_buffer;
-  struct v4l2_buffer buffer;
+  GstV4l2BufferPool *pool;
+  GstStructure *s;
+  gint fd;
 
-  memset (&buffer, 0x00, sizeof (buffer));
-  buffer.type = pool->type;
-  buffer.memory = V4L2_MEMORY_MMAP;
+  fd = v4l2_dup (obj->video_fd);
+  if (fd < 0)
+    goto dup_failed;
 
+  pool = (GstV4l2BufferPool *) g_object_new (GST_TYPE_V4L2_BUFFER_POOL, NULL);
+  pool->video_fd = fd;
+  pool->obj = obj;
 
-  if (v4l2_ioctl (pool->video_fd, VIDIOC_DQBUF, &buffer) >= 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);
 
-    GST_V4L2_BUFFER_POOL_LOCK (pool);
+  return GST_BUFFER_POOL (pool);
 
-    /* get our GstBuffer with that index from the pool, if the buffer was
-     * outstanding we have a serious problem.
-     */
-    pool_buffer = pool->buffers[buffer.index];
+  /* ERRORS */
+dup_failed:
+  {
+    GST_DEBUG ("failed to dup fd %d (%s)", errno, g_strerror (errno));
+    return NULL;
+  }
+}
 
-    if (pool_buffer == NULL) {
-      GST_ELEMENT_ERROR (pool->v4l2elem, RESOURCE, FAILED,
-          (_("Failed trying to get video frames from device '%s'."),
-              v4l2object->videodev),
-          (_("No free buffers found in the pool at index %d."), buffer.index));
-      GST_V4L2_BUFFER_POOL_UNLOCK (pool);
-      return NULL;
-    }
+static GstFlowReturn
+gst_v4l2_do_read (GstV4l2BufferPool * pool, GstBuffer * buf)
+{
+  GstFlowReturn res;
+  GstV4l2Object *obj = pool->obj;
+  gint amount;
+  GstMapInfo map;
+  gint toread;
 
-    GST_LOG_OBJECT (pool->v4l2elem,
-        "grabbed frame %d (ix=%d), flags %08x, pool-ct=%d, buffer=%p",
-        buffer.sequence, buffer.index, buffer.flags, pool->num_live_buffers,
-        pool_buffer);
+  toread = obj->sizeimage;
 
-    pool->num_live_buffers++;
-    GST_DEBUG_OBJECT (pool->v4l2elem, "num_live_buffers++: %d",
-        pool->num_live_buffers);
+  GST_LOG_OBJECT (pool, "reading %d bytes into buffer %p", toread, buf);
 
-    /* set top/bottom field first if v4l2_buffer has the information */
-    if (buffer.field == V4L2_FIELD_INTERLACED_TB)
-      GST_BUFFER_FLAG_SET (pool_buffer, GST_VIDEO_BUFFER_TFF);
-    if (buffer.field == V4L2_FIELD_INTERLACED_BT)
-      GST_BUFFER_FLAG_UNSET (pool_buffer, GST_VIDEO_BUFFER_TFF);
+  gst_buffer_map (buf, &map, GST_MAP_WRITE);
 
-    /* this can change at every frame, esp. with jpeg */
-    GST_BUFFER_SIZE (pool_buffer) = buffer.bytesused;
+  do {
+    if ((res = gst_v4l2_object_poll (obj)) != GST_FLOW_OK)
+      goto poll_error;
 
-    GST_V4L2_BUFFER_POOL_UNLOCK (pool);
+    amount = v4l2_read (obj->video_fd, map.data, toread);
 
-    return pool_buffer;
-  }
+    if (amount == toread) {
+      break;
+    } else if (amount == -1) {
+      if (errno == EAGAIN || errno == EINTR) {
+        continue;
+      } else
+        goto read_error;
+    } else {
+      /* short reads can happen if a signal interrupts the read */
+      continue;
+    }
+  } while (TRUE);
 
+  GST_LOG_OBJECT (pool, "read %d bytes", amount);
+  gst_buffer_unmap (buf, &map);
+  gst_buffer_resize (buf, 0, amount);
 
-  GST_WARNING_OBJECT (pool->v4l2elem,
-      "problem grabbing frame %d (ix=%d), pool-ct=%d, buf.flags=%d",
-      buffer.sequence, buffer.index,
-      GST_MINI_OBJECT_REFCOUNT (pool), buffer.flags);
+  return GST_FLOW_OK;
 
-  switch (errno) {
-    case EAGAIN:
-      GST_WARNING_OBJECT (pool->v4l2elem,
-          "Non-blocking I/O has been selected using O_NONBLOCK and"
-          " no buffer was in the outgoing queue. device %s",
-          v4l2object->videodev);
-      break;
-    case EINVAL:
-      GST_ELEMENT_ERROR (pool->v4l2elem, RESOURCE, FAILED,
-          (_("Failed trying to get video frames from device '%s'."),
-              v4l2object->videodev),
-          (_("The buffer type is not supported, or the index is out of bounds,"
-                  " or no buffers have been allocated yet, or the userptr"
-                  " or length are invalid. device %s"), v4l2object->videodev));
-      break;
-    case ENOMEM:
-      GST_ELEMENT_ERROR (pool->v4l2elem, RESOURCE, FAILED,
-          (_("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));
-      break;
-    case EIO:
-      GST_INFO_OBJECT (pool->v4l2elem,
-          "VIDIOC_DQBUF failed due to an internal error."
-          " Can also indicate temporary problems like signal loss."
-          " Note the driver might dequeue an (empty) buffer despite"
-          " returning an error, or even stop capturing."
-          " device %s", v4l2object->videodev);
-      /* have we de-queued a buffer ? */
-      if (!(buffer.flags & (V4L2_BUF_FLAG_QUEUED | V4L2_BUF_FLAG_DONE))) {
-        GST_DEBUG_OBJECT (pool->v4l2elem, "reenqueing buffer");
-        /* FIXME ... should we do something here? */
-      }
-      break;
-    case EINTR:
-      GST_WARNING_OBJECT (pool->v4l2elem,
-          "could not sync on a buffer on device %s", v4l2object->videodev);
-      break;
-    default:
-      GST_WARNING_OBJECT (pool->v4l2elem,
-          "Grabbing frame got interrupted on %s unexpectedly. %d: %s.",
-          v4l2object->videodev, errno, g_strerror (errno));
-      break;
+  /* ERRORS */
+poll_error:
+  {
+    GST_DEBUG ("poll error %s", gst_flow_get_name (res));
+    goto cleanup;
+  }
+read_error:
+  {
+    GST_ELEMENT_ERROR (obj->element, RESOURCE, READ,
+        (_("Error reading %d bytes from device '%s'."),
+            toread, obj->videodev), GST_ERROR_SYSTEM);
+    res = GST_FLOW_ERROR;
+    goto cleanup;
+  }
+cleanup:
+  {
+    gst_buffer_unmap (buf, &map);
+    gst_buffer_resize (buf, 0, 0);
+    return res;
   }
-
-  return NULL;
 }
 
 /**
- * gst_v4l2_buffer_pool_available_buffers:
- * @pool: the pool
+ * gst_v4l2_buffer_pool_process:
+ * @bpool: a #GstBufferPool
+ * @buf: a #GstBuffer
  *
- * Check the number of buffers available to the driver, ie. buffers that
- * have been QBUF'd but not yet DQBUF'd.
+ * Process @buf in @bpool. For capture devices, this functions fills @buf with
+ * data from the device. For output devices, this functions send the contents of
+ * @buf to the device for playback.
  *
- * Returns: the number of buffers available.
+ * Returns: %GST_FLOW_OK on success.
  */
-gint
-gst_v4l2_buffer_pool_available_buffers (GstV4l2BufferPool * pool)
+GstFlowReturn
+gst_v4l2_buffer_pool_process (GstV4l2BufferPool * pool, GstBuffer * buf)
 {
-  return pool->buffer_count - pool->num_live_buffers;
+  GstFlowReturn ret = GST_FLOW_OK;
+  GstBufferPool *bpool = GST_BUFFER_POOL_CAST (pool);
+  GstV4l2Object *obj = pool->obj;
+
+  GST_DEBUG_OBJECT (pool, "process buffer %p", buf);
+
+  switch (obj->type) {
+    case V4L2_BUF_TYPE_VIDEO_CAPTURE:
+      /* capture */
+      switch (obj->mode) {
+        case GST_V4L2_IO_RW:
+          /* capture into the buffer */
+          ret = gst_v4l2_do_read (pool, buf);
+          break;
+
+        case GST_V4L2_IO_MMAP:
+        {
+          GstBuffer *tmp;
+
+          if (buf->pool == bpool)
+            /* nothing, data was inside the buffer when we did _acquire() */
+            goto done;
+
+          /* buffer not from our pool, grab a frame and copy it into the target */
+          if ((ret = gst_v4l2_buffer_pool_dqbuf (pool, &tmp)) != GST_FLOW_OK)
+            goto done;
+
+          if (!gst_v4l2_object_copy (obj, buf, tmp))
+            goto copy_failed;
+
+          /* an queue the buffer again after the copy */
+          if ((ret = gst_v4l2_buffer_pool_qbuf (pool, tmp)) != GST_FLOW_OK)
+            goto done;
+          break;
+        }
+
+        case GST_V4L2_IO_USERPTR:
+        default:
+          g_assert_not_reached ();
+          break;
+      }
+      break;
+
+    case V4L2_BUF_TYPE_VIDEO_OUTPUT:
+      /* playback */
+      switch (obj->mode) {
+        case GST_V4L2_IO_RW:
+          /* FIXME, do write() */
+          GST_WARNING_OBJECT (pool, "implement write()");
+          break;
+
+        case GST_V4L2_IO_MMAP:
+        {
+          GstBuffer *to_queue;
+
+          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_OK)
+              goto acquire_failed;
+
+            /* copy into it and queue */
+            if (!gst_v4l2_object_copy (obj, to_queue, buf))
+              goto copy_failed;
+          }
+
+          if ((ret = gst_v4l2_buffer_pool_qbuf (pool, to_queue)) != GST_FLOW_OK)
+            goto done;
+
+          /* if we are not streaming yet (this is the first buffer, start
+           * streaming now */
+          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;
+        }
+
+        case GST_V4L2_IO_USERPTR:
+        default:
+          g_assert_not_reached ();
+          break;
+      }
+      break;
+    default:
+      g_assert_not_reached ();
+      break;
+  }
+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");
+    return GST_FLOW_ERROR;
+  }
+start_failed:
+  {
+    GST_ERROR_OBJECT (obj->element, "failed to start streaming");
+    return GST_FLOW_ERROR;
+  }
 }