(index: u32)
| 42 | |
| 43 | impl VideoCapture { |
| 44 | pub fn new(index: u32) -> Result<Self> { |
| 45 | // 1. 创建驱动 (移动到后台线程前先创建) |
| 46 | let driver = backend::create_driver()?; |
| 47 | |
| 48 | // 2. 查找设备 ID |
| 49 | let device_id = Self::resolve_device_id(&*driver, index)?; |
| 50 | |
| 51 | // 3. 创建通道 |
| 52 | let (cmd_tx, cmd_rx) = bounded::<Command>(1); |
| 53 | let (res_tx, res_rx) = bounded::<Response>(1); |
| 54 | |
| 55 | // 4. 【升级】启动后台任务 |
| 56 | // 我们将 driver 和 device_id 移动到后台,让后台全权管理生命周期 |
| 57 | runtime::get_runtime().spawn(async move { |
| 58 | // 初始配置 (默认) |
| 59 | let mut current_config = CameraConfig::new(); |
| 60 | // 当前流 (Option,允许为空以便重启) |
| 61 | let mut current_stream: Option<Box<dyn Stream>> = None; |
| 62 | |
| 63 | // 内部辅助:尝试打开流 |
| 64 | // 这是一个闭包无法捕获 async 引用,所以我们用 macro 或者简单的代码块复用逻辑 |
| 65 | // 这里为了简单,直接在循环外先尝试打开一次 |
| 66 | match driver.open(&device_id, current_config.clone()) { |
| 67 | Ok((s, _)) => { |
| 68 | // 启动流 |
| 69 | let mut s = s; |
| 70 | if let Err(e) = s.start().await { |
| 71 | let _ = res_tx.send(Response::Error(format!("Stream start failed: {}", e))); |
| 72 | return; |
| 73 | } |
| 74 | current_stream = Some(s); |
| 75 | } |
| 76 | Err(e) => { |
| 77 | // 初始打开失败不要紧,后续 NextFrame 会报错,或者允许 SetResolution 修复 |
| 78 | eprintln!("Warning: Initial open failed: {}", e); |
| 79 | } |
| 80 | } |
| 81 | |
| 82 | // 循环处理指令 |
| 83 | while let Ok(cmd) = cmd_rx.recv() { |
| 84 | match cmd { |
| 85 | Command::NextFrame => { |
| 86 | if let Some(stream) = current_stream.as_mut() { |
| 87 | match stream.next_frame().await { |
| 88 | Ok(frame) => { |
| 89 | let data_vec = frame.data.to_vec(); |
| 90 | let w = frame.width; |
| 91 | let h = frame.height; |
| 92 | // 提取 FourCC |
| 93 | let fourcc_val: u32 = match frame.format { |
| 94 | PixelFormat::Known(fcc) => fcc.0, |
| 95 | PixelFormat::Unknown(val) => val, |
| 96 | }; |
| 97 | |
| 98 | let _ = res_tx.send(Response::FrameData { |
| 99 | width: w, |
| 100 | height: h, |
| 101 | data: data_vec, |
nothing calls this directly
no test coverage detected