A silence cut's boundary decodes forward, not flush
Browse files at this commite045b5e071e02e369f9dded1c176cbb3d9de6ab6Parent: c707e9d- fix
- a silence cut's boundary decodes forward, not flush
5 changed files +482 -11
- crates/app/src/player/transport.rs +54 -1
- crates/engine-hw/src/lib.rs +128 -6
- crates/engine/examples/bench.rs +193 -4
- crates/engine/src/playback.rs +30 -0
- crates/engine/tests/playback.rs +77 -0
crates/app/src/player/transport.rsmodified+54 -1
| @@ -18,6 +18,12 @@ impl Player { | ||
| 18 | 18 | let Some(session) = &mut self.session else { |
| 19 | 19 | return; |
| 20 | 20 | }; |
| 21 | + // Whether the span now decoding has yet to hand over a picture, read | |
| 22 | + // *before* the drain: the frame the drain is about to take is the one | |
| 23 | + // that ends the prime, and its own lateness -- however long the span's | |
| 24 | + // reopen took -- is exactly what the resync below must not answer with | |
| 25 | + // another reopen. | |
| 26 | + let priming = session.picture_priming(); | |
| 21 | 27 | let target = session.now() * self.fps; |
| 22 | 28 | let mut newest: Option<Frame> = None; |
| 23 | 29 | // A frame the screen is owed: a seek's landing, and the one readiness |
| @@ -95,6 +101,12 @@ impl Player { | ||
| 95 | 101 | // (`PlaybackSession::resync_picture`), so nothing the ear is following |
| 96 | 102 | // moves. Never on a frame a seek owed: that one is late by however long |
| 97 | 103 | // its own reopen took, and answering it with another reopen is a loop. |
| 104 | + // The same is true of a *clip boundary's* first frame -- a silence cut | |
| 105 | + // leaves a timeline of clips shorter than their own reopen -- so the | |
| 106 | + // restart waits for a span that has delivered and fallen behind after | |
| 107 | + // it (`resync_due`, primed on `PlaybackSession::picture_priming`): | |
| 108 | + // restarting the prime only buys the same lateness again, and every | |
| 109 | + // `RESYNC_GAP` after that. | |
| 98 | 110 | // |
| 99 | 111 | // corner-cut: on a machine that cannot decode the file in real time at |
| 100 | 112 | // all this settles into one restart per `RESYNC_GAP` -- in sync, and |
| @@ -102,7 +114,7 @@ impl Player { | ||
| 102 | 114 | // The upgrade path is dropping late frames *inside* the worker (skip |
| 103 | 115 | // the convert and the send for anything already past due), which needs |
| 104 | 116 | // the deadline shared with it. |
| 105 | - if !owed && session.is_playing() && should_resync(late, self.resynced) { | |
| 117 | + if !owed && session.is_playing() && resync_due(late, self.resynced, priming) { | |
| 106 | 118 | eprintln!("picture {late:.3}s behind the clock: restarting it there"); |
| 107 | 119 | session.resync_picture(); |
| 108 | 120 | self.held = None; |
| @@ -306,3 +318,44 @@ impl Player { | ||
| 306 | 318 | } |
| 307 | 319 | } |
| 308 | 320 | } |
| 321 | + | |
| 322 | +/// Whether a late picture is restarted at the clock: the rule | |
| 323 | +/// [`should_resync`] always was, plus the prime it must not interrupt. A span | |
| 324 | +/// that has not handed over a picture yet is late by exactly its own reopen | |
| 325 | +/// -- a clip boundary on a silence-cut timeline most of all, where the clips | |
| 326 | +/// are shorter than that reopen -- and restarting it spends the reopen again | |
| 327 | +/// for the same lateness, every `RESYNC_GAP` after that. The restart is for a | |
| 328 | +/// span that has *delivered* and fallen behind afterwards. | |
| 329 | +pub(crate) fn resync_due(late: f64, last: Option<Instant>, priming: bool) -> bool { | |
| 330 | + !priming && should_resync(late, last) | |
| 331 | +} | |
| 332 | + | |
| 333 | +#[cfg(test)] | |
| 334 | +mod tests { | |
| 335 | + use super::*; | |
| 336 | + | |
| 337 | + /// The prime gate: a span still owing its first picture is never | |
| 338 | + /// restarted, however late the last frame to arrive was. The same span | |
| 339 | + /// once it has delivered keeps the rule -- thresholds and cooldown | |
| 340 | + /// unchanged -- because a decoder that is genuinely too slow is still | |
| 341 | + /// behind on its second frame, one repaint later. | |
| 342 | + #[test] | |
| 343 | + fn a_priming_span_is_never_restarted() { | |
| 344 | + assert!(!resync_due(0., None, true)); | |
| 345 | + assert!(!resync_due(LATE_RESYNC, None, true)); | |
| 346 | + assert!(!resync_due(9., None, true)); | |
| 347 | + // ...and the rule itself, exactly as it was, once the prime is over. | |
| 348 | + assert!(!resync_due(0., None, false)); | |
| 349 | + assert!(!resync_due(LATE_RESYNC, None, false)); | |
| 350 | + assert!(resync_due(LATE_RESYNC + 0.1, None, false)); | |
| 351 | + // A decoder still behind right after a restart waits out the gap | |
| 352 | + // instead of reopening at every repaint... | |
| 353 | + assert!(!resync_due(9., Some(Instant::now()), false)); | |
| 354 | + // ...and fires again once it has passed. | |
| 355 | + assert!(resync_due( | |
| 356 | + 9., | |
| 357 | + Some(Instant::now() - RESYNC_GAP - Duration::from_millis(1)), | |
| 358 | + false | |
| 359 | + )); | |
| 360 | + } | |
| 361 | +} |
crates/engine-hw/src/lib.rsmodified+128 -6
| @@ -141,6 +141,53 @@ const LEADING_LIMIT: u32 = 64; | ||
| 141 | 141 | /// at ~3 MB of video memory each. |
| 142 | 142 | const DMA_HOLD: usize = 6; |
| 143 | 143 | |
| 144 | +/// How far ahead of the decode position [`Session::seek_to`] walks forward | |
| 145 | +/// rather than flushing, in seconds of the stream's own frames. A silence cut | |
| 146 | +/// lands the next span ahead of the decoder by the length of what it removed | |
| 147 | +/// -- tenths of a second -- and walking that forward costs only the decode of | |
| 148 | +/// the frames in between, dropped without the read-back ([`Session::pump`]'s | |
| 149 | +/// skip path) with the decoder's reference chain and pipeline depth left | |
| 150 | +/// standing. The flush it replaces costs a decoder reset, a demuxer seek to | |
| 151 | +/// the random access point, up to a group of skip-decoded pictures behind it, | |
| 152 | +/// and a full re-prime before the first frame is out again (~178 ms measured | |
| 153 | +/// at 4K, which is longer than the clips a silence cut leaves); past half a | |
| 154 | +/// second of walking, the skip-decode run alone approaches that bill and a | |
| 155 | +/// real seek wins. | |
| 156 | +const FORWARD_SECS: f64 = 0.5; | |
| 157 | + | |
| 158 | +/// The forward reach in frames: [`FORWARD_SECS`] at the stream's own rate. | |
| 159 | +/// `0` for a rate the stream does not really state, which is "never forward" | |
| 160 | +/// -- exactly the flush every reposition did before this distinction existed. | |
| 161 | +fn forward_limit(frame_rate: f64) -> u32 { | |
| 162 | + (FORWARD_SECS * frame_rate).round().max(0.) as u32 | |
| 163 | +} | |
| 164 | + | |
| 165 | +/// How a reposition to `target` (a 0-based display frame) is reached from | |
| 166 | +/// `position`, the frame the session would hand out next. Pure arithmetic, | |
| 167 | +/// so every shape of the answer is testable without a GPU. | |
| 168 | +#[derive(Debug, PartialEq, Eq, Clone, Copy)] | |
| 169 | +enum Reposition { | |
| 170 | + /// Decode forward from where the session stands, dropping this many | |
| 171 | + /// pictures on the way: no flush, no demuxer seek, no re-prime. | |
| 172 | + Forward(u32), | |
| 173 | + /// Flush the decoder and seek the demuxer to the random access point at | |
| 174 | + /// or before `target`. | |
| 175 | + Flush, | |
| 176 | +} | |
| 177 | + | |
| 178 | +fn reposition(position: i64, target: i64, frame_count: u32, limit: u32) -> Reposition { | |
| 179 | + // A decoder cannot walk backwards, and a target at or past the last frame | |
| 180 | + // is not one decoding forward can hand out -- both take the seek that has | |
| 181 | + // always handled them, EOF included. | |
| 182 | + if target < position || target >= i64::from(frame_count) { | |
| 183 | + return Reposition::Flush; | |
| 184 | + } | |
| 185 | + match u32::try_from(target - position) { | |
| 186 | + Ok(ahead) if ahead <= limit => Reposition::Forward(ahead), | |
| 187 | + _ => Reposition::Flush, | |
| 188 | + } | |
| 189 | +} | |
| 190 | + | |
| 144 | 191 | struct Session { |
| 145 | 192 | decoder: Decoder, |
| 146 | 193 | /// NV12 (or, for a 10-bit stream, P010) descriptor for `vaGetImage`, |
| @@ -159,6 +206,11 @@ struct Session { | ||
| 159 | 206 | flushed: bool, |
| 160 | 207 | /// Pictures still to be decoded and thrown away to land on a seek target. |
| 161 | 208 | skip: u32, |
| 209 | + /// The display frame the next `pump` would hand out, however it gets | |
| 210 | + /// there: one further along for every handle taken off `ready`, skipped | |
| 211 | + /// past and delivered alike. The one thing that can tell a reposition | |
| 212 | + /// *ahead* of the decoder from one behind it ([`Session::seek_to`]). | |
| 213 | + position: i64, | |
| 162 | 214 | /// Access units dropped because they referenced pictures this session never |
| 163 | 215 | /// decoded -- see [`Session::pump`]. Counted rather than flagged so the |
| 164 | 216 | /// tolerance ends somewhere, and raised to [`LEADING_LIMIT`] the moment a |
| @@ -321,6 +373,7 @@ impl Session { | ||
| 321 | 373 | timestamp: 0, |
| 322 | 374 | flushed: false, |
| 323 | 375 | skip: 0, |
| 376 | + position: 0, | |
| 324 | 377 | // A stream read from its own beginning has no missing references |
| 325 | 378 | // and therefore no leading pictures to forgive: the window opens |
| 326 | 379 | // only for a session positioned somewhere else ([`Session::open_at`]), |
| @@ -349,6 +402,7 @@ impl Session { | ||
| 349 | 402 | let target_frame = target_sample.saturating_sub(1); |
| 350 | 403 | let first = session.demuxer.seek_to_sync_at_or_before(target_frame); |
| 351 | 404 | session.skip = (i64::from(target_frame) - first).max(0) as u32; |
| 405 | + session.position = first; | |
| 352 | 406 | if target_frame > 0 { |
| 353 | 407 | session.leading = 0; |
| 354 | 408 | } |
| @@ -358,10 +412,15 @@ impl Session { | ||
| 358 | 412 | /// Repositions an **open** session, exactly as [`Session::open_at`] positions |
| 359 | 413 | /// a new one: the next [`Session::pump`] hands back sample `target_sample`. |
| 360 | 414 | /// |
| 361 | - /// This is what a seek costs when the session is kept: a demuxer seek and a | |
| 362 | - /// decoder flush, and *not* the VA-API initialisation (~90 ms measured), the | |
| 363 | - /// render node probe, the container parse and the surface pool that opening | |
| 364 | - /// one again pays for. | |
| 415 | + /// This is what a seek costs when the session is kept, and most of it is | |
| 416 | + /// skippable: a target *ahead* of where the decoder stands, within | |
| 417 | + /// [`FORWARD_SECS`] of it, is reached by decoding on and dropping the | |
| 418 | + /// pictures in between ([`reposition`]) -- no flush, no demuxer seek, no | |
| 419 | + /// re-prime -- which is the landing a silence cut leaves at every boundary | |
| 420 | + /// it cuts to, a fraction of a second ahead of the clip that just ended. | |
| 421 | + /// Everything else pays the demuxer seek and the decoder flush, and *not* | |
| 422 | + /// the VA-API initialisation (~90 ms measured), the render node probe, the | |
| 423 | + /// container parse and the surface pool that opening one again pays for. | |
| 365 | 424 | /// |
| 366 | 425 | /// The flush is the whole of the decoder's reset: cros-codecs finishes what |
| 367 | 426 | /// is in flight and goes to `Reset`, from where it resumes on the next |
| @@ -371,6 +430,22 @@ impl Session { | ||
| 371 | 430 | /// flush makes ready are dropped with `ready`: they belong to where the |
| 372 | 431 | /// session *was*. |
| 373 | 432 | fn seek_to(&mut self, target_sample: u32) -> Result<(), String> { |
| 433 | + // The same arithmetic `open_at` does, for the same reason. | |
| 434 | + let target_frame = target_sample.saturating_sub(1); | |
| 435 | + if let Reposition::Forward(ahead) = reposition( | |
| 436 | + self.position, | |
| 437 | + i64::from(target_frame), | |
| 438 | + self.meta.frame_count, | |
| 439 | + forward_limit(self.meta.frame_rate), | |
| 440 | + ) { | |
| 441 | + // Nothing about the session moves but the skip: not the decoder, | |
| 442 | + // not the access unit half-fed to it, not the pictures already | |
| 443 | + // waiting in `ready` -- the skip walks past all of them exactly | |
| 444 | + // as it walks past the ones still to decode, one `position` step | |
| 445 | + // per handle either way. | |
| 446 | + self.skip = self.skip.saturating_add(ahead); | |
| 447 | + return Ok(()); | |
| 448 | + } | |
| 374 | 449 | self.decoder.get().flush().map_err(|e| e.to_string())?; |
| 375 | 450 | // Drain what the flush completed, dropping every handle: each one holds |
| 376 | 451 | // a pool buffer out of circulation, and none of them is ours to show. |
| @@ -388,10 +463,9 @@ impl Session { | ||
| 388 | 463 | self.ready.clear(); |
| 389 | 464 | self.pending.clear(); |
| 390 | 465 | self.flushed = false; |
| 391 | - // The same arithmetic `open_at` does, for the same reason. | |
| 392 | - let target_frame = target_sample.saturating_sub(1); | |
| 393 | 466 | let first = self.demuxer.seek_to_sync_at_or_before(target_frame); |
| 394 | 467 | self.skip = (i64::from(target_frame) - first).max(0) as u32; |
| 468 | + self.position = first; | |
| 395 | 469 | // ...and the same open-GOP window: a session positioned anywhere but the |
| 396 | 470 | // start may meet leading pictures that reference what it never decoded. |
| 397 | 471 | self.leading = if target_frame > 0 { 0 } else { LEADING_LIMIT }; |
| @@ -425,6 +499,9 @@ impl Session { | ||
| 425 | 499 | } |
| 426 | 500 | } |
| 427 | 501 | if let Some(handle) = self.ready.pop_front() { |
| 502 | + // One picture further along, shown or skipped past alike: | |
| 503 | + // this is the only place [`Session::position`] walks. | |
| 504 | + self.position += 1; | |
| 428 | 505 | // Seek discards: dropping the handle skips the `vaGetImage` |
| 429 | 506 | // read-back (~1.2 ms/picture) and frees its pool buffer. |
| 430 | 507 | if self.skip > 0 { |
| @@ -1982,4 +2059,49 @@ mod tests { | ||
| 1982 | 2059 | // H.264 here is 8-bit 4:2:0; the table has no 10-bit profile for it. |
| 1983 | 2060 | assert_eq!(caps.decode_10bit & CAP_H264, 0, "{caps:?}"); |
| 1984 | 2061 | } |
| 2062 | + | |
| 2063 | + /// Every shape of the forward-or-flush decision a reposition makes, with | |
| 2064 | + /// no GPU in sight: the boundary a silence cut leaves is a target a few | |
| 2065 | + /// frames *ahead* of the decoder and that is the walk; behind it, past the | |
| 2066 | + /// reach, and past the end of the stream are the flush. | |
| 2067 | + #[test] | |
| 2068 | + fn a_target_ahead_within_the_reach_walks_forward() { | |
| 2069 | + use Reposition::{Flush, Forward}; | |
| 2070 | + // A 30 fps stream, so the reach is [`FORWARD_SECS`] of it. | |
| 2071 | + let (count, limit) = (10_000u32, forward_limit(30.0)); | |
| 2072 | + assert_eq!(forward_limit(30.0), 15); | |
| 2073 | + // The boundary a 0.3 s silence cut leaves: 9 frames ahead, dropped | |
| 2074 | + // unread on the way to exactly the target. | |
| 2075 | + assert_eq!(reposition(120, 129, count, limit), Forward(9)); | |
| 2076 | + // Exactly at the reach, and a reseek to exactly where the decoder | |
| 2077 | + // stands (a superseded span's landing): nothing to do but not flush. | |
| 2078 | + assert_eq!(reposition(120, 135, count, limit), Forward(15)); | |
| 2079 | + assert_eq!(reposition(120, 120, count, limit), Forward(0)); | |
| 2080 | + // One frame past either end of the walk is the flush's. | |
| 2081 | + assert_eq!(reposition(120, 136, count, limit), Flush); | |
| 2082 | + assert_eq!(reposition(120, 119, count, limit), Flush); | |
| 2083 | + assert_eq!(reposition(120, 0, count, limit), Flush); | |
| 2084 | + // The last frame of the stream is a frame like any other... | |
| 2085 | + assert_eq!(reposition(9_995, 9_999, count, limit), Forward(4)); | |
| 2086 | + // ...while a target at or past the end is not one decoding forward | |
| 2087 | + // can hand out: EOF falls back to the seek that always handled it. | |
| 2088 | + assert_eq!(reposition(9_995, 10_000, count, limit), Flush); | |
| 2089 | + assert_eq!(reposition(9_995, 60_000, count, limit), Flush); | |
| 2090 | + // From the end itself -- everything delivered, `pump` at clean EOF -- | |
| 2091 | + // even a target inside the stream is behind. | |
| 2092 | + assert_eq!(reposition(10_000, 9_999, count, limit), Flush); | |
| 2093 | + } | |
| 2094 | + | |
| 2095 | + /// The reach is time, carried at the stream's own rate, and a stream that | |
| 2096 | + /// states no rate gets none of it: such a session keeps the behaviour | |
| 2097 | + /// every reposition had, rather than a skip of nonsense frames. | |
| 2098 | + #[test] | |
| 2099 | + fn the_reach_is_half_a_second_at_the_streams_own_rate() { | |
| 2100 | + assert_eq!(forward_limit(23.976), 12); | |
| 2101 | + assert_eq!(forward_limit(24.0), 12); | |
| 2102 | + assert_eq!(forward_limit(60.0), 30); | |
| 2103 | + assert_eq!(forward_limit(0.0), 0); | |
| 2104 | + assert_eq!(forward_limit(f64::NAN), 0); | |
| 2105 | + assert_eq!(forward_limit(-30.0), 0); | |
| 2106 | + } | |
| 1985 | 2107 | } |
crates/engine/examples/bench.rsmodified+193 -4
| @@ -45,7 +45,7 @@ use std::path::{Path, PathBuf}; | ||
| 45 | 45 | use std::time::{Duration, Instant}; |
| 46 | 46 | |
| 47 | 47 | use engine::export::{EncoderSeat, ExportSettings, Format}; |
| 48 | -use engine::project::{Clip, LaneKind, Project, Source, Speed}; | |
| 48 | +use engine::project::{Clip, Lane, LaneKind, Project, Source, Speed}; | |
| 49 | 49 | |
| 50 | 50 | // `posix_fadvise(2)`, straight from libc, which std already links: dropping |
| 51 | 51 | // this file's pages needs no crate and no privilege. |
| @@ -63,6 +63,12 @@ fn main() { | ||
| 63 | 63 | "seek" => seek_bench(&path, arg_f64(args.next(), "seconds")), |
| 64 | 64 | "seekstorm" => seekstorm_bench(&path, arg_seed(args.next())), |
| 65 | 65 | "playloop" => playloop_bench(&path, arg_f64(args.next(), "seconds"), arg_seed(args.next())), |
| 66 | + "cutloop" => cutloop_bench( | |
| 67 | + &path, | |
| 68 | + arg_or(args.next(), 20.0) as u32, | |
| 69 | + arg_or(args.next(), 0.5), | |
| 70 | + arg_or(args.next(), 0.3), | |
| 71 | + ), | |
| 66 | 72 | "scrub" => scrub_bench(&path), |
| 67 | 73 | "waveform" => waveform_bench(&path), |
| 68 | 74 | "export" => { |
| @@ -79,6 +85,7 @@ fn usage() -> ! { | ||
| 79 | 85 | "usage: bench open <file>\n bench seek <file> <secs>\n \ |
| 80 | 86 | bench seekstorm <file> [seed]\n \ |
| 81 | 87 | bench playloop <file> <secs> [seed]\n \ |
| 88 | + bench cutloop <file> [regions=20] [keep_s=0.5] [cut_s=0.3]\n \ | |
| 82 | 89 | bench scrub <file>\n bench waveform <file>\n \ |
| 83 | 90 | bench export <file> <h264sw|h264hw|av1|hevc|hevchw> <out_dir>" |
| 84 | 91 | ); |
| @@ -90,6 +97,12 @@ fn arg_f64(arg: Option<String>, what: &str) -> f64 { | ||
| 90 | 97 | .unwrap_or_else(|| panic!("missing {what}")) |
| 91 | 98 | } |
| 92 | 99 | |
| 100 | +/// An optional measurement parameter with a default, so a rerun that names | |
| 101 | +/// nothing runs the same shape of timeline the last one did. | |
| 102 | +fn arg_or(arg: Option<String>, default: f64) -> f64 { | |
| 103 | + arg.and_then(|s| s.parse().ok()).unwrap_or(default) | |
| 104 | +} | |
| 105 | + | |
| 93 | 106 | /// The seed the random metrics draw their positions from: same seed, same |
| 94 | 107 | /// seeks, so a before and an after are the same measurement. |
| 95 | 108 | fn arg_seed(arg: Option<String>) -> u64 { |
| @@ -387,9 +400,10 @@ fn seekstorm_bench(path: &Path, seed: u64) { | ||
| 387 | 400 | /// boundary, or by the late-picture resync, which is counted separately in the |
| 388 | 401 | /// note. |
| 389 | 402 | /// |
| 390 | -/// The resync rule is the app's, repeated here (`LATE_RESYNC`, `RESYNC_GAP` in | |
| 391 | -/// `crates/app/src/transport.rs`) because an engine example cannot depend on | |
| 392 | -/// the binary. Repeated only: nothing in this file changes how playback runs. | |
| 403 | +/// The resync rule is the app's, repeated here (`LATE_RESYNC`, `RESYNC_GAP` | |
| 404 | +/// and the never-during-a-prime gate in `crates/app/src/player/transport.rs`) | |
| 405 | +/// because an engine example cannot depend on the binary. Repeated only: | |
| 406 | +/// nothing in this file changes how playback runs. | |
| 393 | 407 | const PLAYLOOP_SEEK_GAP: Duration = Duration::from_secs(5); |
| 394 | 408 | const LATE_RESYNC: f64 = 0.4; |
| 395 | 409 | const RESYNC_GAP: Duration = Duration::from_secs(2); |
| @@ -421,6 +435,9 @@ fn playloop_bench(path: &Path, secs: f64, seed: u64) { | ||
| 421 | 435 | let mut next_seek = start + PLAYLOOP_SEEK_GAP; |
| 422 | 436 | while Instant::now() < deadline { |
| 423 | 437 | session.tick(); |
| 438 | + // Read before the drain, as the app does: the frame the drain takes | |
| 439 | + // is the one that ends the prime, and its lateness is the reopen's. | |
| 440 | + let priming = session.picture_priming(); | |
| 424 | 441 | let target = session.now() * fps; |
| 425 | 442 | let mut newest = None; |
| 426 | 443 | while session.is_playing() || owed { |
| @@ -455,6 +472,7 @@ fn playloop_bench(path: &Path, secs: f64, seed: u64) { | ||
| 455 | 472 | owed = false; |
| 456 | 473 | } |
| 457 | 474 | if !owed |
| 475 | + && !priming | |
| 458 | 476 | && session.is_playing() |
| 459 | 477 | && late > LATE_RESYNC |
| 460 | 478 | && last_resync.is_none_or(|t| t.elapsed() >= RESYNC_GAP) |
| @@ -514,6 +532,177 @@ fn playloop_bench(path: &Path, secs: f64, seed: u64) { | ||
| 514 | 532 | ); |
| 515 | 533 | } |
| 516 | 534 | |
| 535 | +// ----------------------------------------------------------------- cutloop | |
| 536 | + | |
| 537 | +/// The freeze metric: a **silence-cut** timeline -- `regions` holes of | |
| 538 | +/// `cut_s` punched out of one file, `keep_s` of picture left between them -- | |
| 539 | +/// played end to end with the app's own pump, drop policy and resync rule | |
| 540 | +/// (`playloop_bench`'s, without the random seeks). Every boundary between two | |
| 541 | +/// kept clips is a same-file reseek of the picture worker while the audio | |
| 542 | +/// feeder runs straight through -- exactly the timeline a silence removal | |
| 543 | +/// leaves, and the complaint it brought: clips shorter than a decoder's own | |
| 544 | +/// re-prime, a picture that starves while the sound plays on, and a | |
| 545 | +/// late-picture resync every `RESYNC_GAP` buying the same reopen again. | |
| 546 | +/// | |
| 547 | +/// What comes out: displayed and dropped pictures per wall-clock second (a | |
| 548 | +/// freeze is a second that shows nothing), on stderr one line each, and in | |
| 549 | +/// the TSV the per-second displayed counts beside the totals -- restarts, | |
| 550 | +/// resyncs and underruns -- that say which mechanism spent the time. | |
| 551 | +/// | |
| 552 | +/// ```text | |
| 553 | +/// bench cutloop <4k file> 20 0.5 0.3 | |
| 554 | +/// ``` | |
| 555 | +fn cutloop_bench(path: &Path, regions: u32, keep_s: f64, cut_s: f64) { | |
| 556 | + let mut session = match engine::PlaybackSession::open(path) { | |
| 557 | + Ok(session) => session, | |
| 558 | + Err(e) => { | |
| 559 | + row(path, "cutloop_displayed", "count", &[], &format!("FAIL({e})")); | |
| 560 | + return; | |
| 561 | + } | |
| 562 | + }; | |
| 563 | + // Muted like the tests: the device still schedules the stream and the | |
| 564 | + // clock still counts its samples, which is the whole of what this | |
| 565 | + // measures -- the sound is the master the picture is starving against. | |
| 566 | + session.set_gain(0.0); | |
| 567 | + session.drop_late_pictures(true); | |
| 568 | + let fps = session.meta().frame_rate; | |
| 569 | + | |
| 570 | + // Cut every hole out before a single picture decodes: keep, cut, keep, | |
| 571 | + // cut -- `regions` pairs of boundaries, so the timeline that plays is | |
| 572 | + // `regions + 1` clips of one file with the holes joined shut. | |
| 573 | + let stride = keep_s + cut_s; | |
| 574 | + for i in 0..regions { | |
| 575 | + let at = keep_s + f64::from(i) * stride; | |
| 576 | + if !session.cut_at(at) || !session.cut_at(at + cut_s) { | |
| 577 | + row( | |
| 578 | + path, | |
| 579 | + "cutloop_displayed", | |
| 580 | + "count", | |
| 581 | + &[], | |
| 582 | + &format!("FAIL(file shorter than region {i} of {regions})"), | |
| 583 | + ); | |
| 584 | + return; | |
| 585 | + } | |
| 586 | + } | |
| 587 | + // The holes are the odd clips: index 1, `regions` times over, as every | |
| 588 | + // delete closes the list up onto the next one. | |
| 589 | + for i in 0..regions { | |
| 590 | + if !session.delete_clip(Lane::V1, 1) { | |
| 591 | + row( | |
| 592 | + path, | |
| 593 | + "cutloop_displayed", | |
| 594 | + "count", | |
| 595 | + &[], | |
| 596 | + &format!("FAIL(hole {i} of {regions} would not delete)"), | |
| 597 | + ); | |
| 598 | + return; | |
| 599 | + } | |
| 600 | + } | |
| 601 | + let timeline = session.timeline_duration(); | |
| 602 | + eprintln!( | |
| 603 | + "cutloop: {regions} regions of {cut_s}s cut, {} clips of {keep_s}s left, \ | |
| 604 | + {timeline:.1}s of timeline at {fps:.3} fps", | |
| 605 | + regions + 1 | |
| 606 | + ); | |
| 607 | + | |
| 608 | + session.seek(0.0); | |
| 609 | + session.play(); | |
| 610 | + let start = Instant::now(); | |
| 611 | + let mut held: Option<engine::Frame> = None; | |
| 612 | + let (mut shown, mut dropped, mut resyncs) = (0u64, 0u64, 0u64); | |
| 613 | + let mut last_resync: Option<Instant> = None; | |
| 614 | + // The first frame of the run is owed exactly as a seek's landing is. | |
| 615 | + let mut owed = true; | |
| 616 | + let mut per_second: Vec<(u64, u64)> = vec![(0, 0)]; | |
| 617 | + loop { | |
| 618 | + session.tick(); | |
| 619 | + // Read before the drain, as the app does: the frame the drain takes | |
| 620 | + // is the one that ends the prime, and its lateness is the reopen's. | |
| 621 | + let priming = session.picture_priming(); | |
| 622 | + let target = session.now() * fps; | |
| 623 | + let mut newest = None; | |
| 624 | + let mut dropped_now = 0u64; | |
| 625 | + while session.is_playing() || owed { | |
| 626 | + let frame = match held.take() { | |
| 627 | + Some(frame) => frame, | |
| 628 | + None => match session.try_frame() { | |
| 629 | + Some(frame) => frame, | |
| 630 | + None => break, | |
| 631 | + }, | |
| 632 | + }; | |
| 633 | + if f64::from(frame.index) <= target { | |
| 634 | + dropped_now += u64::from(newest.is_some()); | |
| 635 | + newest = Some(frame); | |
| 636 | + } else { | |
| 637 | + held = Some(frame); | |
| 638 | + break; | |
| 639 | + } | |
| 640 | + } | |
| 641 | + dropped += dropped_now; | |
| 642 | + let late = newest | |
| 643 | + .as_ref() | |
| 644 | + .map_or(0.0, |f| (target - f64::from(f.index)) / fps); | |
| 645 | + if newest.is_some() { | |
| 646 | + shown += 1; | |
| 647 | + owed = false; | |
| 648 | + } | |
| 649 | + let slot = start.elapsed().as_secs() as usize; | |
| 650 | + if per_second.len() <= slot { | |
| 651 | + per_second.resize(slot + 1, (0, 0)); | |
| 652 | + } | |
| 653 | + per_second[slot].0 += u64::from(newest.is_some()); | |
| 654 | + per_second[slot].1 += dropped_now; | |
| 655 | + if !owed | |
| 656 | + && !priming | |
| 657 | + && session.is_playing() | |
| 658 | + && late > LATE_RESYNC | |
| 659 | + && last_resync.is_none_or(|t| t.elapsed() >= RESYNC_GAP) | |
| 660 | + { | |
| 661 | + eprintln!("cutloop: picture {late:.3}s behind the clock: restarting it there"); | |
| 662 | + session.resync_picture(); | |
| 663 | + held = None; | |
| 664 | + last_resync = Some(Instant::now()); | |
| 665 | + resyncs += 1; | |
| 666 | + } | |
| 667 | + // End of stream is the end of the run: the clock is halted on the out | |
| 668 | + // point, as the app's transport does, so the last second's bucket is | |
| 669 | + // closed rather than walked off the end of the timeline. | |
| 670 | + if session.is_eos() { | |
| 671 | + session.halt_at_end(); | |
| 672 | + break; | |
| 673 | + } | |
| 674 | + std::thread::sleep(Duration::from_millis(1)); | |
| 675 | + } | |
| 676 | + session.pause(); | |
| 677 | + | |
| 678 | + let elapsed = start.elapsed().as_secs_f64(); | |
| 679 | + let rates: Vec<f64> = per_second.iter().map(|(s, _)| *s as f64).collect(); | |
| 680 | + let backend = session.decode_backend().label(); | |
| 681 | + let underruns = session.audio_underruns().map_or(0, |(n, _)| n); | |
| 682 | + for (i, (shown, dropped)) in per_second.iter().enumerate() { | |
| 683 | + eprintln!("cutloop[{i:2}s]: {shown:3} displayed, {dropped:3} dropped"); | |
| 684 | + } | |
| 685 | + row( | |
| 686 | + path, | |
| 687 | + "cutloop_displayed", | |
| 688 | + "count", | |
| 689 | + &rates, | |
| 690 | + &format!( | |
| 691 | + "per second; backend {backend}, {shown} displayed, {dropped} dropped, \ | |
| 692 | + {resyncs} resyncs in {elapsed:.1}s, {regions} x {cut_s}s cuts of {keep_s}s clips" | |
| 693 | + ), | |
| 694 | + ); | |
| 695 | + row( | |
| 696 | + path, | |
| 697 | + "cutloop_restarts", | |
| 698 | + "count", | |
| 699 | + &[session.restarts() as f64], | |
| 700 | + &format!( | |
| 701 | + "backend {backend}, {resyncs} late-picture resyncs, {underruns} underruns" | |
| 702 | + ), | |
| 703 | + ); | |
| 704 | +} | |
| 705 | + | |
| 517 | 706 | // ---------------------------------------------------------------- waveform |
| 518 | 707 | |
| 519 | 708 | /// What a lane waits for before it has an envelope: one whole |
crates/engine/src/playback.rsmodified+30 -0
| @@ -360,6 +360,14 @@ pub struct PlaybackSession { | ||
| 360 | 360 | /// the sound is silence, the duration is zero, and placing anything reseeks |
| 361 | 361 | /// straight back out of it. |
| 362 | 362 | span: Option<Span>, |
| 363 | + /// Whether the span now decoding still owes its first picture: set by | |
| 364 | + /// every span start ([`start_span`](Self::start_span)), cleared by the | |
| 365 | + /// first frame that span hands over ([`try_frame`](Self::try_frame)). | |
| 366 | + /// This is the window a clip boundary -- or any picture restart -- spends | |
| 367 | + /// reopening the decoder, and a front-end must not answer a picture that | |
| 368 | + /// is late by exactly this window's length with another restart of it | |
| 369 | + /// ([`picture_priming`](Self::picture_priming)). | |
| 370 | + span_priming: bool, | |
| 363 | 371 | /// The last clip has been played out; see [`PlaybackSession::is_eos`]. |
| 364 | 372 | eos: bool, |
| 365 | 373 | /// The mix the running mixer is reading, when there is one: what lets a |
| @@ -510,6 +518,7 @@ impl PlaybackSession { | ||
| 510 | 518 | rates: vec![Rate::REAL_TIME], |
| 511 | 519 | span_rate: Rate::REAL_TIME, |
| 512 | 520 | span, |
| 521 | + span_priming: true, | |
| 513 | 522 | eos: false, |
| 514 | 523 | mix: None, |
| 515 | 524 | priming: false, |
| @@ -627,6 +636,7 @@ impl PlaybackSession { | ||
| 627 | 636 | rates: vec![Rate::REAL_TIME], |
| 628 | 637 | span_rate: Rate::REAL_TIME, |
| 629 | 638 | span, |
| 639 | + span_priming: true, | |
| 630 | 640 | eos: false, |
| 631 | 641 | mix: None, |
| 632 | 642 | priming: false, |
| @@ -708,6 +718,7 @@ impl PlaybackSession { | ||
| 708 | 718 | rates: vec![Rate::REAL_TIME], |
| 709 | 719 | span_rate: Rate::REAL_TIME, |
| 710 | 720 | span, |
| 721 | + span_priming: true, | |
| 711 | 722 | eos: false, |
| 712 | 723 | mix: None, |
| 713 | 724 | priming: false, |
| @@ -1010,6 +1021,7 @@ impl PlaybackSession { | ||
| 1010 | 1021 | rates, |
| 1011 | 1022 | span_rate: Rate::REAL_TIME, |
| 1012 | 1023 | span, |
| 1024 | + span_priming: true, | |
| 1013 | 1025 | eos: false, |
| 1014 | 1026 | mix: None, |
| 1015 | 1027 | priming: false, |
| @@ -1332,6 +1344,9 @@ impl PlaybackSession { | ||
| 1332 | 1344 | frame.index = self.span.map_or(frame.index, |s| { |
| 1333 | 1345 | s.timeline_at(self.span_rate.timeline_at(frame.index)) |
| 1334 | 1346 | }); |
| 1347 | + // The first picture out of the span now decoding ends its | |
| 1348 | + // prime ([`Self::span_priming`]). | |
| 1349 | + self.span_priming = false; | |
| 1335 | 1350 | return Some(frame); |
| 1336 | 1351 | } |
| 1337 | 1352 | Err(TryRecvError::Empty) => return None, |
| @@ -1426,6 +1441,17 @@ impl PlaybackSession { | ||
| 1426 | 1441 | self.restarts |
| 1427 | 1442 | } |
| 1428 | 1443 | |
| 1444 | + /// Whether the picture span now decoding has yet to hand over a frame: | |
| 1445 | + /// true from the moment a span is started -- a seek, a clip boundary, a | |
| 1446 | + /// picture restart -- until that span's first frame arrives. Whatever | |
| 1447 | + /// lateness that first frame carries is the span's own reopen, not a | |
| 1448 | + /// decoder falling behind, so a front-end gating its late-picture restart | |
| 1449 | + /// on this answers a prime with the decode already on its way rather than | |
| 1450 | + /// with another restart of it. | |
| 1451 | + pub fn picture_priming(&self) -> bool { | |
| 1452 | + self.span_priming | |
| 1453 | + } | |
| 1454 | + | |
| 1429 | 1455 | /// Starved audio callbacks since the device opened, and how far into the |
| 1430 | 1456 | /// device's own playback (seconds) the last of them was -- `None` for a |
| 1431 | 1457 | /// session with no device at all. The counter the plugin prints on drop, |
| @@ -1498,6 +1524,10 @@ impl PlaybackSession { | ||
| 1498 | 1524 | Some((source, _)) => self.rates.get(source).copied().unwrap_or(Rate::REAL_TIME), |
| 1499 | 1525 | None => Rate::REAL_TIME, |
| 1500 | 1526 | }; |
| 1527 | + // The new span owes its first picture from the moment it is asked for: | |
| 1528 | + // every path below, the reused worker as much as a fresh one | |
| 1529 | + // ([`Self::span_priming`]). | |
| 1530 | + self.span_priming = true; | |
| 1501 | 1531 | let opened = match span { |
| 1502 | 1532 | // The grade is the composite's at this frame -- the same clip the |
| 1503 | 1533 | // span itself came from -- and it is constant across the span, so |
crates/engine/tests/playback.rsmodified+77 -0
| @@ -706,6 +706,83 @@ fn edits_traverse_cuts() { | ||
| 706 | 706 | ); |
| 707 | 707 | } |
| 708 | 708 | |
| 709 | +/// A cut small enough to land *ahead* of the decoder rather than behind it: | |
| 710 | +/// less than half a second of file removed, which is the shape a silence cut | |
| 711 | +/// leaves at every boundary it makes. The picture worker reaches the next | |
| 712 | +/// span by decoding forward and dropping (the plugin's forward skip, no | |
| 713 | +/// flush) -- and what must survive that is the exactness of the landing: the | |
| 714 | +/// first frame past the boundary is the source frame the cut ended on, pixel | |
| 715 | +/// for pixel, exactly as the long cut above is asserted. | |
| 716 | +#[test] | |
| 717 | +fn a_small_cut_lands_frame_exact_across_the_boundary() { | |
| 718 | + let path = asset("test_baseline.mp4"); | |
| 719 | + let mut session = open(&path); | |
| 720 | + let (fps, total) = (session.meta().frame_rate, session.meta().frame_count); | |
| 721 | + // 0.2 s out of the middle: 6 frames at 30 fps, well inside the half a | |
| 722 | + // second a reposition may walk forward. | |
| 723 | + let (cut, hole_end) = ((1.0 * fps) as u32, (1.2 * fps) as u32); | |
| 724 | + assert!(session.cut_at(1.0), "cut at 1 s"); | |
| 725 | + assert!(session.cut_at(1.2), "cut at 1.2 s"); | |
| 726 | + assert!(session.delete_clip(Lane::V1, 1), "drop the hole"); | |
| 727 | + let kept = total - (hole_end - cut); | |
| 728 | + | |
| 729 | + // Play the whole edited timeline from the top, one frame at a time. | |
| 730 | + session.seek(0.0); | |
| 731 | + session.play(); | |
| 732 | + let deadline = Instant::now() + Duration::from_secs(20); | |
| 733 | + let (mut expect, mut boundary) = (0, None); | |
| 734 | + loop { | |
| 735 | + session.tick(); | |
| 736 | + while let Some(frame) = session.try_frame() { | |
| 737 | + assert_eq!(frame.index, expect, "timeline indices must be contiguous"); | |
| 738 | + if frame.index == cut { | |
| 739 | + boundary = Some(frame.bgra); | |
| 740 | + } | |
| 741 | + expect += 1; | |
| 742 | + } | |
| 743 | + if session.is_eos() { | |
| 744 | + break; | |
| 745 | + } | |
| 746 | + assert!(Instant::now() < deadline, "still draining after 20 s"); | |
| 747 | + sleep(Duration::from_millis(4)); | |
| 748 | + } | |
| 749 | + assert_eq!(expect, kept, "the edited timeline, whole and nothing but"); | |
| 750 | + session.pause(); | |
| 751 | + | |
| 752 | + let boundary = boundary.expect("no frame at the cut"); | |
| 753 | + assert!( | |
| 754 | + boundary == source_frame(&path, hole_end), | |
| 755 | + "the boundary frame is not source {hole_end}" | |
| 756 | + ); | |
| 757 | + assert!( | |
| 758 | + boundary != source_frame(&path, cut), | |
| 759 | + "the deleted range is still being decoded" | |
| 760 | + ); | |
| 761 | +} | |
| 762 | + | |
| 763 | +/// The prime a picture restart spends, as the session reports it: owed from | |
| 764 | +/// the moment a span is started until that span's first frame arrives. A | |
| 765 | +/// front-end gates its late-picture restart on this, so what it reads has to | |
| 766 | +/// be exactly this and nothing looser. | |
| 767 | +#[test] | |
| 768 | +fn picture_priming_spans_a_restart_and_ends_at_its_first_frame() { | |
| 769 | + let path = asset("test_baseline.mp4"); | |
| 770 | + let mut session = open(&path); | |
| 771 | + // The open itself is a span that has not delivered yet. | |
| 772 | + assert!(session.picture_priming(), "a fresh session is priming"); | |
| 773 | + let first = next_frame(&mut session, "the open"); | |
| 774 | + assert!(!session.picture_priming(), "the first frame ends the prime"); | |
| 775 | + assert_eq!(first.index, 0); | |
| 776 | + | |
| 777 | + // A seek restarts the picture at its target: a new span, a new prime -- | |
| 778 | + // the same start every clip boundary and edit takes. | |
| 779 | + session.seek(2.0); | |
| 780 | + assert!(session.picture_priming(), "the reseek is priming again"); | |
| 781 | + let landed = next_frame(&mut session, "the reseek"); | |
| 782 | + assert!(!session.picture_priming()); | |
| 783 | + assert_eq!(landed.index, (2.0 * session.meta().frame_rate) as u32); | |
| 784 | +} | |
| 785 | + | |
| 709 | 786 | /// Copy and paste. A clipboard clip is a pair of *source* frame numbers, so the |
| 710 | 787 | /// pasted stretch has to decode its own range -- not the frames the timeline |
| 711 | 788 | /// used to hold at that position. |