uvc — USB webcam output

[中文]

On boards whose build enables native USB-device UVC, CDC, MSC and UVC are exposed together at startup. Open the ESP-VISION Camera in a host webcam application. If no application image is available, firmware generates a monochrome ESP mark as a JPEG at the selected mode’s dimensions. Opening UVC does not initialize or reconfigure sensor. This module is not enabled on every board.

The released fallback profile advertises one MJPEG mode: 320×240 at 10 FPS, using isochronous transport. JPEG frames must fit within 48 KiB. Target mode tables are opt-in and disabled by default. Their first entry preserves 320×240 at 10 FPS. Configured screen candidates include 240×240 on P4X-EYE and S3-EYE and 1024×600 on P4X Function EV Board. Mosaico candidates include a 480×480 screen-sized target and a 640×480 configured raw-input target, each at 10, 20 and 30 FPS. P4 candidates follow their configured 1280×720 raw-input size. P4X-VISION and AtomS3R-M12 board configuration defines no LCD size, so their tables add no screen candidate. The configured sizes describe the UVC modes offered to the host and may differ from the sensor’s physical limits. At runtime, all UVC builds accept input images whose dimensions differ from the advertised mode, but host compatibility for mismatched dimensions is not guaranteed. Actual delivery also depends on host scheduling and concurrent USB traffic. get_mode() reports the mode selected by the host; is_streaming() reports whether the host enabled the streaming interface, not whether a particular application displayed a frame.

UVC keeps one lazily allocated PSRAM buffer for application frames, capped at 48 KiB by the current profiles. The source image or encoder buffer can be reused after a successful call because UVC copies the JPEG into its own buffer. While TinyUSB is sending that application frame, another application frame cannot replace it; the frame remains owned until transfer completion or confirmed cancellation. The generated ESP mark is a separate fallback source, not a second application-frame queue slot.

Boards with candidate tables require both MICROPY_HW_USB_UVC_ENABLE_TARGET_MODES=1 and MICROPY_HW_USB_UVC_MODE_TABLE_CAPABLE=1 to enable the experimental modes. The P4X-EYE table includes 320×240, 240×240 and 1280×720 at 10, 20 and 30 FPS. Check host compatibility with the specific firmware, camera workload and USB connection before enabling these modes in a release.

uvc.write(img)

Publish a processed image.Image. Runtime accepts input dimensions that differ from the advertised UVC mode; hosts may reject or mishandle mismatched frames. Returns False if the host stream is inactive or an application frame is still in flight, and True once the JPEG has been copied into UVC’s independent buffer. Acceptance does not acknowledge host receipt. RGB565, grayscale and JPEG inputs use the shared JPEG path. Invalid inputs or oversized encoded frames raise ValueError; encoding/allocation failures raise OSError. Camera buffers may be reused immediately after return. A pending frame may be replaced, but an in-flight frame is never overwritten.

uvc.set_frame(img)

Copy a fixed image only while the host has an active UVC stream. Runtime accepts dimensions that differ from the advertised mode, without a host compatibility guarantee. On success, detach the preview source and repeat the copied frame until replaced or reset. Return False if the stream is inactive or the application buffer is still in flight. Disconnect clears the fixed frame and returns output to the generated ESP mark. Failed updates preserve the previous source.

uvc.bind(source)

Bind "preview" to processed images published by img.flush(). UVC works without an IDE session. Runtime accepts preview images whose dimensions differ from the advertised UVC mode, but host compatibility is not guaranteed. Oversized frames or UVC allocation failures are dropped without blocking EV-MUX. None detaches the preview source and returns output to the generated ESP mark until another application frame is supplied.

uvc.reset()

Detach the source and return output to the generated monochrome ESP mark. This does not reset the USB controller or disconnect CDC/MSC. VM soft reset also clears the source. A stopped or idle live producer otherwise leaves its last frame repeating.

uvc.is_streaming()

Return whether the host has enabled streaming and the USB bus is not suspended.

uvc.get_mode()

Return the mode selected by the host. Before negotiation, the released fallback and every opt-in table start at {"format": "MJPEG", "width": 320, "height": 240, "interval_us": 100000}. The selected size may differ after the host commits another advertised mode.

uvc.set_mode_callback(callback)

Register a callable to receive a dictionary with the same fields as get_mode() after each successful host Commit. If a Commit already occurred, registration schedules the latest committed mode once. The callback is deferred to the MicroPython VM task; it never runs inside the USB callback. If several Commit events arrive before the VM dispatches them, only the newest mode is delivered. Callback exceptions are reported by MicroPython and do not change the USB Commit result. Pass None to unregister. Soft reset clears the callback; uvc.reset() only changes the frame source.

Examples

IDE and UVC preview. Draw on each QVGA camera frame and publish it via img.flush().

import sensor
import uvc

sensor.reset()
sensor.set_pixformat(sensor.RGB565)
sensor.set_framesize(sensor.QVGA)
sensor.skip_frames(time=1000)
uvc.bind("preview")
try:
    while True:
        img = sensor.snapshot()
        img.draw_string(8, 8, "ESP-VISION UVC", color=(255, 0, 0), scale=2)
        # JPEG is encoded once and independently offered to UVC and EV-MUX.
        img.flush()
finally:
    uvc.reset()

Direct camera output. Select 320×240 in the host app. The script opens the camera on demand and retries each encoded JPEG briefly while UVC is busy.

"""Stream the camera directly to UVC at the default 320x240 mode."""

import image
import sensor
import time
import uvc


def stream_camera():
    sensor.reset()
    try:
        sensor.set_pixformat(sensor.RGB565)
        sensor.set_framesize(sensor.QVGA)
        sensor.skip_frames(time=350)
        while uvc.is_streaming():
            frame = sensor.snapshot()
            jpeg = frame.to_jpeg(quality=45, subsampling=image.JPEG_SUBSAMPLING_422, copy=True)
            if jpeg.size() > 48 * 1024:
                continue

            # Retry the same JPEG briefly if the previous frame is still in flight.
            deadline = time.ticks_add(time.ticks_ms(), 120)
            while uvc.is_streaming():
                if uvc.write(jpeg) or time.ticks_diff(deadline, time.ticks_ms()) <= 0:
                    break
                time.sleep_ms(1)
    finally:
        sensor.shutdown(True)


uvc.reset()
try:
    while True:
        if uvc.is_streaming():
            stream_camera()
        else:
            time.sleep_ms(25)
finally:
    uvc.reset()

Watch mode negotiation. Print the dimensions and frame interval committed by the host.

"""Log the mode selected by the UVC host after a successful Commit."""

import time
import uvc


def on_mode(mode):
    print("UVC mode:", mode["width"], mode["height"], mode["interval_us"])


uvc.set_mode_callback(on_mode)
try:
    while True:
        time.sleep_ms(1000)
finally:
    # This unregisters the callback; uvc.reset() only resets the frame source.
    uvc.set_mode_callback(None)

Fixed color chart. Generate a picture at the negotiated size and publish one fixed image per stream with uvc.set_frame(). A camera image can be used in its place.

"""Display a generated color chart as a fixed UVC picture."""

import image
import time
import uvc


def publish_color_chart():
    mode = uvc.get_mode()
    width, height = mode["width"], mode["height"]
    colors = (
        (255, 255, 255),
        (255, 255, 0),
        (0, 255, 255),
        (0, 255, 0),
        (255, 0, 255),
        (255, 0, 0),
        (0, 0, 255),
    )
    frame = image.Image(width, height, image.RGB565)
    for i, color in enumerate(colors):
        left = width * i // len(colors)
        right = width * (i + 1) // len(colors)
        frame.draw_rectangle((left, 0, right - left, height), color=color, fill=True)

    while uvc.is_streaming():
        if uvc.set_frame(frame):
            return  # UVC repeats its own copy until the stream closes.
        time.sleep_ms(10)


uvc.reset()
try:
    while True:
        while not uvc.is_streaming():
            time.sleep_ms(25)
        publish_color_chart()
        while uvc.is_streaming():
            time.sleep_ms(25)
finally:
    uvc.reset()

App-controlled camera size. The registered callback records the negotiated dimensions and the application loop configures a matching QVGA or VGA camera mode. Select a size supported by your board’s camera and UVC table.

"""Let the application choose a matching camera size after a host Commit."""

import sensor
import time
import uvc

# Add entries for sizes that the camera can produce and the board advertises.
CAMERA_SIZES = {
    (320, 240): sensor.QVGA,
    (640, 480): sensor.VGA,
}
requested_size = None


def on_mode(mode):
    global requested_size
    requested_size = (mode["width"], mode["height"])


def still_selected(size):
    return uvc.is_streaming() and requested_size == size


def stream_mode(size):
    framesize = CAMERA_SIZES.get(size)
    if framesize is None:
        print("No camera size configured for UVC mode:", size)
        while still_selected(size):
            time.sleep_ms(25)
        return

    sensor.reset()
    try:
        sensor.set_pixformat(sensor.RGB565)
        sensor.set_framesize(framesize)
        sensor.skip_frames(time=350)
        uvc.bind("preview")
        while still_selected(size):
            sensor.snapshot().flush()
    finally:
        uvc.reset()
        sensor.shutdown(True)


uvc.reset()
uvc.set_mode_callback(on_mode)
try:
    while True:
        size = requested_size
        if size is not None and uvc.is_streaming():
            stream_mode(size)
        else:
            time.sleep_ms(25)
finally:
    uvc.set_mode_callback(None)
    uvc.reset()