l1npengtul / nokhwa

Cross Platform Rust Library for Powerful Webcam/Camera Capture
Apache License 2.0
531 stars 137 forks source link

Multiple AVFoundation cameras on macOS panics with an NSException #145

Open MoonBarc opened 1 year ago

MoonBarc commented 1 year ago

I am trying to read from multiple USB cameras on my M1 mac via AVFoundation but whenever two (callback-based) cameras exist at the same time, nokhwa panics:

thread 'main' panicked at 'Uncaught exception <NSException: 0x600000e1be70>', /Users/me/.cargo/registry/src/index.crates.io-6f17d22bba15001f/nokhwa-bindings-macos-0.2.1/src/lib.rs:1024:17

Here's a small example that triggers the panic:

use nokhwa::CallbackCamera;
use nokhwa::pixel_format::RgbFormat;
use nokhwa::utils::{RequestedFormat, RequestedFormatType};
use nokhwa::utils::CameraIndex::Index;

fn main() {
    // (nokhwa_initialize)
    let n = vec![0, 1];

    let rq = RequestedFormat::new::<RgbFormat>(RequestedFormatType::AbsoluteHighestFrameRate);
    let mut cameras = n.into_iter().map(|idx| {
        CallbackCamera::new(Index(idx), rq.clone(), |_buf| {
            println!("got frame!");
        }).expect(&format!("failed to open cam#{}", idx))
    }).collect::<Vec<_>>();

    for cam in &mut cameras {
        cam.open_stream().expect("failed to open stream!");
    }
    loop {};
}

If the n array just has one element, the program runs fine and the camera starts capturing, however as soon as another one is created (with CallbackCamera::new()), it panics.

Strangely, if one of the two cameras is an iPhone via continuity camera then it works fine, receiving frames from both devices, but any two wired cameras will cause a panic.