nokhwa

repository·senpai·Indexed 21 days ago

https://github.com/l1npengtul/nokhwa

A simple-to-use, cross-platform Rust webcam capture library. It provides a stable API for camera capture on Linux, MacOS, and Windows via the `input-native` feature. The library includes `nokhwa-core` for foundational type definitions, a `CameraTrait` for hardware control and streaming, and a flexible decoder system supporting formats like NV12, YUY2, MJPEG, GRAY, and RGB24.

Tokens
24.5K
Snippets
91
Records
104
Agent score
74%

What's inside nokhwa

  1. Overview of nokhwa-core

    senpai

    The nokhwa-core crate provides the foundational type definitions used throughout the nokhwa ecosystem. It is designed to be a lightweight dependency that other crates can consume without pulling in the full camera capture logic.

    Key features include:

    • Standard Definitions: Core types such as Resolution, CameraInfo, CameraIndex, and CameraFormat.
    • Built-in Decoders: Support for NV12, YUY2/YUYV, MJPEG, GRAY, and RGB24 formats.
    • Extensible Decoder System: A flexible, trait-based architecture that allows developers to implement and integrate their own custom decoders.
  2. Use native Windows camera capture via nokhwa

    senpai

    The nokhwa-bindings-windows crate provides low-level MediaFoundation bindings and is not intended for direct use. For standard Windows camera capture functionality, use the main nokhwa crate with the input-native feature enabled. This provides a stable, high-level API for accessing cameras on Windows.

    [dependencies]
    nokhwa = {
        version = "0.10.11",
        features = ["input-native"]
    }
  3. Use the Capture CLI to test backend features

    senpai

    The capture command-line application is used to test the implementation of various camera backends. It allows you to verify if specific backend features are correctly implemented by interacting with them via the CLI.

    # To view available options and usage instructions
    # (Note: the README indicates '--help lol' as a placeholder/test command)
    nokhwavctl capture --help
  4. Use native MacOS camera capture via nokhwa

    senpai

    The nokhwa-bindings-macos crate provides low-level AVFoundation bindings for nokhwa. However, it is not intended for general consumption and lacks API stability guarantees.

    For standard MacOS camera capture in your projects, you should instead use the main nokhwa crate with the input-native feature enabled. This provides a stable and supported way to access native camera inputs on MacOS.

    # In your Cargo.toml, use the main nokhwa crate with the input-native feature
    nokhwa = { version = "0.10.11", features = ["input-native"] }
  5. Use native Linux camera capture with nokhwa

    senpai

    The nokhwa-bindings-linux crate provides V4L2 bindings but is not intended for direct use by end-users. For stable Linux camera capture, use the main nokhwa crate with the input-native feature enabled. This provides the necessary Linux support through the official, supported interface.

    nokhwa = { version = "0.10.11", features = ["input-native"] }
  6. Explore the `nokhwa` core module structure

    senpai

    The nokhwa-core crate provides the fundamental types and abstractions for camera interaction, video streaming, and frame processing. The public API is organized into several specialized modules:

    • camera: High-level camera management and device discovery.
    • codec: Video codec definitions and handling.
    • control: Camera control interfaces (e.g., brightness, focus).
    • decoder: Logic for decoding video streams.
    • error: Error types for the library.
    • format_request: Structures for requesting specific frame formats.
    • frame_buffer: Management of raw frame data buffers.
    • frame_format: Definitions of pixel formats and frame layouts.
    • image: Image processing and representation utilities.
    • metadata: Camera and frame metadata.
    • pixel_destination: Logic for directing pixel data to specific outputs.
    • platform: Platform-specific abstraction layers.
    • ranges: Utility for handling ranges (e.g., supported resolutions).
    • stream: Stream management and lifecycle.
    • traits: Core traits for implementing custom decoders or camera backends.
    • types: Common primitive types used across the library.
    • utils: General utility functions.
  7. Initialize and use a Camera with Nokhwa

    senpai

    The primary way to interact with webcams in Nokhwa is through the Camera struct. To use the library, you must enable at least one input-* feature (the recommended default is input-native).

    Commonly used types and modules include:

    • Camera: The main struct for capturing video.
    • init: Provides initialization logic (via pub use init::*).
    • query: Provides methods for querying available devices and capabilities.
    • nokhwa_core::frame_buffer::FrameBuffer: Used for handling captured frames.
    • NokhwaError: The standard error type for the library.

    Depending on your requirements, you can also use specialized camera types:

    • CallbackCamera: (Requires output-threaded feature) A camera that runs in a separate thread and uses callbacks to deliver frames.
    • async_camera: (Requires output-async feature) Provides asynchronous camera capabilities.
    use nokhwa::prelude::*;nokhwa::Camera;
    
    // Example conceptual usage:
    // let camera = Camera::new(index, ...)?;
    // let frame = camera.get_frame()?;
  8. Use AVFoundationCaptureDevice for macOS camera capture

    senpai

    The AVFoundationCaptureDevice struct provides a macOS-specific implementation of the CaptureTrait using Apple's AVFoundation framework.

    Important Requirements & Quirks

    • Initialization: You must call nokhwa_initialize before performing any operations with AVFoundation.
    • Platform: This backend only works on 64-bit macOS platforms.
    • Permissions: If the application has not been granted camera permissions by the user, calling new() or open_stream() will result in an error.
    • Limitations:
      • FPS (Frames Per Second) adjustment is not supported.
      • While iOS is technically allowed by the underlying framework, it is not officially supported and may not function correctly.

    Lifecycle

    1. Create: Use new(index, req_fmt) to instantiate the device.
    2. Open: Call open_stream() to start the AVCaptureSession.
    3. Capture: Use frame() to retrieve the next FrameBuffer.
    4. Stop: Call stop_stream() to release the session and inputs, or allow the object to be dropped.
    use nokhwa_core::types::{CameraIndex, RequestedFormat, RequestedFormatType};
    use nokhwa_core::pixel_format::RgbFormat;
    
    // Note: Ensure nokhwa_initialize() is called elsewhere in your setup
    let index = CameraIndex::Index(0);
    let req_fmt = RequestedFormat::new::<RgbFormat>(RequestedFormatType::Exact(camera_format));
    let mut device = AVFoundationCaptureDevice::new(&index, req_fmt)?;
  9. Specify camera format selection strategies with FormatRequestType

    senpai

    When selecting a camera format from a list of available options, you can use FormatRequestType to define a strategy for picking the best match. This is an optional helper; alternatively, you can use crate::camera::Camera::enumerate_formats for a simpler approach.

    Available strategies:

    • Closest: Attempts to find the CameraFormat closest to a preferred resolution and frame rate. It can optionally take Range constraints for resolution and frame_rate to filter valid candidates.
    • HighestFrameRate: Filters formats within a specific frame_rate range and sorts them to prioritize the highest available rate.
    • HighestResolution: Filters formats within a specific resolution range and sorts them to prioritize the highest available resolution.
    • Exact: Returns only formats that exactly match the provided resolution and frame_rate.
    • Any: Returns all available formats without filtering or sorting.
    use nokhwa::format_request::FormatRequestType;
    use nokhwa::types::{Resolution, FrameRate};
    use nokhwa::ranges::Range;
    
    // Example: Requesting the closest format to a specific target
    let strategy = FormatRequestType::Closest {
        resolution: Some(Range::new(Resolution::new(1280, 720), Resolution::new(1920, 1080))),
        preferred_resolution: Some(Resolution::new(1920, 1080)),
        frame_rate: None,
        preferred_frame_rate: Some(FrameRate::from_fps(30.0)),
    };
  10. Implement ValidatableRange for custom types

    senpai

    To use a custom type within a Range<T>, the type must implement the RangeItem trait. This trait ensures the type can be used for arithmetic and comparison operations required for range validation.

    Requirements for RangeItem:

    • Must implement Copy, Clone, Debug, Hash, Ord, PartialOrd, Eq, and PartialEq.
    • Must implement Div, Sub, and Rem (for step validation).
    • Must define the following constants:
      • ZERO
      • MIN
      • MAX
  11. Use the deprecated GStreamer backend for camera capture

    senpai

    The GStreamerCaptureDevice provides a way to capture video using GStreamer pipelines.

    Warning: This backend is deprecated since version 0.10. It is recommended to use native backends (V4L2 on Linux, AVF on macOS, MSMF on Windows) or OpenCV instead.

    Known Limitations:

    • Setting camera controls (brightness, contrast, etc.) is not supported.
    • Setting the FrameFormat is not supported.
    • Dropping the device instance may cause a panic in certain scenarios.
    use nokhwa::backends::capture::GStreamerCaptureDevice;
    use nokhwa::utils::{CameraFormat, Resolution};
    
    // Example: Creating a device with specific resolution
    let cam_fmt = CameraFormat::new(Resolution::new(1280, 720));
    let mut device = GStreamerCaptureDevice::new(0, Some(cam_fmt)).unwrap();
    
    // Example: Creating a device with default settings (640x480 @ 15 FPS, MJPEG)
    let mut device = GStreamerCaptureDevice::new(0, None).unwrap();
  12. Use the Media Foundation backend for Windows capture

    senpai

    The MediaFoundationCaptureDevice is the backend implementation for Windows (Windows 7 or newer) using the Media Foundation API. It implements the CaptureTrait.

    Quirks & Limitations

    • Platform Specificity: While it may build on non-Windows platforms, the backend will be empty and return errors for any operation if not running on Windows.
    • Device Naming: Device names may contain invalid characters due to conversion from UTF16.
    • Device Identification: The symbolic link for the device is stored in the misc attribute of the CameraInformation.
    • Lifecycle: initialize and de_initialize are automatically called when the struct is created (new) or dropped.
    use nokhwa::MediaFoundationCaptureDevice;
    use nokhwa::types::{CameraIndex, RequestedFormatType};
    use nokhwa::core::camera_format::CameraFormat;
    
    // Example initialization (conceptual)
    // let device = MediaFoundationCaptureDevice::new(&index, requested_format)?;