From 34ef3c89ad15d4d1f552acbf2e1c131f79f22082 Mon Sep 17 00:00:00 2001
From: Zebediah Figura <z.figura12@gmail.com>
Date: Wed, 10 Apr 2019 09:46:25 -0500
Subject: [PATCH] qcap: Port to libv4l2.

Signed-off-by: Zebediah Figura <z.figura12@gmail.com>
Signed-off-by: Alexandre Julliard <julliard@winehq.org>
---
 configure             |  61 +++--
 configure.ac          |  14 +-
 dlls/qcap/qcap_main.h |   1 +
 dlls/qcap/v4l.c       | 614 +++++++++++++++++-------------------------
 dlls/qcap/yuv.c       |   2 +-
 include/config.h.in   |  10 +-
 6 files changed, 284 insertions(+), 418 deletions(-)

diff --git a/configure b/configure
index a966217eba9..a7c072bfddc 100755
--- a/configure
+++ b/configure
@@ -870,7 +870,7 @@ with_sane
 with_sdl
 with_tiff
 with_udev
-with_v4l
+with_v4l2
 with_vkd3d
 with_vulkan
 with_xcomposite
@@ -2541,7 +2541,7 @@ Optional Packages:
   --without-sdl           do not use SDL
   --without-tiff          do not use TIFF
   --without-udev          do not use udev (plug and play support)
-  --without-v4l           do not use v4l1 (v4l support)
+  --without-v4l2          do not use v4l2 (video capture)
   --without-vkd3d         do not use vkd3d (Direct3D 12 support)
   --without-vulkan        do not use Vulkan
   --without-xcomposite    do not use the Xcomposite extension
@@ -4045,9 +4045,9 @@ if test "${with_udev+set}" = set; then :
 fi
 
 
-# Check whether --with-v4l was given.
-if test "${with_v4l+set}" = set; then :
-  withval=$with_v4l;
+# Check whether --with-v4l2 was given.
+if test "${with_v4l2+set}" = set; then :
+  withval=$with_v4l2;
 fi
 
 
@@ -7734,10 +7734,9 @@ fi
 done
 
 
-for ac_header in linux/videodev.h linux/videodev2.h libv4l1.h
+for ac_header in linux/videodev2.h
 do :
-  as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh`
-ac_fn_c_check_header_compile "$LINENO" "$ac_header" "$as_ac_Header" "#ifdef HAVE_SYS_TIME_H
+  ac_fn_c_check_header_compile "$LINENO" "linux/videodev2.h" "ac_cv_header_linux_videodev2_h" "#ifdef HAVE_SYS_TIME_H
 #include <sys/time.h>
 #endif
 #include <sys/types.h>
@@ -7745,9 +7744,9 @@ ac_fn_c_check_header_compile "$LINENO" "$ac_header" "$as_ac_Header" "#ifdef HAVE
 #include <asm/types.h>
 #endif
 "
-if eval test \"x\$"$as_ac_Header"\" = x"yes"; then :
+if test "x$ac_cv_header_linux_videodev2_h" = xyes; then :
   cat >>confdefs.h <<_ACEOF
-#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1
+#define HAVE_LINUX_VIDEODEV2_H 1
 _ACEOF
 
 fi
@@ -13483,15 +13482,15 @@ esac
 
 fi
 
-if test "x$with_v4l" != "xno"
+if test "x$with_v4l2" != "xno"
 then
-    { $as_echo "$as_me:${as_lineno-$LINENO}: checking for -lv4l1" >&5
-$as_echo_n "checking for -lv4l1... " >&6; }
-if ${ac_cv_lib_soname_v4l1+:} false; then :
+    { $as_echo "$as_me:${as_lineno-$LINENO}: checking for -lv4l2" >&5
+$as_echo_n "checking for -lv4l2... " >&6; }
+if ${ac_cv_lib_soname_v4l2+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   ac_check_soname_save_LIBS=$LIBS
-LIBS="-lv4l1  $LIBS"
+LIBS="-lv4l2  $LIBS"
   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 
@@ -13501,22 +13500,22 @@ LIBS="-lv4l1  $LIBS"
 #ifdef __cplusplus
 extern "C"
 #endif
-char v4l1_open ();
+char v4l2_open ();
 int
 main ()
 {
-return v4l1_open ();
+return v4l2_open ();
   ;
   return 0;
 }
 _ACEOF
 if ac_fn_c_try_link "$LINENO"; then :
   case "$LIBEXT" in
-    dll) ac_cv_lib_soname_v4l1=`$ac_cv_path_LDD conftest.exe | grep "v4l1" | sed -e "s/dll.*/dll/"';2,$d'` ;;
-    dylib) ac_cv_lib_soname_v4l1=`$OTOOL -L conftest$ac_exeext | grep "libv4l1\\.[0-9A-Za-z.]*dylib" | sed -e "s/^.*\/\(libv4l1\.[0-9A-Za-z.]*dylib\).*$/\1/"';2,$d'` ;;
-    *) ac_cv_lib_soname_v4l1=`$READELF -d conftest$ac_exeext | grep "NEEDED.*libv4l1\\.$LIBEXT" | sed -e "s/^.*\\[\\(libv4l1\\.$LIBEXT[^	 ]*\\)\\].*$/\1/"';2,$d'`
-       if ${ac_cv_lib_soname_v4l1:+false} :; then :
-  ac_cv_lib_soname_v4l1=`$LDD conftest$ac_exeext | grep "libv4l1\\.$LIBEXT" | sed -e "s/^.*\(libv4l1\.$LIBEXT[^	 ]*\).*$/\1/"';2,$d'`
+    dll) ac_cv_lib_soname_v4l2=`$ac_cv_path_LDD conftest.exe | grep "v4l2" | sed -e "s/dll.*/dll/"';2,$d'` ;;
+    dylib) ac_cv_lib_soname_v4l2=`$OTOOL -L conftest$ac_exeext | grep "libv4l2\\.[0-9A-Za-z.]*dylib" | sed -e "s/^.*\/\(libv4l2\.[0-9A-Za-z.]*dylib\).*$/\1/"';2,$d'` ;;
+    *) ac_cv_lib_soname_v4l2=`$READELF -d conftest$ac_exeext | grep "NEEDED.*libv4l2\\.$LIBEXT" | sed -e "s/^.*\\[\\(libv4l2\\.$LIBEXT[^	 ]*\\)\\].*$/\1/"';2,$d'`
+       if ${ac_cv_lib_soname_v4l2:+false} :; then :
+  ac_cv_lib_soname_v4l2=`$LDD conftest$ac_exeext | grep "libv4l2\\.$LIBEXT" | sed -e "s/^.*\(libv4l2\.$LIBEXT[^	 ]*\).*$/\1/"';2,$d'`
 fi ;;
   esac
 fi
@@ -13524,27 +13523,27 @@ rm -f core conftest.err conftest.$ac_objext \
     conftest$ac_exeext conftest.$ac_ext
   LIBS=$ac_check_soname_save_LIBS
 fi
-if ${ac_cv_lib_soname_v4l1:+false} :; then :
+if ${ac_cv_lib_soname_v4l2:+false} :; then :
   { $as_echo "$as_me:${as_lineno-$LINENO}: result: not found" >&5
 $as_echo "not found" >&6; }
 
 else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_soname_v4l1" >&5
-$as_echo "$ac_cv_lib_soname_v4l1" >&6; }
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_soname_v4l2" >&5
+$as_echo "$ac_cv_lib_soname_v4l2" >&6; }
 
 cat >>confdefs.h <<_ACEOF
-#define SONAME_LIBV4L1 "$ac_cv_lib_soname_v4l1"
+#define SONAME_LIBV4L2 "$ac_cv_lib_soname_v4l2"
 _ACEOF
 
 
 fi
 fi
-if test "x$ac_cv_lib_soname_v4l1" = "x"; then :
-  case "x$with_v4l" in
-  x)   as_fn_append wine_notices "|libv4l ${notice_platform}development files not found." ;;
+if test "x$ac_cv_lib_soname_v4l2" = "x"; then :
+  case "x$with_v4l2" in
+  x)   as_fn_append wine_notices "|libv4l2 ${notice_platform}development files not found." ;;
   xno) ;;
-  *)   as_fn_error $? "libv4l ${notice_platform}development files not found.
-This is an error since --with-v4l was requested." "$LINENO" 5 ;;
+  *)   as_fn_error $? "libv4l2 ${notice_platform}development files not found.
+This is an error since --with-v4l2 was requested." "$LINENO" 5 ;;
 esac
 
 fi
diff --git a/configure.ac b/configure.ac
index d8ab7823c1f..bb02ec4d595 100644
--- a/configure.ac
+++ b/configure.ac
@@ -81,7 +81,7 @@ AC_ARG_WITH(sane,      AS_HELP_STRING([--without-sane],[do not use SANE (scanner
 AC_ARG_WITH(sdl,       AS_HELP_STRING([--without-sdl],[do not use SDL]))
 AC_ARG_WITH(tiff,      AS_HELP_STRING([--without-tiff],[do not use TIFF]))
 AC_ARG_WITH(udev,      AS_HELP_STRING([--without-udev],[do not use udev (plug and play support)]))
-AC_ARG_WITH(v4l,       AS_HELP_STRING([--without-v4l],[do not use v4l1 (v4l support)]))
+AC_ARG_WITH(v4l2,      AS_HELP_STRING([--without-v4l2],[do not use v4l2 (video capture)]))
 AC_ARG_WITH(vkd3d,     AS_HELP_STRING([--without-vkd3d],[do not use vkd3d (Direct3D 12 support)]))
 AC_ARG_WITH(vulkan,    AS_HELP_STRING([--without-vulkan],[do not use Vulkan]))
 AC_ARG_WITH(xcomposite,AS_HELP_STRING([--without-xcomposite],[do not use the Xcomposite extension]),
@@ -674,7 +674,7 @@ AC_CHECK_HEADERS([pthread_np.h],,,
 #include <pthread.h>
 #endif])
 
-AC_CHECK_HEADERS([linux/videodev.h linux/videodev2.h libv4l1.h],,,
+AC_CHECK_HEADERS([linux/videodev2.h],,,
 [#ifdef HAVE_SYS_TIME_H
 #include <sys/time.h>
 #endif
@@ -1417,13 +1417,13 @@ fi
 WINE_NOTICE_WITH(sane,[test "x$ac_cv_lib_soname_sane" = "x"],
                  [libsane ${notice_platform}development files not found, scanners won't be supported.])
 
-dnl **** Check for libv4l1 ****
-if test "x$with_v4l" != "xno"
+dnl **** Check for libv4l2 ****
+if test "x$with_v4l2" != "xno"
 then
-    WINE_CHECK_SONAME(v4l1,v4l1_open,,,)
+    WINE_CHECK_SONAME(v4l2,v4l2_open)
 fi
-WINE_NOTICE_WITH(v4l,[test "x$ac_cv_lib_soname_v4l1" = "x"],
-                 [libv4l ${notice_platform}development files not found.])
+WINE_NOTICE_WITH(v4l2,[test "x$ac_cv_lib_soname_v4l2" = "x"],
+                 [libv4l2 ${notice_platform}development files not found.])
 
 dnl **** Check for libgphoto2 ****
 if test "x$with_gphoto" != "xno"
diff --git a/dlls/qcap/qcap_main.h b/dlls/qcap/qcap_main.h
index 69d94bfff69..733772ee739 100644
--- a/dlls/qcap/qcap_main.h
+++ b/dlls/qcap/qcap_main.h
@@ -20,6 +20,7 @@
 #ifndef _QCAP_MAIN_H_DEFINED
 #define _QCAP_MAIN_H_DEFINED
 
+#include "wine/heap.h"
 #include "wine/strmbase.h"
 
 extern DWORD ObjectRefCount(BOOL increment) DECLSPEC_HIDDEN;
diff --git a/dlls/qcap/v4l.c b/dlls/qcap/v4l.c
index 80b0fe82d8d..04f9718f2df 100644
--- a/dlls/qcap/v4l.c
+++ b/dlls/qcap/v4l.c
@@ -1,11 +1,8 @@
 /*
- * DirectShow capture services (QCAP.DLL)
+ * v4l2 backend to the VFW Capture filter
  *
  * Copyright 2005 Maarten Lankhorst
- *
- * This file contains the part of the vfw capture interface that
- * does the actual Video4Linux(1/2) stuff required for capturing
- * and setting/getting media format..
+ * Copyright 2019 Zebediah Figura
  *
  * This library is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
@@ -22,6 +19,8 @@
  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
  */
 
+#define BIONIC_IOCTL_NO_SIGNEDNESS_OVERLOAD  /* work around ioctl breakage on Android */
+
 #include "config.h"
 #include "wine/port.h"
 
@@ -43,11 +42,8 @@
 #ifdef HAVE_ASM_TYPES_H
 #include <asm/types.h>
 #endif
-#ifdef HAVE_LIBV4L1_H
-#include <libv4l1.h>
-#endif
-#ifdef HAVE_LINUX_VIDEODEV_H
-#include <linux/videodev.h>
+#ifdef HAVE_LINUX_VIDEODEV2_H
+#include <linux/videodev2.h>
 #endif
 #ifdef HAVE_UNISTD_H
 #include <unistd.h>
@@ -67,33 +63,34 @@
 #include "capture.h"
 #include "qcap_main.h"
 
-WINE_DEFAULT_DEBUG_CHANNEL(qcap_v4l);
+WINE_DEFAULT_DEBUG_CHANNEL(qcap);
 
-#ifdef VIDIOCMCAPTURE
+#ifdef HAVE_LINUX_VIDEODEV2_H
+
+WINE_DECLARE_DEBUG_CHANNEL(winediag);
 
 static typeof(open) *video_open = open;
 static typeof(close) *video_close = close;
 static typeof(ioctl) *video_ioctl = ioctl;
 static typeof(read) *video_read = read;
-static typeof(mmap) *video_mmap = mmap;
-static typeof(munmap) *video_munmap = munmap;
 
-static void video_init(void)
+static BOOL video_init(void)
 {
-#ifdef SONAME_LIBV4L1
+#ifdef SONAME_LIBV4L2
     static void *video_lib;
 
     if (video_lib)
-        return;
-    video_lib = wine_dlopen(SONAME_LIBV4L1, RTLD_NOW, NULL, 0);
-    if (!video_lib)
-        return;
-    video_open = wine_dlsym(video_lib, "v4l1_open", NULL, 0);
-    video_close = wine_dlsym(video_lib, "v4l1_close", NULL, 0);
-    video_ioctl = wine_dlsym(video_lib, "v4l1_ioctl", NULL, 0);
-    video_read = wine_dlsym(video_lib, "v4l1_read", NULL, 0);
-    video_mmap = wine_dlsym(video_lib, "v4l1_mmap", NULL, 0);
-    video_munmap = wine_dlsym(video_lib, "v4l1_munmap", NULL, 0);
+        return TRUE;
+    if (!(video_lib = wine_dlopen(SONAME_LIBV4L2, RTLD_NOW, NULL, 0)))
+        return FALSE;
+    video_open = wine_dlsym(video_lib, "v4l2_open", NULL, 0);
+    video_close = wine_dlsym(video_lib, "v4l2_close", NULL, 0);
+    video_ioctl = wine_dlsym(video_lib, "v4l2_ioctl", NULL, 0);
+    video_read = wine_dlsym(video_lib, "v4l2_read", NULL, 0);
+
+    return TRUE;
+#else
+    return FALSE;
 #endif
 }
 
@@ -109,62 +106,39 @@ struct _Capture
     IPin *pOut;
     int fd, mmap;
     BOOL iscommitted, stopped;
-    struct video_picture pict;
-    int dbrightness, dhue, dcolour, dcontrast;
 
-    /* mmap (V4l1) */
-    struct video_mmap *grab_buf;
-    struct video_mbuf gb_buffers;
-    unsigned char *pmap;
-    int buffers;
-
-    /* read (V4l1) */
-    int imagesize;
-    char * grab_data;
+    __u32 pixelformat;
+    int depth;
 
-    int curframe;
+    int image_size;
+    unsigned char *image_data;
 
     HANDLE thread;
     Renderer renderer;
 };
 
-struct renderlist
-{
-    int depth;
-    const char* name;
-    Renderer renderer;
-};
-
 static void renderer_RGB(const Capture *capBox, LPBYTE bufferin, const BYTE *stream);
 static void renderer_YUV(const Capture *capBox, LPBYTE bufferin, const BYTE *stream);
 
-static const struct renderlist renderlist_V4l[] = {
-    {  0, "NULL renderer",               NULL },
-    {  8, "Gray scales",                 NULL }, /* 1,  Don't support  */
-    {  0, "High 240 cube (BT848)",       NULL }, /* 2,  Don't support  */
-    { 16, "16 bit RGB (565)",            NULL }, /* 3,  Don't support  */
-    { 24, "24 bit RGB values",   renderer_RGB }, /* 4,  Supported,     */
-    { 32, "32 bit RGB values",   renderer_RGB }, /* 5,  Supported      */
-    { 16, "15 bit RGB (555)",            NULL }, /* 6,  Don't support  */
-    { 16, "YUV 422 (Not P)",     renderer_YUV }, /* 7,  Supported */
-    { 16, "YUYV (Not P)",        renderer_YUV }, /* 8,  Supported */
-    { 16, "UYVY (Not P)",        renderer_YUV }, /* 9,  Supported */
-    { 16, "YUV 420 (Not P)", NULL }, /* 10, Not supported, if I had to guess it's YYUYYV */
-    { 12, "YUV 411 (Not P)",     renderer_YUV }, /* 11, Supported */
-    {  0, "Raw capturing (BT848)",       NULL }, /* 12, Don't support  */
-    { 16, "YUV 422 (Planar)",    renderer_YUV }, /* 13, Supported */
-    { 12, "YUV 411 (Planar)",    renderer_YUV }, /* 14, Supported */
-    { 12, "YUV 420 (Planar)",    renderer_YUV }, /* 15, Supported */
-    { 10, "YUV 410 (Planar)",    renderer_YUV }, /* 16, Supported */
-    /* FIXME: add YUV420 support */
-    {  0, NULL,                          NULL },
+static const struct
+{
+    int depth;
+    __u32 pixelformat;
+    Renderer renderer;
+}
+renderlist_V4l[] =
+{
+    {24, V4L2_PIX_FMT_BGR24, renderer_RGB},
+    {32, V4L2_PIX_FMT_BGR32, renderer_RGB},
+    {16, V4L2_PIX_FMT_YUYV, renderer_YUV},
+    {16, V4L2_PIX_FMT_UYVY, renderer_YUV},
+    {12, V4L2_PIX_FMT_Y41P, renderer_YUV},
+    {16, V4L2_PIX_FMT_YUV422P, renderer_YUV},
+    {12, V4L2_PIX_FMT_YUV411P, renderer_YUV},
+    {12, V4L2_PIX_FMT_YUV420, renderer_YUV},
+    {10, V4L2_PIX_FMT_YUV410, renderer_YUV},
 };
 
-static const int fallback_V4l[] = { 4, 5, 7, 8, 9, 13, 15, 14, 16, 11, -1 };
-/* Fallback: First try raw formats (Should try yuv first perhaps?), then yuv */
-
-/* static const Capture defbox; */
-
 static int xioctl(int fd, int request, void * arg)
 {
     int r;
@@ -177,69 +151,17 @@ static int xioctl(int fd, int request, void * arg)
 }
 
 /* Prepare the capture buffers */
-static HRESULT V4l_Prepare(Capture *capBox)
+static HRESULT V4l_Prepare(Capture *device)
 {
-    TRACE("%p: Preparing for %dx%d resolution\n", capBox, capBox->width, capBox->height);
-
-    /* Try mmap */
-    capBox->mmap = 0;
-    if (xioctl(capBox->fd, VIDIOCGMBUF, &capBox->gb_buffers) != -1 &&
-        capBox->gb_buffers.frames)
-    {
-        capBox->buffers = capBox->gb_buffers.frames;
-        if (capBox->gb_buffers.frames > 1)
-            capBox->buffers = 1;
-        TRACE("%p: Using %d/%d buffers\n", capBox,
-              capBox->buffers, capBox->gb_buffers.frames);
-
-        capBox->pmap = video_mmap( 0, capBox->gb_buffers.size, PROT_READ|PROT_WRITE,
-                                   MAP_SHARED, capBox->fd, 0 );
-        if (capBox->pmap != MAP_FAILED)
-        {
-            int i;
-
-            capBox->grab_buf = CoTaskMemAlloc(sizeof(struct video_mmap) * capBox->buffers);
-            if (!capBox->grab_buf)
-            {
-                video_munmap(capBox->pmap, capBox->gb_buffers.size);
-                return E_OUTOFMEMORY;
-            }
-
-            /* Setup mmap capture buffers. */
-            for (i = 0; i < capBox->buffers; i++)
-            {
-                capBox->grab_buf[i].format = capBox->pict.palette;
-                capBox->grab_buf[i].frame = i;
-                capBox->grab_buf[i].width = capBox->width;
-                capBox->grab_buf[i].height = capBox->height;
-            }
-            capBox->mmap = 1;
-        }
-    }
-    if (!capBox->mmap)
-    {
-        capBox->buffers = 1;
-        capBox->imagesize = renderlist_V4l[capBox->pict.palette].depth *
-                                capBox->height * capBox->width / 8;
-        capBox->grab_data = CoTaskMemAlloc(capBox->imagesize);
-        if (!capBox->grab_data)
-            return E_OUTOFMEMORY;
-    }
-    TRACE("Using mmap: %d\n", capBox->mmap);
+    device->image_size = device->depth * device->height * device->width / 8;
+    if (!(device->image_data = heap_alloc(device->image_size)))
+        return E_OUTOFMEMORY;
     return S_OK;
 }
 
-static void V4l_Unprepare(Capture *capBox)
+static void V4l_Unprepare(Capture *device)
 {
-    if (capBox->mmap)
-    {
-        for (capBox->curframe = 0; capBox->curframe < capBox->buffers; capBox->curframe++) 
-            xioctl(capBox->fd, VIDIOCSYNC, &capBox->grab_buf[capBox->curframe]);
-        video_munmap(capBox->pmap, capBox->gb_buffers.size);
-        CoTaskMemFree(capBox->grab_buf);
-    }
-    else
-        CoTaskMemFree(capBox->grab_data);
+    heap_free(device->image_data);
 }
 
 HRESULT qcap_driver_destroy(Capture *capBox)
@@ -254,52 +176,53 @@ HRESULT qcap_driver_destroy(Capture *capBox)
     return S_OK;
 }
 
-HRESULT qcap_driver_set_format(Capture *capBox, AM_MEDIA_TYPE * mT)
+HRESULT qcap_driver_set_format(Capture *device, AM_MEDIA_TYPE *mt)
 {
+    struct v4l2_format format = {0};
     int newheight, newwidth;
-    struct video_window window;
-    VIDEOINFOHEADER *format;
+    VIDEOINFOHEADER *vih;
+    int fd = device->fd;
 
-    TRACE("%p\n", capBox);
-
-    format = (VIDEOINFOHEADER *) mT->pbFormat;
-    if (format->bmiHeader.biBitCount != 24 ||
-        format->bmiHeader.biCompression != BI_RGB)
+    vih = (VIDEOINFOHEADER *)mt->pbFormat;
+    if (vih->bmiHeader.biBitCount != 24 || vih->bmiHeader.biCompression != BI_RGB)
     {
-        FIXME("unsupported media type %d %d\n", format->bmiHeader.biBitCount,
-              format->bmiHeader.biCompression );
+        FIXME("Unsupported compression %#x, bpp %u.\n", vih->bmiHeader.biCompression,
+                vih->bmiHeader.biBitCount);
         return VFW_E_INVALIDMEDIATYPE;
     }
 
-    newwidth = format->bmiHeader.biWidth;
-    newheight = format->bmiHeader.biHeight;
-
-    TRACE("%p -> (%p) - %d %d\n", capBox, mT, newwidth, newheight);
+    newwidth = vih->bmiHeader.biWidth;
+    newheight = vih->bmiHeader.biHeight;
 
-    if (capBox->height == newheight && capBox->width == newwidth)
+    if (device->height == newheight && device->width == newwidth)
         return S_OK;
 
-    if(-1 == xioctl(capBox->fd, VIDIOCGWIN, &window))
+    format.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
+    if (xioctl(fd, VIDIOC_G_FMT, &format) == -1)
     {
-        ERR("ioctl(VIDIOCGWIN) failed (%d)\n", errno);
-        return E_FAIL;
+        ERR("Failed to get current format: %s\n", strerror(errno));
+        return VFW_E_TYPE_NOT_ACCEPTED;
     }
-    window.width = newwidth;
-    window.height = newheight;
-    if (xioctl(capBox->fd, VIDIOCSWIN, &window) == -1)
+
+    format.fmt.pix.width = newwidth;
+    format.fmt.pix.height = newheight;
+
+    if (!xioctl(fd, VIDIOC_S_FMT, &format)
+            && format.fmt.pix.width == newwidth
+            && format.fmt.pix.height == newheight)
     {
-        TRACE("using software resize: %dx%d -> %dx%d\n",
-               window.width, window.height, capBox->width, capBox->height);
-        capBox->swresize = TRUE;
+        device->width = newwidth;
+        device->height = newheight;
+        device->swresize = FALSE;
     }
     else
     {
-        capBox->height = window.height;
-        capBox->width = window.width;
-        capBox->swresize = FALSE;
+        TRACE("Using software resize: %dx%d -> %dx%d.\n",
+               format.fmt.pix.width, format.fmt.pix.height, device->width, device->height);
+        device->swresize = TRUE;
     }
-    capBox->outputwidth = window.width;
-    capBox->outputheight = window.height;
+    device->outputwidth = format.fmt.pix.width;
+    device->outputheight = format.fmt.pix.height;
     return S_OK;
 }
 
@@ -349,109 +272,92 @@ HRESULT qcap_driver_get_format(const Capture *capBox, AM_MEDIA_TYPE ** mT)
     return S_OK;
 }
 
-HRESULT qcap_driver_get_prop_range( Capture *capBox,
-            VideoProcAmpProperty Property, LONG *pMin, LONG *pMax,
-            LONG *pSteppingDelta, LONG *pDefault, LONG *pCapsFlags )
+static __u32 v4l2_cid_from_qcap_property(VideoProcAmpProperty property)
 {
-    TRACE("%p -> %d %p %p %p %p %p\n", capBox, Property,
-          pMin, pMax, pSteppingDelta, pDefault, pCapsFlags);
-
-    switch (Property)
+    switch (property)
     {
     case VideoProcAmp_Brightness:
-        *pDefault = capBox->dbrightness;
-        break;
+        return V4L2_CID_BRIGHTNESS;
     case VideoProcAmp_Contrast:
-        *pDefault = capBox->dcontrast;
-        break;
+        return V4L2_CID_CONTRAST;
     case VideoProcAmp_Hue:
-        *pDefault = capBox->dhue;
-        break;
+        return V4L2_CID_HUE;
     case VideoProcAmp_Saturation:
-        *pDefault = capBox->dcolour;
-        break;
+        return V4L2_CID_SATURATION;
     default:
-        FIXME("Not implemented %d\n", Property);
-        return E_NOTIMPL;
+        FIXME("Unhandled property %d.\n", property);
+        return 0;
     }
-    *pMin = 0;
-    *pMax = 65535;
-    *pSteppingDelta = 65536/256;
-    *pCapsFlags = VideoProcAmp_Flags_Manual;
-    return S_OK;
 }
 
-HRESULT qcap_driver_get_prop( Capture *capBox,
-            VideoProcAmpProperty Property, LONG *lValue, LONG *Flags )
+HRESULT qcap_driver_get_prop_range(Capture *device, VideoProcAmpProperty property,
+        LONG *min, LONG *max, LONG *step, LONG *default_value, LONG *flags)
 {
-    TRACE("%p -> %d %p %p\n", capBox, Property, lValue, Flags);
+    struct v4l2_queryctrl ctrl;
+
+    ctrl.id = v4l2_cid_from_qcap_property(property);
 
-    switch (Property)
+    if (xioctl(device->fd, VIDIOC_QUERYCTRL, &ctrl) == -1)
     {
-    case VideoProcAmp_Brightness:
-        *lValue = capBox->pict.brightness;
-        break;
-    case VideoProcAmp_Contrast:
-        *lValue = capBox->pict.contrast;
-        break;
-    case VideoProcAmp_Hue:
-        *lValue = capBox->pict.hue;
-        break;
-    case VideoProcAmp_Saturation:
-        *lValue = capBox->pict.colour;
-        break;
-    default:
-        FIXME("Not implemented %d\n", Property);
-        return E_NOTIMPL;
+        WARN("Failed to query control: %s\n", strerror(errno));
+        return E_PROP_ID_UNSUPPORTED;
     }
-    *Flags = VideoProcAmp_Flags_Manual;
+
+    *min = ctrl.minimum;
+    *max = ctrl.maximum;
+    *step = ctrl.step;
+    *default_value = ctrl.default_value;
+    *flags = VideoProcAmp_Flags_Manual;
     return S_OK;
 }
 
-HRESULT qcap_driver_set_prop(Capture *capBox, VideoProcAmpProperty Property,
-            LONG lValue, LONG Flags)
+HRESULT qcap_driver_get_prop(Capture *device, VideoProcAmpProperty property,
+        LONG *value, LONG *flags)
 {
-    TRACE("%p -> %d %d %d\n", capBox, Property, lValue, Flags);
+    struct v4l2_control ctrl;
 
-    switch (Property)
+    ctrl.id = v4l2_cid_from_qcap_property(property);
+
+    if (xioctl(device->fd, VIDIOC_G_CTRL, &ctrl) == -1)
     {
-    case VideoProcAmp_Brightness:
-        capBox->pict.brightness = lValue;
-        break;
-    case VideoProcAmp_Contrast:
-        capBox->pict.contrast = lValue;
-        break;
-    case VideoProcAmp_Hue:
-        capBox->pict.hue = lValue;
-        break;
-    case VideoProcAmp_Saturation:
-        capBox->pict.colour = lValue;
-        break;
-    default:
-        FIXME("Not implemented %d\n", Property);
-        return E_NOTIMPL;
+        WARN("Failed to get property: %s\n", strerror(errno));
+        return E_FAIL;
     }
 
-    if (xioctl(capBox->fd, VIDIOCSPICT, &capBox->pict) == -1)
+    *value = ctrl.value;
+    *flags = VideoProcAmp_Flags_Manual;
+
+    return S_OK;
+}
+
+HRESULT qcap_driver_set_prop(Capture *device, VideoProcAmpProperty property,
+        LONG value, LONG flags)
+{
+    struct v4l2_control ctrl;
+
+    ctrl.id = v4l2_cid_from_qcap_property(property);
+    ctrl.value = value;
+
+    if (xioctl(device->fd, VIDIOC_S_CTRL, &ctrl) == -1)
     {
-        ERR("ioctl(VIDIOCSPICT) failed (%d)\n",errno);
+        WARN("Failed to set property: %s\n", strerror(errno));
         return E_FAIL;
     }
+
     return S_OK;
 }
 
-static void renderer_RGB(const Capture *capBox, LPBYTE bufferin, const BYTE *stream)
+static void renderer_RGB(const Capture *device, BYTE *bufferin, const BYTE *stream)
 {
-    int depth = renderlist_V4l[capBox->pict.palette].depth;
-    int size = capBox->height * capBox->width * depth / 8;
+    int size = device->height * device->width * device->depth / 8;
     int pointer, offset;
 
-    switch (depth)
+    switch (device->pixelformat)
     {
-    case 24:
+    case V4L2_PIX_FMT_BGR24:
         memcpy(bufferin, stream, size);
         break;
-    case 32:
+    case V4L2_PIX_FMT_BGR32:
         pointer = 0;
         offset = 1;
         while (pointer + offset <= size)
@@ -466,44 +372,43 @@ static void renderer_RGB(const Capture *capBox, LPBYTE bufferin, const BYTE *str
         }
         break;
     default:
-        ERR("Unknown bit depth %d\n", depth);
+        FIXME("Unhandled pixel format %#x.\n", device->pixelformat);
         return;
     }
 }
 
-static void renderer_YUV(const Capture *capBox, LPBYTE bufferin, const BYTE *stream)
+static void renderer_YUV(const Capture *device, BYTE *bufferin, const BYTE *stream)
 {
     enum YUV_Format format;
 
-    switch (capBox->pict.palette)
+    switch (device->pixelformat)
     {
-    case  7: /* YUV422  -  same as YUYV */
-    case  8: /* YUYV    */
+    case V4L2_PIX_FMT_YUYV:
         format = YUYV;
         break;
-    case  9: /* UYVY    */
+    case V4L2_PIX_FMT_UYVY:
         format = UYVY;
         break;
-    case 11: /* YUV411  */
+    case V4L2_PIX_FMT_Y41P:
         format = UYYVYY;
         break;
-    case 13: /* YUV422P */
+    case V4L2_PIX_FMT_YUV422P:
         format = YUVP_421;
         break;
-    case 14: /* YUV411P */
+    case V4L2_PIX_FMT_YUV411P:
         format = YUVP_441;
         break;
-    case 15: /* YUV420P */
+    case V4L2_PIX_FMT_YUV420:
         format = YUVP_422;
         break;
-    case 16: /* YUV410P */
+    case V4L2_PIX_FMT_YUV410:
         format = YUVP_444;
         break;
     default:
-        ERR("Unknown palette %d\n", capBox->pict.palette);
+        FIXME("Unhandled pixel format %#x.\n", device->pixelformat);
         return;
     }
-    YUV_To_RGB24(format, bufferin, stream, capBox->width, capBox->height);
+    YUV_To_RGB24(format, bufferin, stream, device->width, device->height);
 }
 
 static void Resize(const Capture * capBox, LPBYTE output, const BYTE *input)
@@ -562,36 +467,18 @@ static void Resize(const Capture * capBox, LPBYTE output, const BYTE *input)
     }
 }
 
-static void V4l_GetFrame(Capture * capBox, unsigned char ** pInput)
-{
-    if (capBox->mmap)
-    {
-        if (xioctl(capBox->fd, VIDIOCSYNC, &capBox->grab_buf[capBox->curframe]) == -1)
-            WARN("Syncing ioctl failed: %d\n", errno);
-
-        *pInput = capBox->pmap + capBox->gb_buffers.offsets[capBox->curframe];
-    }
-    else
-    {
-        int retval;
-        while ((retval = video_read(capBox->fd, capBox->grab_data, capBox->imagesize)) == -1)
-            if (errno != EAGAIN) break;
-        if (retval == -1)
-            WARN("Error occurred while reading from device: %s\n", strerror(errno));
-        *pInput = (unsigned char*) capBox->grab_data;
-    }
-}
-
-static void V4l_FreeFrame(Capture * capBox)
+static void V4l_GetFrame(Capture *device, unsigned char **buffer)
 {
-    TRACE("\n");
-    if (capBox->mmap)
+    while (video_read(device->fd, device->image_data, device->image_size) == -1)
     {
-        if (xioctl(capBox->fd, VIDIOCMCAPTURE, &capBox->grab_buf[capBox->curframe]) == -1)
-           ERR("Freeing frame for capture failed: %s\n", strerror(errno));
+        if (errno != EAGAIN)
+        {
+            ERR("Failed to read frame: %s\n", strerror(errno));
+            break;
+        }
     }
-    if (++capBox->curframe == capBox->buffers)
-        capBox->curframe = 0;
+    TRACE("Successfully read a frame.\n");
+    *buffer = device->image_data;
 }
 
 static DWORD WINAPI ReadThread(LPVOID lParam)
@@ -612,10 +499,6 @@ static DWORD WINAPI ReadThread(LPVOID lParam)
     }
 
     pOutput = CoTaskMemAlloc(capBox->width * capBox->height * capBox->bitDepth / 8);
-    capBox->curframe = 0;
-    do {
-        V4l_FreeFrame(capBox);
-    } while (capBox->curframe != 0);
 
     while (1)
     {
@@ -644,7 +527,6 @@ static DWORD WINAPI ReadThread(LPVOID lParam)
             hr = BaseOutputPinImpl_Deliver((BaseOutputPin *)capBox->pOut, pSample);
             TRACE("%p -> Frame %u: %x\n", capBox, ++framecount, hr);
             IMediaSample_Release(pSample);
-            V4l_FreeFrame(capBox);
         }
         if (FAILED(hr) && hr != VFW_E_NOT_CONNECTED)
         {
@@ -777,137 +659,127 @@ HRESULT qcap_driver_stop(Capture *capBox, FILTER_STATE *state)
     return S_OK;
 }
 
+static int negotiate_format(Capture *device)
+{
+    struct v4l2_format format = {0};
+    int fd = device->fd;
+    unsigned int i;
+
+    format.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
+
+    if (xioctl(fd, VIDIOC_G_FMT, &format) == -1)
+    {
+        ERR("Failed to get device format: %s\n", strerror(errno));
+        return -1;
+    }
+
+    for (i = 0; i < ARRAY_SIZE(renderlist_V4l); ++i)
+    {
+        if (renderlist_V4l[i].pixelformat == format.fmt.pix.pixelformat)
+        {
+            TRACE("Using device-reported format %#x.\n", format.fmt.pix.pixelformat);
+            device->depth = renderlist_V4l[i].depth;
+            device->renderer = renderlist_V4l[i].renderer;
+            device->pixelformat = format.fmt.pix.pixelformat;
+            device->width = format.fmt.pix.width;
+            device->height = format.fmt.pix.height;
+            return 0;
+        }
+    }
+
+    for (i = 0; i < ARRAY_SIZE(renderlist_V4l); ++i)
+    {
+        format.fmt.pix.pixelformat = renderlist_V4l[i].pixelformat;
+        if (!xioctl(fd, VIDIOC_S_FMT, &format)
+                && format.fmt.pix.pixelformat == renderlist_V4l[i].pixelformat)
+        {
+            TRACE("Using format %#x.\n", format.fmt.pix.pixelformat);
+            device->depth = renderlist_V4l[i].depth;
+            device->renderer = renderlist_V4l[i].renderer;
+            device->pixelformat = format.fmt.pix.pixelformat;
+            device->width = format.fmt.pix.width;
+            device->height = format.fmt.pix.height;
+            return 0;
+        }
+    }
+
+    FIXME("Could not negotiate an acceptable format.\n");
+    return -1;
+}
+
 Capture * qcap_driver_init( IPin *pOut, USHORT card )
 {
-    Capture * capBox = NULL;
-    char device[20];
-    struct video_capability capa;
-    struct video_picture pict;
-    struct video_window window;
+    struct v4l2_capability caps = {{0}};
+    Capture *device = NULL;
+    BOOL have_libv4l2;
+    char path[20];
+    int fd;
 
     YUV_Init();
-    video_init();
+    have_libv4l2 = video_init();
 
-    capBox = CoTaskMemAlloc(sizeof(Capture));
-    if (!capBox)
-        goto error;
+    if (!(device = CoTaskMemAlloc(sizeof(*device))))
+        return NULL;
 
-    /* capBox->vtbl = &defboxVtbl; */
+    InitializeCriticalSection(&device->CritSect);
+    device->CritSect.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": Capture.CritSect");
 
-    InitializeCriticalSection( &capBox->CritSect );
-    capBox->CritSect.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": Capture.CritSect");
-
-    sprintf(device, "/dev/video%i", card);
-    TRACE("opening %s\n", device);
+    sprintf(path, "/dev/video%i", card);
+    TRACE("Opening device %s.\n", path);
 #ifdef O_CLOEXEC
-    if ((capBox->fd = video_open(device, O_RDWR | O_NONBLOCK | O_CLOEXEC)) == -1 && errno == EINVAL)
+    if ((fd = video_open(path, O_RDWR | O_NONBLOCK | O_CLOEXEC)) == -1 && errno == EINVAL)
 #endif
-        capBox->fd = video_open(device, O_RDWR | O_NONBLOCK);
-    if (capBox->fd == -1)
+        fd = video_open(path, O_RDWR | O_NONBLOCK);
+    if (fd == -1)
     {
-        WARN("open failed (%d)\n", errno);
+        WARN("Failed to open video device: %s\n", strerror(errno));
         goto error;
     }
-    fcntl( capBox->fd, F_SETFD, FD_CLOEXEC );  /* in case O_CLOEXEC isn't supported */
-
-    memset(&capa, 0, sizeof(capa));
+    fcntl(fd, F_SETFD, FD_CLOEXEC);  /* in case O_CLOEXEC isn't supported */
+    device->fd = fd;
 
-    if (xioctl(capBox->fd, VIDIOCGCAP, &capa) == -1)
+    if (xioctl(fd, VIDIOC_QUERYCAP, &caps) == -1)
     {
-        WARN("ioctl(VIDIOCGCAP) failed (%d)\n", errno);
+        WARN("Failed to query device capabilities: %s\n", strerror(errno));
         goto error;
     }
 
-    if (!(capa.type & VID_TYPE_CAPTURE))
+    if (!(caps.capabilities & V4L2_CAP_VIDEO_CAPTURE))
     {
-        WARN("not a video capture device\n");
+        WARN("Device does not support single-planar video capture.\n");
         goto error;
     }
 
-    TRACE("%d inputs on %s\n", capa.channels, capa.name );
-
-    if (xioctl(capBox->fd, VIDIOCGPICT, &pict) == -1)
+    if (!(caps.capabilities & V4L2_CAP_READWRITE))
     {
-        ERR("ioctl(VIDIOCGPICT) failed (%d)\n", errno );
+        WARN("Device does not support read().\n");
+        if (!have_libv4l2)
+#ifdef SONAME_LIBV4L2
+            ERR_(winediag)("Reading from %s requires libv4l2, but it could not be loaded.\n", path);
+#else
+            ERR_(winediag)("Reading from %s requires libv4l2, but Wine was compiled without libv4l2 support.\n", path);
+#endif
         goto error;
     }
 
-    TRACE("depth %d palette %d (%s) hue %d color %d contrast %d\n",
-          pict.depth, pict.palette, renderlist_V4l[pict.palette].name,
-          pict.hue, pict.colour, pict.contrast );
-
-    capBox->dbrightness = pict.brightness;
-    capBox->dcolour = pict.colour;
-    capBox->dhue = pict.hue;
-    capBox->dcontrast = pict.contrast;
-
-    if (!renderlist_V4l[pict.palette].renderer)
-    {
-        int palet = pict.palette, i;
-
-        TRACE("No renderer available for %s, falling back to defaults\n",
-             renderlist_V4l[pict.palette].name);
-        capBox->renderer = NULL;
-        for (i = 0; fallback_V4l[i] >=0 ; i++)
-        {
-            int n = fallback_V4l[i];
-
-            if (renderlist_V4l[n].renderer == NULL)
-                continue;
-
-            pict.depth = renderlist_V4l[n].depth;
-            pict.palette = n;
-            if (xioctl(capBox->fd, VIDIOCSPICT, &pict) == -1)
-            {
-                TRACE("Could not render with %s (%d)\n",
-                      renderlist_V4l[n].name, n);
-                continue;
-            }
-            TRACE("using renderer %s (%d)\n", 
-                  renderlist_V4l[n].name, n);
-            capBox->renderer = renderlist_V4l[n].renderer;
-            break;
-        }
-
-        if (!capBox->renderer)
-        {
-            ERR("video format %s isn't available\n",
-                 renderlist_V4l[palet].name);
-            goto error;
-        }
-    }
-    else
-    {
-        TRACE("Using the suggested format\n");
-        capBox->renderer = renderlist_V4l[pict.palette].renderer;
-    }
-    memcpy(&capBox->pict, &pict, sizeof(struct video_picture));
-
-    memset(&window, 0, sizeof(window));
-    if (xioctl(capBox->fd, VIDIOCGWIN, &window) == -1)
-    {
-        WARN("VIDIOCGWIN failed (%d)\n", errno);
+    if (negotiate_format(device) == -1)
         goto error;
-    }
 
-    capBox->height = capBox->outputheight = window.height;
-    capBox->width = capBox->outputwidth = window.width;
-    capBox->swresize = FALSE;
-    capBox->bitDepth = 24;
-    capBox->pOut = pOut;
-    capBox->fps = 3;
-    capBox->stopped = FALSE;
-    capBox->curframe = 0;
-    capBox->iscommitted = FALSE;
+    device->outputwidth = device->width;
+    device->outputheight = device->height;
+    device->swresize = FALSE;
+    device->bitDepth = 24;
+    device->pOut = pOut;
+    device->fps = 3;
+    device->stopped = FALSE;
+    device->iscommitted = FALSE;
 
-    TRACE("format: %d bits - %d x %d\n", capBox->bitDepth, capBox->width, capBox->height);
+    TRACE("Format: %d bpp - %dx%d.\n", device->bitDepth, device->width, device->height);
 
-    return capBox;
+    return device;
 
 error:
-    if (capBox)
-        qcap_driver_destroy( capBox );
-
+    qcap_driver_destroy(device);
     return NULL;
 }
 
diff --git a/dlls/qcap/yuv.c b/dlls/qcap/yuv.c
index 7e17add949c..0ba78d053da 100644
--- a/dlls/qcap/yuv.c
+++ b/dlls/qcap/yuv.c
@@ -32,7 +32,7 @@
 #include "wine/debug.h"
 
 /* This is not used if V4L support is missing */
-#if defined(HAVE_LINUX_VIDEODEV_H) || defined(HAVE_LIBV4L1_H)
+#ifdef HAVE_LINUX_VIDEODEV2_H
 
 WINE_DEFAULT_DEBUG_CHANNEL(qcap);
 
diff --git a/include/config.h.in b/include/config.h.in
index 17676b99163..535f43fc91b 100644
--- a/include/config.h.in
+++ b/include/config.h.in
@@ -411,9 +411,6 @@
 /* Define to 1 if you have the <libunwind.h> header file. */
 #undef HAVE_LIBUNWIND_H
 
-/* Define to 1 if you have the <libv4l1.h> header file. */
-#undef HAVE_LIBV4L1_H
-
 /* Define if you have the libxml2 library */
 #undef HAVE_LIBXML2
 
@@ -501,9 +498,6 @@
 /* Define to 1 if you have the <linux/videodev2.h> header file. */
 #undef HAVE_LINUX_VIDEODEV2_H
 
-/* Define to 1 if you have the <linux/videodev.h> header file. */
-#undef HAVE_LINUX_VIDEODEV_H
-
 /* Define to 1 if you have the `llrint' function. */
 #undef HAVE_LLRINT
 
@@ -1410,8 +1404,8 @@
 /* Define to the soname of the libtiff library. */
 #undef SONAME_LIBTIFF
 
-/* Define to the soname of the libv4l1 library. */
-#undef SONAME_LIBV4L1
+/* Define to the soname of the libv4l2 library. */
+#undef SONAME_LIBV4L2
 
 /* Define to the soname of the libvkd3d library. */
 #undef SONAME_LIBVKD3D
-- 
GitLab