]> git.sesse.net Git - vlc/blobdiff - modules/access/v4l2/demux.c
BluRay instead of Blu-Ray. Re-using short messages for long ones
[vlc] / modules / access / v4l2 / demux.c
index 13bce7e6f5da1eed026999669ac3456fab7849bb..9d9b2ffcca4e87887ca892f8beb875b8f963071a 100644 (file)
@@ -1,21 +1,21 @@
 /*****************************************************************************
  * demux.c : V4L2 raw video demux module for vlc
  *****************************************************************************
- * Copyright (C) 2002-2011 the VideoLAN team
+ * Copyright (C) 2002-2011 VLC authors and VideoLAN
  *
  * Authors: Benjamin Pracht <bigben at videolan dot org>
  *          Richard Hosking <richard at hovis dot net>
  *          Antoine Cellerier <dionoea at videolan d.t org>
  *          Dennis Lou <dlou99 at yahoo dot com>
  *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU Lesser General Public License as published by
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as published by
  * the Free Software Foundation; either version 2.1 of the License, or
  * (at your option) any later version.
  *
  * This program is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  * GNU Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public License
 #include <math.h>
 #include <errno.h>
 #include <assert.h>
-#include <fcntl.h>
 #include <sys/ioctl.h>
 #include <sys/mman.h>
+#ifndef MAP_ANONYMOUS
+# define MAP_ANONYMOUS MAP_ANON
+#endif
 #include <poll.h>
 
 #include <vlc_common.h>
 #include <vlc_demux.h>
-#include <vlc_fs.h>
 
 #include "v4l2.h"
 
+struct demux_sys_t
+{
+    int fd;
+    vlc_thread_t thread;
+
+    struct buffer_t *bufv;
+    union
+    {
+        uint32_t bufc;
+        uint32_t blocksize;
+    };
+    uint32_t block_flags;
+
+    es_out_id_t *es;
+    vlc_v4l2_ctrl_t *controls;
+    mtime_t start;
+
+#ifdef ZVBI_COMPILED
+    vlc_v4l2_vbi_t *vbi;
+#endif
+};
+
+static void *UserPtrThread (void *);
+static void *MmapThread (void *);
+static void *ReadThread (void *);
 static int DemuxControl( demux_t *, int, va_list );
-static int Demux( demux_t * );
-static int InitVideo (demux_t *, int);
+static int InitVideo (demux_t *, int fd, uint32_t caps);
 
 int DemuxOpen( vlc_object_t *obj )
 {
     demux_t *demux = (demux_t *)obj;
 
-    demux_sys_t *sys = calloc( 1, sizeof( demux_sys_t ) );
-    if( unlikely(sys == NULL) )
+    demux_sys_t *sys = malloc (sizeof (*sys));
+    if (unlikely(sys == NULL))
         return VLC_ENOMEM;
     demux->p_sys = sys;
+#ifdef ZVBI_COMPILED
+    sys->vbi = NULL;
+#endif
 
     ParseMRL( obj, demux->psz_location );
 
     char *path = var_InheritString (obj, CFG_PREFIX"dev");
     if (unlikely(path == NULL))
         goto error; /* probably OOM */
-    msg_Dbg (obj, "opening device '%s'", path);
 
-    int rawfd = vlc_open (path, O_RDWR);
-    if (rawfd == -1)
-    {
-        msg_Err (obj, "cannot open device '%s': %m", path);
-        free (path);
-        goto error;
-    }
+    uint32_t caps;
+    int fd = OpenDevice (obj, path, &caps);
     free (path);
-
-    int fd = v4l2_fd_open (rawfd, 0);
     if (fd == -1)
-    {
-        msg_Warn (obj, "cannot initialize user-space library: %m");
-        /* fallback to direct kernel mode anyway */
-        fd = rawfd;
-    }
+        goto error;
+    sys->fd = fd;
 
-    if (InitVideo (demux, fd))
+    if (InitVideo (demux, fd, caps))
     {
         v4l2_close (fd);
         goto error;
     }
 
-    sys->i_fd = fd;
     sys->controls = ControlsInit (VLC_OBJECT(demux), fd);
-    demux->pf_demux = Demux;
+    sys->start = mdate ();
+    demux->pf_demux = NULL;
     demux->pf_control = DemuxControl;
     demux->info.i_update = 0;
     demux->info.i_title = 0;
@@ -237,66 +254,32 @@ static vlc_fourcc_t var_InheritFourCC (vlc_object_t *obj, const char *varname)
 }
 #define var_InheritFourCC(o, v) var_InheritFourCC(VLC_OBJECT(o), v)
 
-/**
- * List of V4L2 chromas were confident enough to use as fallbacks if the
- * user hasn't provided a --v4l2-chroma value.
- *
- * Try YUV chromas first, then RGB little endian and MJPEG as last resort.
- */
-static const uint32_t p_chroma_fallbacks[] =
-{ V4L2_PIX_FMT_YUV420, V4L2_PIX_FMT_YVU420, V4L2_PIX_FMT_YUV422P,
-  V4L2_PIX_FMT_YUYV, V4L2_PIX_FMT_UYVY, V4L2_PIX_FMT_BGR24,
-  V4L2_PIX_FMT_BGR32, V4L2_PIX_FMT_MJPEG, V4L2_PIX_FMT_JPEG };
-
-static int InitVideo (demux_t *demux, int fd)
+static void GetAR (int fd, unsigned *restrict num, unsigned *restrict den)
 {
-    demux_sys_t *sys = demux->p_sys;
-    enum v4l2_buf_type buf_type;
+    struct v4l2_cropcap cropcap = { .type = V4L2_BUF_TYPE_VIDEO_CAPTURE };
 
-    /* Get device capabilites */
-    struct v4l2_capability cap;
-    if (v4l2_ioctl (fd, VIDIOC_QUERYCAP, &cap) < 0)
+    /* TODO: get CROPCAP only once (see ResetCrop()). */
+    if (v4l2_ioctl (fd, VIDIOC_CROPCAP, &cropcap) < 0)
     {
-        msg_Err (demux, "cannot get device capabilities: %m");
-        return -1;
+        *num = *den = 1;
+        return;
     }
+    *num = cropcap.pixelaspect.numerator;
+    *den = cropcap.pixelaspect.denominator;
+}
 
-    msg_Dbg (demux, "device %s using driver %s (version %u.%u.%u) on %s",
-            cap.card, cap.driver, (cap.version >> 16) & 0xFF,
-            (cap.version >> 8) & 0xFF, cap.version & 0xFF, cap.bus_info);
+static int InitVideo (demux_t *demux, int fd, uint32_t caps)
+{
+    demux_sys_t *sys = demux->p_sys;
+    v4l2_std_id std;
 
-    uint32_t caps;
-#ifdef V4L2_CAP_DEVICE_CAPS
-    if (cap.capabilities & V4L2_CAP_DEVICE_CAPS)
-    {
-        msg_Dbg (demux, " with capabilities 0x%08"PRIX32" "
-                 "(overall 0x%08"PRIX32")", cap.device_caps, cap.capabilities);
-        caps = cap.device_caps;
-    }
-    else
-#endif
-    {
-        msg_Dbg (demux, " with unknown capabilities  "
-                 "(overall 0x%08"PRIX32")", cap.capabilities);
-        caps = cap.capabilities;
-    }
     if (!(caps & V4L2_CAP_VIDEO_CAPTURE))
     {
         msg_Err (demux, "not a video capture device");
         return -1;
     }
 
-    if (caps & V4L2_CAP_STREAMING)
-        sys->io = IO_METHOD_MMAP;
-    else if (caps & V4L2_CAP_READWRITE)
-        sys->io = IO_METHOD_READ;
-    else
-    {
-        msg_Err (demux, "no supported I/O method");
-        return -1;
-    }
-
-    if (SetupInput (VLC_OBJECT(demux), fd))
+    if (SetupInput (VLC_OBJECT(demux), fd, &std))
         return -1;
 
     /* Picture format negotiation */
@@ -349,71 +332,17 @@ static int InitVideo (demux_t *demux, int fd)
     msg_Dbg (demux, "selected format %4.4s (%4.4s)",
              (const char *)&selected->v4l2, (const char *)&selected->vlc);
 
-    struct v4l2_format fmt = { .type = V4L2_BUF_TYPE_VIDEO_CAPTURE };
-    if (v4l2_ioctl (fd, VIDIOC_G_FMT, &fmt) < 0)
-    {
-        msg_Err (demux, "cannot get device default format: %m");
+    /* Find best resolution and frame rate available */
+    struct v4l2_format fmt;
+    struct v4l2_streamparm parm;
+    if (SetupFormat (demux, fd, selected->v4l2, &fmt, &parm))
         return -1;
-    }
-
-    fmt.fmt.pix.pixelformat = selected->v4l2;
-
-    uint32_t width = var_InheritInteger (demux, CFG_PREFIX"width");
-    if (width != (uint32_t)-1)
-        fmt.fmt.pix.width = width; /* override width */
-    uint32_t height = var_InheritInteger (demux, CFG_PREFIX"height");
-    if (height != (uint32_t)-1)
-        fmt.fmt.pix.height = height; /* override height */
-
-    if (v4l2_ioctl (fd, VIDIOC_S_FMT, &fmt) < 0)
-    {
-        msg_Err (demux, "cannot set format: %m");
-        return -1;
-    }
-
-    /* Try and find default resolution if not specified */
-    float fps = 0.;
-    if (width == (uint32_t)-1 || height == (uint32_t)-1)
-    {
-        fps = var_InheritFloat (demux, CFG_PREFIX"fps");
-        if (fps <= 0.)
-        {
-            fps = GetAbsoluteMaxFrameRate (VLC_OBJECT(demux), fd,
-                                           fmt.fmt.pix.pixelformat);
-            msg_Dbg (demux, "Found maximum framerate of %f", fps);
-        }
-        uint32_t i_width, i_height;
-        GetMaxDimensions (VLC_OBJECT(demux), fd, fmt.fmt.pix.pixelformat, fps,
-                          &i_width, &i_height);
-        if (i_width || i_height)
-        {
-            msg_Dbg (demux, "Found optimal dimensions for framerate %f "
-                            "of %ux%u", fps, i_width, i_height);
-            fmt.fmt.pix.width = i_width;
-            fmt.fmt.pix.height = i_height;
-            if (v4l2_ioctl (fd, VIDIOC_S_FMT, &fmt) < 0)
-            {
-                msg_Err (demux, "Cannot set size to optimal dimensions %ux%u",
-                         i_width, i_height);
-                return -1;
-            }
-        }
-        else
-        {
-            msg_Warn (demux, "Could not find optimal width and height, "
-                      "falling back to driver default.");
-        }
-    }
-
-    width = fmt.fmt.pix.width;
-    height = fmt.fmt.pix.height;
-
-    if (v4l2_ioctl (fd, VIDIOC_G_FMT, &fmt) < 0) {;}
 
     /* Print extra info */
     msg_Dbg (demux, "%d bytes maximum for complete image",
              fmt.fmt.pix.sizeimage);
     /* Check interlacing */
+    sys->block_flags = 0;
     switch (fmt.fmt.pix.field)
     {
         case V4L2_FIELD_NONE:
@@ -428,9 +357,9 @@ static int InitVideo (demux_t *demux, int fd)
         case V4L2_FIELD_INTERLACED:
             msg_Dbg (demux, "Interlacing setting: interleaved");
             /*if (NTSC)
-                sys->i_block_flags = BLOCK_FLAG_BOTTOM_FIELD_FIRST;
+                sys->block_flags = BLOCK_FLAG_BOTTOM_FIELD_FIRST;
             else*/
-                sys->i_block_flags = BLOCK_FLAG_TOP_FIELD_FIRST;
+                sys->block_flags = BLOCK_FLAG_TOP_FIELD_FIRST;
             break;
         case V4L2_FIELD_SEQ_TB:
             msg_Dbg (demux, "Interlacing setting: sequential top bottom (TODO)");
@@ -440,15 +369,15 @@ static int InitVideo (demux_t *demux, int fd)
             break;
         case V4L2_FIELD_ALTERNATE:
             msg_Dbg (demux, "Interlacing setting: alternate fields (TODO)");
-            height *= 2;
+            fmt.fmt.pix.height *= 2;
             break;
         case V4L2_FIELD_INTERLACED_TB:
             msg_Dbg (demux, "Interlacing setting: interleaved top bottom");
-            sys->i_block_flags = BLOCK_FLAG_TOP_FIELD_FIRST;
+            sys->block_flags = BLOCK_FLAG_TOP_FIELD_FIRST;
             break;
         case V4L2_FIELD_INTERLACED_BT:
             msg_Dbg (demux, "Interlacing setting: interleaved bottom top");
-            sys->i_block_flags = BLOCK_FLAG_BOTTOM_FIELD_FIRST;
+            sys->block_flags = BLOCK_FLAG_BOTTOM_FIELD_FIRST;
             break;
         default:
             msg_Warn (demux, "Interlacing setting: unknown type (%d)",
@@ -456,77 +385,88 @@ static int InitVideo (demux_t *demux, int fd)
             break;
     }
 
-    /* Look up final fourcc */
+    /* Declare our unique elementary (video) stream */
     es_format_t es_fmt;
+
     es_format_Init (&es_fmt, VIDEO_ES, selected->vlc);
     es_fmt.video.i_rmask = selected->red;
     es_fmt.video.i_gmask = selected->green;
     es_fmt.video.i_bmask = selected->blue;
+    es_fmt.video.i_width = fmt.fmt.pix.width;
+    es_fmt.video.i_height = fmt.fmt.pix.height;
+    es_fmt.video.i_frame_rate = parm.parm.capture.timeperframe.denominator;
+    es_fmt.video.i_frame_rate_base = parm.parm.capture.timeperframe.numerator;
+    GetAR (fd, &es_fmt.video.i_sar_num, &es_fmt.video.i_sar_den);
+
+    msg_Dbg (demux, "added new video ES %4.4s %ux%u", (char *)&es_fmt.i_codec,
+             es_fmt.video.i_width, es_fmt.video.i_height);
+    msg_Dbg (demux, " frame rate: %u/%u", es_fmt.video.i_frame_rate,
+             es_fmt.video.i_frame_rate_base);
+    msg_Dbg (demux, " aspect ratio: %u/%u", es_fmt.video.i_sar_num,
+             es_fmt.video.i_sar_den);
+    sys->es = es_out_Add (demux->out, &es_fmt);
 
     /* Init I/O method */
-    switch (sys->io)
+    void *(*entry) (void *);
+    if (caps & V4L2_CAP_STREAMING)
     {
-    case IO_METHOD_READ:
-        sys->blocksize = fmt.fmt.pix.sizeimage;
-        break;
-
-    case IO_METHOD_MMAP:
-        if (InitMmap (VLC_OBJECT(demux), sys, fd))
-            return -1;
-        for (unsigned int i = 0; i < sys->i_nbuffers; i++)
+        if (0 /* BROKEN */ && StartUserPtr (VLC_OBJECT(demux), fd) == 0)
         {
-            struct v4l2_buffer buf = {
-                .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
-                .memory = V4L2_MEMORY_MMAP,
-                .index = i,
-            };
-
-            if (v4l2_ioctl (fd, VIDIOC_QBUF, &buf) < 0)
-            {
-                msg_Err (demux, "cannot queue buffer: %m");
-                return -1;
-            }
+            /* In principles, mmap() will pad the length to a multiple of the
+             * page size, so there is no need to care. Nevertheless with the
+             * page size, block->i_size can be set optimally. */
+            const long pagemask = sysconf (_SC_PAGE_SIZE) - 1;
+
+            sys->blocksize = (fmt.fmt.pix.sizeimage + pagemask) & ~pagemask;
+            sys->bufv = NULL;
+            entry = UserPtrThread;
+            msg_Dbg (demux, "streaming with %"PRIu32"-bytes user buffers",
+                     sys->blocksize);
         }
-
-        buf_type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
-        if (v4l2_ioctl (fd, VIDIOC_STREAMON, &buf_type) < 0)
+        else /* fall back to memory map */
         {
-            msg_Err (demux, "cannot start streaming: %m");
-            return -1;
+            sys->bufc = 4;
+            sys->bufv = StartMmap (VLC_OBJECT(demux), fd, &sys->bufc);
+            if (sys->bufv == NULL)
+                return -1;
+            entry = MmapThread;
+            msg_Dbg (demux, "streaming with %"PRIu32" memory-mapped buffers",
+                     sys->bufc);
         }
-        break;
-
-    default:
-        assert (0);
     }
-
-    int ar = 4 * VOUT_ASPECT_FACTOR / 3;
-    char *str = var_InheritString (demux, CFG_PREFIX"aspect-ratio");
-    if (likely(str != NULL))
+    else if (caps & V4L2_CAP_READWRITE)
     {
-        const char *delim = strchr (str, ':');
-        if (delim != NULL)
-            ar = atoi (str) * VOUT_ASPECT_FACTOR / atoi (delim + 1);
-        free (str);
+        sys->blocksize = fmt.fmt.pix.sizeimage;
+        sys->bufv = NULL;
+        entry = ReadThread;
+        msg_Dbg (demux, "reading %"PRIu32" bytes at a time", sys->blocksize);
+    }
+    else
+    {
+        msg_Err (demux, "no supported capture method");
+        return -1;
     }
 
-    /* Add */
-    es_fmt.video.i_width  = width;
-    es_fmt.video.i_height = height;
-
-    /* Get aspect-ratio */
-    es_fmt.video.i_sar_num = ar * es_fmt.video.i_height;
-    es_fmt.video.i_sar_den = VOUT_ASPECT_FACTOR * es_fmt.video.i_width;
-
-    /* Framerate */
-    es_fmt.video.i_frame_rate = lround (fps * 1000000.);
-    es_fmt.video.i_frame_rate_base = 1000000;
-
-    msg_Dbg (demux, "added new video es %4.4s %dx%d", (char *)&es_fmt.i_codec,
-             es_fmt.video.i_width, es_fmt.video.i_height);
-    msg_Dbg (demux, " frame rate: %f", fps);
+#ifdef ZVBI_COMPILED
+    if (std & V4L2_STD_NTSC_M)
+    {
+        char *vbi_path = var_InheritString (demux, CFG_PREFIX"vbidev");
+        if (vbi_path != NULL)
+            sys->vbi = OpenVBI (demux, vbi_path);
+        free(vbi_path);
+    }
+#endif
 
-    sys->p_es = es_out_Add (demux->out, &es_fmt);
+    if (vlc_clone (&sys->thread, entry, demux, VLC_THREAD_PRIORITY_INPUT))
+    {
+#ifdef ZVBI_COMPILED
+        if (sys->vbi != NULL)
+            CloseVBI (sys->vbi);
+#endif
+        if (sys->bufv != NULL)
+            StopMmap (sys->fd, sys->bufv, sys->bufc);
+        return -1;
+    }
     return 0;
 }
 
@@ -534,311 +474,246 @@ void DemuxClose( vlc_object_t *obj )
 {
     demux_t *demux = (demux_t *)obj;
     demux_sys_t *sys = demux->p_sys;
-    int fd = sys->i_fd;
 
-    /* Stop video capture */
-    switch( sys->io )
-    {
-        case IO_METHOD_READ:
-            /* Nothing to do */
-            break;
-
-        case IO_METHOD_MMAP:
-        {
-            /* NOTE: Some buggy drivers hang if buffers are not unmapped before
-             * streamoff */
-            for( unsigned i = 0; i < sys->i_nbuffers; i++ )
-            {
-                struct v4l2_buffer buf = {
-                    .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
-                    .memory = V4L2_MEMORY_MMAP,
-                };
-                v4l2_ioctl( fd, VIDIOC_DQBUF, &buf );
-            }
-            enum v4l2_buf_type buf_type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
-            v4l2_ioctl( sys->i_fd, VIDIOC_STREAMOFF, &buf_type );
-            break;
-        }
-    }
-
-    /* Free Video Buffers */
-    if( sys->p_buffers ) {
-        switch( sys->io )
-        {
-        case IO_METHOD_READ:
-            free( sys->p_buffers[0].start );
-            break;
+    vlc_cancel (sys->thread);
+    vlc_join (sys->thread, NULL);
+    if (sys->bufv != NULL)
+        StopMmap (sys->fd, sys->bufv, sys->bufc);
+    ControlsDeinit( obj, sys->controls );
+    v4l2_close (sys->fd);
 
-        case IO_METHOD_MMAP:
-            for( unsigned i = 0; i < sys->i_nbuffers; ++i )
-                v4l2_munmap( sys->p_buffers[i].start,
-                             sys->p_buffers[i].length );
-            break;
-        }
-        free( sys->p_buffers );
-    }
+#ifdef ZVBI_COMPILED
+    if (sys->vbi != NULL)
+        CloseVBI (sys->vbi);
+#endif
 
-    ControlsDeinit( obj, sys->controls );
-    v4l2_close( fd );
     free( sys );
 }
 
-static int DemuxControl( demux_t *demux, int query, va_list args )
+/** Allocates and queue a user buffer using mmap(). */
+static block_t *UserPtrQueue (vlc_object_t *obj, int fd, size_t length)
 {
-    switch( query )
+    void *ptr = mmap (NULL, length, PROT_READ | PROT_WRITE,
+                      MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
+    if (ptr == MAP_FAILED)
     {
-        /* Special for access_demux */
-        case DEMUX_CAN_PAUSE:
-        case DEMUX_CAN_SEEK:
-        case DEMUX_CAN_CONTROL_PACE:
-            *va_arg( args, bool * ) = false;
-            return VLC_SUCCESS;
-
-        case DEMUX_GET_PTS_DELAY:
-            *va_arg(args,int64_t *) = INT64_C(1000)
-                * var_InheritInteger( demux, "live-caching" );
-            return VLC_SUCCESS;
-
-        case DEMUX_GET_TIME:
-            *va_arg( args, int64_t * ) = mdate();
-            return VLC_SUCCESS;
-
-        /* TODO implement others */
-        default:
-            return VLC_EGENERIC;
+        msg_Err (obj, "cannot allocate %zu-bytes buffer: %m", length);
+        return NULL;
     }
 
-    return VLC_EGENERIC;
-}
-
-/** Gets a frame in read/write mode */
-static block_t *BlockRead( vlc_object_t *obj, int fd, size_t size )
-{
-    block_t *block = block_Alloc( size );
-    if( unlikely(block == NULL) )
+    block_t *block = block_mmap_Alloc (ptr, length);
+    if (unlikely(block == NULL))
+    {
+        munmap (ptr, length);
         return NULL;
+    }
+
+    struct v4l2_buffer buf = {
+        .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
+        .memory = V4L2_MEMORY_USERPTR,
+        .m = {
+            .userptr = (uintptr_t)ptr,
+        },
+        .length = length,
+    };
 
-    ssize_t val = v4l2_read( fd, block->p_buffer, size );
-    if( val == -1 )
+    if (v4l2_ioctl (fd, VIDIOC_QBUF, &buf) < 0)
     {
-        block_Release( block );
-        switch( errno )
-        {
-            case EAGAIN:
-                return NULL;
-            case EIO: /* could be ignored per specification */
-                /* fall through */
-            default:
-                msg_Err( obj, "cannot read frame: %m" );
-                return NULL;
-        }
+        msg_Err (obj, "cannot queue buffer: %m");
+        block_Release (block);
+        return NULL;
     }
-    block->i_buffer = val;
     return block;
 }
 
-static int Demux( demux_t *demux )
+static void *UserPtrThread (void *data)
 {
+    demux_t *demux = data;
     demux_sys_t *sys = demux->p_sys;
-    struct pollfd ufd;
-
-    ufd.fd = sys->i_fd;
-    ufd.events = POLLIN|POLLPRI;
-    /* Wait for data */
-    /* FIXME: remove timeout */
-    while( poll( &ufd, 1, 500 ) == -1 )
-        if( errno != EINTR )
-        {
-            msg_Err( demux, "poll error: %m" );
-            return -1;
-        }
-
-    if( ufd.revents == 0 )
-        return 1;
+    int fd = sys->fd;
+    struct pollfd ufd[2];
+    nfds_t numfds = 1;
 
-    block_t *block;
+    ufd[0].fd = fd;
+    ufd[0].events = POLLIN;
 
-    if( sys->io == IO_METHOD_READ )
-        block = BlockRead( VLC_OBJECT(demux), ufd.fd, sys->blocksize );
-    else
-        block = GrabVideo( VLC_OBJECT(demux), sys );
-    if( block == NULL )
-        return 1;
-
-    block->i_pts = block->i_dts = mdate();
-    block->i_flags |= sys->i_block_flags;
-    es_out_Control( demux->out, ES_OUT_SET_PCR, block->i_pts );
-    es_out_Send( demux->out, sys->p_es, block );
-    return 1;
-}
-
-static float GetMaxFPS( vlc_object_t *obj, int fd, uint32_t pixel_format,
-                        uint32_t width, uint32_t height )
-{
-#ifdef VIDIOC_ENUM_FRAMEINTERVALS
-    /* This is new in Linux 2.6.19 */
-    struct v4l2_frmivalenum fie = {
-        .pixel_format = pixel_format,
-        .width = width,
-        .height = height,
-    };
+    int canc = vlc_savecancel ();
+    for (;;)
+    {
+        struct v4l2_buffer buf = {
+            .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
+            .memory = V4L2_MEMORY_USERPTR,
+        };
+        block_t *block = UserPtrQueue (VLC_OBJECT(demux), fd, sys->blocksize);
+        if (block == NULL)
+            break;
 
-    if( v4l2_ioctl( fd, VIDIOC_ENUM_FRAMEINTERVALS, &fie ) < 0 )
-        return -1.;
+        /* Wait for data */
+        vlc_restorecancel (canc);
+        block_cleanup_push (block);
+        while (poll (ufd, numfds, -1) == -1)
+           if (errno != EINTR)
+               msg_Err (demux, "poll error: %m");
+        vlc_cleanup_pop ();
+        canc = vlc_savecancel ();
 
-    switch( fie.type )
-    {
-        case V4L2_FRMIVAL_TYPE_DISCRETE:
+        if (v4l2_ioctl (fd, VIDIOC_DQBUF, &buf) < 0)
         {
-            float max = -1.;
-            do
-            {
-                float fps = (float)fie.discrete.denominator
-                          / (float)fie.discrete.numerator;
-                if( fps > max )
-                    max = fps;
-                msg_Dbg( obj, "  discrete frame interval %"PRIu32"/%"PRIu32
-                         " supported",
-                         fie.discrete.numerator, fie.discrete.denominator );
-                fie.index++;
-            } while( v4l2_ioctl( fd, VIDIOC_ENUM_FRAMEINTERVALS, &fie ) >= 0 );
-            return max;
+            msg_Err (demux, "cannot dequeue buffer: %m");
+            block_Release (block);
+            continue;
         }
 
-        case V4L2_FRMIVAL_TYPE_STEPWISE:
-        case V4L2_FRMIVAL_TYPE_CONTINUOUS:
-            msg_Dbg( obj, "  frame intervals from %"PRIu32"/%"PRIu32
-                    "to %"PRIu32"/%"PRIu32" supported",
-                    fie.stepwise.min.numerator, fie.stepwise.min.denominator,
-                    fie.stepwise.max.numerator, fie.stepwise.max.denominator );
-            if( fie.type == V4L2_FRMIVAL_TYPE_STEPWISE )
-                msg_Dbg( obj, "  with %"PRIu32"/%"PRIu32" step",
-                         fie.stepwise.step.numerator,
-                         fie.stepwise.step.denominator );
-            return __MAX( (float)fie.stepwise.max.denominator
-                        / (float)fie.stepwise.max.numerator,
-                          (float)fie.stepwise.min.denominator
-                        / (float)fie.stepwise.min.numerator );
+        assert (block->p_buffer == (void *)buf.m.userptr);
+        block->i_buffer = buf.length;
+        block->i_pts = block->i_dts = GetBufferPTS (&buf);
+        block->i_flags |= sys->block_flags;
+        es_out_Control (demux->out, ES_OUT_SET_PCR, block->i_pts);
+        es_out_Send (demux->out, sys->es, block);
     }
-#endif
-    return -1.;
+    vlc_restorecancel (canc); /* <- hmm, this is purely cosmetic */
+    return NULL;
 }
 
-float GetAbsoluteMaxFrameRate( vlc_object_t *obj, int fd,
-                               uint32_t pixel_format )
+static void *MmapThread (void *data)
 {
-#ifdef VIDIOC_ENUM_FRAMESIZES
-    /* This is new in Linux 2.6.19 */
-    struct v4l2_frmsizeenum fse = {
-        .pixel_format = pixel_format
-    };
+    demux_t *demux = data;
+    demux_sys_t *sys = demux->p_sys;
+    int fd = sys->fd;
+    struct pollfd ufd[2];
+    nfds_t numfds = 1;
+
+    ufd[0].fd = fd;
+    ufd[0].events = POLLIN;
 
-    if( v4l2_ioctl( fd, VIDIOC_ENUM_FRAMESIZES, &fse ) < 0 )
-        return -1.;
+#ifdef ZVBI_COMPILED
+    if (sys->vbi != NULL)
+    {
+        ufd[1].fd = GetFdVBI (sys->vbi);
+        ufd[1].events = POLLIN;
+        numfds++;
+    }
+#endif
 
-    float max = -1.;
-    switch( fse.type )
+    for (;;)
     {
-      case V4L2_FRMSIZE_TYPE_DISCRETE:
-        do
+        /* Wait for data */
+        if (poll (ufd, numfds, -1) == -1)
         {
-            float fps = GetMaxFPS( obj, fd, pixel_format,
-                                   fse.discrete.width, fse.discrete.height );
-            if( fps > max )
-                max = fps;
-            fse.index++;
-        } while( v4l2_ioctl( fd, VIDIOC_ENUM_FRAMESIZES, &fse ) >= 0 );
-        break;
-
-      case V4L2_FRMSIZE_TYPE_STEPWISE:
-      case V4L2_FRMSIZE_TYPE_CONTINUOUS:
-        msg_Dbg( obj, " sizes from %"PRIu32"x%"PRIu32" "
-                 "to %"PRIu32"x%"PRIu32" supported",
-                 fse.stepwise.min_width, fse.stepwise.min_height,
-                 fse.stepwise.max_width, fse.stepwise.max_height );
-        if( fse.type == V4L2_FRMSIZE_TYPE_STEPWISE )
-            msg_Dbg( obj, "  with %"PRIu32"x%"PRIu32" steps",
-                     fse.stepwise.step_width, fse.stepwise.step_height );
-
-        for( uint32_t width =  fse.stepwise.min_width;
-                      width <= fse.stepwise.max_width;
-                      width += fse.stepwise.step_width )
-            for( uint32_t height =  fse.stepwise.min_height;
-                          height <= fse.stepwise.max_width;
-                          height += fse.stepwise.step_height )
+           if (errno != EINTR)
+               msg_Err (demux, "poll error: %m");
+           continue;
+        }
+
+        if( ufd[0].revents )
+        {
+            int canc = vlc_savecancel ();
+            block_t *block = GrabVideo (VLC_OBJECT(demux), fd, sys->bufv);
+            if (block != NULL)
             {
-                float fps = GetMaxFPS( obj, fd, pixel_format, width, height );
-                if( fps > max )
-                    max = fps;
+                block->i_flags |= sys->block_flags;
+                es_out_Control (demux->out, ES_OUT_SET_PCR, block->i_pts);
+                es_out_Send (demux->out, sys->es, block);
             }
-        break;
-    }
-    return max;
-#else
-    return -1.;
+            vlc_restorecancel (canc);
+        }
+#ifdef ZVBI_COMPILED
+        if (sys->vbi != NULL && ufd[1].revents)
+            GrabVBI (demux, sys->vbi);
 #endif
+    }
+
+    assert (0);
 }
 
-void GetMaxDimensions( vlc_object_t *obj, int fd, uint32_t pixel_format,
-                       float fps_min, uint32_t *pwidth, uint32_t *pheight )
+static void *ReadThread (void *data)
 {
-    *pwidth = 0;
-    *pheight = 0;
+    demux_t *demux = data;
+    demux_sys_t *sys = demux->p_sys;
+    int fd = sys->fd;
+    struct pollfd ufd[2];
+    nfds_t numfds = 1;
 
-#ifdef VIDIOC_ENUM_FRAMESIZES
-    /* This is new in Linux 2.6.19 */
-    struct v4l2_frmsizeenum fse = {
-        .pixel_format = pixel_format
-    };
+    ufd[0].fd = fd;
+    ufd[0].events = POLLIN;
 
-    if( v4l2_ioctl( fd, VIDIOC_ENUM_FRAMESIZES, &fse ) < 0 )
-        return;
+#ifdef ZVBI_COMPILED
+    if (sys->vbi != NULL)
+    {
+        ufd[1].fd = GetFdVBI (sys->vbi);
+        ufd[1].events = POLLIN;
+        numfds++;
+    }
+#endif
 
-    switch( fse.type )
+    for (;;)
     {
-      case V4L2_FRMSIZE_TYPE_DISCRETE:
-        do
+        /* Wait for data */
+        if (poll (ufd, numfds, -1) == -1)
         {
-            msg_Dbg( obj, " discrete size %"PRIu32"x%"PRIu32" supported",
-                     fse.discrete.width, fse.discrete.height );
+           if (errno != EINTR)
+               msg_Err (demux, "poll error: %m");
+           continue;
+        }
 
-            float fps = GetMaxFPS( obj, fd, pixel_format,
-                                   fse.discrete.width, fse.discrete.height );
-            if( fps >= fps_min && fse.discrete.width > *pwidth )
+        if( ufd[0].revents )
+        {
+            block_t *block = block_Alloc (sys->blocksize);
+            if (unlikely(block == NULL))
             {
-                *pwidth = fse.discrete.width;
-                *pheight = fse.discrete.height;
+                msg_Err (demux, "read error: %m");
+                v4l2_read (fd, NULL, 0); /* discard frame */
+                continue;
             }
-            fse.index++;
-        }
-        while( v4l2_ioctl( fd, VIDIOC_ENUM_FRAMESIZES, &fse ) >= 0 );
-        break;
-
-      case V4L2_FRMSIZE_TYPE_STEPWISE:
-      case V4L2_FRMSIZE_TYPE_CONTINUOUS:
-        msg_Dbg( obj, " sizes from %"PRIu32"x%"PRIu32" "
-                 "to %"PRIu32"x%"PRIu32" supported",
-                 fse.stepwise.min_width, fse.stepwise.min_height,
-                 fse.stepwise.max_width, fse.stepwise.max_height );
-        if( fse.type == V4L2_FRMSIZE_TYPE_STEPWISE )
-            msg_Dbg( obj, "  with %"PRIu32"x%"PRIu32" steps",
-                     fse.stepwise.step_width, fse.stepwise.step_height );
-
-        for( uint32_t width =  fse.stepwise.min_width;
-                      width <= fse.stepwise.max_width;
-                      width += fse.stepwise.step_width )
-            for( uint32_t height = fse.stepwise.min_height;
-                          height <= fse.stepwise.max_width;
-                          height += fse.stepwise.step_height )
+            block->i_pts = block->i_dts = mdate ();
+            block->i_flags |= sys->block_flags;
+
+            int canc = vlc_savecancel ();
+            ssize_t val = v4l2_read (fd, block->p_buffer, block->i_buffer);
+            if (val != -1)
             {
-                float fps = GetMaxFPS( obj, fd, pixel_format, width, height );
-                if( fps >= fps_min && width > *pwidth )
-                {
-                    *pwidth = width;
-                    *pheight = height;
-                }
+                block->i_buffer = val;
+                es_out_Control (demux->out, ES_OUT_SET_PCR, block->i_pts);
+                es_out_Send (demux->out, sys->es, block);
             }
-        break;
-    }
+            else
+                block_Release (block);
+            vlc_restorecancel (canc);
+        }
+#ifdef ZVBI_COMPILED
+        if (sys->vbi != NULL && ufd[1].revents)
+            GrabVBI (demux, sys->vbi);
 #endif
+    }
+    assert (0);
+}
+
+static int DemuxControl( demux_t *demux, int query, va_list args )
+{
+    demux_sys_t *sys = demux->p_sys;
+
+    switch( query )
+    {
+        /* Special for access_demux */
+        case DEMUX_CAN_PAUSE:
+        case DEMUX_CAN_SEEK:
+        case DEMUX_CAN_CONTROL_PACE:
+            *va_arg( args, bool * ) = false;
+            return VLC_SUCCESS;
+
+        case DEMUX_GET_PTS_DELAY:
+            *va_arg(args,int64_t *) = INT64_C(1000)
+                * var_InheritInteger( demux, "live-caching" );
+            return VLC_SUCCESS;
+
+        case DEMUX_GET_TIME:
+            *va_arg (args, int64_t *) = mdate() - sys->start;
+            return VLC_SUCCESS;
+
+        /* TODO implement others */
+        default:
+            return VLC_EGENERIC;
+    }
+
+    return VLC_EGENERIC;
 }