forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'worktree-agent-a76fa5a3e33750073'

Browse files at this commit

a24eb7e0ebca02b7f0e371f9e92c4d18acc6d1b8Ahmet Kaan GümüşParent: 84d0c15ba88e8f
Cargo.tomlmodified+6 -1
@@ -20,7 +20,12 @@ edition = "2024"
20 # cros-libva - fails to build against libva >= 1.23 headers20 # cros-libva - fails to build against libva >= 1.23 headers
21 # cros-codecs - probes VA-API with a 16x16 context that Mesa radeonsi refuses;21 # cros-codecs - probes VA-API with a 16x16 context that Mesa radeonsi refuses;
22 # and creates every decode context as 8-bit 4:2:0, which no HEVC22 # and creates every decode context as 8-bit 4:2:0, which no HEVC
23-# Main 10 stream can decode into (its own TODO, its own answer)23+# Main 10 stream can decode into (its own TODO, its own answer);
24+# and refuses an H.264 frame_num gap outright unless the stream
25+# declared one, which fails every seek into an open-GOP Blu-ray
26+# remux -- the gap is the *editor's*, made by restarting at a
27+# random access point, so the patch fills it with the §8.2.5.2
28+# non-existing frames the loop right below it already builds
24 # rusty_aac - its *decoder* runs the direct O(N²) IMDCT with a `cos` call per29 # rusty_aac - its *decoder* runs the direct O(N²) IMDCT with a `cos` call per
25 # term (the fast path in the same file serves the encoder only),30 # term (the fast path in the same file serves the encoder only),
26 # which is 4x slower than real time for 5.1 and therefore not31 # which is 4x slower than real time for 5.1 and therefore not
crates/engine-hw/src/lib.rsmodified+40 -0
@@ -104,6 +104,13 @@ type Av1Encoder = Av1StatelessEncoder<
104 /// exists so a misbehaving driver returns an error instead of hanging the app.104 /// exists so a misbehaving driver returns an error instead of hanging the app.
105 const STALL_LIMIT: u32 = 10_000;105 const STALL_LIMIT: u32 = 10_000;
106 106
107+/// How many undecodable access units a seek may drop before the session gives
108+/// up and calls the stream broken. An open GOP's leading pictures are a handful
109+/// (a Blu-ray remux's are 8-16); a file that keeps failing past this is not one
110+/// we restarted in the middle of, so the error is real and the caller still
111+/// hears it.
112+const LEADING_LIMIT: u32 = 64;
113+
107 struct Session {114 struct Session {
108 decoder: Decoder,115 decoder: Decoder,
109 /// NV12 (or, for a 10-bit stream, P010) descriptor for `vaGetImage`,116 /// NV12 (or, for a 10-bit stream, P010) descriptor for `vaGetImage`,
@@ -122,6 +129,11 @@ struct Session {
122 flushed: bool,129 flushed: bool,
123 /// Pictures still to be decoded and thrown away to land on a seek target.130 /// Pictures still to be decoded and thrown away to land on a seek target.
124 skip: u32,131 skip: u32,
132+ /// Access units dropped because they referenced pictures this session never
133+ /// decoded -- see [`Session::pump`]. Counted rather than flagged so the
134+ /// tolerance ends somewhere, and raised to [`LEADING_LIMIT`] the moment a
135+ /// picture is handed out, which is where the window closes.
136+ leading: u32,
125 /// Tightly packed I420 handed out through [`VhFrame`]; reused every frame,137 /// Tightly packed I420 handed out through [`VhFrame`]; reused every frame,
126 /// which is exactly why the pointers are only valid until the next call.138 /// which is exactly why the pointers are only valid until the next call.
127 out: Vec<u8>,139 out: Vec<u8>,
@@ -260,6 +272,12 @@ impl Session {
260 timestamp: 0,272 timestamp: 0,
261 flushed: false,273 flushed: false,
262 skip: 0,274 skip: 0,
275+ // A stream read from its own beginning has no missing references
276+ // and therefore no leading pictures to forgive: the window opens
277+ // only for a session positioned somewhere else ([`Session::open_at`]),
278+ // so a file whose first picture will not decode is still refused at
279+ // the door rather than opening onto nothing.
280+ leading: LEADING_LIMIT,
263 out: Vec::new(),281 out: Vec::new(),
264 luma: 0,282 luma: 0,
265 chroma: 0,283 chroma: 0,
@@ -277,6 +295,9 @@ impl Session {
277 let target_frame = target_sample.saturating_sub(1);295 let target_frame = target_sample.saturating_sub(1);
278 let first = session.demuxer.seek_to_sync_at_or_before(target_frame);296 let first = session.demuxer.seek_to_sync_at_or_before(target_frame);
279 session.skip = (i64::from(target_frame) - first).max(0) as u32;297 session.skip = (i64::from(target_frame) - first).max(0) as u32;
298+ if target_frame > 0 {
299+ session.leading = 0;
300+ }
280 Some(session)301 Some(session)
281 }302 }
282 303
@@ -309,6 +330,9 @@ impl Session {
309 continue;330 continue;
310 }331 }
311 self.emit(handle);332 self.emit(handle);
333+ // Past the random access point's leading pictures: a decode
334+ // error from here on is a real one again.
335+ self.leading = LEADING_LIMIT;
312 return Ok(true);336 return Ok(true);
313 }337 }
314 if self.flushed {338 if self.flushed {
@@ -332,6 +356,7 @@ impl Session {
332 pool,356 pool,
333 pending,357 pending,
334 timestamp,358 timestamp,
359+ leading,
335 ..360 ..
336 } = self;361 } = self;
337 match decoder362 match decoder
@@ -353,6 +378,21 @@ impl Session {
353 return Err("decoder stalled waiting for output buffers".into());378 return Err("decoder stalled waiting for output buffers".into());
354 }379 }
355 }380 }
381+ // A picture that references pictures we never decoded, which is
382+ // what an open GOP's leading pictures are after a seek: they
383+ // display *before* the random access point we restarted at, so
384+ // they are not ours to show and the stream is not broken. Drop
385+ // the rest of the access unit (they are picture-aligned) and
386+ // walk on -- failing here is what used to make a Blu-ray remux
387+ // fall back to software on 17 seeks out of 20.
388+ Err(e) if *leading < LEADING_LIMIT => {
389+ if *leading == 0 {
390+ eprintln!("engine_hw: skipping leading pictures after seek ({e})");
391+ }
392+ *leading += 1;
393+ pending.clear();
394+ *timestamp += 1;
395+ }
356 Err(e) => return Err(e.to_string()),396 Err(e) => return Err(e.to_string()),
357 }397 }
358 }398 }
crates/engine/examples/bench.rsmodified+35 -1
@@ -49,6 +49,7 @@ fn main() {
49 "open" => open_bench(&path),49 "open" => open_bench(&path),
50 "seek" => seek_bench(&path, arg_f64(args.next(), "seconds")),50 "seek" => seek_bench(&path, arg_f64(args.next(), "seconds")),
51 "scrub" => scrub_bench(&path),51 "scrub" => scrub_bench(&path),
52+ "waveform" => waveform_bench(&path),
52 "export" => {53 "export" => {
53 let seat = args.next().unwrap_or_else(|| usage());54 let seat = args.next().unwrap_or_else(|| usage());
54 let out_dir = PathBuf::from(args.next().unwrap_or_else(|| usage()));55 let out_dir = PathBuf::from(args.next().unwrap_or_else(|| usage()));
@@ -61,7 +62,8 @@ fn main() {
61 fn usage() -> ! {62 fn usage() -> ! {
62 eprintln!(63 eprintln!(
63 "usage: bench open <file>\n bench seek <file> <secs>\n \64 "usage: bench open <file>\n bench seek <file> <secs>\n \
64- bench scrub <file>\n bench export <file> <h264sw|h264hw|av1|hevc> <out_dir>"65+ bench scrub <file>\n bench waveform <file>\n \
66+ bench export <file> <h264sw|h264hw|av1|hevc> <out_dir>"
65 );67 );
66 std::process::exit(2)68 std::process::exit(2)
67 }69 }
@@ -247,6 +249,38 @@ fn seek_bench(path: &Path, secs: f64) {
247 row(path, &format!("seek_ttff_{secs:.0}s"), "ms", &samples, &note);249 row(path, &format!("seek_ttff_{secs:.0}s"), "ms", &samples, &note);
248 }250 }
249 251
252+// ---------------------------------------------------------------- waveform
253+
254+/// What a lane waits for before it has an envelope: one whole
255+/// [`engine::waveform::peaks`] of the file's first audio stream, at the app's
256+/// own ten buckets a second. Cold once, then warm -- the mkv sidecar index is
257+/// written on the first open, so the two are different questions.
258+fn waveform_bench(path: &Path) {
259+ const BPS: u32 = 10;
260+ evict(path);
261+ let mut cold = Vec::new();
262+ let mut warm = Vec::new();
263+ let mut note = String::new();
264+ for i in 0..3 {
265+ let t = Instant::now();
266+ match engine::waveform::peaks(path, 0, BPS) {
267+ Ok(peaks) => {
268+ let ms = t.elapsed().as_secs_f64() * 1000.0;
269+ if i == 0 { cold.push(ms) } else { warm.push(ms) }
270+ if note.is_empty() {
271+ note = format!("{} buckets", peaks.map_or(0, |p| p.len()));
272+ }
273+ }
274+ Err(e) => {
275+ row(path, "waveform_cold", "ms", &[], &format!("FAIL({e})"));
276+ return;
277+ }
278+ }
279+ }
280+ row(path, "waveform_cold", "ms", &cold, &note);
281+ row(path, "waveform_warm", "ms", &warm, &note);
282+}
283+
250 // ------------------------------------------------------------------- scrub284 // ------------------------------------------------------------------- scrub
251 285
252 /// Twenty scrub steps: the playhead dragged across a quarter of the film, one286 /// Twenty scrub steps: the playhead dragged across a quarter of the film, one
crates/engine/examples/dump_frame.rsmodified+35 -7
@@ -1,5 +1,11 @@
1 //! Dump decoded frames as PPM for visual inspection.1 //! Dump decoded frames as PPM for visual inspection.
2-//! Usage: cargo run -p engine --release --example dump_frame -- <video.mp4> <frame_index> <out.ppm>2+//! Usage: cargo run -p engine --release --example dump_frame -- <video.mp4> <frame_index> <out.ppm> [seek]
3+//!
4+//! With `seek` the frame is reached the way a scrub reaches it -- restart at the
5+//! random access point at or before it -- instead of by decoding the file from
6+//! its start. The two must be the same picture, byte for byte, which is what
7+//! makes a `cmp` of the two dumps a check that seeking into an open GOP decodes
8+//! the frame it claims and not a smear of missing references.
3 9
4 use std::env;10 use std::env;
5 use std::fs::File;11 use std::fs::File;
@@ -9,26 +15,48 @@ fn main() -> engine::Result<()> {
9 let mut args = env::args().skip(1);15 let mut args = env::args().skip(1);
10 let path = args16 let path = args
11 .next()17 .next()
12- .ok_or("usage: dump_frame <video.mp4> <frame_index> <out.ppm>")?;18+ .ok_or("usage: dump_frame <video.mp4> <frame_index> <out.ppm> [seek]")?;
13 let target: u32 = args.next().ok_or("missing frame index")?.parse()?;19 let target: u32 = args.next().ok_or("missing frame index")?.parse()?;
14 let out = args.next().ok_or("missing output path")?;20 let out = args.next().ok_or("missing output path")?;
21+ let seek = args.next().is_some_and(|a| a == "seek");
15 22
16 let (meta, rx) = engine::DecodeSession::open(&path)?;23 let (meta, rx) = engine::DecodeSession::open(&path)?;
17 eprintln!(24 eprintln!(
18 "{}x{} @ {:.2} fps",25 "{}x{} @ {:.2} fps",
19 meta.width, meta.height, meta.frame_rate26 meta.width, meta.height, meta.frame_rate
20 );27 );
28+ if seek {
29+ drop(rx);
30+ let mut session = engine::PlaybackSession::open(&path)?;
31+ session.seek(f64::from(target) / meta.frame_rate);
32+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(60);
33+ while std::time::Instant::now() < deadline {
34+ session.tick();
35+ if let Some(frame) = session.try_frame() {
36+ write_ppm(&out, frame.width, frame.height, &frame.bgra)?;
37+ eprintln!("wrote frame {} (asked {target}) to {out}", frame.index);
38+ return Ok(());
39+ }
40+ std::thread::sleep(std::time::Duration::from_millis(4));
41+ }
42+ return Err(format!("no frame arrived within 60 s of seeking to {target}").into());
43+ }
21 44
22 for frame in rx {45 for frame in rx {
23 if frame.index == target {46 if frame.index == target {
24- let mut w = BufWriter::new(File::create(&out)?);47+ write_ppm(&out, frame.width, frame.height, &frame.bgra)?;
25- writeln!(w, "P6\n{} {}\n255", frame.width, frame.height)?;
26- for px in frame.bgra.chunks_exact(4) {
27- w.write_all(&[px[2], px[1], px[0]])?; // BGRA -> RGB
28- }
29 eprintln!("wrote frame {target} to {out}");48 eprintln!("wrote frame {target} to {out}");
30 return Ok(());49 return Ok(());
31 }50 }
32 }51 }
33 Err(format!("stream ended before frame {target}").into())52 Err(format!("stream ended before frame {target}").into())
34 }53 }
54+
55+fn write_ppm(out: &str, width: u32, height: u32, bgra: &[u8]) -> engine::Result<()> {
56+ let mut w = BufWriter::new(File::create(out)?);
57+ writeln!(w, "P6\n{width} {height}\n255")?;
58+ for px in bgra.chunks_exact(4) {
59+ w.write_all(&[px[2], px[1], px[0]])?; // BGRA -> RGB
60+ }
61+ Ok(())
62+}
crates/engine/src/decode.rsmodified+7 -1
@@ -877,7 +877,13 @@ fn hw_decodes(path: &PathBuf, start_frame: u32, codec: Codec) -> Result<(), Stri
877 let Some(mut hw) = open_hw(path, start_frame) else {877 let Some(mut hw) = open_hw(path, start_frame) else {
878 return Err(codec.needs_plugin());878 return Err(codec.needs_plugin());
879 };879 };
880- hw.next_frame().map(|_| ()).map_err(|_| codec.undecodable())880+ // End of stream counts as a refusal, not as a pass: a session that hands
881+ // back no picture at all is exactly the black-frame-and-instant-eof this
882+ // probe exists to catch, and `Ok(None)` is how the plugin says it.
883+ match hw.next_frame() {
884+ Ok(Some(_)) => Ok(()),
885+ _ => Err(codec.undecodable()),
886+ }
881 }887 }
882 888
883 /// Returns whether the session was handled; `false` only when hardware decode889 /// Returns whether the session was handled; `false` only when hardware decode
crates/engine/src/export.rsmodified+212 -9
@@ -58,6 +58,7 @@ use std::fs::File;
58 use std::io::{BufWriter, Write};58 use std::io::{BufWriter, Write};
59 use std::path::{Path, PathBuf};59 use std::path::{Path, PathBuf};
60 use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};60 use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
61+use std::sync::mpsc::{Receiver, SyncSender, sync_channel};
61 use std::sync::{Arc, Mutex};62 use std::sync::{Arc, Mutex};
62 use std::thread;63 use std::thread;
63 64
@@ -3142,14 +3143,73 @@ fn pop_av1<'a>(
3142 /// software: a hardware decode that fails after the first picture fails the3143 /// software: a hardware decode that fails after the first picture fails the
3143 /// export, which then deletes the half-written file.3144 /// export, which then deletes the half-written file.
3144 enum ClipDecoder {3145 enum ClipDecoder {
3145- Hw(HwSession),3146+ /// A stream, decoded on a thread of its own: the encode of picture *n* and
3146- Sw(SwDecoder),3147+ /// the decode of picture *n + 1* are the two halves an export used to do in
3148+ /// turns, each idle while the other worked. The channel is two pictures
3149+ /// deep, so the decoder runs no further ahead than that (a 1080p I420
3150+ /// picture is 3.1 MB) and a slow encoder still stops it.
3151+ ///
3152+ /// The thread is also where the plugin is *opened*: a VA-API session is not
3153+ /// ours to hand between threads ([`crate::decode::open_worker_deferred`]
3154+ /// keeps the same rule), which is why the open's error comes back down the
3155+ /// channel rather than out of [`ClipDecoder::open`].
3156+ Streamed(Streamed),
3147 /// A still image: one picture, handed out for as long as the span runs.3157 /// A still image: one picture, handed out for as long as the span runs.
3148 /// It is decoded here rather than in `run`'s loop for the same reason the3158 /// It is decoded here rather than in `run`'s loop for the same reason the
3149- /// other two are opened there -- the span's pictures come from one place.3159+ /// other two are opened there -- the span's pictures come from one place,
3160+ /// and no thread can make one picture arrive sooner.
3150 Still(crate::decode::Still),3161 Still(crate::decode::Still),
3151 }3162 }
3152 3163
3164+/// The receiving half of a decode thread, plus the picture it last handed out
3165+/// -- which is what lets `next` keep lending planes rather than moving them.
3166+///
3167+/// The first two fields are in this order on purpose, and it is the order
3168+/// [`crate::decode::FrameStream`] states for the same pair: Rust drops fields as
3169+/// they are declared, so the receiver disconnects *first* -- the only thing that
3170+/// wakes a decoder parked in a full `send` -- and the join inside
3171+/// [`DecodeThread::drop`] runs second. The other way round is a hang and not a
3172+/// slow path.
3173+struct Streamed {
3174+ frames: Receiver<crate::Result<Option<Yuv>>>,
3175+ /// Held only to be dropped: joining is all it does, and it must happen
3176+ /// after the receiver above (`_lib` in `crate::hw` is kept the same way).
3177+ _thread: DecodeThread,
3178+ current: Option<Yuv>,
3179+ /// Whether the thread has said "no more pictures" in as many words. What
3180+ /// separates a stream that ended from a thread that vanished: after this,
3181+ /// the channel is disconnected because the decoder is *done*, and a further
3182+ /// ask is end of stream rather than a failure.
3183+ ended: bool,
3184+}
3185+
3186+/// A decode thread, joined when its span's decoder is dropped -- the rule
3187+/// [`crate::decode::Worker`] is written for: a thread abandoned mid
3188+/// `vaInitialize` outlives the process, and Mesa's `atexit` handlers then free
3189+/// the state it is still reading, which is a SIGSEGV at exit long after the
3190+/// export succeeded.
3191+struct DecodeThread(Option<thread::JoinHandle<()>>);
3192+
3193+impl Drop for DecodeThread {
3194+ fn drop(&mut self) {
3195+ if let Some(handle) = self.0.take() {
3196+ // The receiver is already gone (see `Streamed`'s field order), so a
3197+ // decoder blocked on `send` has been woken and this waits only for
3198+ // the thread to unwind its VA-API session.
3199+ let _ = handle.join();
3200+ }
3201+ }
3202+}
3203+
3204+/// One picture, owned, on its way from a decode thread to the encoder.
3205+struct Yuv {
3206+ y: Vec<u8>,
3207+ u: Vec<u8>,
3208+ v: Vec<u8>,
3209+ width: u32,
3210+ height: u32,
3211+}
3212+
3153 impl ClipDecoder {3213 impl ClipDecoder {
3154 fn open(path: &Path, start_frame: u32) -> crate::Result<Self> {3214 fn open(path: &Path, start_frame: u32) -> crate::Result<Self> {
3155 // Before either decoder: an image is not a stream, so `start_frame`3215 // Before either decoder: an image is not a stream, so `start_frame`
@@ -3158,18 +3218,120 @@ impl ClipDecoder {
3158 if crate::is_image(path) {3218 if crate::is_image(path) {
3159 return Ok(Self::Still(crate::decode::Still::open(path)?));3219 return Ok(Self::Still(crate::decode::Still::open(path)?));
3160 }3220 }
3161- if !forced("VE_SW")3221+ let path = path.to_path_buf();
3162- && let Some(hw) = HwSession::open_at(path, start_frame)3222+ let (tx, frames) = sync_channel(2);
3163- {3223+ let handle = thread::Builder::new()
3164- return Ok(Self::Hw(hw));3224+ .name("export-decode".into())
3165- }3225+ .spawn(move || decode_stream(&path, start_frame, &tx))?;
3166- Ok(Self::Sw(SwDecoder::open(path, start_frame)?))3226+ Ok(Self::Streamed(Streamed {
3227+ frames,
3228+ _thread: DecodeThread(Some(handle)),
3229+ current: None,
3230+ ended: false,
3231+ }))
3167 }3232 }
3168 3233
3169 /// The next picture as tightly packed I420, borrowed until the call after.3234 /// The next picture as tightly packed I420, borrowed until the call after.
3170 fn next(&mut self) -> crate::Result<Option<(&[u8], &[u8], &[u8], u32, u32)>> {3235 fn next(&mut self) -> crate::Result<Option<(&[u8], &[u8], &[u8], u32, u32)>> {
3171 match self {3236 match self {
3172 Self::Still(still) => Ok(Some(still.picture())),3237 Self::Still(still) => Ok(Some(still.picture())),
3238+ Self::Streamed(stream) if stream.ended => Ok(None),
3239+ Self::Streamed(stream) => match stream.frames.recv() {
3240+ Ok(Ok(Some(frame))) => {
3241+ let frame = stream.current.insert(frame);
3242+ Ok(Some((
3243+ &frame.y,
3244+ &frame.u,
3245+ &frame.v,
3246+ frame.width,
3247+ frame.height,
3248+ )))
3249+ }
3250+ // The decoder said end of stream in as many words -- a source
3251+ // shorter than the clip that names it, which the span loop ends
3252+ // gracefully on.
3253+ Ok(Ok(None)) => {
3254+ stream.ended = true;
3255+ Ok(None)
3256+ }
3257+ Ok(Err(e)) => Err(e),
3258+ // The channel went quiet without either: the thread panicked.
3259+ // Read as end of stream that would truncate the export at this
3260+ // frame and *report success*, which is the one outcome an
3261+ // export must never have -- before the decode moved onto a
3262+ // thread the same panic took the whole export down, and it
3263+ // still does.
3264+ Err(_) => Err("the decoder stopped without a picture or a reason".into()),
3265+ },
3266+ }
3267+ }
3268+}
3269+
3270+/// One span's decode, on its own thread: open the file (hardware if the plugin
3271+/// will have it, software otherwise) and send every picture until the encoder
3272+/// stops taking them.
3273+///
3274+/// Unlike playback there is no mid-clip fallback to software: a hardware decode
3275+/// that fails after the first picture fails the export, which then deletes the
3276+/// half-written file.
3277+///
3278+/// Every way this returns says which way it was, down the channel: a picture, an
3279+/// error, or the `Ok(None)` that *is* end of stream. Closing the channel is not
3280+/// one of them -- a silent close is a panicked thread, and the receiver treats
3281+/// it as the failure it is rather than as a source that ran out.
3282+fn decode_stream(path: &Path, start_frame: u32, tx: &SyncSender<crate::Result<Option<Yuv>>>) {
3283+ let opened = match forced("VE_SW") {
3284+ false => HwSession::open_at(path, start_frame).map(Pictures::Hw),
3285+ true => None,
3286+ };
3287+ let mut decoder = match opened {
3288+ Some(hw) => hw,
3289+ None => match SwDecoder::open(path, start_frame) {
3290+ Ok(sw) => Pictures::Sw(sw),
3291+ Err(e) => {
3292+ let _ = tx.send(Err(e));
3293+ return;
3294+ }
3295+ },
3296+ };
3297+ loop {
3298+ // Copied out of the decoder's own buffer, which it reuses for the next
3299+ // picture: one 3 MB memcpy per frame against the decode and the encode
3300+ // it lets overlap.
3301+ let frame = match decoder.next() {
3302+ Ok(Some((y, u, v, width, height))) => Yuv {
3303+ y: y.to_vec(),
3304+ u: u.to_vec(),
3305+ v: v.to_vec(),
3306+ width,
3307+ height,
3308+ },
3309+ Ok(None) => {
3310+ let _ = tx.send(Ok(None));
3311+ return;
3312+ }
3313+ Err(e) => {
3314+ let _ = tx.send(Err(e));
3315+ return;
3316+ }
3317+ };
3318+ // The consumer went away: the span ended early, or the export was
3319+ // cancelled. Either way there is nothing left to decode for.
3320+ if tx.send(Ok(Some(frame))).is_err() {
3321+ return;
3322+ }
3323+ }
3324+}
3325+
3326+/// The two stream decoders, on the thread that opened them.
3327+enum Pictures {
3328+ Hw(HwSession),
3329+ Sw(SwDecoder),
3330+}
3331+
3332+impl Pictures {
3333+ fn next(&mut self) -> crate::Result<Option<(&[u8], &[u8], &[u8], u32, u32)>> {
3334+ match self {
3173 Self::Hw(hw) => hw.next_frame(),3335 Self::Hw(hw) => hw.next_frame(),
3174 Self::Sw(sw) => {3336 Self::Sw(sw) => {
3175 if !sw.advance()? {3337 if !sw.advance()? {
@@ -3245,6 +3407,47 @@ impl SwDecoder {
3245 mod tests {3407 mod tests {
3246 use super::*;3408 use super::*;
3247 3409
3410+ /// How a decode thread ended is never guessed from the channel being shut.
3411+ /// A source that genuinely ran out says so, and the span ends on it; a
3412+ /// thread that died without a word is a failure, because reading it as end
3413+ /// of stream would truncate the picture and *report the export finished*.
3414+ #[test]
3415+ fn a_decoder_that_dies_without_a_word_is_not_end_of_stream() {
3416+ let streamed = |handle, frames| {
3417+ ClipDecoder::Streamed(Streamed {
3418+ frames,
3419+ _thread: DecodeThread(Some(handle)),
3420+ current: None,
3421+ ended: false,
3422+ })
3423+ };
3424+
3425+ let (tx, frames) = sync_channel::<crate::Result<Option<Yuv>>>(2);
3426+ // Said its piece, then finished: the span walks on to its next clip.
3427+ let handle = thread::spawn(move || {
3428+ tx.send(Ok(None)).expect("the receiver is alive");
3429+ });
3430+ let mut ended = streamed(handle, frames);
3431+ assert!(ended.next().expect("a clean end is not an error").is_none());
3432+ // ...and asking again is the same answer and not a disconnect error.
3433+ assert!(ended.next().expect("still not an error").is_none());
3434+
3435+ let (tx, frames) = sync_channel::<crate::Result<Option<Yuv>>>(2);
3436+ // Died holding the sender: the channel shuts with nothing said.
3437+ let handle = thread::spawn(move || {
3438+ let _tx = tx;
3439+ panic!("decoder died");
3440+ });
3441+ let mut died = streamed(handle, frames);
3442+ let e = died
3443+ .next()
3444+ .expect_err("a silent death must fail the export, not end the clip");
3445+ assert!(
3446+ e.to_string().contains("without a picture or a reason"),
3447+ "{e}"
3448+ );
3449+ }
3450+
3248 /// Three seconds of two tones, one per channel, interleaved: enough shape3451 /// Three seconds of two tones, one per channel, interleaved: enough shape
3249 /// that a correlation says something and enough length that the encoder3452 /// that a correlation says something and enough length that the encoder
3250 /// settles into a mode.3453 /// settles into a mode.
crates/engine/src/waveform.rsmodified+157 -12
@@ -2,9 +2,12 @@
2 //! off the same read-only decode path playback uses. Path in, peaks out — no2 //! off the same read-only decode path playback uses. Path in, peaks out — no
3 //! project model, so a lane rework cannot reach it.3 //! project model, so a lane rework cannot reach it.
4 4
5-use std::path::Path;5+use std::path::{Path, PathBuf};
6+use std::sync::mpsc::Receiver;
7+use std::thread;
6 8
7 use crate::AudioSession;9 use crate::AudioSession;
10+use crate::audio::AudioChunk;
8 11
9 /// `(min, max)` of every sample in each `1 / buckets_per_sec` window of12 /// `(min, max)` of every sample in each `1 / buckets_per_sec` window of
10 /// `stream` of `path`'s audio, from media time 0 (priming already trimmed by13 /// `stream` of `path`'s audio, from media time 0 (priming already trimmed by
@@ -23,28 +26,141 @@ use crate::AudioSession;
23 /// flat in it, though: chunks are consumed as they arrive and only the buckets26 /// flat in it, though: chunks are consumed as they arrive and only the buckets
24 /// are kept (2 hours at 10/s is 70k pairs).27 /// are kept (2 hours at 10/s is 70k pairs).
25 ///28 ///
26-/// ponytail: that 50x is 2.4 minutes of background decode for a two-hour film29+/// A source long enough for it is decoded in **windows on several threads** and
27-/// before its lane has a waveform. The upgrade path is decoding the source in30+/// the buckets stitched, which is what that linear cost is divided by:
28-/// segments on several threads — `open_multi_streams` already takes a window per31+/// `open_multi_streams` takes a window per call and seeks to it, and the fold to
29-/// call — and stitching the buckets, which the fold to one envelope makes safe.32+/// one envelope is what makes the join safe — a bucket two windows straddle is
33+/// folded from both, and min/max cannot double-count. A film that cost 23 s of
34+/// one core costs about a quarter of that; a clip short enough that the extra
35+/// opens would outweigh the decode they save ([`jobs_for`]) is read exactly as
36+/// it always was, on this thread.
30 pub fn peaks(37 pub fn peaks(
31 path: impl AsRef<Path>,38 path: impl AsRef<Path>,
32 stream: usize,39 stream: usize,
33 buckets_per_sec: u32,40 buckets_per_sec: u32,
34 ) -> crate::Result<Option<Vec<(f32, f32)>>> {41 ) -> crate::Result<Option<Vec<(f32, f32)>>> {
35- let sources = [(path.as_ref().to_path_buf(), stream)];42+ peaks_over(path.as_ref(), stream, buckets_per_sec, None)
36- let Some((meta, rx)) =43+}
37- AudioSession::open_multi_streams(&sources, &[(Some(0), 0.0, f64::INFINITY)])?44+
38- else {45+/// [`peaks`] with the split forced to `jobs` windows, which is how a test asks
46+/// for the same envelope by both routes.
47+fn peaks_over(
48+ path: &Path,
49+ stream: usize,
50+ buckets_per_sec: u32,
51+ jobs: Option<usize>,
52+) -> crate::Result<Option<Vec<(f32, f32)>>> {
53+ let Some((meta, rx)) = open_window(path, stream, 0.0, f64::INFINITY)? else {
39 return Ok(None);54 return Ok(None);
40 };55 };
41 // Kept fractional: 44100 / 30 is not whole, and rounding it would drift a56 // Kept fractional: 44100 / 30 is not whole, and rounding it would drift a
42 // bucket every few seconds over a long source.57 // bucket every few seconds over a long source.
43 let per_bucket = f64::from(meta.sample_rate) / f64::from(buckets_per_sec.max(1));58 let per_bucket = f64::from(meta.sample_rate) / f64::from(buckets_per_sec.max(1));
44 let channels = (meta.channels as usize).max(1);59 let channels = (meta.channels as usize).max(1);
45- let mut peaks: Vec<(f32, f32)> = Vec::new();60+ let rate = f64::from(meta.sample_rate.max(1));
61+ // A track whose length the container does not state cannot be cut into
62+ // windows at all: `secs` is 0 and the whole of it is read on this thread,
63+ // exactly as it was before there was a split.
64+ let secs = meta.total_samples.unwrap_or(0) as f64 / rate;
65+ let jobs = jobs.unwrap_or_else(|| jobs_for(secs)).max(1);
66+ if jobs == 1 {
67+ return Ok(Some(fold(rx, per_bucket, channels, u64::MAX)));
68+ }
69+ let window = secs / jobs as f64;
70+ // Every other window is spawned before this thread folds its own, so they
71+ // all decode side by side; each carries its own error home rather than
72+ // taking a worker down.
73+ let rest: Vec<_> = (1..jobs)
74+ .map(|k| {
75+ let path = path.to_path_buf();
76+ let start = window * k as f64;
77+ // The last window runs to the end of the file: `total_samples` is
78+ // the container's word for a length, and a tail past it must still
79+ // be drawn.
80+ let end = match k + 1 == jobs {
81+ true => f64::INFINITY,
82+ false => window * (k + 1) as f64,
83+ };
84+ thread::Builder::new()
85+ .name("waveform".into())
86+ .spawn(move || -> crate::Result<Vec<(f32, f32)>> {
87+ match open_window(&path, stream, start, end)? {
88+ Some((_, rx)) => Ok(fold(rx, per_bucket, channels, u64::MAX)),
89+ None => Ok(Vec::new()),
90+ }
91+ })
92+ })
93+ .collect::<Result<_, _>>()?;
94+ // This window ends where the next one's decoder was told to start, by the
95+ // same arithmetic, so the two meet with no gap; the chunk that straddles the
96+ // joint is folded into both and min/max does not double-count.
97+ let mut peaks = fold(rx, per_bucket, channels, (window * rate) as u64);
98+ for handle in rest {
99+ let part = handle.join().map_err(|_| "waveform worker panicked")??;
100+ merge(&mut peaks, &part);
101+ }
102+ Ok(Some(peaks))
103+}
104+
105+/// How many threads a source of `secs` is worth splitting across: one below two
106+/// minutes of sound, where the extra opens (a Matroska's is a cluster walk) cost
107+/// more than the decode they would save, and never more than the machine has —
108+/// nor more than a handful, since an import asks this of every source at once.
109+///
110+/// ponytail: that last clause is a ceiling and not a bound — a library import of
111+/// twenty films runs as many of these as the background executor has threads,
112+/// each with eight of its own. The upgrade path is one pool the waveforms share,
113+/// which is also where a "visible range first" order would live.
114+fn jobs_for(secs: f64) -> usize {
115+ const PER_JOB_SECS: f64 = 60.0;
116+ const CEILING: usize = 8;
117+ if !secs.is_finite() || secs < 2.0 * PER_JOB_SECS {
118+ return 1;
119+ }
120+ let cores = thread::available_parallelism().map_or(1, |n| n.get());
121+ ((secs / PER_JOB_SECS) as usize).min(cores).min(CEILING).max(1)
122+}
123+
124+/// `part` folded into `peaks` bucket for bucket. Both are indexed absolutely,
125+/// so this is a straight min/max: an empty bucket is `(0.0, 0.0)` and every
126+/// value is clamped to `[-1.0, 1.0]`, which makes the empty pair the identity.
127+fn merge(peaks: &mut Vec<(f32, f32)>, part: &[(f32, f32)]) {
128+ if part.len() > peaks.len() {
129+ peaks.resize(part.len(), (0.0, 0.0));
130+ }
131+ for (slot, &(lo, hi)) in peaks.iter_mut().zip(part) {
132+ slot.0 = slot.0.min(lo);
133+ slot.1 = slot.1.max(hi);
134+ }
135+}
46 136
137+/// One window of one stream, opened the way playback opens it.
138+fn open_window(
139+ path: &Path,
140+ stream: usize,
141+ start_secs: f64,
142+ end_secs: f64,
143+) -> crate::Result<Option<(crate::AudioMeta, Receiver<AudioChunk>)>> {
144+ let sources = [(PathBuf::from(path), stream)];
145+ AudioSession::open_multi_streams(&sources, &[(Some(0), start_secs, end_secs)])
146+}
147+
148+/// Min/max per bucket of everything `rx` carries, at absolute bucket positions:
149+/// `start_sample` counts from the source's own first audible sample whatever
150+/// window the session was opened at. Stops at the first chunk beginning at or
151+/// past `stop_sample`, and dropping the receiver there is what stops that
152+/// window's decoder.
153+fn fold(
154+ rx: Receiver<AudioChunk>,
155+ per_bucket: f64,
156+ channels: usize,
157+ stop_sample: u64,
158+) -> Vec<(f32, f32)> {
159+ let mut peaks: Vec<(f32, f32)> = Vec::new();
47 for chunk in rx {160 for chunk in rx {
161+ if chunk.start_sample >= stop_sample {
162+ break;
163+ }
48 for (frame, values) in chunk.samples.chunks(channels).enumerate() {164 for (frame, values) in chunk.samples.chunks(channels).enumerate() {
49 let bucket = ((chunk.start_sample + frame as u64) as f64 / per_bucket) as usize;165 let bucket = ((chunk.start_sample + frame as u64) as f64 / per_bucket) as usize;
50 if bucket >= peaks.len() {166 if bucket >= peaks.len() {
@@ -58,14 +174,14 @@ pub fn peaks(
58 }174 }
59 }175 }
60 }176 }
61- Ok(Some(peaks))177+ peaks
62 }178 }
63 179
64 #[cfg(test)]180 #[cfg(test)]
65 mod tests {181 mod tests {
66 use std::path::PathBuf;182 use std::path::PathBuf;
67 183
68- use super::peaks;184+ use super::{peaks, peaks_over};
69 185
70 const BPS: u32 = 10;186 const BPS: u32 = 10;
71 187
@@ -176,6 +292,35 @@ mod tests {
176 }292 }
177 }293 }
178 294
295+ /// The split is an optimisation and nothing else: four windows decoded side
296+ /// by side draw the very envelope the single-threaded walk draws, bucket for
297+ /// bucket. The joints are where a window that started a sample late or
298+ /// stopped a chunk early would show, so this is the check that a film's
299+ /// waveform is still the film's.
300+ #[test]
301+ fn a_split_decode_draws_the_same_envelope() {
302+ let file = asset("test_av.mp4");
303+ let whole = peaks_over(&file, 0, BPS, Some(1))
304+ .expect("open")
305+ .expect("test_av.mp4 has an audio track");
306+ let split = peaks_over(&file, 0, BPS, Some(4))
307+ .expect("open")
308+ .expect("test_av.mp4 has an audio track");
309+ assert_eq!(whole.len(), split.len(), "the split lost or grew buckets");
310+ // Not bit-equality: a window seeks into the middle of an AAC stream and
311+ // its filterbank is primed from a preceding packet rather than carried
312+ // over, so a bucket can land a ten-thousandth away. A lane is drawn a
313+ // hundred pixels tall, where that is a thousandth of a pixel; a window
314+ // that started late or stopped early is off by whole tenths and is what
315+ // this catches.
316+ for (i, (w, s)) in whole.iter().zip(&split).enumerate() {
317+ assert!(
318+ (w.0 - s.0).abs() < 1e-3 && (w.1 - s.1).abs() < 1e-3,
319+ "bucket {i}: whole {w:?}, split {s:?}"
320+ );
321+ }
322+ }
323+
179 #[test]324 #[test]
180 fn video_only_source_has_no_peaks() {325 fn video_only_source_has_no_peaks() {
181 assert!(326 assert!(
vendor/cros-codecs/src/decoder/stateless/h264.rsmodified+10 -7
@@ -954,13 +954,16 @@ where
954 954
955 debug!("frame_num gap detected.");955 debug!("frame_num gap detected.");
956 956
957- if !sps.gaps_in_frame_num_value_allowed_flag {957+ // LOCAL PATCH (see /Cargo.toml [patch.crates-io]): a gap is filled with
958- return Err(anyhow!(958+ // the §8.2.5.2 non-existing frames whatever the flag says, instead of
959- "Invalid frame_num: {}. Assuming unintentional loss of pictures",959+ // failing the stream. The flag means "this file has no intentional
960- frame_num960+ // gaps", and it is right -- the gap is *ours*: an editor starts decoding
961- ));961+ // at a random access point in the middle of a film, and the pictures
962- }962+ // between the previous reference and it were never decoded. Refusing
963-963+ // here is what made every seek into an open-GOP Blu-ray remux fall back
964+ // to a software decoder (17 of 20 in `bench scrub`), and the standing in
965+ // frames this loop builds are exactly what the reference lists of the
966+ // pictures after the gap look for.
964 let mut unused_short_term_frame_num =967 let mut unused_short_term_frame_num =
965 (self.codec.prev_ref_pic_info.frame_num + 1) % sps.max_frame_num();968 (self.codec.prev_ref_pic_info.frame_num + 1) % sps.max_frame_num();
966 while unused_short_term_frame_num != frame_num {969 while unused_short_term_frame_num != frame_num {