Camera open can't explode memory (nokhwa expands v4l2loopback continuous sizes×intervals into billions of formats
Browse files at this commitce566cb0610598b09cfc056af5a911352d7b8832Parent: 81b4c3d- fix
- camera open can't explode memory (nokhwa expands v4l2loopback continuous sizes×intervals into billions of formats
- v4l pre-count rejects >100k) and a stuck camera thread keeps its device busy until it returns
2 changed files +94 -16
crates/client/Cargo.tomlmodified+1 -0
| @@ -44,6 +44,7 @@ resvg = "0.50.0" | |||
| 44 | nokhwa = { version = "0.10.11", default-features = false, features = ["input-native"] } | 44 | nokhwa = { version = "0.10.11", default-features = false, features = ["input-native"] } |
| 45 | 45 | ||
| 46 | [target.'cfg(target_os = "linux")'.dependencies] | 46 | [target.'cfg(target_os = "linux")'.dependencies] |
| 47 | +v4l = "0.14.0" | ||
| 47 | pipewire = { version = "0.10.1", features = ["v0_3_49"] } | 48 | pipewire = { version = "0.10.1", features = ["v0_3_49"] } |
| 48 | ksni = "0.3.7" | 49 | ksni = "0.3.7" |
| 49 | ashpd = { version = "0.14.3", default-features = false, features = ["tokio", "screencast"] } | 50 | ashpd = { version = "0.14.3", default-features = false, features = ["tokio", "screencast"] } |
crates/client/src/share/camera.rsmodified+93 -16
| @@ -2,6 +2,7 @@ use std::{ | |||
| 2 | sync::{ | 2 | sync::{ |
| 3 | Arc, | 3 | Arc, |
| 4 | atomic::{AtomicBool, AtomicU32, Ordering}, | 4 | atomic::{AtomicBool, AtomicU32, Ordering}, |
| 5 | + Mutex, | ||
| 5 | mpsc::{Receiver, RecvTimeoutError, SyncSender, sync_channel}, | 6 | mpsc::{Receiver, RecvTimeoutError, SyncSender, sync_channel}, |
| 6 | }, | 7 | }, |
| 7 | thread::JoinHandle, | 8 | thread::JoinHandle, |
| @@ -27,6 +28,7 @@ const SLACK_MS: u32 = 4; | |||
| 27 | const MAX_FAILURES: u32 = 200; | 28 | const MAX_FAILURES: u32 = 200; |
| 28 | const STALL: Duration = Duration::from_secs(5); | 29 | const STALL: Duration = Duration::from_secs(5); |
| 29 | const JOIN_TIMEOUT: Duration = Duration::from_secs(1); | 30 | const JOIN_TIMEOUT: Duration = Duration::from_secs(1); |
| 31 | +const MAX_FORMATS: u64 = 100_000; | ||
| 30 | const WANTED_FORMATS: [RequestedFormatType; 4] = [ | 32 | const WANTED_FORMATS: [RequestedFormatType; 4] = [ |
| 31 | RequestedFormatType::HighestFrameRate(30), | 33 | RequestedFormatType::HighestFrameRate(30), |
| 32 | RequestedFormatType::HighestFrameRate(60), | 34 | RequestedFormatType::HighestFrameRate(60), |
| @@ -49,18 +51,33 @@ pub struct Camera { | |||
| 49 | alive: Arc<AtomicU32>, | 51 | alive: Arc<AtomicU32>, |
| 50 | opened: Instant, | 52 | opened: Instant, |
| 51 | stop: Arc<AtomicBool>, | 53 | stop: Arc<AtomicBool>, |
| 52 | - thread: Option<(JoinHandle<()>, Receiver<()>)>, | 54 | + thread: Option<(JoinHandle<()>, Receiver<()>, CameraIndex)>, |
| 53 | _fake: Option<fake::Generator>, | 55 | _fake: Option<fake::Generator>, |
| 54 | } | 56 | } |
| 55 | 57 | ||
| 58 | +static HELD: Mutex<Vec<CameraIndex>> = Mutex::new(Vec::new()); | ||
| 59 | + | ||
| 60 | +fn held() -> std::sync::MutexGuard<'static, Vec<CameraIndex>> { | ||
| 61 | + HELD.lock().unwrap_or_else(std::sync::PoisonError::into_inner) | ||
| 62 | +} | ||
| 63 | + | ||
| 56 | impl Drop for Camera { | 64 | impl Drop for Camera { |
| 57 | fn drop(&mut self) { | 65 | fn drop(&mut self) { |
| 58 | self.stop.store(true, Ordering::Relaxed); | 66 | self.stop.store(true, Ordering::Relaxed); |
| 59 | - if let Some((thread, done)) = self.thread.take() | 67 | + let Some((thread, done, index)) = self.thread.take() else { |
| 60 | - && done.recv_timeout(JOIN_TIMEOUT) != Err(RecvTimeoutError::Timeout) | 68 | + return; |
| 61 | - { | 69 | + }; |
| 70 | + if done.recv_timeout(JOIN_TIMEOUT) != Err(RecvTimeoutError::Timeout) { | ||
| 62 | let _ = thread.join(); | 71 | let _ = thread.join(); |
| 72 | + return; | ||
| 63 | } | 73 | } |
| 74 | + tracing::warn!(?index, "camera thread stuck, device held until it returns"); | ||
| 75 | + held().push(index.clone()); | ||
| 76 | + std::thread::spawn(move || { | ||
| 77 | + let _ = done.recv(); | ||
| 78 | + let _ = thread.join(); | ||
| 79 | + held().retain(|busy| *busy != index); | ||
| 80 | + }); | ||
| 64 | } | 81 | } |
| 65 | } | 82 | } |
| 66 | 83 | ||
| @@ -109,8 +126,8 @@ pub fn label(name: &str) -> &str { | |||
| 109 | } | 126 | } |
| 110 | } | 127 | } |
| 111 | 128 | ||
| 112 | -fn index(device: Option<&str>) -> CameraIndex { | 129 | +fn index(device: Option<&str>) -> Option<CameraIndex> { |
| 113 | - device | 130 | + let index = device |
| 114 | .and_then(|name| { | 131 | .and_then(|name| { |
| 115 | nokhwa::query(nokhwa::utils::ApiBackend::Auto) | 132 | nokhwa::query(nokhwa::utils::ApiBackend::Auto) |
| 116 | .ok()? | 133 | .ok()? |
| @@ -118,7 +135,64 @@ fn index(device: Option<&str>) -> CameraIndex { | |||
| 118 | .find(|info| info.human_name() == name) | 135 | .find(|info| info.human_name() == name) |
| 119 | .map(|info| info.index().clone()) | 136 | .map(|info| info.index().clone()) |
| 120 | }) | 137 | }) |
| 121 | - .unwrap_or(CameraIndex::Index(0)) | 138 | + .unwrap_or(CameraIndex::Index(0)); |
| 139 | + if held().contains(&index) { | ||
| 140 | + tracing::warn!(?index, "camera still held by a stuck thread"); | ||
| 141 | + return None; | ||
| 142 | + } | ||
| 143 | + let count = format_count(&index); | ||
| 144 | + if count > MAX_FORMATS { | ||
| 145 | + tracing::warn!(?index, count, "camera reports too many formats, device not ready"); | ||
| 146 | + return None; | ||
| 147 | + } | ||
| 148 | + Some(index) | ||
| 149 | +} | ||
| 150 | + | ||
| 151 | +#[cfg(target_os = "linux")] | ||
| 152 | +fn format_count(index: &CameraIndex) -> u64 { | ||
| 153 | + use v4l::{frameinterval::FrameIntervalEnum, framesize::FrameSizeEnum, video::Capture}; | ||
| 154 | + let steps = |min: u32, max: u32, step: u32| u64::from(max.saturating_sub(min) / step.max(1)) + 1; | ||
| 155 | + let Some(device) = index | ||
| 156 | + .as_index() | ||
| 157 | + .ok() | ||
| 158 | + .and_then(|number| v4l::Device::new(number as usize).ok()) | ||
| 159 | + else { | ||
| 160 | + return 0; | ||
| 161 | + }; | ||
| 162 | + let mut count = 0u64; | ||
| 163 | + for format in device.enum_formats().unwrap_or_default() { | ||
| 164 | + for size in device.enum_framesizes(format.fourcc).unwrap_or_default() { | ||
| 165 | + let (sizes, width, height) = match size.size { | ||
| 166 | + FrameSizeEnum::Discrete(size) => (1, size.width, size.height), | ||
| 167 | + FrameSizeEnum::Stepwise(size) => ( | ||
| 168 | + steps(size.min_width, size.max_width, size.step_width) | ||
| 169 | + .min(steps(size.min_height, size.max_height, size.step_height)), | ||
| 170 | + size.min_width, | ||
| 171 | + size.min_height, | ||
| 172 | + ), | ||
| 173 | + }; | ||
| 174 | + let intervals: u64 = device | ||
| 175 | + .enum_frameintervals(format.fourcc, width, height) | ||
| 176 | + .unwrap_or_default() | ||
| 177 | + .iter() | ||
| 178 | + .map(|interval| match &interval.interval { | ||
| 179 | + FrameIntervalEnum::Discrete(_) => 1, | ||
| 180 | + FrameIntervalEnum::Stepwise(range) => steps( | ||
| 181 | + range.min.numerator, | ||
| 182 | + range.max.numerator, | ||
| 183 | + range.step.numerator, | ||
| 184 | + ), | ||
| 185 | + }) | ||
| 186 | + .sum(); | ||
| 187 | + count = count.saturating_add(sizes.saturating_mul(intervals.max(1))); | ||
| 188 | + } | ||
| 189 | + } | ||
| 190 | + count | ||
| 191 | +} | ||
| 192 | + | ||
| 193 | +#[cfg(not(target_os = "linux"))] | ||
| 194 | +fn format_count(_: &CameraIndex) -> u64 { | ||
| 195 | + 0 | ||
| 122 | } | 196 | } |
| 123 | 197 | ||
| 124 | pub fn open(top: Quality, device: Option<String>) -> Result<Camera, String> { | 198 | pub fn open(top: Quality, device: Option<String>) -> Result<Camera, String> { |
| @@ -142,6 +216,7 @@ pub fn open(top: Quality, device: Option<String>) -> Result<Camera, String> { | |||
| 142 | if !available() { | 216 | if !available() { |
| 143 | return Err(w().camera.needs_media_pack.to_string()); | 217 | return Err(w().camera.needs_media_pack.to_string()); |
| 144 | } | 218 | } |
| 219 | + let index = index(device.as_deref()).ok_or_else(|| w().camera.no_response.to_string())?; | ||
| 145 | let (negotiated_tx, negotiated_rx) = sync_channel::<Result<Negotiated, String>>(1); | 220 | let (negotiated_tx, negotiated_rx) = sync_channel::<Result<Negotiated, String>>(1); |
| 146 | let (frames_tx, frames_rx) = sync_channel(FRAME_QUEUE); | 221 | let (frames_tx, frames_rx) = sync_channel(FRAME_QUEUE); |
| 147 | let stop = Arc::new(AtomicBool::new(false)); | 222 | let stop = Arc::new(AtomicBool::new(false)); |
| @@ -150,7 +225,7 @@ pub fn open(top: Quality, device: Option<String>) -> Result<Camera, String> { | |||
| 150 | let opened = Instant::now(); | 225 | let opened = Instant::now(); |
| 151 | let (done_tx, done) = sync_channel::<()>(0); | 226 | let (done_tx, done) = sync_channel::<()>(0); |
| 152 | let thread = { | 227 | let thread = { |
| 153 | - let (stop, fps, alive) = (stop.clone(), fps.clone(), alive.clone()); | 228 | + let (stop, fps, alive, index) = (stop.clone(), fps.clone(), alive.clone(), index.clone()); |
| 154 | std::thread::Builder::new() | 229 | std::thread::Builder::new() |
| 155 | .name("camera-capture".to_string()) | 230 | .name("camera-capture".to_string()) |
| 156 | .spawn(move || { | 231 | .spawn(move || { |
| @@ -159,7 +234,7 @@ pub fn open(top: Quality, device: Option<String>) -> Result<Camera, String> { | |||
| 159 | opened, | 234 | opened, |
| 160 | alive: &alive, | 235 | alive: &alive, |
| 161 | }; | 236 | }; |
| 162 | - run(top, device, &stop, &fps, &clock, negotiated_tx, frames_tx) | 237 | + run(top, &index, &stop, &fps, &clock, negotiated_tx, frames_tx) |
| 163 | }) | 238 | }) |
| 164 | .map_err(|error| error.to_string())? | 239 | .map_err(|error| error.to_string())? |
| 165 | }; | 240 | }; |
| @@ -188,7 +263,7 @@ pub fn open(top: Quality, device: Option<String>) -> Result<Camera, String> { | |||
| 188 | alive, | 263 | alive, |
| 189 | opened, | 264 | opened, |
| 190 | stop, | 265 | stop, |
| 191 | - thread: Some((thread, done)), | 266 | + thread: Some((thread, done, index)), |
| 192 | _fake: None, | 267 | _fake: None, |
| 193 | }) | 268 | }) |
| 194 | } | 269 | } |
| @@ -206,8 +281,11 @@ pub fn list(device: Option<&str>) -> Vec<Mode> { | |||
| 206 | if !available() { | 281 | if !available() { |
| 207 | return Vec::new(); | 282 | return Vec::new(); |
| 208 | } | 283 | } |
| 284 | + let Some(index) = index(device) else { | ||
| 285 | + return Vec::new(); | ||
| 286 | + }; | ||
| 209 | let any = RequestedFormat::new::<RgbFormat>(RequestedFormatType::None); | 287 | let any = RequestedFormat::new::<RgbFormat>(RequestedFormatType::None); |
| 210 | - Device::new(index(device), any) | 288 | + Device::new(index, any) |
| 211 | .and_then(|mut camera| camera.compatible_camera_formats()) | 289 | .and_then(|mut camera| camera.compatible_camera_formats()) |
| 212 | .map(|formats| modes(&decodable(formats))) | 290 | .map(|formats| modes(&decodable(formats))) |
| 213 | .unwrap_or_default() | 291 | .unwrap_or_default() |
| @@ -260,9 +338,8 @@ fn open_fitting(top: Quality, index: &CameraIndex) -> Option<(Device, Vec<Camera | |||
| 260 | Some((camera, formats)) | 338 | Some((camera, formats)) |
| 261 | } | 339 | } |
| 262 | 340 | ||
| 263 | -fn open_device(top: Quality, device: Option<&str>) -> Result<(Device, Vec<CameraFormat>), String> { | 341 | +fn open_device(top: Quality, index: &CameraIndex) -> Result<(Device, Vec<CameraFormat>), String> { |
| 264 | - let index = index(device); | 342 | + if let Some(opened) = open_fitting(top, index) { |
| 265 | - if let Some(opened) = open_fitting(top, &index) { | ||
| 266 | return Ok(opened); | 343 | return Ok(opened); |
| 267 | } | 344 | } |
| 268 | for wanted in WANTED_FORMATS { | 345 | for wanted in WANTED_FORMATS { |
| @@ -293,14 +370,14 @@ impl Clock<'_> { | |||
| 293 | 370 | ||
| 294 | fn run( | 371 | fn run( |
| 295 | top: Quality, | 372 | top: Quality, |
| 296 | - device: Option<String>, | 373 | + index: &CameraIndex, |
| 297 | stop: &AtomicBool, | 374 | stop: &AtomicBool, |
| 298 | fps: &AtomicU32, | 375 | fps: &AtomicU32, |
| 299 | clock: &Clock, | 376 | clock: &Clock, |
| 300 | negotiated: SyncSender<Result<Negotiated, String>>, | 377 | negotiated: SyncSender<Result<Negotiated, String>>, |
| 301 | frames: SyncSender<Frame>, | 378 | frames: SyncSender<Frame>, |
| 302 | ) { | 379 | ) { |
| 303 | - let (mut camera, formats) = match open_device(top, device.as_deref()) { | 380 | + let (mut camera, formats) = match open_device(top, index) { |
| 304 | Ok(opened) => opened, | 381 | Ok(opened) => opened, |
| 305 | Err(error) => { | 382 | Err(error) => { |
| 306 | let _ = negotiated.send(Err(error)); | 383 | let _ = negotiated.send(Err(error)); |