diff --git a/Cargo.toml b/Cargo.toml index 5f1f1d0..e336592 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -20,7 +20,12 @@ edition = "2024" # cros-libva - fails to build against libva >= 1.23 headers # cros-codecs - probes VA-API with a 16x16 context that Mesa radeonsi refuses; # and creates every decode context as 8-bit 4:2:0, which no HEVC -# Main 10 stream can decode into (its own TODO, its own answer) +# Main 10 stream can decode into (its own TODO, its own answer); +# and refuses an H.264 frame_num gap outright unless the stream +# declared one, which fails every seek into an open-GOP Blu-ray +# remux -- the gap is the *editor's*, made by restarting at a +# random access point, so the patch fills it with the §8.2.5.2 +# non-existing frames the loop right below it already builds # rusty_aac - its *decoder* runs the direct O(N²) IMDCT with a `cos` call per # term (the fast path in the same file serves the encoder only), # which is 4x slower than real time for 5.1 and therefore not diff --git a/crates/engine-hw/src/lib.rs b/crates/engine-hw/src/lib.rs index 4c01862..db85183 100644 --- a/crates/engine-hw/src/lib.rs +++ b/crates/engine-hw/src/lib.rs @@ -104,6 +104,13 @@ type Av1Encoder = Av1StatelessEncoder< /// exists so a misbehaving driver returns an error instead of hanging the app. const STALL_LIMIT: u32 = 10_000; +/// How many undecodable access units a seek may drop before the session gives +/// up and calls the stream broken. An open GOP's leading pictures are a handful +/// (a Blu-ray remux's are 8-16); a file that keeps failing past this is not one +/// we restarted in the middle of, so the error is real and the caller still +/// hears it. +const LEADING_LIMIT: u32 = 64; + struct Session { decoder: Decoder, /// NV12 (or, for a 10-bit stream, P010) descriptor for `vaGetImage`, @@ -122,6 +129,11 @@ struct Session { flushed: bool, /// Pictures still to be decoded and thrown away to land on a seek target. skip: u32, + /// Access units dropped because they referenced pictures this session never + /// decoded -- see [`Session::pump`]. Counted rather than flagged so the + /// tolerance ends somewhere, and raised to [`LEADING_LIMIT`] the moment a + /// picture is handed out, which is where the window closes. + leading: u32, /// Tightly packed I420 handed out through [`VhFrame`]; reused every frame, /// which is exactly why the pointers are only valid until the next call. out: Vec, @@ -260,6 +272,12 @@ impl Session { timestamp: 0, flushed: false, skip: 0, + // A stream read from its own beginning has no missing references + // and therefore no leading pictures to forgive: the window opens + // only for a session positioned somewhere else ([`Session::open_at`]), + // so a file whose first picture will not decode is still refused at + // the door rather than opening onto nothing. + leading: LEADING_LIMIT, out: Vec::new(), luma: 0, chroma: 0, @@ -277,6 +295,9 @@ impl Session { let target_frame = target_sample.saturating_sub(1); let first = session.demuxer.seek_to_sync_at_or_before(target_frame); session.skip = (i64::from(target_frame) - first).max(0) as u32; + if target_frame > 0 { + session.leading = 0; + } Some(session) } @@ -309,6 +330,9 @@ impl Session { continue; } self.emit(handle); + // Past the random access point's leading pictures: a decode + // error from here on is a real one again. + self.leading = LEADING_LIMIT; return Ok(true); } if self.flushed { @@ -332,6 +356,7 @@ impl Session { pool, pending, timestamp, + leading, .. } = self; match decoder @@ -353,6 +378,21 @@ impl Session { return Err("decoder stalled waiting for output buffers".into()); } } + // A picture that references pictures we never decoded, which is + // what an open GOP's leading pictures are after a seek: they + // display *before* the random access point we restarted at, so + // they are not ours to show and the stream is not broken. Drop + // the rest of the access unit (they are picture-aligned) and + // walk on -- failing here is what used to make a Blu-ray remux + // fall back to software on 17 seeks out of 20. + Err(e) if *leading < LEADING_LIMIT => { + if *leading == 0 { + eprintln!("engine_hw: skipping leading pictures after seek ({e})"); + } + *leading += 1; + pending.clear(); + *timestamp += 1; + } Err(e) => return Err(e.to_string()), } } diff --git a/crates/engine/examples/bench.rs b/crates/engine/examples/bench.rs index 2c4b10a..69807f3 100644 --- a/crates/engine/examples/bench.rs +++ b/crates/engine/examples/bench.rs @@ -49,6 +49,7 @@ fn main() { "open" => open_bench(&path), "seek" => seek_bench(&path, arg_f64(args.next(), "seconds")), "scrub" => scrub_bench(&path), + "waveform" => waveform_bench(&path), "export" => { let seat = args.next().unwrap_or_else(|| usage()); let out_dir = PathBuf::from(args.next().unwrap_or_else(|| usage())); @@ -61,7 +62,8 @@ fn main() { fn usage() -> ! { eprintln!( "usage: bench open \n bench seek \n \ - bench scrub \n bench export " + bench scrub \n bench waveform \n \ + bench export " ); std::process::exit(2) } @@ -247,6 +249,38 @@ fn seek_bench(path: &Path, secs: f64) { row(path, &format!("seek_ttff_{secs:.0}s"), "ms", &samples, ¬e); } +// ---------------------------------------------------------------- waveform + +/// What a lane waits for before it has an envelope: one whole +/// [`engine::waveform::peaks`] of the file's first audio stream, at the app's +/// own ten buckets a second. Cold once, then warm -- the mkv sidecar index is +/// written on the first open, so the two are different questions. +fn waveform_bench(path: &Path) { + const BPS: u32 = 10; + evict(path); + let mut cold = Vec::new(); + let mut warm = Vec::new(); + let mut note = String::new(); + for i in 0..3 { + let t = Instant::now(); + match engine::waveform::peaks(path, 0, BPS) { + Ok(peaks) => { + let ms = t.elapsed().as_secs_f64() * 1000.0; + if i == 0 { cold.push(ms) } else { warm.push(ms) } + if note.is_empty() { + note = format!("{} buckets", peaks.map_or(0, |p| p.len())); + } + } + Err(e) => { + row(path, "waveform_cold", "ms", &[], &format!("FAIL({e})")); + return; + } + } + } + row(path, "waveform_cold", "ms", &cold, ¬e); + row(path, "waveform_warm", "ms", &warm, ¬e); +} + // ------------------------------------------------------------------- scrub /// Twenty scrub steps: the playhead dragged across a quarter of the film, one diff --git a/crates/engine/examples/dump_frame.rs b/crates/engine/examples/dump_frame.rs index b41d677..3fb5f31 100644 --- a/crates/engine/examples/dump_frame.rs +++ b/crates/engine/examples/dump_frame.rs @@ -1,5 +1,11 @@ //! Dump decoded frames as PPM for visual inspection. -//! Usage: cargo run -p engine --release --example dump_frame -- +//! Usage: cargo run -p engine --release --example dump_frame -- [seek] +//! +//! With `seek` the frame is reached the way a scrub reaches it -- restart at the +//! random access point at or before it -- instead of by decoding the file from +//! its start. The two must be the same picture, byte for byte, which is what +//! makes a `cmp` of the two dumps a check that seeking into an open GOP decodes +//! the frame it claims and not a smear of missing references. use std::env; use std::fs::File; @@ -9,26 +15,48 @@ fn main() -> engine::Result<()> { let mut args = env::args().skip(1); let path = args .next() - .ok_or("usage: dump_frame ")?; + .ok_or("usage: dump_frame [seek]")?; let target: u32 = args.next().ok_or("missing frame index")?.parse()?; let out = args.next().ok_or("missing output path")?; + let seek = args.next().is_some_and(|a| a == "seek"); let (meta, rx) = engine::DecodeSession::open(&path)?; eprintln!( "{}x{} @ {:.2} fps", meta.width, meta.height, meta.frame_rate ); + if seek { + drop(rx); + let mut session = engine::PlaybackSession::open(&path)?; + session.seek(f64::from(target) / meta.frame_rate); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(60); + while std::time::Instant::now() < deadline { + session.tick(); + if let Some(frame) = session.try_frame() { + write_ppm(&out, frame.width, frame.height, &frame.bgra)?; + eprintln!("wrote frame {} (asked {target}) to {out}", frame.index); + return Ok(()); + } + std::thread::sleep(std::time::Duration::from_millis(4)); + } + return Err(format!("no frame arrived within 60 s of seeking to {target}").into()); + } for frame in rx { if frame.index == target { - let mut w = BufWriter::new(File::create(&out)?); - writeln!(w, "P6\n{} {}\n255", frame.width, frame.height)?; - for px in frame.bgra.chunks_exact(4) { - w.write_all(&[px[2], px[1], px[0]])?; // BGRA -> RGB - } + write_ppm(&out, frame.width, frame.height, &frame.bgra)?; eprintln!("wrote frame {target} to {out}"); return Ok(()); } } Err(format!("stream ended before frame {target}").into()) } + +fn write_ppm(out: &str, width: u32, height: u32, bgra: &[u8]) -> engine::Result<()> { + let mut w = BufWriter::new(File::create(out)?); + writeln!(w, "P6\n{width} {height}\n255")?; + for px in bgra.chunks_exact(4) { + w.write_all(&[px[2], px[1], px[0]])?; // BGRA -> RGB + } + Ok(()) +} diff --git a/crates/engine/src/decode.rs b/crates/engine/src/decode.rs index cb1d0c6..6766d24 100644 --- a/crates/engine/src/decode.rs +++ b/crates/engine/src/decode.rs @@ -877,7 +877,13 @@ fn hw_decodes(path: &PathBuf, start_frame: u32, codec: Codec) -> Result<(), Stri let Some(mut hw) = open_hw(path, start_frame) else { return Err(codec.needs_plugin()); }; - hw.next_frame().map(|_| ()).map_err(|_| codec.undecodable()) + // End of stream counts as a refusal, not as a pass: a session that hands + // back no picture at all is exactly the black-frame-and-instant-eof this + // probe exists to catch, and `Ok(None)` is how the plugin says it. + match hw.next_frame() { + Ok(Some(_)) => Ok(()), + _ => Err(codec.undecodable()), + } } /// Returns whether the session was handled; `false` only when hardware decode diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index 9378350..aac8072 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -58,6 +58,7 @@ use std::fs::File; use std::io::{BufWriter, Write}; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; +use std::sync::mpsc::{Receiver, SyncSender, sync_channel}; use std::sync::{Arc, Mutex}; use std::thread; @@ -3142,14 +3143,73 @@ fn pop_av1<'a>( /// software: a hardware decode that fails after the first picture fails the /// export, which then deletes the half-written file. enum ClipDecoder { - Hw(HwSession), - Sw(SwDecoder), + /// A stream, decoded on a thread of its own: the encode of picture *n* and + /// the decode of picture *n + 1* are the two halves an export used to do in + /// turns, each idle while the other worked. The channel is two pictures + /// deep, so the decoder runs no further ahead than that (a 1080p I420 + /// picture is 3.1 MB) and a slow encoder still stops it. + /// + /// The thread is also where the plugin is *opened*: a VA-API session is not + /// ours to hand between threads ([`crate::decode::open_worker_deferred`] + /// keeps the same rule), which is why the open's error comes back down the + /// channel rather than out of [`ClipDecoder::open`]. + Streamed(Streamed), /// A still image: one picture, handed out for as long as the span runs. /// It is decoded here rather than in `run`'s loop for the same reason the - /// other two are opened there -- the span's pictures come from one place. + /// other two are opened there -- the span's pictures come from one place, + /// and no thread can make one picture arrive sooner. Still(crate::decode::Still), } +/// The receiving half of a decode thread, plus the picture it last handed out +/// -- which is what lets `next` keep lending planes rather than moving them. +/// +/// The first two fields are in this order on purpose, and it is the order +/// [`crate::decode::FrameStream`] states for the same pair: Rust drops fields as +/// they are declared, so the receiver disconnects *first* -- the only thing that +/// wakes a decoder parked in a full `send` -- and the join inside +/// [`DecodeThread::drop`] runs second. The other way round is a hang and not a +/// slow path. +struct Streamed { + frames: Receiver>>, + /// Held only to be dropped: joining is all it does, and it must happen + /// after the receiver above (`_lib` in `crate::hw` is kept the same way). + _thread: DecodeThread, + current: Option, + /// Whether the thread has said "no more pictures" in as many words. What + /// separates a stream that ended from a thread that vanished: after this, + /// the channel is disconnected because the decoder is *done*, and a further + /// ask is end of stream rather than a failure. + ended: bool, +} + +/// A decode thread, joined when its span's decoder is dropped -- the rule +/// [`crate::decode::Worker`] is written for: a thread abandoned mid +/// `vaInitialize` outlives the process, and Mesa's `atexit` handlers then free +/// the state it is still reading, which is a SIGSEGV at exit long after the +/// export succeeded. +struct DecodeThread(Option>); + +impl Drop for DecodeThread { + fn drop(&mut self) { + if let Some(handle) = self.0.take() { + // The receiver is already gone (see `Streamed`'s field order), so a + // decoder blocked on `send` has been woken and this waits only for + // the thread to unwind its VA-API session. + let _ = handle.join(); + } + } +} + +/// One picture, owned, on its way from a decode thread to the encoder. +struct Yuv { + y: Vec, + u: Vec, + v: Vec, + width: u32, + height: u32, +} + impl ClipDecoder { fn open(path: &Path, start_frame: u32) -> crate::Result { // Before either decoder: an image is not a stream, so `start_frame` @@ -3158,18 +3218,120 @@ impl ClipDecoder { if crate::is_image(path) { return Ok(Self::Still(crate::decode::Still::open(path)?)); } - if !forced("VE_SW") - && let Some(hw) = HwSession::open_at(path, start_frame) - { - return Ok(Self::Hw(hw)); - } - Ok(Self::Sw(SwDecoder::open(path, start_frame)?)) + let path = path.to_path_buf(); + let (tx, frames) = sync_channel(2); + let handle = thread::Builder::new() + .name("export-decode".into()) + .spawn(move || decode_stream(&path, start_frame, &tx))?; + Ok(Self::Streamed(Streamed { + frames, + _thread: DecodeThread(Some(handle)), + current: None, + ended: false, + })) } /// The next picture as tightly packed I420, borrowed until the call after. fn next(&mut self) -> crate::Result> { match self { Self::Still(still) => Ok(Some(still.picture())), + Self::Streamed(stream) if stream.ended => Ok(None), + Self::Streamed(stream) => match stream.frames.recv() { + Ok(Ok(Some(frame))) => { + let frame = stream.current.insert(frame); + Ok(Some(( + &frame.y, + &frame.u, + &frame.v, + frame.width, + frame.height, + ))) + } + // The decoder said end of stream in as many words -- a source + // shorter than the clip that names it, which the span loop ends + // gracefully on. + Ok(Ok(None)) => { + stream.ended = true; + Ok(None) + } + Ok(Err(e)) => Err(e), + // The channel went quiet without either: the thread panicked. + // Read as end of stream that would truncate the export at this + // frame and *report success*, which is the one outcome an + // export must never have -- before the decode moved onto a + // thread the same panic took the whole export down, and it + // still does. + Err(_) => Err("the decoder stopped without a picture or a reason".into()), + }, + } + } +} + +/// One span's decode, on its own thread: open the file (hardware if the plugin +/// will have it, software otherwise) and send every picture until the encoder +/// stops taking them. +/// +/// Unlike playback there is no mid-clip fallback to software: a hardware decode +/// that fails after the first picture fails the export, which then deletes the +/// half-written file. +/// +/// Every way this returns says which way it was, down the channel: a picture, an +/// error, or the `Ok(None)` that *is* end of stream. Closing the channel is not +/// one of them -- a silent close is a panicked thread, and the receiver treats +/// it as the failure it is rather than as a source that ran out. +fn decode_stream(path: &Path, start_frame: u32, tx: &SyncSender>>) { + let opened = match forced("VE_SW") { + false => HwSession::open_at(path, start_frame).map(Pictures::Hw), + true => None, + }; + let mut decoder = match opened { + Some(hw) => hw, + None => match SwDecoder::open(path, start_frame) { + Ok(sw) => Pictures::Sw(sw), + Err(e) => { + let _ = tx.send(Err(e)); + return; + } + }, + }; + loop { + // Copied out of the decoder's own buffer, which it reuses for the next + // picture: one 3 MB memcpy per frame against the decode and the encode + // it lets overlap. + let frame = match decoder.next() { + Ok(Some((y, u, v, width, height))) => Yuv { + y: y.to_vec(), + u: u.to_vec(), + v: v.to_vec(), + width, + height, + }, + Ok(None) => { + let _ = tx.send(Ok(None)); + return; + } + Err(e) => { + let _ = tx.send(Err(e)); + return; + } + }; + // The consumer went away: the span ended early, or the export was + // cancelled. Either way there is nothing left to decode for. + if tx.send(Ok(Some(frame))).is_err() { + return; + } + } +} + +/// The two stream decoders, on the thread that opened them. +enum Pictures { + Hw(HwSession), + Sw(SwDecoder), +} + +impl Pictures { + fn next(&mut self) -> crate::Result> { + match self { Self::Hw(hw) => hw.next_frame(), Self::Sw(sw) => { if !sw.advance()? { @@ -3245,6 +3407,47 @@ impl SwDecoder { mod tests { use super::*; + /// How a decode thread ended is never guessed from the channel being shut. + /// A source that genuinely ran out says so, and the span ends on it; a + /// thread that died without a word is a failure, because reading it as end + /// of stream would truncate the picture and *report the export finished*. + #[test] + fn a_decoder_that_dies_without_a_word_is_not_end_of_stream() { + let streamed = |handle, frames| { + ClipDecoder::Streamed(Streamed { + frames, + _thread: DecodeThread(Some(handle)), + current: None, + ended: false, + }) + }; + + let (tx, frames) = sync_channel::>>(2); + // Said its piece, then finished: the span walks on to its next clip. + let handle = thread::spawn(move || { + tx.send(Ok(None)).expect("the receiver is alive"); + }); + let mut ended = streamed(handle, frames); + assert!(ended.next().expect("a clean end is not an error").is_none()); + // ...and asking again is the same answer and not a disconnect error. + assert!(ended.next().expect("still not an error").is_none()); + + let (tx, frames) = sync_channel::>>(2); + // Died holding the sender: the channel shuts with nothing said. + let handle = thread::spawn(move || { + let _tx = tx; + panic!("decoder died"); + }); + let mut died = streamed(handle, frames); + let e = died + .next() + .expect_err("a silent death must fail the export, not end the clip"); + assert!( + e.to_string().contains("without a picture or a reason"), + "{e}" + ); + } + /// Three seconds of two tones, one per channel, interleaved: enough shape /// that a correlation says something and enough length that the encoder /// settles into a mode. diff --git a/crates/engine/src/waveform.rs b/crates/engine/src/waveform.rs index 14e06aa..3a7367b 100644 --- a/crates/engine/src/waveform.rs +++ b/crates/engine/src/waveform.rs @@ -2,9 +2,12 @@ //! off the same read-only decode path playback uses. Path in, peaks out — no //! project model, so a lane rework cannot reach it. -use std::path::Path; +use std::path::{Path, PathBuf}; +use std::sync::mpsc::Receiver; +use std::thread; use crate::AudioSession; +use crate::audio::AudioChunk; /// `(min, max)` of every sample in each `1 / buckets_per_sec` window of /// `stream` of `path`'s audio, from media time 0 (priming already trimmed by @@ -23,28 +26,141 @@ use crate::AudioSession; /// flat in it, though: chunks are consumed as they arrive and only the buckets /// are kept (2 hours at 10/s is 70k pairs). /// -/// ponytail: that 50x is 2.4 minutes of background decode for a two-hour film -/// before its lane has a waveform. The upgrade path is decoding the source in -/// segments on several threads — `open_multi_streams` already takes a window per -/// call — and stitching the buckets, which the fold to one envelope makes safe. +/// A source long enough for it is decoded in **windows on several threads** and +/// the buckets stitched, which is what that linear cost is divided by: +/// `open_multi_streams` takes a window per call and seeks to it, and the fold to +/// one envelope is what makes the join safe — a bucket two windows straddle is +/// folded from both, and min/max cannot double-count. A film that cost 23 s of +/// one core costs about a quarter of that; a clip short enough that the extra +/// opens would outweigh the decode they save ([`jobs_for`]) is read exactly as +/// it always was, on this thread. pub fn peaks( path: impl AsRef, stream: usize, buckets_per_sec: u32, ) -> crate::Result>> { - let sources = [(path.as_ref().to_path_buf(), stream)]; - let Some((meta, rx)) = - AudioSession::open_multi_streams(&sources, &[(Some(0), 0.0, f64::INFINITY)])? - else { + peaks_over(path.as_ref(), stream, buckets_per_sec, None) +} + +/// [`peaks`] with the split forced to `jobs` windows, which is how a test asks +/// for the same envelope by both routes. +fn peaks_over( + path: &Path, + stream: usize, + buckets_per_sec: u32, + jobs: Option, +) -> crate::Result>> { + let Some((meta, rx)) = open_window(path, stream, 0.0, f64::INFINITY)? else { return Ok(None); }; // Kept fractional: 44100 / 30 is not whole, and rounding it would drift a // bucket every few seconds over a long source. let per_bucket = f64::from(meta.sample_rate) / f64::from(buckets_per_sec.max(1)); let channels = (meta.channels as usize).max(1); - let mut peaks: Vec<(f32, f32)> = Vec::new(); + let rate = f64::from(meta.sample_rate.max(1)); + // A track whose length the container does not state cannot be cut into + // windows at all: `secs` is 0 and the whole of it is read on this thread, + // exactly as it was before there was a split. + let secs = meta.total_samples.unwrap_or(0) as f64 / rate; + let jobs = jobs.unwrap_or_else(|| jobs_for(secs)).max(1); + if jobs == 1 { + return Ok(Some(fold(rx, per_bucket, channels, u64::MAX))); + } + let window = secs / jobs as f64; + // Every other window is spawned before this thread folds its own, so they + // all decode side by side; each carries its own error home rather than + // taking a worker down. + let rest: Vec<_> = (1..jobs) + .map(|k| { + let path = path.to_path_buf(); + let start = window * k as f64; + // The last window runs to the end of the file: `total_samples` is + // the container's word for a length, and a tail past it must still + // be drawn. + let end = match k + 1 == jobs { + true => f64::INFINITY, + false => window * (k + 1) as f64, + }; + thread::Builder::new() + .name("waveform".into()) + .spawn(move || -> crate::Result> { + match open_window(&path, stream, start, end)? { + Some((_, rx)) => Ok(fold(rx, per_bucket, channels, u64::MAX)), + None => Ok(Vec::new()), + } + }) + }) + .collect::>()?; + // This window ends where the next one's decoder was told to start, by the + // same arithmetic, so the two meet with no gap; the chunk that straddles the + // joint is folded into both and min/max does not double-count. + let mut peaks = fold(rx, per_bucket, channels, (window * rate) as u64); + for handle in rest { + let part = handle.join().map_err(|_| "waveform worker panicked")??; + merge(&mut peaks, &part); + } + Ok(Some(peaks)) +} + +/// How many threads a source of `secs` is worth splitting across: one below two +/// minutes of sound, where the extra opens (a Matroska's is a cluster walk) cost +/// more than the decode they would save, and never more than the machine has — +/// nor more than a handful, since an import asks this of every source at once. +/// +/// ponytail: that last clause is a ceiling and not a bound — a library import of +/// twenty films runs as many of these as the background executor has threads, +/// each with eight of its own. The upgrade path is one pool the waveforms share, +/// which is also where a "visible range first" order would live. +fn jobs_for(secs: f64) -> usize { + const PER_JOB_SECS: f64 = 60.0; + const CEILING: usize = 8; + if !secs.is_finite() || secs < 2.0 * PER_JOB_SECS { + return 1; + } + let cores = thread::available_parallelism().map_or(1, |n| n.get()); + ((secs / PER_JOB_SECS) as usize).min(cores).min(CEILING).max(1) +} + +/// `part` folded into `peaks` bucket for bucket. Both are indexed absolutely, +/// so this is a straight min/max: an empty bucket is `(0.0, 0.0)` and every +/// value is clamped to `[-1.0, 1.0]`, which makes the empty pair the identity. +fn merge(peaks: &mut Vec<(f32, f32)>, part: &[(f32, f32)]) { + if part.len() > peaks.len() { + peaks.resize(part.len(), (0.0, 0.0)); + } + for (slot, &(lo, hi)) in peaks.iter_mut().zip(part) { + slot.0 = slot.0.min(lo); + slot.1 = slot.1.max(hi); + } +} +/// One window of one stream, opened the way playback opens it. +fn open_window( + path: &Path, + stream: usize, + start_secs: f64, + end_secs: f64, +) -> crate::Result)>> { + let sources = [(PathBuf::from(path), stream)]; + AudioSession::open_multi_streams(&sources, &[(Some(0), start_secs, end_secs)]) +} + +/// Min/max per bucket of everything `rx` carries, at absolute bucket positions: +/// `start_sample` counts from the source's own first audible sample whatever +/// window the session was opened at. Stops at the first chunk beginning at or +/// past `stop_sample`, and dropping the receiver there is what stops that +/// window's decoder. +fn fold( + rx: Receiver, + per_bucket: f64, + channels: usize, + stop_sample: u64, +) -> Vec<(f32, f32)> { + let mut peaks: Vec<(f32, f32)> = Vec::new(); for chunk in rx { + if chunk.start_sample >= stop_sample { + break; + } for (frame, values) in chunk.samples.chunks(channels).enumerate() { let bucket = ((chunk.start_sample + frame as u64) as f64 / per_bucket) as usize; if bucket >= peaks.len() { @@ -58,14 +174,14 @@ pub fn peaks( } } } - Ok(Some(peaks)) + peaks } #[cfg(test)] mod tests { use std::path::PathBuf; - use super::peaks; + use super::{peaks, peaks_over}; const BPS: u32 = 10; @@ -176,6 +292,35 @@ mod tests { } } + /// The split is an optimisation and nothing else: four windows decoded side + /// by side draw the very envelope the single-threaded walk draws, bucket for + /// bucket. The joints are where a window that started a sample late or + /// stopped a chunk early would show, so this is the check that a film's + /// waveform is still the film's. + #[test] + fn a_split_decode_draws_the_same_envelope() { + let file = asset("test_av.mp4"); + let whole = peaks_over(&file, 0, BPS, Some(1)) + .expect("open") + .expect("test_av.mp4 has an audio track"); + let split = peaks_over(&file, 0, BPS, Some(4)) + .expect("open") + .expect("test_av.mp4 has an audio track"); + assert_eq!(whole.len(), split.len(), "the split lost or grew buckets"); + // Not bit-equality: a window seeks into the middle of an AAC stream and + // its filterbank is primed from a preceding packet rather than carried + // over, so a bucket can land a ten-thousandth away. A lane is drawn a + // hundred pixels tall, where that is a thousandth of a pixel; a window + // that started late or stopped early is off by whole tenths and is what + // this catches. + for (i, (w, s)) in whole.iter().zip(&split).enumerate() { + assert!( + (w.0 - s.0).abs() < 1e-3 && (w.1 - s.1).abs() < 1e-3, + "bucket {i}: whole {w:?}, split {s:?}" + ); + } + } + #[test] fn video_only_source_has_no_peaks() { assert!( diff --git a/vendor/cros-codecs/src/decoder/stateless/h264.rs b/vendor/cros-codecs/src/decoder/stateless/h264.rs index baa3fbf..9606da8 100644 --- a/vendor/cros-codecs/src/decoder/stateless/h264.rs +++ b/vendor/cros-codecs/src/decoder/stateless/h264.rs @@ -954,13 +954,16 @@ where debug!("frame_num gap detected."); - if !sps.gaps_in_frame_num_value_allowed_flag { - return Err(anyhow!( - "Invalid frame_num: {}. Assuming unintentional loss of pictures", - frame_num - )); - } - + // LOCAL PATCH (see /Cargo.toml [patch.crates-io]): a gap is filled with + // the §8.2.5.2 non-existing frames whatever the flag says, instead of + // failing the stream. The flag means "this file has no intentional + // gaps", and it is right -- the gap is *ours*: an editor starts decoding + // at a random access point in the middle of a film, and the pictures + // between the previous reference and it were never decoded. Refusing + // here is what made every seek into an open-GOP Blu-ray remux fall back + // to a software decoder (17 of 20 in `bench scrub`), and the standing in + // frames this loop builds are exactly what the reference lists of the + // pictures after the gap look for. let mut unused_short_term_frame_num = (self.codec.prev_ref_pic_info.frame_num + 1) % sps.max_frame_num(); while unused_short_term_frame_num != frame_num {