| 1 | |
| 2 | |
| 3 | |
| 4 | use std::path::{Path, PathBuf}; |
| 5 | use std::sync::Arc; |
| 6 | use std::sync::atomic::{AtomicBool, Ordering}; |
| 7 | use std::sync::mpsc::{Receiver, SyncSender, sync_channel}; |
| 8 | use std::thread; |
| 9 | |
| 10 | use rusty_h264::Decoder; |
| 11 | |
| 12 | use crate::convert::i420_to_bgra; |
| 13 | use crate::demux::{Demuxer, VideoMeta}; |
| 14 | use crate::hw::HwSession; |
| 15 | |
| 16 | |
| 17 | pub struct Frame { |
| 18 | |
| 19 | pub index: u32, |
| 20 | pub width: u32, |
| 21 | pub height: u32, |
| 22 | |
| 23 | pub bgra: Vec<u8>, |
| 24 | } |
| 25 | |
| 26 | |
| 27 | |
| 28 | |
| 29 | |
| 30 | |
| 31 | pub(crate) struct Worker { |
| 32 | cancel: Arc<AtomicBool>, |
| 33 | |
| 34 | |
| 35 | handle: Option<thread::JoinHandle<()>>, |
| 36 | } |
| 37 | |
| 38 | impl Worker { |
| 39 | |
| 40 | |
| 41 | |
| 42 | |
| 43 | pub(crate) fn cancel(&self) { |
| 44 | self.cancel.store(true, Ordering::Release); |
| 45 | } |
| 46 | |
| 47 | |
| 48 | |
| 49 | |
| 50 | pub(crate) fn is_finished(&self) -> bool { |
| 51 | self.handle |
| 52 | .as_ref() |
| 53 | .is_none_or(thread::JoinHandle::is_finished) |
| 54 | } |
| 55 | |
| 56 | |
| 57 | |
| 58 | fn detach(mut self) -> Arc<AtomicBool> { |
| 59 | self.handle = None; |
| 60 | Arc::clone(&self.cancel) |
| 61 | } |
| 62 | } |
| 63 | |
| 64 | impl Drop for Worker { |
| 65 | fn drop(&mut self) { |
| 66 | if let Some(handle) = self.handle.take() { |
| 67 | self.cancel(); |
| 68 | let _ = handle.join(); |
| 69 | } |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | |
| 74 | |
| 75 | |
| 76 | |
| 77 | |
| 78 | |
| 79 | |
| 80 | |
| 81 | |
| 82 | |
| 83 | pub(crate) struct FrameStream { |
| 84 | pub(crate) frames: Receiver<Frame>, |
| 85 | pub(crate) worker: Worker, |
| 86 | } |
| 87 | |
| 88 | pub struct DecodeSession; |
| 89 | |
| 90 | impl DecodeSession { |
| 91 | |
| 92 | |
| 93 | |
| 94 | pub fn open(path: impl AsRef<Path>) -> crate::Result<(VideoMeta, Receiver<Frame>)> { |
| 95 | let (meta, rx, _cancel) = Self::open_at(path, 0)?; |
| 96 | Ok((meta, rx)) |
| 97 | } |
| 98 | |
| 99 | |
| 100 | |
| 101 | |
| 102 | |
| 103 | pub fn open_at( |
| 104 | path: impl AsRef<Path>, |
| 105 | start_frame: u32, |
| 106 | ) -> crate::Result<(VideoMeta, Receiver<Frame>, Arc<AtomicBool>)> { |
| 107 | |
| 108 | |
| 109 | Self::open_range(path, start_frame, u32::MAX) |
| 110 | } |
| 111 | |
| 112 | |
| 113 | |
| 114 | |
| 115 | |
| 116 | |
| 117 | pub fn open_range( |
| 118 | path: impl AsRef<Path>, |
| 119 | start_frame: u32, |
| 120 | end_frame: u32, |
| 121 | ) -> crate::Result<(VideoMeta, Receiver<Frame>, Arc<AtomicBool>)> { |
| 122 | let (meta, stream) = Self::open_worker(path, start_frame, end_frame)?; |
| 123 | |
| 124 | |
| 125 | Ok((meta, stream.frames, stream.worker.detach())) |
| 126 | } |
| 127 | |
| 128 | |
| 129 | |
| 130 | |
| 131 | |
| 132 | |
| 133 | pub(crate) fn open_black(width: u32, height: u32, len: u32) -> FrameStream { |
| 134 | let (tx, rx) = sync_channel(2); |
| 135 | let cancel = Arc::new(AtomicBool::new(false)); |
| 136 | if len == 0 { |
| 137 | return FrameStream { |
| 138 | frames: rx, |
| 139 | worker: Worker { |
| 140 | cancel, |
| 141 | handle: None, |
| 142 | }, |
| 143 | }; |
| 144 | } |
| 145 | let worker_cancel = Arc::clone(&cancel); |
| 146 | |
| 147 | |
| 148 | let black = vec![[0u8, 0, 0, 255]; (width as usize) * (height as usize)].concat(); |
| 149 | let handle = thread::Builder::new() |
| 150 | .name("black".into()) |
| 151 | .spawn(move || { |
| 152 | for index in 0..len { |
| 153 | if worker_cancel.load(Ordering::Relaxed) { |
| 154 | return; |
| 155 | } |
| 156 | let frame = Frame { |
| 157 | index, |
| 158 | width, |
| 159 | height, |
| 160 | bgra: black.clone(), |
| 161 | }; |
| 162 | if tx.send(frame).is_err() { |
| 163 | return; |
| 164 | } |
| 165 | } |
| 166 | }) |
| 167 | .ok(); |
| 168 | FrameStream { |
| 169 | frames: rx, |
| 170 | worker: Worker { cancel, handle }, |
| 171 | } |
| 172 | } |
| 173 | |
| 174 | |
| 175 | |
| 176 | |
| 177 | pub(crate) fn open_worker( |
| 178 | path: impl AsRef<Path>, |
| 179 | start_frame: u32, |
| 180 | end_frame: u32, |
| 181 | ) -> crate::Result<(VideoMeta, FrameStream)> { |
| 182 | let path = path.as_ref().to_path_buf(); |
| 183 | let (meta, demuxer) = Demuxer::open(&path)?; |
| 184 | let end_frame = end_frame.min(meta.frame_count); |
| 185 | |
| 186 | |
| 187 | let (tx, rx) = sync_channel(2); |
| 188 | let cancel = Arc::new(AtomicBool::new(false)); |
| 189 | if end_frame <= start_frame { |
| 190 | |
| 191 | |
| 192 | return Ok(( |
| 193 | meta, |
| 194 | FrameStream { |
| 195 | frames: rx, |
| 196 | worker: Worker { |
| 197 | cancel, |
| 198 | handle: None, |
| 199 | }, |
| 200 | }, |
| 201 | )); |
| 202 | } |
| 203 | let worker_cancel = Arc::clone(&cancel); |
| 204 | let handle = thread::Builder::new() |
| 205 | .name("decode".into()) |
| 206 | .spawn(move || { |
| 207 | |
| 208 | |
| 209 | |
| 210 | |
| 211 | if worker_cancel.load(Ordering::Relaxed) { |
| 212 | return; |
| 213 | } |
| 214 | |
| 215 | |
| 216 | if let Some(hw) = open_hw(&path, start_frame) { |
| 217 | |
| 218 | |
| 219 | if worker_cancel.load(Ordering::Relaxed) { |
| 220 | return; |
| 221 | } |
| 222 | eprintln!("decode backend: hardware (VA-API plugin)"); |
| 223 | if run_hw(hw, &tx, start_frame, end_frame, &worker_cancel) { |
| 224 | return; |
| 225 | } |
| 226 | |
| 227 | |
| 228 | eprintln!("hardware decode failed before any frame, falling back to software"); |
| 229 | } |
| 230 | eprintln!("decode backend: software (rusty_h264)"); |
| 231 | run(demuxer, tx, start_frame, end_frame, &worker_cancel) |
| 232 | })?; |
| 233 | Ok(( |
| 234 | meta, |
| 235 | FrameStream { |
| 236 | frames: rx, |
| 237 | worker: Worker { |
| 238 | cancel, |
| 239 | handle: Some(handle), |
| 240 | }, |
| 241 | }, |
| 242 | )) |
| 243 | } |
| 244 | } |
| 245 | |
| 246 | |
| 247 | |
| 248 | fn open_hw(path: &PathBuf, start_frame: u32) -> Option<HwSession> { |
| 249 | if std::env::var_os("VE_SW").is_some_and(|v| v == "1") { |
| 250 | return None; |
| 251 | } |
| 252 | HwSession::open_at(path, start_frame) |
| 253 | } |
| 254 | |
| 255 | |
| 256 | |
| 257 | |
| 258 | |
| 259 | |
| 260 | |
| 261 | fn run_hw( |
| 262 | mut hw: HwSession, |
| 263 | tx: &SyncSender<Frame>, |
| 264 | start_frame: u32, |
| 265 | end_frame: u32, |
| 266 | cancel: &AtomicBool, |
| 267 | ) -> bool { |
| 268 | let mut index = start_frame; |
| 269 | loop { |
| 270 | if cancel.load(Ordering::Relaxed) { |
| 271 | return true; |
| 272 | } |
| 273 | match hw.next_frame() { |
| 274 | Ok(Some((y, u, v, width, height))) => { |
| 275 | let frame = Frame { |
| 276 | index, |
| 277 | width, |
| 278 | height, |
| 279 | bgra: i420_to_bgra(y, u, v, width as usize, height as usize), |
| 280 | }; |
| 281 | index += 1; |
| 282 | if tx.send(frame).is_err() { |
| 283 | return true; |
| 284 | } |
| 285 | if index >= end_frame { |
| 286 | return true; |
| 287 | } |
| 288 | } |
| 289 | Ok(None) => return true, |
| 290 | Err(e) => { |
| 291 | if index == start_frame { |
| 292 | return false; |
| 293 | } |
| 294 | eprintln!("hardware decode error at frame {index}: {e}"); |
| 295 | return true; |
| 296 | } |
| 297 | } |
| 298 | } |
| 299 | } |
| 300 | |
| 301 | #[cfg(test)] |
| 302 | mod tests { |
| 303 | use super::*; |
| 304 | use std::sync::mpsc::RecvTimeoutError; |
| 305 | use std::time::Duration; |
| 306 | |
| 307 | fn asset(name: &str) -> PathBuf { |
| 308 | PathBuf::from(env!("CARGO_MANIFEST_DIR")) |
| 309 | .join("../../assets") |
| 310 | .join(name) |
| 311 | } |
| 312 | |
| 313 | |
| 314 | |
| 315 | |
| 316 | |
| 317 | |
| 318 | |
| 319 | |
| 320 | |
| 321 | |
| 322 | #[test] |
| 323 | fn dropping_a_frame_stream_never_waits_for_an_undrained_channel() { |
| 324 | let (_meta, stream) = |
| 325 | DecodeSession::open_worker(&asset("test_baseline.mp4"), 0, u32::MAX).expect("open"); |
| 326 | |
| 327 | |
| 328 | thread::sleep(Duration::from_millis(500)); |
| 329 | |
| 330 | let (done_tx, done_rx) = sync_channel(1); |
| 331 | thread::spawn(move || { |
| 332 | drop(stream); |
| 333 | let _ = done_tx.send(()); |
| 334 | }); |
| 335 | assert!( |
| 336 | done_rx.recv_timeout(Duration::from_secs(10)) != Err(RecvTimeoutError::Timeout), |
| 337 | "dropping a parked stream deadlocked: it joined a decode thread \ |
| 338 | while still holding the receiver that thread is waiting on" |
| 339 | ); |
| 340 | } |
| 341 | } |
| 342 | |
| 343 | fn run( |
| 344 | mut demuxer: Demuxer, |
| 345 | tx: SyncSender<Frame>, |
| 346 | start_frame: u32, |
| 347 | end_frame: u32, |
| 348 | cancel: &AtomicBool, |
| 349 | ) { |
| 350 | let mut decoder = Decoder::new(); |
| 351 | |
| 352 | |
| 353 | |
| 354 | |
| 355 | let mut index = demuxer.seek_to_sync_at_or_before(start_frame); |
| 356 | |
| 357 | |
| 358 | |
| 359 | loop { |
| 360 | if cancel.load(Ordering::Relaxed) { |
| 361 | break; |
| 362 | } |
| 363 | let au = match demuxer.next_access_unit() { |
| 364 | Ok(Some(au)) => au, |
| 365 | Ok(None) => break, |
| 366 | Err(e) => { |
| 367 | eprintln!("demux error: {e}"); |
| 368 | break; |
| 369 | } |
| 370 | }; |
| 371 | let yuv = match decoder.decode(&au) { |
| 372 | Ok(Some(yuv)) => yuv, |
| 373 | Ok(None) => continue, |
| 374 | Err(e) => { |
| 375 | eprintln!("decode error at access unit {index}: {e}"); |
| 376 | break; |
| 377 | } |
| 378 | }; |
| 379 | if index < i64::from(start_frame) { |
| 380 | index += 1; |
| 381 | continue; |
| 382 | } |
| 383 | let frame = Frame { |
| 384 | index: index as u32, |
| 385 | width: yuv.width as u32, |
| 386 | height: yuv.height as u32, |
| 387 | bgra: i420_to_bgra(&yuv.y, &yuv.u, &yuv.v, yuv.width, yuv.height), |
| 388 | }; |
| 389 | index += 1; |
| 390 | if tx.send(frame).is_err() { |
| 391 | break; |
| 392 | } |
| 393 | if index >= i64::from(end_frame) { |
| 394 | break; |
| 395 | } |
| 396 | } |
| 397 | } |