Skip to contentSkip to conversation

Introduce camera subsystem and USB video device

PATCH Superseded zhenwei pi 3 participants 12 messages Dec 27, 2021 – Jan 11, 2022 Arm/Amlogic Meson SoC support

v1 of 2 Superseded Latest is v2 →

lore
Share & tools
lore

zhenwei pi

author
#0 lore raw

cover Introduce camera subsystem and USB video device

1, The full picture of this patch set:

   +---------+       +------------+     +---------------+
   |UVC(done)|       |virtio(TODO)|     |other HW device|
   +---------+       +------------+     +---------------+
         |                 |                     |
         |            +------------+             |
	 +------------+camera(done)+-------------+
                      +----+-------+
                           |
         +-----------------+---------------------+
         |                 |                     |
  +------+------+     +----+-----+        +------+------+
  |builtin(done)|     |v4l2(done)|        |other drivers|
  +-------------+     +----------+        +-------------+

With this patch set, We can run a desktop VM (Ex Ubuntu-2004), several camera APPs(cheese, kamoso, guvcview and qcam) work fine.

Some works still in working:
1, hot-plug
2, compat with live migration
3, several actions defined in UVC SPEC

Zhenwei Pi (5):
camera: Introduce camera subsystem and builtin driver
camera: v4l2: Introduce v4l2 camera driver
usb: Introduce video&mescellaneous
usb: allow max 8192 bytes for desc
usb-video: Introduce USB video class

 camera/builtin.c        |  717 ++++++++++++++++++++
 camera/camera-int.h     |   19 +
 camera/camera.c         |  522 +++++++++++++++
 camera/meson.build      |   20 +
 camera/trace-events     |   28 +
 camera/trace.h          |    1 +
 camera/v4l2.c           |  637 ++++++++++++++++++
 hw/usb/Kconfig          |    5 +
 hw/usb/desc.c           |   15 +-
 hw/usb/desc.h           |    1 +
 hw/usb/dev-video.c      | 1395 +++++++++++++++++++++++++++++++++++++++
 hw/usb/meson.build      |    1 +
 hw/usb/trace-events     |   11 +
 include/camera/camera.h |  238 +++++++
 include/hw/usb.h        |    2 +
 include/hw/usb/video.h  |  303 +++++++++
 meson.build             |   20 +-
 meson_options.txt       |    3 +
 qapi/camera.json        |  101 +++
 qapi/meson.build        |    1 +
 qapi/qapi-schema.json   |    1 +
 qemu-options.hx         |   13 +
 softmmu/vl.c            |    4 +
 23 files changed, 4050 insertions(+), 8 deletions(-)
 create mode 100644 camera/builtin.c
 create mode 100644 camera/camera-int.h
 create mode 100644 camera/camera.c
 create mode 100644 camera/meson.build
 create mode 100644 camera/trace-events
 create mode 100644 camera/trace.h
 create mode 100644 camera/v4l2.c
 create mode 100644 hw/usb/dev-video.c
 create mode 100644 include/camera/camera.h
 create mode 100644 include/hw/usb/video.h
 create mode 100644 qapi/camera.json
Signature · 1 line
2.25.1
author
#1 lore raw

PATCH 1/5 camera: Introduce camera subsystem and builtin driver

Web camera is an important port of a desktop instance, QEMU supports USB passthrough and USB redirect to support for general cases. Several problems we have hit:
1, the heavy bandwidth of network. a 1080*720@30FPS(MJPEG) uses

     ~5MB/s.

2, Issues of USB passthrough, Ex USB reset from guest side triggers
wrong state of host side.
3, extention features, Ex to limit FPS/width&height of a camera
device by hypervisor.
...

So introduce camera subsystem to QEMU, abstruct basic API to operate a camera device. Also introduce a builtin driver which draws pure color, rainbow and digital rain background, and shows information for guest side to debug by libcairo.

The full picture of QEMU camera subsystem works like this:

   +----------+       +------------+     +---------------+
   |UVC(ready)|       |virtio(TODO)|     |other HW device|
   +----------+       +------------+     +---------------+
         |                 |                     |
         |            +--------+                 |
	 +------------+ Camera +-----------------+
                      +----+---+
                           |
         +-----------------+---------------------+
         |                 |                     |
     +---+---+       +-----+-----+        +-------------+
     |builtin|       |v4l2(ready)|        |other drivers|
     +-------+       +-----------+        +-------------+
---
 camera/builtin.c        | 717 ++++++++++++++++++++++++++++++++++++++++
 camera/camera-int.h     |  19 ++
 camera/camera.c         | 522 +++++++++++++++++++++++++++++
 camera/meson.build      |  16 +
 camera/trace-events     |  24 ++
 camera/trace.h          |   1 +
 include/camera/camera.h | 238 +++++++++++++
 meson.build             |  20 +-
 meson_options.txt       |   3 +
 qapi/camera.json        |  84 +++++
 qapi/meson.build        |   1 +
 qapi/qapi-schema.json   |   1 +
 qemu-options.hx         |  10 +
 softmmu/vl.c            |   4 +
 14 files changed, 1659 insertions(+), 1 deletion(-)
 create mode 100644 camera/builtin.c
 create mode 100644 camera/camera-int.h
 create mode 100644 camera/camera.c
 create mode 100644 camera/meson.build
 create mode 100644 camera/trace-events
 create mode 100644 camera/trace.h
 create mode 100644 include/camera/camera.h
 create mode 100644 qapi/camera.json
camera/builtin.c new file +717 -0
new file mode 100644
index 0000000000..26828e74d1
@@ -0,0 +1,717 @@
+/*
+ * Builtin camera backend implemention
+ *
+ * Copyright 2021 Bytedance, Inc.
+ *
+ * Authors:
+ *   zhenwei pi <[email protected]>
+ *
+ * This work is licensed under the terms of the GNU GPL, version 2 or later.
+ * See the COPYING file in the top-level directory.
+ */
+#include "qemu/osdep.h"
+#include "qemu/module.h"
+#include "qemu/log.h"
+#include "qemu/main-loop.h"
+#include "qom/object.h"
+#include "qapi/error.h"
+#include "qapi/visitor.h"
+#include "qapi/qapi-visit-camera.h"
+#include "camera/camera.h"
+#include "camera-int.h"
+#include "trace.h"
+
+#ifdef CONFIG_VNC_JPEG /* TODO shoud it rename to CONFIG_LIB_JPEG? */
+#include <jpeglib.h>
+#endif
+
+#include <cairo/cairo.h>
+
+#define TYPE_CAMERA_BUILTIN TYPE_CAMERADEV"-builtin"
+
+#define CAMERA_BUILTIN_DEF_WIDTH 640
+#define CAMERA_BUILTIN_MAX_WIDTH 3840
+#define CAMERA_BUILTIN_MIN_WIDTH 160
+#define CAMERA_BUILTIN_DEF_HEIGHT 480
+#define CAMERA_BUILTIN_MAX_HEIGHT 2880
+#define CAMERA_BUILTIN_MIN_HEIGHT 120
+#define CAMERA_BUILTIN_DEF_FPS 10
+#define CAMERA_BUILTIN_MAX_FPS 60
+#define CAMERA_BUILTIN_MIN_FPS 1
+
+/* mjpeg, yuv, rgb565 */
+#define CAMERA_BUILTIN_MAX_PIXFMT 3
+
+enum AttributeIndex {
+    ATTRIBUTE_DEF,
+    ATTRIBUTE_MIN,
+    ATTRIBUTE_MAX,
+    ATTRIBUTE_CUR,
+    ATTRIBUTE_STEP,
+
+    ATTRIBUTE_ALL
+};
+
+typedef struct CameraBuiltin {
+    QEMUCamera parent;
+
+    /* opts */
+    uint16_t width;
+    uint16_t height;
+    uint16_t fps;
+    bool debug;
+    bool mjpeg;
+    bool yuv;
+    bool rgb565;
+    ColorType bgcolor;
+
+    /* state */
+    QEMUTimer *frame_timer;
+    cairo_surface_t *surface;
+    cairo_t *cr;
+    size_t image_size;
+    uint8_t *image;
+    uint8_t pixbytes;
+    uint8_t npixfmts;
+    uint32_t pixfmts[CAMERA_BUILTIN_MAX_PIXFMT];
+    uint32_t pixfmt; /* current in use */
+    void *opaque; /* used by driver itself */
+
+    /* debug infomations */
+    uint32_t sequence;
+    int32_t ctrl[QEMUCameraControlMax][ATTRIBUTE_ALL];
+} CameraBuiltin;
+
+DECLARE_INSTANCE_CHECKER(CameraBuiltin, CAMERA_BUILTIN_DEV, TYPE_CAMERA_BUILTIN)
+
+static inline uint8_t pixel_clip(int x)
+{
+    if (x > 255) {
+        return 255;
+    } else if (x < 0) {
+        return 0;
+    }
+
+    return x;
+}
+
+static void camera_builtin_rgb24_to_yuyv(uint8_t *rgb, uint8_t *yuv, int width,
+                                         int height, uint8_t pixbytes)
+{
+    int r1, g1, b1, r2, g2, b2, y1, u1, y2, v1;
+    int x, y;
+    uint8_t *dst, *src;
+    uint32_t val;
+
+    for (x = 0; x < height; x++) {
+        for (y = 0; y < width / 2; y++) {
+            src = rgb + x * width * pixbytes + y * pixbytes * 2;
+            val = le32_to_cpu(*(uint32_t *)src);
+            r1 = (val >> 16) & 0xff;
+            g1 = (val >> 8) & 0xff;
+            b1 = val & 0xff;
+            val = le32_to_cpu(*(uint32_t *)(src + pixbytes));
+            r2 = (val >> 16) & 0xff;
+            g2 = (val >> 8) & 0xff;
+            b2 = val & 0xff;
+
+            y1 = pixel_clip(((66 * r1 + 129 * g1 + 25 * b1 + 128) >> 8) + 16);
+            u1 = pixel_clip((((-38 * r1 - 74 * g1 + 112 * b1 + 128) >> 8)
+                            + ((-38 * r2 - 74 * g2 + 112 * b2 + 128) >> 8)) / 2
+                            + 128);
+            y2 = pixel_clip(((66 * r2 + 129 * g2 + 25 * b2 + 128) >> 8) + 16);
+            v1 = pixel_clip((((112 * r1 - 94 * g1 - 18 * b1 + 128) >> 8)
+                            + ((112 * r2 - 94 * g2 - 18 * b2 + 128) >> 8)) / 2
+                            + 128);
+            dst = yuv + x * width * 2 + y * 4;
+            *dst++ = y1;
+            *dst++ = u1;
+            *dst++ = y2;
+            *dst = v1;
+        }
+    }
+}
+
+static void camera_builtin_draw_info(QEMUCamera *camera)
+{
+    CameraBuiltin *builtin = CAMERA_BUILTIN_DEV(camera);
+    char text[32];
+    uint16_t fontsize = 20;
+    uint16_t y = fontsize;
+    QEMUCameraControlType t;
+
+    cairo_set_source_rgb(builtin->cr, 1, 1, 1);
+    cairo_select_font_face(builtin->cr, "Georgia", CAIRO_FONT_SLANT_NORMAL,
+                           CAIRO_FONT_WEIGHT_BOLD);
+
+    cairo_set_font_size(builtin->cr, fontsize);
+    cairo_move_to(builtin->cr, 0, y);
+    sprintf(text, "Sequence %d", builtin->sequence++);
+    cairo_show_text(builtin->cr, text);
+
+    for (t = 0; (t < QEMUCameraControlMax)&&(y <= builtin->height); t++) {
+        y += fontsize;
+        cairo_move_to(builtin->cr, 0, y);
+        sprintf(text, "%s %d", QEMUCameraControlTypeString(t),
+                builtin->ctrl[t][ATTRIBUTE_CUR]);
+        cairo_show_text(builtin->cr, text);
+    }
+}
+
+static void camera_builtin_draw_pure_color(QEMUCamera *camera, ColorType color)
+{
+    CameraBuiltin *builtin = CAMERA_BUILTIN_DEV(camera);
+    uint8_t r = 0, g = 0, b = 0;
+
+    switch ((int)color) {
+    case COLOR_TYPE_RED:
+        r = 1;
+        break;
+    case COLOR_TYPE_GREEN:
+        g = 1;
+        break;
+    case COLOR_TYPE_BLUE:
+        b = 1;
+        break;
+    }
+
+    cairo_move_to(builtin->cr, 0, 0);
+    cairo_set_source_rgb(builtin->cr, r, g, b);
+    cairo_rectangle(builtin->cr, 0, 0, builtin->width, builtin->height);
+    cairo_fill(builtin->cr);
+}
+
+static void camera_builtin_draw_rainbow(QEMUCamera *camera)
+{
+    CameraBuiltin *builtin = CAMERA_BUILTIN_DEV(camera);
+    uint16_t colors;
+    uint16_t lines = builtin->height / 7;
+    uint8_t rainbow[7][3] = {
+        {0xff, 0x00, 0x00}, /* red */
+        {0xff, 0xa5, 0x00}, /* orange */
+        {0xff, 0xff, 0x00}, /* yellow */
+        {0x00, 0x80, 0x00}, /* green */
+        {0x00, 0x00, 0xff}, /* blue */
+        {0x4b, 0x00, 0x82}, /* indigo */
+        {0xee, 0x82, 0xee}, /* violet */
+    };
+    uint8_t *addr;
+
+    for (colors = 0 ; colors < 7; colors++) {
+        cairo_move_to(builtin->cr, 0, lines * colors);
+        addr = rainbow[colors];
+        cairo_set_source_rgb(builtin->cr, addr[0] / (float)255,
+                             addr[1] / (float)255, addr[2] / (float)255);
+        cairo_rectangle(builtin->cr, 0, lines * colors, builtin->width, lines);
+        cairo_fill(builtin->cr);
+    }
+}
+
+static void camera_builtin_draw_digital_rain(QEMUCamera *camera)
+{
+#define DIGITAL_RAIN_FONT 20
+    CameraBuiltin *builtin = CAMERA_BUILTIN_DEV(camera);
+    int rain_rows = builtin->width / 2 / DIGITAL_RAIN_FONT;
+    int rain_len = builtin->height * 2 / DIGITAL_RAIN_FONT;
+    int i, j, x, y, asterisks, first, last;
+    char *addr, *base;
+    char text[2] = {0};
+    int len = rain_len / 2;
+
+    if (!builtin->opaque) {
+        builtin->opaque = g_malloc(rain_rows * rain_len);
+        memset(builtin->opaque, '*', rain_rows * rain_len);
+    }
+
+    base = builtin->opaque;
+
+    cairo_set_source_rgb(builtin->cr, 0, 0, 0);
+    cairo_rectangle(builtin->cr, 0, 0, builtin->width, builtin->height);
+    cairo_fill(builtin->cr);
+
+    cairo_select_font_face(builtin->cr, "Georgia", CAIRO_FONT_SLANT_NORMAL,
+                           CAIRO_FONT_WEIGHT_BOLD);
+    cairo_set_font_size(builtin->cr, DIGITAL_RAIN_FONT);
+    for (i = 0; i < rain_rows; i++) {
+        addr = base + i * rain_len + len;
+        asterisks = 0;
+
+        for (j = 0; (j < len) && (addr[j] == '*'); j++) {
+            asterisks++;
+        }
+
+        if (asterisks == len) {
+rerandom:
+            first = random() % len;
+            last = random() % len;
+            if ((first + len / 4) >= last) {
+                goto rerandom;
+            }
+
+            for (j = first; j < last; j++) {
+                *(addr + j) = random() % 26 + 'A' + (random() % 2) * 32;
+            }
+        }
+
+        addr = base + i * rain_len;
+
+        for (j = 0; (j < len) && (addr[j] == '*'); ) {
+            j++;
+        }
+
+        if (j == len) {
+            goto update_frame;
+        }
+
+        cairo_set_source_rgb(builtin->cr, 1, 1, 1); /* first char of row */
+        x = DIGITAL_RAIN_FONT * i * 2;
+        y = DIGITAL_RAIN_FONT * (len - j);
+        cairo_move_to(builtin->cr, x, y);
+        sprintf(text, "%c", addr[j]);
+        cairo_show_text(builtin->cr, text);
+
+        for (j++; j < len; j++) {
+            if (addr[j] == '*') {
+                continue;
+            }
+            x = DIGITAL_RAIN_FONT * i * 2;
+            y = DIGITAL_RAIN_FONT * (len - j);
+            cairo_set_source_rgb(builtin->cr, 0, 1, 0);
+            cairo_move_to(builtin->cr, x, y);
+
+            sprintf(text, "%c", addr[j]);
+            cairo_show_text(builtin->cr, text);
+        }
+
+update_frame:
+        addr = base + i * rain_len;
+        memmove(addr, addr + 1, 2 * len - 1);
+        addr[2 * len - 1] = '*';
+    }
+}
+
+#ifdef CONFIG_VNC_JPEG
+static void camera_builtin_jpeg_init_destination(j_compress_ptr cinfo)
+{
+    CameraBuiltin *builtin = cinfo->client_data;
+
+    cinfo->dest->next_output_byte = builtin->image;
+    cinfo->dest->free_in_buffer = builtin->image_size;
+}
+
+static void camera_builtin_jpeg_term_destination(j_compress_ptr cinfo)
+{
+    /* nothing to do, but avoid libjpeg to crash! */
+}
+
+static void camera_builtin_rgb24_to_jpeg_line(uint8_t *rgb, uint8_t *jpeg,
+                                              uint16_t width, uint8_t pixbytes)
+{
+    uint16_t x;
+    uint32_t val;
+    uint8_t *dst, *src;
+
+    for (x = 0; x < width; x++) {
+        src = rgb + x * pixbytes;
+        val = le32_to_cpu(*(uint32_t *)src);
+        dst = jpeg + 3 * x;
+        *(dst++) = (val >> 16) & 0xff; /* R */
+        *(dst++) = (val >> 8) & 0xff; /* G */
+        *dst = val & 0xff; /* B */
+    }
+}
+
+static size_t camera_builtin_rgb24_to_jpeg(QEMUCamera *camera, uint8_t *rgb,
+                                           uint8_t *jpeg, uint16_t width,
+                                           int height, uint8_t pixbytes)
+{
+    CameraBuiltin *builtin = CAMERA_BUILTIN_DEV(camera);
+    struct jpeg_compress_struct cinfo;
+    struct jpeg_error_mgr jerr;
+    struct jpeg_destination_mgr manager = {0};
+    JSAMPROW row_pointer[1];
+    g_autofree uint8_t *linebuf = g_malloc(width * 3);
+    uint8_t *addr;
+    int quality = 50;
+
+    cinfo.err = jpeg_std_error(&jerr);
+    jpeg_create_compress(&cinfo);
+    cinfo.client_data = builtin;
+    cinfo.image_width = builtin->width;
+    cinfo.image_height = builtin->height;
+    cinfo.input_components = 3;
+    cinfo.in_color_space = JCS_RGB;
+    jpeg_set_defaults(&cinfo);
+    jpeg_set_quality(&cinfo, quality, TRUE);
+    manager.init_destination = camera_builtin_jpeg_init_destination;
+    manager.term_destination = camera_builtin_jpeg_term_destination;
+    cinfo.dest = &manager;
+    row_pointer[0] = linebuf;
+
+    jpeg_start_compress(&cinfo, true);
+
+    while (cinfo.next_scanline < cinfo.image_height) {
+        addr = rgb + cinfo.next_scanline * width * pixbytes;
+        camera_builtin_rgb24_to_jpeg_line(addr, linebuf, width, pixbytes);
+        jpeg_write_scanlines(&cinfo, row_pointer, 1);
+    }
+
+    jpeg_finish_compress(&cinfo);
+    jpeg_destroy_compress(&cinfo);
+
+    return builtin->image_size - cinfo.dest->free_in_buffer;
+}
+#else
+static size_t camera_builtin_rgb24_to_jpeg(QEMUCamera *camera, uint8_t *rgb,
+                                           uint8_t *jpeg, uint16_t width,
+                                           int height, uint8_t pixbytes)
+{
+    return -1;
+}
+#endif
+
+static void camera_builtin_frame_timer(void *opaque)
+{
+    QEMUCamera *camera = opaque;
+    CameraBuiltin *builtin = CAMERA_BUILTIN_DEV(camera);
+    uint8_t *image_addr = cairo_image_surface_get_data(builtin->surface);
+    size_t image_bytes = 0;
+    uint16_t w = builtin->width, h = builtin->height;
+
+    /* 1, draw a frame by cairo */
+    switch (builtin->bgcolor) {
+    case COLOR_TYPE_BLUE:
+    case COLOR_TYPE_GREEN:
+    case COLOR_TYPE_RED:
+        camera_builtin_draw_pure_color(camera, builtin->bgcolor);
+        break;
+
+    case COLOR_TYPE_RAINBOW:
+        camera_builtin_draw_rainbow(camera);
+        break;
+
+    case COLOR_TYPE_DIGITAL_RAIN:
+        camera_builtin_draw_digital_rain(camera);
+        break;
+
+    case COLOR_TYPE__MAX:
+    default:
+        return;
+    }
+
+    if (builtin->debug) {
+        camera_builtin_draw_info(camera);
+    }
+
+    /* 2, convert to a suitable format */
+    switch (builtin->pixfmt) {
+    case QEMU_CAMERA_PIX_FMT_MJPEG:
+        image_bytes = camera_builtin_rgb24_to_jpeg(camera, image_addr,
+                          builtin->image, w, h, builtin->pixbytes);
+        image_addr = builtin->image;
+        break;
+    case QEMU_CAMERA_PIX_FMT_YUYV:
+        camera_builtin_rgb24_to_yuyv(image_addr, builtin->image, w, h,
+                                     builtin->pixbytes);
+        image_bytes = w * h * 2;
+        image_addr = builtin->image;
+        break;
+    case QEMU_CAMERA_PIX_FMT_RGB565:
+        /* no need to convert, just put builtin->surface to uplayer */
+        image_bytes = w * h * 2;
+        break;
+    }
+
+    /* 3, delivery to uplayer */
+    qemu_camera_new_image(camera, image_addr, image_bytes);
+
+    /* 4, modify timer for next frame */
+    timer_mod(builtin->frame_timer, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL)
+              + NANOSECONDS_PER_SECOND / builtin->fps);
+
+    trace_camera_builtin_timer(qemu_camera_id(camera));
+}
+
+static int camera_builtin_enum_pixel_format(QEMUCamera *camera,
+                                            uint32_t *pixfmts, int npixfmt,
+                                            Error **errp)
+{
+    CameraBuiltin *builtin = CAMERA_BUILTIN_DEV(camera);
+    int index, total = 0;
+
+    for (index = 0; index < MIN(npixfmt, builtin->npixfmts); index++) {
+        pixfmts[total++] = builtin->pixfmts[index];
+    }
+
+    return total;
+}
+
+static int camera_builtin_enum_frame_size(QEMUCamera *camera, uint32_t pixfmt,
+                                          QEMUCameraFrameSize *frmszs,
+                                          int nfrmsz, Error **errp)
+{
+    CameraBuiltin *builtin = CAMERA_BUILTIN_DEV(camera);
+    QEMUCameraFrameSize *frmsz;
+
+    if (nfrmsz < 1) {
+        return 0;
+    }
+
+    frmsz = frmszs;
+    frmsz->pixel_format = pixfmt;
+    frmsz->type = QEMU_CAMERA_FRMSIZE_TYPE_DISCRETE;
+    frmsz->d.width = builtin->width;
+    frmsz->d.height = builtin->height;
+
+    return 1;
+}
+
+static int camera_builtin_enum_frame_interval(QEMUCamera *camera,
+                                              const QEMUCameraFormat *format,
+                                              QEMUCameraFrameInterval *frmivals,
+                                              int nfrmival, Error **errp)
+{
+    CameraBuiltin *builtin = CAMERA_BUILTIN_DEV(camera);
+    QEMUCameraFrameInterval *frmival;
+
+    if (nfrmival < 1) {
+        return 0;
+    }
+
+    if (format->width != builtin->width || format->height != builtin->height) {
+        error_setg(errp, "%s: enum frame interval unsupported mismatched "
+                   "width(%d)/height(%d)", TYPE_CAMERA_BUILTIN, format->width,
+                   format->height);
+        return 0;
+    }
+
+    frmival = frmivals;
+    frmival->pixel_format = format->pixel_format;
+    frmival->width = format->width;
+    frmival->height = format->height;
+    frmival->type = QEMU_CAMERA_FRMIVAL_TYPE_DISCRETE;
+    frmival->d.numerator = 1;
+    frmival->d.denominator = builtin->fps;
+
+    return 1;
+}
+
+static int camera_builtin_set_frame_interval(QEMUCamera *camera,
+               const QEMUCameraFrameInterval *frmival, Error **errp)
+{
+    CameraBuiltin *builtin = CAMERA_BUILTIN_DEV(camera);
+
+    if (frmival->width != builtin->width
+        || frmival->height != builtin->height) {
+        error_setg(errp, "%s: set frame interval unsupported mismatched "
+                   "width(%d)/height(%d)", TYPE_CAMERA_BUILTIN, frmival->width,
+                   frmival->height);
+        return 0;
+    }
+
+    builtin->pixfmt = frmival->pixel_format;
+
+    return 0;
+}
+
+static int camera_builtin_enum_control(QEMUCamera *camera,
+               QEMUCameraControl *controls, int ncontrols, Error **errp)
+{
+    CameraBuiltin *builtin = CAMERA_BUILTIN_DEV(camera);
+    QEMUCameraControl *control;
+    QEMUCameraControlType t;
+
+    for (t = 0; t < QEMUCameraControlMax; t++) {
+        control = controls + t;
+        control->type = t;
+        control->cur = builtin->ctrl[t][ATTRIBUTE_CUR];
+        control->def = builtin->ctrl[t][ATTRIBUTE_DEF];
+        control->min = builtin->ctrl[t][ATTRIBUTE_MIN];
+        control->max = builtin->ctrl[t][ATTRIBUTE_MAX];
+        control->step = builtin->ctrl[t][ATTRIBUTE_STEP];
+    }
+
+    return t;
+}
+
+static int camera_builtin_set_control(QEMUCamera *camera,
+               const QEMUCameraControl *control, Error **errp)
+{
+    CameraBuiltin *builtin = CAMERA_BUILTIN_DEV(camera);
+
+    builtin->ctrl[control->type][ATTRIBUTE_CUR] = control->cur;
+
+    return 0;
+}
+
+#define CHECK_AND_GET_OPTS(x, y)                               \
+    do {                                                       \
+        if (builtinopts->has_##x) {                            \
+            if (builtinopts->x > CAMERA_BUILTIN_MAX_##y        \
+               || builtinopts->x < CAMERA_BUILTIN_MIN_##y) {   \
+                error_setg(errp, "%s: unsupported %s(%d, %d)", \
+                           TYPE_CAMERA_BUILTIN, #x,            \
+                           CAMERA_BUILTIN_MIN_##y,             \
+                           CAMERA_BUILTIN_MAX_##y);            \
+                return;                                        \
+            }                                                  \
+            builtin->x = builtinopts->x;                       \
+        } else {                                               \
+            builtin->x = CAMERA_BUILTIN_DEF_##y;               \
+        }                                                      \
+    } while (0)
+
+#define CHECK_AND_GET_VAL(x, def)                              \
+    do {                                                       \
+        if (builtinopts->has_##x) {                            \
+            builtin->x = builtinopts->x;                       \
+        } else {                                               \
+            builtin->x = def;                                  \
+        }                                                      \
+    } while (0)
+
+static void camera_builtin_open(QEMUCamera *camera, Error **errp)
+{
+    CameraBuiltin *builtin = CAMERA_BUILTIN_DEV(camera);
+    CameraBuiltinOptions *builtinopts = &camera->dev->u.builtin;
+
+    CHECK_AND_GET_OPTS(width, WIDTH);
+    CHECK_AND_GET_OPTS(height, HEIGHT);
+    CHECK_AND_GET_OPTS(fps, FPS);
+    CHECK_AND_GET_VAL(bgcolor, COLOR_TYPE_BLUE);
+    CHECK_AND_GET_VAL(debug, false);
+    CHECK_AND_GET_VAL(yuv, true);
+    CHECK_AND_GET_VAL(rgb565, true);
+#ifdef CONFIG_VNC_JPEG
+    CHECK_AND_GET_VAL(mjpeg, true);
+#else
+    if (builtinopts->has_mjpeg && builtinopts->mjpeg) {
+        error_setg(errp, "%s: no libjpeg supported", TYPE_CAMERA_BUILTIN);
+        return;
+    }
+#endif
+
+    if (builtin->mjpeg) {
+        builtin->pixfmts[builtin->npixfmts++] = QEMU_CAMERA_PIX_FMT_MJPEG;
+    }
+
+    if (builtin->yuv) {
+        builtin->pixfmts[builtin->npixfmts++] = QEMU_CAMERA_PIX_FMT_YUYV;
+    }
+
+    if (builtin->rgb565) {
+        builtin->pixfmts[builtin->npixfmts++] = QEMU_CAMERA_PIX_FMT_RGB565;
+    }
+
+    if (!builtin->npixfmts) {
+        error_setg(errp, "%s: all formats disabled", TYPE_CAMERA_BUILTIN);
+    }
+}
+
+static void camera_builtin_stream_on(QEMUCamera *camera, Error **errp)
+{
+    CameraBuiltin *builtin = CAMERA_BUILTIN_DEV(camera);
+    cairo_format_t cairofmt;
+    size_t imagesize;
+
+    imagesize = builtin->height * builtin->width * 2;
+    if (builtin->pixfmt == QEMU_CAMERA_PIX_FMT_RGB565) {
+        cairofmt = CAIRO_FORMAT_RGB16_565;
+        builtin->pixbytes = 2;
+    } else {
+        cairofmt = CAIRO_FORMAT_RGB24;
+        builtin->pixbytes = 4; /* see enum cairo_format_t in cairo.h */
+    }
+    builtin->surface = cairo_image_surface_create(cairofmt, builtin->width,
+                                                  builtin->height);
+    builtin->cr = cairo_create(builtin->surface);
+    qemu_camera_alloc_image(camera, imagesize, errp);
+    builtin->image_size = imagesize;
+    builtin->image = g_malloc(imagesize);
+
+    builtin->frame_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL,
+                               camera_builtin_frame_timer, camera);
+    timer_mod(builtin->frame_timer, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL)
+              + NANOSECONDS_PER_SECOND / builtin->fps);
+}
+
+static void camera_builtin_stream_off(QEMUCamera *camera, Error **errp)
+{
+    CameraBuiltin *builtin = CAMERA_BUILTIN_DEV(camera);
+
+    timer_free(builtin->frame_timer);
+
+    qemu_camera_free_image(camera);
+    g_free(builtin->image);
+    builtin->image = NULL;
+    builtin->sequence = 0;
+
+    cairo_destroy(builtin->cr);
+    cairo_surface_destroy(builtin->surface);
+
+    g_free(builtin->opaque);
+    builtin->opaque = NULL;
+}
+
+
+static void camera_builtin_init(Object *obj)
+{
+    QEMUCamera *camera = CAMERADEV(obj);
+    CameraBuiltin *builtin = CAMERA_BUILTIN_DEV(camera);
+    int i;
+
+    /*
+     * Because builtin camera is designed for debug purpose only, so this table
+     * does't keep align with the read camera, just to make the code easy.
+     */
+    for (i = 0; i < QEMUCameraControlMax; i++) {
+        builtin->ctrl[i][ATTRIBUTE_DEF] = 0x7f;
+        builtin->ctrl[i][ATTRIBUTE_MIN] = 0;
+        builtin->ctrl[i][ATTRIBUTE_MAX] = 0xff;
+        builtin->ctrl[i][ATTRIBUTE_CUR] = 0;
+        builtin->ctrl[i][ATTRIBUTE_STEP] = 1;
+    }
+
+    builtin->ctrl[QEMUCameraHueAuto][ATTRIBUTE_DEF] = 0;
+    builtin->ctrl[QEMUCameraHueAuto][ATTRIBUTE_MIN] = 0;
+    builtin->ctrl[QEMUCameraHueAuto][ATTRIBUTE_MAX] = 1;
+}
+
+static void camera_builtin_finalize(Object *obj)
+{
+    QEMUCamera *camera = CAMERADEV(obj);
+    Error *local_err = NULL;
+
+    camera_builtin_stream_off(camera, &local_err);
+}
+
+static void camera_builtin_class_init(ObjectClass *oc, void *data)
+{
+    QEMUCameraClass *klass = CAMERADEV_CLASS(oc);
+
+    klass->open = camera_builtin_open;
+    klass->stream_on = camera_builtin_stream_on;
+    klass->stream_off = camera_builtin_stream_off;
+    klass->enum_pixel_format = camera_builtin_enum_pixel_format;
+    klass->enum_frame_size = camera_builtin_enum_frame_size;
+    klass->enum_frame_interval = camera_builtin_enum_frame_interval;
+    klass->set_frame_interval = camera_builtin_set_frame_interval;
+    klass->enum_control = camera_builtin_enum_control;
+    klass->set_control = camera_builtin_set_control;
+}
+
+static const TypeInfo camera_builtin_type_info = {
+    .name = TYPE_CAMERA_BUILTIN,
+    .parent = TYPE_CAMERADEV,
+    .instance_size = sizeof(CameraBuiltin),
+    .instance_init = camera_builtin_init,
+    .instance_finalize = camera_builtin_finalize,
+    .class_init = camera_builtin_class_init,
+};
+
+static void register_types(void)
+{
+    type_register_static(&camera_builtin_type_info);
+}
+
+type_init(register_types);
camera/camera-int.h new file +19 -0
new file mode 100644
index 0000000000..f3f67ac43e
@@ -0,0 +1,19 @@
+/*
+ * QEMU Camera subsystem
+ *
+ * Copyright 2021 Bytedance, Inc.
+ *
+ * Authors:
+ *   zhenwei pi <[email protected]>
+ *
+ * This work is licensed under the terms of the GNU GPL, version 2 or later.
+ * See the COPYING file in the top-level directory.
+ */
+#ifndef QEMU_CAMERA_INT_H
+#define QEMU_CAMERA_INT_H
+
+void qemu_camera_alloc_image(QEMUCamera *camera, size_t size, Error **errp);
+void qemu_camera_free_image(QEMUCamera *camera);
+void qemu_camera_new_image(QEMUCamera *camera, const void *addr, size_t size);
+
+#endif /* QEMU_CAMERA_INT_H */
camera/camera.c new file +522 -0

522 lines not on this page · raw message

camera/meson.build new file +16 -0
new file mode 100644
index 0000000000..d50ee5ebf7
@@ -0,0 +1,16 @@
+camera_ss.add([files(
+  'camera.c',
+)])
+
+camera_modules = {}
+foreach m : [
+  ['builtin', cairo, files('builtin.c')],
+]
+  if m[1].found()
+    module_ss = ss.source_set()
+    module_ss.add(m[1], m[2])
+    camera_modules += {m[0] : module_ss}
+  endif
+endforeach
+
+modules += {'camera': camera_modules}
camera/trace-events new file +24 -0
new file mode 100644
index 0000000000..2f4d93e924
@@ -0,0 +1,24 @@
+# See docs/devel/tracing.rst for syntax documentation.
+
+# camera.c
+qemu_camera_new(const char *dev, char *typename) "%s: new camera with type %s"
+qemu_camera_del(const char *dev) "%s: delete camera"
+qemu_camera_set_control(const char *dev, const char *type, int value) "%s: set control type %s, value %d"
+qemu_camera_stream_on(const char *dev) "%s: stream on"
+qemu_camera_stream_off(const char *dev) "%s: stream off"
+qemu_camera_stream_read(const char *dev, size_t length) "%s: stream read length %ld"
+qemu_camera_alloc_image(const char *dev, size_t size) "%s: alloc image size %ld"
+qemu_camera_free_image(const char *dev) "%s: free image size"
+qemu_camera_new_image(const char *dev, uint32_t seq, size_t size) "%s: new image sequence %u, size %ld"
+qemu_camera_enum_pixel_format(const char *dev, uint32_t pixfmt) "%s: pixfmt 0x%x"
+qemu_camera_enum_pixel_format_ret(const char *dev, int ret) "%s: ret %d"
+qemu_camera_enum_frame_size_d(const char *dev, uint32_t pixfmt, uint32_t w, uint32_t h) "%s: pixfmt 0x%x, discrete width %u, height %u"
+qemu_camera_enum_frame_size_ret(const char *dev, int ret) "%s: ret %d"
+qemu_camera_enum_frame_interval_d(const char *dev, uint32_t pixfmt, uint32_t w, uint32_t h, uint32_t n, uint32_t d) "%s: pixfmt 0x%x, width %u, height %u, discrete numerator %u, denominator %u"
+qemu_camera_enum_frame_interval_ret(const char *dev, int ret) "%s: ret %d"
+qemu_camera_set_frame_interval(const char *dev, uint32_t pixfmt, uint32_t w, uint32_t h, uint32_t n, uint32_t d, int ret) "%s: pixfmt 0x%x, width %u, height %u, discrete numerator %u, denominator %u, retval %d"
+qemu_camera_enum_control(const char *dev, const char *type, int def, int min, int max, int step) "%s: type %s, def %d, min %d, max %d, step %d"
+qemu_camera_enum_control_ret(const char *dev, int ret) "%s: ret %d"
+
+# builtin.c
+camera_builtin_timer(const char *dev) "%s: new image"
camera/trace.h new file +1 -0
new file mode 100644
index 0000000000..f248af5c9b
@@ -0,0 +1 @@
+#include "trace/trace-camera.h"
include/camera/camera.h new file +238 -0

238 lines not on this page · raw message

meson.build +19 -1
index 886f0a9343..f0b51a0861 100644
@@ -423,6 +423,13 @@ if 'ust' in get_option('trace_backends')
   lttng = dependency('lttng-ust', required: true, method: 'pkg-config',
                      kwargs: static_kwargs)
 endif
+
+cairo = not_found
+if have_system
+  cairo = dependency('cairo', required: have_system,
+                     method: 'pkg-config', kwargs: static_kwargs)
+endif
+
 pixman = not_found
 if have_system or have_tools
   pixman = dependency('pixman-1', required: have_system, version:'>=0.21.8',
@@ -1452,6 +1459,7 @@ config_host_data.set('HOST_' + host_arch.to_upper(), 1)
 
 config_host_data.set('CONFIG_ATTR', libattr.found())
 config_host_data.set('CONFIG_BRLAPI', brlapi.found())
+config_host_data.set('CONFIG_CAIRO', cairo.found())
 config_host_data.set('CONFIG_COCOA', cocoa.found())
 config_host_data.set('CONFIG_FUZZ', get_option('fuzzing'))
 config_host_data.set('CONFIG_GCOV', get_option('b_coverage'))
@@ -2395,6 +2403,7 @@ genh += hxdep
 authz_ss = ss.source_set()
 blockdev_ss = ss.source_set()
 block_ss = ss.source_set()
+camera_ss = ss.source_set()
 chardev_ss = ss.source_set()
 common_ss = ss.source_set()
 common_user_ss = ss.source_set()
@@ -2453,6 +2462,7 @@ if have_system
     'audio',
     'backends',
     'backends/tpm',
+    'camera',
     'chardev',
     'ebpf',
     'hw/9pfs',
@@ -2572,6 +2582,7 @@ endif
 
 subdir('audio')
 subdir('io')
+subdir('camera')
 subdir('chardev')
 subdir('fsdev')
 subdir('dump')
@@ -2848,6 +2859,13 @@ libchardev = static_library('chardev', chardev_ss.sources() + genh,
 
 chardev = declare_dependency(link_whole: libchardev)
 
+camera_ss = camera_ss.apply(config_host, strict: false)
+libcamera = static_library('camera', camera_ss.sources() + genh,
+                           name_suffix: 'fa',
+                           build_by_default: false)
+
+camera = declare_dependency(link_whole: libcamera)
+
 hwcore_ss = hwcore_ss.apply(config_host, strict: false)
 libhwcore = static_library('hwcore', sources: hwcore_ss.sources() + genh,
                            name_suffix: 'fa',
@@ -2867,7 +2885,7 @@ foreach m : block_mods + softmmu_mods
                 install_dir: qemu_moddir)
 endforeach
 
-softmmu_ss.add(authz, blockdev, chardev, crypto, io, qmp)
+softmmu_ss.add(authz, blockdev, camera, chardev, crypto, io, qmp)
 common_ss.add(qom, qemuutil)
 
 common_ss.add_all(when: 'CONFIG_SOFTMMU', if_true: [softmmu_ss])
meson_options.txt +3 -0
index 921967eddb..d51729441a 100644
@@ -208,3 +208,6 @@ option('fdt', type: 'combo', value: 'auto',
 
 option('selinux', type: 'feature', value: 'auto',
        description: 'SELinux support in qemu-nbd')
+
+option('camera', type: 'feature', value: 'auto',
+       description: 'Camera subsystem support')
qapi/camera.json new file +84 -0

84 lines not on this page · raw message

qapi/meson.build +1 -0
index c0c49c15e4..404eb2e573 100644
@@ -59,6 +59,7 @@ if have_system
     'rdma',
     'rocker',
     'tpm',
+    'camera',
   ]
 endif
 if have_system or have_tools
qapi/qapi-schema.json +1 -0
index 4912b9744e..58afb77639 100644
@@ -93,3 +93,4 @@
 { 'include': 'audio.json' }
 { 'include': 'acpi.json' }
 { 'include': 'pci.json' }
+{ 'include': 'camera.json' }
qemu-options.hx +10 -0
index 7d47510947..fa439134dc 100644
@@ -3529,6 +3529,16 @@ The available backends are:
     traffic identified by a name (preferably a fqdn).
 ERST
 
+DEFHEADING(Camera device options:)
+
+DEF("cameradev", HAS_ARG, QEMU_OPTION_cameradev,
+    "-cameradev help\n"
+#ifdef CONFIG_CAIRO
+    "-cameradev builtin,id=id[,debug=true|false][,fps=FPS][,width=WIDTH][,height=HEIGHT][,mjpeg=true|false][,yuv=true|false][,rgb565=true|false][,bgcolor=blue|gree|red|rainbow|digital-rain]\n"
+#endif
+    , QEMU_ARCH_ALL
+)
+
 DEFHEADING()
 
 #ifdef CONFIG_TPM
softmmu/vl.c +4 -0
index 620a1f1367..3c5f483355 100644
@@ -94,6 +94,7 @@
 #ifdef CONFIG_VIRTFS
 #include "fsdev/qemu-fsdev.h"
 #endif
+#include "camera/camera.h"
 #include "sysemu/qtest.h"
 
 #include "disas/disas.h"
@@ -3244,6 +3245,9 @@ void qemu_init(int argc, char **argv, char **envp)
                              qemu_opt_get(opts, "mount_tag"), &error_abort);
                 break;
             }
+            case QEMU_OPTION_cameradev:
+                qemu_camera_new_from_opts(optarg);
+                break;
             case QEMU_OPTION_serial:
                 add_device_config(DEV_SERIAL, optarg);
                 default_serial = 0;
Signature · 1 line
2.25.1
author
#2 lore raw

PATCH 2/5 camera: v4l2: Introduce v4l2 camera driver

In reply to zhenwei pi

On a Linux platform, user process could accesses /dev/videoX to capture video frames.

We can run QEMU like this:
qemu-system-x86_64 ... -cameradev v4l2,path=/dev/video0,id=camera0

The basic logic of v4l2 driver:
stream on -> qbuf -> dqbuf(drive by POLLIN event) -> qbuf -> dqbuf

     ... -> stream off
---
 camera/meson.build  |   4 +
 camera/trace-events |   4 +
 camera/v4l2.c       | 637 ++++++++++++++++++++++++++++++++++++++++++++
 qapi/camera.json    |  21 +-
 qemu-options.hx     |   3 +
 5 files changed, 667 insertions(+), 2 deletions(-)
 create mode 100644 camera/v4l2.c
camera/meson.build +4 -0
index d50ee5ebf7..6e7aeb5ebd 100644
@@ -2,6 +2,10 @@ camera_ss.add([files(
   'camera.c',
 )])
 
+camera_ss.add(when: 'CONFIG_LINUX', if_true: files(
+  'v4l2.c',
+))
+
 camera_modules = {}
 foreach m : [
   ['builtin', cairo, files('builtin.c')],
camera/trace-events +4 -0
index 2f4d93e924..4527303d58 100644
@@ -22,3 +22,7 @@ qemu_camera_enum_control_ret(const char *dev, int ret) "%s: ret %d"
 
 # builtin.c
 camera_builtin_timer(const char *dev) "%s: new image"
+
+# v4l2.c
+camera_v4l2_qbuf(const char *dev, uint32_t index) "%s: qbuf index %u"
+camera_v4l2_dqbuf(const char *dev, uint32_t index) "%s: qbuf index %u"
camera/v4l2.c new file +637 -0

637 lines not on this page · raw message

qapi/camera.json +19 -2
index 2c8314ba4a..763f7f0c57 100644
@@ -9,6 +9,22 @@
 # = Camera
 ##
 
+##
+# @CameraV4l2Options:
+#
+# Options of the v4l2 camera.
+#
+# @path: video capture device path
+#
+# @buffers: buffer count of v4l2 driver
+#
+# Since: 6.3
+##
+{ 'struct': 'CameraV4l2Options',
+  'data': {
+    '*path': 'str',
+    '*buffers': 'uint32' } }
+
 ##
 # @ColorType:
 #
@@ -62,7 +78,7 @@
 # Since: 6.3
 ##
 { 'enum': 'CameradevDriver',
-  'data': [ 'builtin' ] }
+  'data': [ 'builtin', 'v4l2' ] }
 
 ##
 # @Cameradev:
@@ -81,4 +97,5 @@
     'driver':      'CameradevDriver'},
   'discriminator': 'driver',
   'data': {
-    'builtin':     'CameraBuiltinOptions' } }
+    'builtin':     'CameraBuiltinOptions',
+    'v4l2':        'CameraV4l2Options' } }
qemu-options.hx +3 -0
index fa439134dc..60975d6c3d 100644
@@ -3535,6 +3535,9 @@ DEF("cameradev", HAS_ARG, QEMU_OPTION_cameradev,
     "-cameradev help\n"
 #ifdef CONFIG_CAIRO
     "-cameradev builtin,id=id[,debug=true|false][,fps=FPS][,width=WIDTH][,height=HEIGHT][,mjpeg=true|false][,yuv=true|false][,rgb565=true|false][,bgcolor=blue|gree|red|rainbow|digital-rain]\n"
+#endif
+#ifdef CONFIG_LINUX
+    "-cameradev v4l2,id=id[,path=PATH][,buffers=COUNT]\n"
 #endif
     , QEMU_ARCH_ALL
 )
Signature · 1 line
2.25.1
author
#3 lore raw

PATCH 3/5 usb: Introduce video&mescellaneous

In reply to zhenwei pi

Define USB class code for video&mescellaneous.

---
 include/hw/usb.h | 2 ++
 1 file changed, 2 insertions(+)
include/hw/usb.h +2 -0
index 33668dd0a9..8e3d30b9f4 100644
@@ -77,9 +77,11 @@
 #define USB_CLASS_PRINTER		7
 #define USB_CLASS_MASS_STORAGE		8
 #define USB_CLASS_HUB			9
+#define USB_CLASS_VIDEO                 0xe
 #define USB_CLASS_CDC_DATA		0x0a
 #define USB_CLASS_CSCID			0x0b
 #define USB_CLASS_CONTENT_SEC		0x0d
+#define USB_CLASS_MISCELLANEOUS         0xef
 #define USB_CLASS_APP_SPEC		0xfe
 #define USB_CLASS_VENDOR_SPEC		0xff
 
Signature · 1 line
2.25.1
author
#4 lore raw

PATCH 4/5 usb: allow max 8192 bytes for desc

In reply to zhenwei pi

A device of USB video class usually uses larger desc structure, so use larger buffer to avoid failure.

---
 hw/usb/desc.c | 15 ++++++++-------
 hw/usb/desc.h |  1 +
 2 files changed, 9 insertions(+), 7 deletions(-)
hw/usb/desc.c +8 -7
index 8b6eaea407..7f6cc2f99b 100644
@@ -632,7 +632,8 @@ int usb_desc_get_descriptor(USBDevice *dev, USBPacket *p,
     bool msos = (dev->flags & (1 << USB_DEV_FLAG_MSOS_DESC_IN_USE));
     const USBDesc *desc = usb_device_get_usb_desc(dev);
     const USBDescDevice *other_dev;
-    uint8_t buf[256];
+    size_t buflen = USB_DESC_MAX_LEN;
+    g_autofree uint8_t *buf = g_malloc(buflen);
     uint8_t type = value >> 8;
     uint8_t index = value & 0xff;
     int flags, ret = -1;
@@ -650,36 +651,36 @@ int usb_desc_get_descriptor(USBDevice *dev, USBPacket *p,
 
     switch(type) {
     case USB_DT_DEVICE:
-        ret = usb_desc_device(&desc->id, dev->device, msos, buf, sizeof(buf));
+        ret = usb_desc_device(&desc->id, dev->device, msos, buf, buflen);
         trace_usb_desc_device(dev->addr, len, ret);
         break;
     case USB_DT_CONFIG:
         if (index < dev->device->bNumConfigurations) {
             ret = usb_desc_config(dev->device->confs + index, flags,
-                                  buf, sizeof(buf));
+                                  buf, buflen);
         }
         trace_usb_desc_config(dev->addr, index, len, ret);
         break;
     case USB_DT_STRING:
-        ret = usb_desc_string(dev, index, buf, sizeof(buf));
+        ret = usb_desc_string(dev, index, buf, buflen);
         trace_usb_desc_string(dev->addr, index, len, ret);
         break;
     case USB_DT_DEVICE_QUALIFIER:
         if (other_dev != NULL) {
-            ret = usb_desc_device_qualifier(other_dev, buf, sizeof(buf));
+            ret = usb_desc_device_qualifier(other_dev, buf, buflen);
         }
         trace_usb_desc_device_qualifier(dev->addr, len, ret);
         break;
     case USB_DT_OTHER_SPEED_CONFIG:
         if (other_dev != NULL && index < other_dev->bNumConfigurations) {
             ret = usb_desc_config(other_dev->confs + index, flags,
-                                  buf, sizeof(buf));
+                                  buf, buflen);
             buf[0x01] = USB_DT_OTHER_SPEED_CONFIG;
         }
         trace_usb_desc_other_speed_config(dev->addr, index, len, ret);
         break;
     case USB_DT_BOS:
-        ret = usb_desc_bos(desc, buf, sizeof(buf));
+        ret = usb_desc_bos(desc, buf, buflen);
         trace_usb_desc_bos(dev->addr, len, ret);
         break;
 
hw/usb/desc.h +1 -0
index 3ac604ecfa..35babdeff6 100644
@@ -199,6 +199,7 @@ struct USBDesc {
     const USBDescMSOS         *msos;
 };
 
+#define USB_DESC_MAX_LEN    8192
 #define USB_DESC_FLAG_SUPER (1 << 1)
 
 /* little helpers */
Signature · 1 line
2.25.1
#5 lore raw

Re: [PATCH 4/5] usb: allow max 8192 bytes for desc

Quoted 14 lines · zhenwei pi

A device of USB video class usually uses larger desc structure, so use larger buffer to avoid failure.

---
  hw/usb/desc.c | 15 ++++++++-------
  hw/usb/desc.h |  1 +
  2 files changed, 9 insertions(+), 7 deletions(-)
hw/usb/desc.c +0 -0
index 8b6eaea407..7f6cc2f99b 100644

hw/usb/desc.c int usb_desc_get_descriptor(USBDevice *dev, USBPacket *p, · line 636

Quoted 6 lines
hw/usb/desc.c +2 -1
@@ -632,7 +632,8 @@ int usb_desc_get_descriptor(USBDevice *dev, USBPacket *p,
      bool msos = (dev->flags & (1 << USB_DEV_FLAG_MSOS_DESC_IN_USE));
      const USBDesc *desc = usb_device_get_usb_desc(dev);
      const USBDescDevice *other_dev;
-    uint8_t buf[256];
+    size_t buflen = USB_DESC_MAX_LEN;
+    g_autofree uint8_t *buf = g_malloc(buflen);

Do we want to have a per-device desc_size (in USBDevice, default to 256, video devices set it to 8K)?

How "hot" is this path? Could we keep 8K on the stack?

Quoted 12 lines
hw/usb/desc.h +1 -0
index 3ac604ecfa..35babdeff6 100644
@@ -199,6 +199,7 @@ struct USBDesc {
      const USBDescMSOS         *msos;
  };
 
+#define USB_DESC_MAX_LEN    8192
  #define USB_DESC_FLAG_SUPER (1 << 1)
 
  /* little helpers */
author
#6 lore raw

Re: Re: [PATCH 4/5] usb: allow max 8192 bytes for desc

Quoted 26 lines · Philippe Mathieu-Daudé
Quoted 14 lines · zhenwei pi

A device of USB video class usually uses larger desc structure, so use larger buffer to avoid failure.

---
  hw/usb/desc.c | 15 ++++++++-------
  hw/usb/desc.h |  1 +

  2 files changed, 9 insertions(+), 7 deletions(-)
hw/usb/desc.c +0 -0
index 8b6eaea407..7f6cc2f99b 100644

hw/usb/desc.c int usb_desc_get_descriptor(USBDevice *dev, · line 637

Quoted 7 lines
hw/usb/desc.c +2 -1
@@ -632,7 +632,8 @@ int usb_desc_get_descriptor(USBDevice *dev, 
 USBPacket *p,
       bool msos = (dev->flags & (1 << USB_DEV_FLAG_MSOS_DESC_IN_USE));
       const USBDesc *desc = usb_device_get_usb_desc(dev);
       const USBDescDevice *other_dev;
-    uint8_t buf[256];
+    size_t buflen = USB_DESC_MAX_LEN;
+    g_autofree uint8_t *buf = g_malloc(buflen);

Do we want to have a per-device desc_size (in USBDevice, default to 256, video devices set it to 8K)?

Quoted 2 lines

How "hot" is this path? Could we keep 8K on the stack?

It's an unlikely code path:
1, During guest startup, guest tries to probe device. 2, run 'lsusb' command in guest

Keeping 8K on the stack also seems OK.

Quoted 11 lines
Quoted 10 lines
hw/usb/desc.h +1 -0
index 3ac604ecfa..35babdeff6 100644
@@ -199,6 +199,7 @@ struct USBDesc {
       const USBDescMSOS         *msos;
   };
+#define USB_DESC_MAX_LEN    8192
   #define USB_DESC_FLAG_SUPER (1 << 1)
   /* little helpers */
Signature · 1 line
zhenwei pi
#7 lore raw

Re: [PATCH 4/5] usb: allow max 8192 bytes for desc

Quoted 28 lines · zhenwei pi
Quoted 26 lines · Philippe Mathieu-Daudé
Quoted 14 lines · zhenwei pi

A device of USB video class usually uses larger desc structure, so use larger buffer to avoid failure.

---
  hw/usb/desc.c | 15 ++++++++-------
  hw/usb/desc.h |  1 +

  2 files changed, 9 insertions(+), 7 deletions(-)
hw/usb/desc.c +0 -0
index 8b6eaea407..7f6cc2f99b 100644

hw/usb/desc.c int usb_desc_get_descriptor(USBDevice *dev, · line 637

Quoted 7 lines
hw/usb/desc.c +2 -1
@@ -632,7 +632,8 @@ int usb_desc_get_descriptor(USBDevice *dev,
 USBPacket *p,
       bool msos = (dev->flags & (1 << USB_DEV_FLAG_MSOS_DESC_IN_USE));
       const USBDesc *desc = usb_device_get_usb_desc(dev);
       const USBDescDevice *other_dev;
-    uint8_t buf[256];
+    size_t buflen = USB_DESC_MAX_LEN;
+    g_autofree uint8_t *buf = g_malloc(buflen);

Do we want to have a per-device desc_size (in USBDevice, default to 256, video devices set it to 8K)?

Quoted 5 lines
Quoted 2 lines

How "hot" is this path? Could we keep 8K on the stack?

It's an unlikely code path:
1, During guest startup, guest tries to probe device. 2, run 'lsusb' command in guest

If you have to respin, do you mind adding this 3 lines in the description? Anyhow:

Reviewed-by on v1 4/5
#8 lore raw

Re: [PATCH 4/5] usb: allow max 8192 bytes for desc

In reply to zhenwei pi
Quoted 8 lines · zhenwei pi

A device of USB video class usually uses larger desc structure, so use larger buffer to avoid failure.

---
 hw/usb/desc.c | 15 ++++++++-------
 hw/usb/desc.h |  1 +
 2 files changed, 9 insertions(+), 7 deletions(-)

Regards,
Daniel

Signature · 3 lines
|: https://berrange.com      -o-    https://www.flickr.com/photos/dberrange :|
|: https://libvirt.org         -o-            https://fstop138.berrange.com :|
|: https://entangle-photo.org    -o-    https://www.instagram.com/dberrange :|
author
#9 lore raw

PATCH 5/5 usb-video: Introduce USB video class

In reply to zhenwei pi

Base on UVC specification 1.5, implement UVC device emulation(camera only). Several changes in this patch:
1, define types and structures(in include/hw/usb/video.h) 2, a camera device with UVC chain: OT 3 <- PU 5 <- SU 4 <- IT
a, video control descriptor. (auto-detected bmControl in PU) b, video streaming descriptor. (auto-detected pixel format,
frame size and frame interval, build .descs dynamicly during .realize)
c, standard VS isochronous video data endpoint
3, support data payload without PresentationTime & scrSourceClock. 4, support brightness, hue ... control settings.
5, support control status interrupt.

Test guest Ubuntu-2004 desktop:
1, several applications: cheese, kamoso, guvcview, qcam(self-built
from libcamera source code), all work fine.
2, both builtin and v4l2 driver work fine.

---
 docs/system/devices/usb.rst |    3 +
 hw/usb/Kconfig              |    5 +
 hw/usb/dev-video.c          | 1395 +++++++++++++++++++++++++++++++++++
 hw/usb/meson.build          |    1 +
 hw/usb/trace-events         |   11 +
 include/hw/usb/video.h      |  303 ++++++++
 6 files changed, 1718 insertions(+)
 create mode 100644 hw/usb/dev-video.c
 create mode 100644 include/hw/usb/video.h
docs/system/devices/usb.rst +3 -0
index afb7d6c226..bf84e3e3d9 100644
@@ -199,6 +199,9 @@ option or the ``device_add`` monitor command. Available devices are:
 ``u2f-{emulated,passthru}``
    Universal Second Factor device
 
+``usb-video``
+   USB video device
+
 Physical port addressing
 ^^^^^^^^^^^^^^^^^^^^^^^^
 
hw/usb/Kconfig +5 -0
index 53f8283ffd..1355db7989 100644
@@ -133,3 +133,8 @@ config XLNX_USB_SUBSYS
     bool
     default y if XLNX_VERSAL
     select USB_DWC3
+
+config USB_VIDEO
+    bool
+    default y
+    depends on USB
hw/usb/dev-video.c new file +1395 -0

1,395 lines not on this page · raw message

hw/usb/meson.build +1 -0
index de853d780d..7706e7088e 100644
@@ -44,6 +44,7 @@ softmmu_ss.add(when: 'CONFIG_USB_STORAGE_UAS', if_true: files('dev-uas.c'))
 softmmu_ss.add(when: 'CONFIG_USB_AUDIO', if_true: files('dev-audio.c'))
 softmmu_ss.add(when: 'CONFIG_USB_SERIAL', if_true: files('dev-serial.c'))
 softmmu_ss.add(when: 'CONFIG_USB_NETWORK', if_true: files('dev-network.c'))
+softmmu_ss.add(when: 'CONFIG_USB_VIDEO', if_true: files('dev-video.c'))
 softmmu_ss.add(when: ['CONFIG_POSIX', 'CONFIG_USB_STORAGE_MTP'], if_true: files('dev-mtp.c'))
 
 # smartcard
hw/usb/trace-events +11 -0
index b8287b63f1..f250da29bd 100644
@@ -345,3 +345,14 @@ usb_serial_set_baud(int bus, int addr, int baud) "dev %d:%u baud rate %d"
 usb_serial_set_data(int bus, int addr, int parity, int data, int stop) "dev %d:%u parity %c, data bits %d, stop bits %d"
 usb_serial_set_flow_control(int bus, int addr, int index) "dev %d:%u flow control %d"
 usb_serial_set_xonxoff(int bus, int addr, uint8_t xon, uint8_t xoff) "dev %d:%u xon 0x%x xoff 0x%x"
+
+# dev-video.c
+usb_video_handle_reset(int bus, int addr) "dev %d:%u reset"
+usb_video_pu(int bus, int addr, int selector, int size, int def, int min, int max, int step) "dev %d:%u build PU control selector %d, size %d, def %d, min %d, max %d, step %d"
+usb_video_handle_streaming_in(int bus, int addr, int len) "dev %d:%u streaming in %d"
+usb_video_handle_control_in(int bus, int addr, int len) "dev %d:%u streaming in %d"
+usb_video_set_interface(int bus, int addr, int iface, int value) "dev %d:%u set iface %d with value %d"
+usb_video_get_control(int bus, int addr, int intfnum, int unit, int cs, int retval) "dev %d:%u get control iface %d, unit %d, cs %d, retval %d"
+usb_video_set_control(int bus, int addr, int intfnum, int cs, int retval) "dev %d:%u set control iface %d, cs %d, retval %d"
+usb_video_handle_control_error(int bus, int addr, int request, int value, int index, int length) "dev %d:%u handle control error, request 0x%x, value 0x%x, index 0x%x, length 0x%x"
+usb_video_queue_control_status(int bus, int addr, uint8_t bOriginator, uint8_t bSelector, uint32_t value, uint8_t size) "dev %d:%u queue control status, originator %d, selector %d, value(le32) 0x%x, size %d"
include/hw/usb/video.h new file +303 -0

303 lines not on this page · raw message

Signature · 1 line
2.25.1
#10 lore raw
In reply to zhenwei pi
Quoted 45 lines · zhenwei pi

1, The full picture of this patch set:

   +---------+       +------------+     +---------------+
   |UVC(done)|       |virtio(TODO)|     |other HW device|
   +---------+       +------------+     +---------------+
         |                 |                     |
         |            +------------+             |
	 +------------+camera(done)+-------------+
                      +----+-------+
                           |
         +-----------------+---------------------+
         |                 |                     |
  +------+------+     +----+-----+        +------+------+
  |builtin(done)|     |v4l2(done)|        |other drivers|
  +-------------+     +----------+        +-------------+

With this patch set, We can run a desktop VM (Ex Ubuntu-2004), several camera APPs(cheese, kamoso, guvcview and qcam) work fine.

Some works still in working:
1, hot-plug
2, compat with live migration
3, several actions defined in UVC SPEC

Zhenwei Pi (5):
camera: Introduce camera subsystem and builtin driver
camera: v4l2: Introduce v4l2 camera driver
usb: Introduce video&mescellaneous
usb: allow max 8192 bytes for desc
usb-video: Introduce USB video class

 camera/builtin.c        |  717 ++++++++++++++++++++
 camera/camera-int.h     |   19 +
 camera/camera.c         |  522 +++++++++++++++
 camera/meson.build      |   20 +
 camera/trace-events     |   28 +
 camera/trace.h          |    1 +
 camera/v4l2.c           |  637 ++++++++++++++++++
 hw/usb/Kconfig          |    5 +
 hw/usb/desc.c           |   15 +-
 hw/usb/desc.h           |    1 +
 hw/usb/dev-video.c      | 1395 +++++++++++++++++++++++++++++++++++++++
 hw/usb/meson.build      |    1 +
 hw/usb/trace-events     |   11 +
 include/camera/camera.h |  238 +++++++
 include/hw/usb.h        |    2 +
Quoted 8 lines
 include/hw/usb/video.h  |  303 +++++++++
 meson.build             |   20 +-
 meson_options.txt       |    3 +
 qapi/camera.json        |  101 +++
 qapi/meson.build        |    1 +
 qapi/qapi-schema.json   |    1 +
 qemu-options.hx         |   13 +
 softmmu/vl.c            |    4 +

There's no MAINTAINERS file update here.

As a general rule, if you are introducing an entire new subsystem into the QEMU codebase, it is expected someone will be nominated as the maintainer for the new subsystem. Usually the person adding it will themselves volunteer to be the maintainer.

Regards,
Daniel

Signature · 3 lines
|: https://berrange.com      -o-    https://www.flickr.com/photos/dberrange :|
|: https://libvirt.org         -o-            https://fstop138.berrange.com :|
|: https://entangle-photo.org    -o-    https://www.instagram.com/dberrange :|
author
#11 lore raw
Quoted 57 lines · Daniel P. Berrangé
Quoted 45 lines · zhenwei pi

1, The full picture of this patch set:

    +---------+       +------------+     +---------------+
    |UVC(done)|       |virtio(TODO)|     |other HW device|
    +---------+       +------------+     +---------------+
          |                 |                     |
          |            +------------+             |
	 +------------+camera(done)+-------------+
                       +----+-------+
                            |
          +-----------------+---------------------+
          |                 |                     |
   +------+------+     +----+-----+        +------+------+
   |builtin(done)|     |v4l2(done)|        |other drivers|
   +-------------+     +----------+        +-------------+

With this patch set, We can run a desktop VM (Ex Ubuntu-2004), several camera APPs(cheese, kamoso, guvcview and qcam) work fine.

Some works still in working:
1, hot-plug
2, compat with live migration
3, several actions defined in UVC SPEC

Zhenwei Pi (5):
camera: Introduce camera subsystem and builtin driver
camera: v4l2: Introduce v4l2 camera driver
usb: Introduce video&mescellaneous
usb: allow max 8192 bytes for desc
usb-video: Introduce USB video class

  camera/builtin.c        |  717 ++++++++++++++++++++
  camera/camera-int.h     |   19 +
  camera/camera.c         |  522 +++++++++++++++
  camera/meson.build      |   20 +
  camera/trace-events     |   28 +
  camera/trace.h          |    1 +
  camera/v4l2.c           |  637 ++++++++++++++++++
  hw/usb/Kconfig          |    5 +
  hw/usb/desc.c           |   15 +-
  hw/usb/desc.h           |    1 +
  hw/usb/dev-video.c      | 1395 +++++++++++++++++++++++++++++++++++++++
  hw/usb/meson.build      |    1 +
  hw/usb/trace-events     |   11 +
  include/camera/camera.h |  238 +++++++
  include/hw/usb.h        |    2 +
Quoted 8 lines
  include/hw/usb/video.h  |  303 +++++++++
  meson.build             |   20 +-
  meson_options.txt       |    3 +
  qapi/camera.json        |  101 +++
  qapi/meson.build        |    1 +
  qapi/qapi-schema.json   |    1 +
  qemu-options.hx         |   13 +
  softmmu/vl.c            |    4 +

There's no MAINTAINERS file update here.

Quoted 8 lines

As a general rule, if you are introducing an entire new subsystem into the QEMU codebase, it is expected someone will be nominated as the maintainer for the new subsystem. Usually the person adding it will themselves volunteer to be the maintainer.

Regards,
Daniel

OK, thanks. I have a plan to add two parts in next version:
1, camera subsystem, include folder qemu/camera and qemu/include/camera/ 2, UVC, include qemu/hw/usb/dev-video.c and qemu/include/hw/usb/video.h

Signature · 1 line
zhenwei pi