diff --git a/crates/app/src/player/transport.rs b/crates/app/src/player/transport.rs
index acbca67..f5a5529 100644
--- a/crates/app/src/player/transport.rs
+++ b/crates/app/src/player/transport.rs
@@ -18,6 +18,12 @@ impl Player {
let Some(session) = &mut self.session else {
return;
};
+ // Whether the span now decoding has yet to hand over a picture, read
+ // *before* the drain: the frame the drain is about to take is the one
+ // that ends the prime, and its own lateness -- however long the span's
+ // reopen took -- is exactly what the resync below must not answer with
+ // another reopen.
+ let priming = session.picture_priming();
let target = session.now() * self.fps;
let mut newest: Option = None;
// A frame the screen is owed: a seek's landing, and the one readiness
@@ -95,6 +101,12 @@ impl Player {
// (`PlaybackSession::resync_picture`), so nothing the ear is following
// moves. Never on a frame a seek owed: that one is late by however long
// its own reopen took, and answering it with another reopen is a loop.
+ // The same is true of a *clip boundary's* first frame -- a silence cut
+ // leaves a timeline of clips shorter than their own reopen -- so the
+ // restart waits for a span that has delivered and fallen behind after
+ // it (`resync_due`, primed on `PlaybackSession::picture_priming`):
+ // restarting the prime only buys the same lateness again, and every
+ // `RESYNC_GAP` after that.
//
// corner-cut: on a machine that cannot decode the file in real time at
// all this settles into one restart per `RESYNC_GAP` -- in sync, and
@@ -102,7 +114,7 @@ impl Player {
// The upgrade path is dropping late frames *inside* the worker (skip
// the convert and the send for anything already past due), which needs
// the deadline shared with it.
- if !owed && session.is_playing() && should_resync(late, self.resynced) {
+ if !owed && session.is_playing() && resync_due(late, self.resynced, priming) {
eprintln!("picture {late:.3}s behind the clock: restarting it there");
session.resync_picture();
self.held = None;
@@ -306,3 +318,44 @@ impl Player {
}
}
}
+
+/// Whether a late picture is restarted at the clock: the rule
+/// [`should_resync`] always was, plus the prime it must not interrupt. A span
+/// that has not handed over a picture yet is late by exactly its own reopen
+/// -- a clip boundary on a silence-cut timeline most of all, where the clips
+/// are shorter than that reopen -- and restarting it spends the reopen again
+/// for the same lateness, every `RESYNC_GAP` after that. The restart is for a
+/// span that has *delivered* and fallen behind afterwards.
+pub(crate) fn resync_due(late: f64, last: Option, priming: bool) -> bool {
+ !priming && should_resync(late, last)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// The prime gate: a span still owing its first picture is never
+ /// restarted, however late the last frame to arrive was. The same span
+ /// once it has delivered keeps the rule -- thresholds and cooldown
+ /// unchanged -- because a decoder that is genuinely too slow is still
+ /// behind on its second frame, one repaint later.
+ #[test]
+ fn a_priming_span_is_never_restarted() {
+ assert!(!resync_due(0., None, true));
+ assert!(!resync_due(LATE_RESYNC, None, true));
+ assert!(!resync_due(9., None, true));
+ // ...and the rule itself, exactly as it was, once the prime is over.
+ assert!(!resync_due(0., None, false));
+ assert!(!resync_due(LATE_RESYNC, None, false));
+ assert!(resync_due(LATE_RESYNC + 0.1, None, false));
+ // A decoder still behind right after a restart waits out the gap
+ // instead of reopening at every repaint...
+ assert!(!resync_due(9., Some(Instant::now()), false));
+ // ...and fires again once it has passed.
+ assert!(resync_due(
+ 9.,
+ Some(Instant::now() - RESYNC_GAP - Duration::from_millis(1)),
+ false
+ ));
+ }
+}
diff --git a/crates/engine-hw/src/lib.rs b/crates/engine-hw/src/lib.rs
index e8b5453..3d84e90 100644
--- a/crates/engine-hw/src/lib.rs
+++ b/crates/engine-hw/src/lib.rs
@@ -141,6 +141,53 @@ const LEADING_LIMIT: u32 = 64;
/// at ~3 MB of video memory each.
const DMA_HOLD: usize = 6;
+/// How far ahead of the decode position [`Session::seek_to`] walks forward
+/// rather than flushing, in seconds of the stream's own frames. A silence cut
+/// lands the next span ahead of the decoder by the length of what it removed
+/// -- tenths of a second -- and walking that forward costs only the decode of
+/// the frames in between, dropped without the read-back ([`Session::pump`]'s
+/// skip path) with the decoder's reference chain and pipeline depth left
+/// standing. The flush it replaces costs a decoder reset, a demuxer seek to
+/// the random access point, up to a group of skip-decoded pictures behind it,
+/// and a full re-prime before the first frame is out again (~178 ms measured
+/// at 4K, which is longer than the clips a silence cut leaves); past half a
+/// second of walking, the skip-decode run alone approaches that bill and a
+/// real seek wins.
+const FORWARD_SECS: f64 = 0.5;
+
+/// The forward reach in frames: [`FORWARD_SECS`] at the stream's own rate.
+/// `0` for a rate the stream does not really state, which is "never forward"
+/// -- exactly the flush every reposition did before this distinction existed.
+fn forward_limit(frame_rate: f64) -> u32 {
+ (FORWARD_SECS * frame_rate).round().max(0.) as u32
+}
+
+/// How a reposition to `target` (a 0-based display frame) is reached from
+/// `position`, the frame the session would hand out next. Pure arithmetic,
+/// so every shape of the answer is testable without a GPU.
+#[derive(Debug, PartialEq, Eq, Clone, Copy)]
+enum Reposition {
+ /// Decode forward from where the session stands, dropping this many
+ /// pictures on the way: no flush, no demuxer seek, no re-prime.
+ Forward(u32),
+ /// Flush the decoder and seek the demuxer to the random access point at
+ /// or before `target`.
+ Flush,
+}
+
+fn reposition(position: i64, target: i64, frame_count: u32, limit: u32) -> Reposition {
+ // A decoder cannot walk backwards, and a target at or past the last frame
+ // is not one decoding forward can hand out -- both take the seek that has
+ // always handled them, EOF included.
+ if target < position || target >= i64::from(frame_count) {
+ return Reposition::Flush;
+ }
+ match u32::try_from(target - position) {
+ Ok(ahead) if ahead <= limit => Reposition::Forward(ahead),
+ _ => Reposition::Flush,
+ }
+}
+
struct Session {
decoder: Decoder,
/// NV12 (or, for a 10-bit stream, P010) descriptor for `vaGetImage`,
@@ -159,6 +206,11 @@ struct Session {
flushed: bool,
/// Pictures still to be decoded and thrown away to land on a seek target.
skip: u32,
+ /// The display frame the next `pump` would hand out, however it gets
+ /// there: one further along for every handle taken off `ready`, skipped
+ /// past and delivered alike. The one thing that can tell a reposition
+ /// *ahead* of the decoder from one behind it ([`Session::seek_to`]).
+ position: i64,
/// 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
@@ -321,6 +373,7 @@ impl Session {
timestamp: 0,
flushed: false,
skip: 0,
+ position: 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`]),
@@ -349,6 +402,7 @@ 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;
+ session.position = first;
if target_frame > 0 {
session.leading = 0;
}
@@ -358,10 +412,15 @@ impl Session {
/// Repositions an **open** session, exactly as [`Session::open_at`] positions
/// a new one: the next [`Session::pump`] hands back sample `target_sample`.
///
- /// This is what a seek costs when the session is kept: a demuxer seek and a
- /// decoder flush, and *not* the VA-API initialisation (~90 ms measured), the
- /// render node probe, the container parse and the surface pool that opening
- /// one again pays for.
+ /// This is what a seek costs when the session is kept, and most of it is
+ /// skippable: a target *ahead* of where the decoder stands, within
+ /// [`FORWARD_SECS`] of it, is reached by decoding on and dropping the
+ /// pictures in between ([`reposition`]) -- no flush, no demuxer seek, no
+ /// re-prime -- which is the landing a silence cut leaves at every boundary
+ /// it cuts to, a fraction of a second ahead of the clip that just ended.
+ /// Everything else pays the demuxer seek and the decoder flush, and *not*
+ /// the VA-API initialisation (~90 ms measured), the render node probe, the
+ /// container parse and the surface pool that opening one again pays for.
///
/// The flush is the whole of the decoder's reset: cros-codecs finishes what
/// is in flight and goes to `Reset`, from where it resumes on the next
@@ -371,6 +430,22 @@ impl Session {
/// flush makes ready are dropped with `ready`: they belong to where the
/// session *was*.
fn seek_to(&mut self, target_sample: u32) -> Result<(), String> {
+ // The same arithmetic `open_at` does, for the same reason.
+ let target_frame = target_sample.saturating_sub(1);
+ if let Reposition::Forward(ahead) = reposition(
+ self.position,
+ i64::from(target_frame),
+ self.meta.frame_count,
+ forward_limit(self.meta.frame_rate),
+ ) {
+ // Nothing about the session moves but the skip: not the decoder,
+ // not the access unit half-fed to it, not the pictures already
+ // waiting in `ready` -- the skip walks past all of them exactly
+ // as it walks past the ones still to decode, one `position` step
+ // per handle either way.
+ self.skip = self.skip.saturating_add(ahead);
+ return Ok(());
+ }
self.decoder.get().flush().map_err(|e| e.to_string())?;
// Drain what the flush completed, dropping every handle: each one holds
// a pool buffer out of circulation, and none of them is ours to show.
@@ -388,10 +463,9 @@ impl Session {
self.ready.clear();
self.pending.clear();
self.flushed = false;
- // The same arithmetic `open_at` does, for the same reason.
- let target_frame = target_sample.saturating_sub(1);
let first = self.demuxer.seek_to_sync_at_or_before(target_frame);
self.skip = (i64::from(target_frame) - first).max(0) as u32;
+ self.position = first;
// ...and the same open-GOP window: a session positioned anywhere but the
// start may meet leading pictures that reference what it never decoded.
self.leading = if target_frame > 0 { 0 } else { LEADING_LIMIT };
@@ -425,6 +499,9 @@ impl Session {
}
}
if let Some(handle) = self.ready.pop_front() {
+ // One picture further along, shown or skipped past alike:
+ // this is the only place [`Session::position`] walks.
+ self.position += 1;
// Seek discards: dropping the handle skips the `vaGetImage`
// read-back (~1.2 ms/picture) and frees its pool buffer.
if self.skip > 0 {
@@ -1982,4 +2059,49 @@ mod tests {
// H.264 here is 8-bit 4:2:0; the table has no 10-bit profile for it.
assert_eq!(caps.decode_10bit & CAP_H264, 0, "{caps:?}");
}
+
+ /// Every shape of the forward-or-flush decision a reposition makes, with
+ /// no GPU in sight: the boundary a silence cut leaves is a target a few
+ /// frames *ahead* of the decoder and that is the walk; behind it, past the
+ /// reach, and past the end of the stream are the flush.
+ #[test]
+ fn a_target_ahead_within_the_reach_walks_forward() {
+ use Reposition::{Flush, Forward};
+ // A 30 fps stream, so the reach is [`FORWARD_SECS`] of it.
+ let (count, limit) = (10_000u32, forward_limit(30.0));
+ assert_eq!(forward_limit(30.0), 15);
+ // The boundary a 0.3 s silence cut leaves: 9 frames ahead, dropped
+ // unread on the way to exactly the target.
+ assert_eq!(reposition(120, 129, count, limit), Forward(9));
+ // Exactly at the reach, and a reseek to exactly where the decoder
+ // stands (a superseded span's landing): nothing to do but not flush.
+ assert_eq!(reposition(120, 135, count, limit), Forward(15));
+ assert_eq!(reposition(120, 120, count, limit), Forward(0));
+ // One frame past either end of the walk is the flush's.
+ assert_eq!(reposition(120, 136, count, limit), Flush);
+ assert_eq!(reposition(120, 119, count, limit), Flush);
+ assert_eq!(reposition(120, 0, count, limit), Flush);
+ // The last frame of the stream is a frame like any other...
+ assert_eq!(reposition(9_995, 9_999, count, limit), Forward(4));
+ // ...while a target at or past the end is not one decoding forward
+ // can hand out: EOF falls back to the seek that always handled it.
+ assert_eq!(reposition(9_995, 10_000, count, limit), Flush);
+ assert_eq!(reposition(9_995, 60_000, count, limit), Flush);
+ // From the end itself -- everything delivered, `pump` at clean EOF --
+ // even a target inside the stream is behind.
+ assert_eq!(reposition(10_000, 9_999, count, limit), Flush);
+ }
+
+ /// The reach is time, carried at the stream's own rate, and a stream that
+ /// states no rate gets none of it: such a session keeps the behaviour
+ /// every reposition had, rather than a skip of nonsense frames.
+ #[test]
+ fn the_reach_is_half_a_second_at_the_streams_own_rate() {
+ assert_eq!(forward_limit(23.976), 12);
+ assert_eq!(forward_limit(24.0), 12);
+ assert_eq!(forward_limit(60.0), 30);
+ assert_eq!(forward_limit(0.0), 0);
+ assert_eq!(forward_limit(f64::NAN), 0);
+ assert_eq!(forward_limit(-30.0), 0);
+ }
}
diff --git a/crates/engine/examples/bench.rs b/crates/engine/examples/bench.rs
index f7e2b44..ecc879c 100644
--- a/crates/engine/examples/bench.rs
+++ b/crates/engine/examples/bench.rs
@@ -45,7 +45,7 @@ use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};
use engine::export::{EncoderSeat, ExportSettings, Format};
-use engine::project::{Clip, LaneKind, Project, Source, Speed};
+use engine::project::{Clip, Lane, LaneKind, Project, Source, Speed};
// `posix_fadvise(2)`, straight from libc, which std already links: dropping
// this file's pages needs no crate and no privilege.
@@ -63,6 +63,12 @@ fn main() {
"seek" => seek_bench(&path, arg_f64(args.next(), "seconds")),
"seekstorm" => seekstorm_bench(&path, arg_seed(args.next())),
"playloop" => playloop_bench(&path, arg_f64(args.next(), "seconds"), arg_seed(args.next())),
+ "cutloop" => cutloop_bench(
+ &path,
+ arg_or(args.next(), 20.0) as u32,
+ arg_or(args.next(), 0.5),
+ arg_or(args.next(), 0.3),
+ ),
"scrub" => scrub_bench(&path),
"waveform" => waveform_bench(&path),
"export" => {
@@ -79,6 +85,7 @@ fn usage() -> ! {
"usage: bench open \n bench seek \n \
bench seekstorm [seed]\n \
bench playloop [seed]\n \
+ bench cutloop [regions=20] [keep_s=0.5] [cut_s=0.3]\n \
bench scrub \n bench waveform \n \
bench export "
);
@@ -90,6 +97,12 @@ fn arg_f64(arg: Option, what: &str) -> f64 {
.unwrap_or_else(|| panic!("missing {what}"))
}
+/// An optional measurement parameter with a default, so a rerun that names
+/// nothing runs the same shape of timeline the last one did.
+fn arg_or(arg: Option, default: f64) -> f64 {
+ arg.and_then(|s| s.parse().ok()).unwrap_or(default)
+}
+
/// The seed the random metrics draw their positions from: same seed, same
/// seeks, so a before and an after are the same measurement.
fn arg_seed(arg: Option) -> u64 {
@@ -387,9 +400,10 @@ fn seekstorm_bench(path: &Path, seed: u64) {
/// boundary, or by the late-picture resync, which is counted separately in the
/// note.
///
-/// The resync rule is the app's, repeated here (`LATE_RESYNC`, `RESYNC_GAP` in
-/// `crates/app/src/transport.rs`) because an engine example cannot depend on
-/// the binary. Repeated only: nothing in this file changes how playback runs.
+/// The resync rule is the app's, repeated here (`LATE_RESYNC`, `RESYNC_GAP`
+/// and the never-during-a-prime gate in `crates/app/src/player/transport.rs`)
+/// because an engine example cannot depend on the binary. Repeated only:
+/// nothing in this file changes how playback runs.
const PLAYLOOP_SEEK_GAP: Duration = Duration::from_secs(5);
const LATE_RESYNC: f64 = 0.4;
const RESYNC_GAP: Duration = Duration::from_secs(2);
@@ -421,6 +435,9 @@ fn playloop_bench(path: &Path, secs: f64, seed: u64) {
let mut next_seek = start + PLAYLOOP_SEEK_GAP;
while Instant::now() < deadline {
session.tick();
+ // Read before the drain, as the app does: the frame the drain takes
+ // is the one that ends the prime, and its lateness is the reopen's.
+ let priming = session.picture_priming();
let target = session.now() * fps;
let mut newest = None;
while session.is_playing() || owed {
@@ -455,6 +472,7 @@ fn playloop_bench(path: &Path, secs: f64, seed: u64) {
owed = false;
}
if !owed
+ && !priming
&& session.is_playing()
&& late > LATE_RESYNC
&& last_resync.is_none_or(|t| t.elapsed() >= RESYNC_GAP)
@@ -514,6 +532,177 @@ fn playloop_bench(path: &Path, secs: f64, seed: u64) {
);
}
+// ----------------------------------------------------------------- cutloop
+
+/// The freeze metric: a **silence-cut** timeline -- `regions` holes of
+/// `cut_s` punched out of one file, `keep_s` of picture left between them --
+/// played end to end with the app's own pump, drop policy and resync rule
+/// (`playloop_bench`'s, without the random seeks). Every boundary between two
+/// kept clips is a same-file reseek of the picture worker while the audio
+/// feeder runs straight through -- exactly the timeline a silence removal
+/// leaves, and the complaint it brought: clips shorter than a decoder's own
+/// re-prime, a picture that starves while the sound plays on, and a
+/// late-picture resync every `RESYNC_GAP` buying the same reopen again.
+///
+/// What comes out: displayed and dropped pictures per wall-clock second (a
+/// freeze is a second that shows nothing), on stderr one line each, and in
+/// the TSV the per-second displayed counts beside the totals -- restarts,
+/// resyncs and underruns -- that say which mechanism spent the time.
+///
+/// ```text
+/// bench cutloop <4k file> 20 0.5 0.3
+/// ```
+fn cutloop_bench(path: &Path, regions: u32, keep_s: f64, cut_s: f64) {
+ let mut session = match engine::PlaybackSession::open(path) {
+ Ok(session) => session,
+ Err(e) => {
+ row(path, "cutloop_displayed", "count", &[], &format!("FAIL({e})"));
+ return;
+ }
+ };
+ // Muted like the tests: the device still schedules the stream and the
+ // clock still counts its samples, which is the whole of what this
+ // measures -- the sound is the master the picture is starving against.
+ session.set_gain(0.0);
+ session.drop_late_pictures(true);
+ let fps = session.meta().frame_rate;
+
+ // Cut every hole out before a single picture decodes: keep, cut, keep,
+ // cut -- `regions` pairs of boundaries, so the timeline that plays is
+ // `regions + 1` clips of one file with the holes joined shut.
+ let stride = keep_s + cut_s;
+ for i in 0..regions {
+ let at = keep_s + f64::from(i) * stride;
+ if !session.cut_at(at) || !session.cut_at(at + cut_s) {
+ row(
+ path,
+ "cutloop_displayed",
+ "count",
+ &[],
+ &format!("FAIL(file shorter than region {i} of {regions})"),
+ );
+ return;
+ }
+ }
+ // The holes are the odd clips: index 1, `regions` times over, as every
+ // delete closes the list up onto the next one.
+ for i in 0..regions {
+ if !session.delete_clip(Lane::V1, 1) {
+ row(
+ path,
+ "cutloop_displayed",
+ "count",
+ &[],
+ &format!("FAIL(hole {i} of {regions} would not delete)"),
+ );
+ return;
+ }
+ }
+ let timeline = session.timeline_duration();
+ eprintln!(
+ "cutloop: {regions} regions of {cut_s}s cut, {} clips of {keep_s}s left, \
+ {timeline:.1}s of timeline at {fps:.3} fps",
+ regions + 1
+ );
+
+ session.seek(0.0);
+ session.play();
+ let start = Instant::now();
+ let mut held: Option = None;
+ let (mut shown, mut dropped, mut resyncs) = (0u64, 0u64, 0u64);
+ let mut last_resync: Option = None;
+ // The first frame of the run is owed exactly as a seek's landing is.
+ let mut owed = true;
+ let mut per_second: Vec<(u64, u64)> = vec![(0, 0)];
+ loop {
+ session.tick();
+ // Read before the drain, as the app does: the frame the drain takes
+ // is the one that ends the prime, and its lateness is the reopen's.
+ let priming = session.picture_priming();
+ let target = session.now() * fps;
+ let mut newest = None;
+ let mut dropped_now = 0u64;
+ while session.is_playing() || owed {
+ let frame = match held.take() {
+ Some(frame) => frame,
+ None => match session.try_frame() {
+ Some(frame) => frame,
+ None => break,
+ },
+ };
+ if f64::from(frame.index) <= target {
+ dropped_now += u64::from(newest.is_some());
+ newest = Some(frame);
+ } else {
+ held = Some(frame);
+ break;
+ }
+ }
+ dropped += dropped_now;
+ let late = newest
+ .as_ref()
+ .map_or(0.0, |f| (target - f64::from(f.index)) / fps);
+ if newest.is_some() {
+ shown += 1;
+ owed = false;
+ }
+ let slot = start.elapsed().as_secs() as usize;
+ if per_second.len() <= slot {
+ per_second.resize(slot + 1, (0, 0));
+ }
+ per_second[slot].0 += u64::from(newest.is_some());
+ per_second[slot].1 += dropped_now;
+ if !owed
+ && !priming
+ && session.is_playing()
+ && late > LATE_RESYNC
+ && last_resync.is_none_or(|t| t.elapsed() >= RESYNC_GAP)
+ {
+ eprintln!("cutloop: picture {late:.3}s behind the clock: restarting it there");
+ session.resync_picture();
+ held = None;
+ last_resync = Some(Instant::now());
+ resyncs += 1;
+ }
+ // End of stream is the end of the run: the clock is halted on the out
+ // point, as the app's transport does, so the last second's bucket is
+ // closed rather than walked off the end of the timeline.
+ if session.is_eos() {
+ session.halt_at_end();
+ break;
+ }
+ std::thread::sleep(Duration::from_millis(1));
+ }
+ session.pause();
+
+ let elapsed = start.elapsed().as_secs_f64();
+ let rates: Vec = per_second.iter().map(|(s, _)| *s as f64).collect();
+ let backend = session.decode_backend().label();
+ let underruns = session.audio_underruns().map_or(0, |(n, _)| n);
+ for (i, (shown, dropped)) in per_second.iter().enumerate() {
+ eprintln!("cutloop[{i:2}s]: {shown:3} displayed, {dropped:3} dropped");
+ }
+ row(
+ path,
+ "cutloop_displayed",
+ "count",
+ &rates,
+ &format!(
+ "per second; backend {backend}, {shown} displayed, {dropped} dropped, \
+ {resyncs} resyncs in {elapsed:.1}s, {regions} x {cut_s}s cuts of {keep_s}s clips"
+ ),
+ );
+ row(
+ path,
+ "cutloop_restarts",
+ "count",
+ &[session.restarts() as f64],
+ &format!(
+ "backend {backend}, {resyncs} late-picture resyncs, {underruns} underruns"
+ ),
+ );
+}
+
// ---------------------------------------------------------------- waveform
/// What a lane waits for before it has an envelope: one whole
diff --git a/crates/engine/src/playback.rs b/crates/engine/src/playback.rs
index 10dc301..56e98a6 100644
--- a/crates/engine/src/playback.rs
+++ b/crates/engine/src/playback.rs
@@ -360,6 +360,14 @@ pub struct PlaybackSession {
/// the sound is silence, the duration is zero, and placing anything reseeks
/// straight back out of it.
span: Option,
+ /// Whether the span now decoding still owes its first picture: set by
+ /// every span start ([`start_span`](Self::start_span)), cleared by the
+ /// first frame that span hands over ([`try_frame`](Self::try_frame)).
+ /// This is the window a clip boundary -- or any picture restart -- spends
+ /// reopening the decoder, and a front-end must not answer a picture that
+ /// is late by exactly this window's length with another restart of it
+ /// ([`picture_priming`](Self::picture_priming)).
+ span_priming: bool,
/// The last clip has been played out; see [`PlaybackSession::is_eos`].
eos: bool,
/// The mix the running mixer is reading, when there is one: what lets a
@@ -510,6 +518,7 @@ impl PlaybackSession {
rates: vec![Rate::REAL_TIME],
span_rate: Rate::REAL_TIME,
span,
+ span_priming: true,
eos: false,
mix: None,
priming: false,
@@ -627,6 +636,7 @@ impl PlaybackSession {
rates: vec![Rate::REAL_TIME],
span_rate: Rate::REAL_TIME,
span,
+ span_priming: true,
eos: false,
mix: None,
priming: false,
@@ -708,6 +718,7 @@ impl PlaybackSession {
rates: vec![Rate::REAL_TIME],
span_rate: Rate::REAL_TIME,
span,
+ span_priming: true,
eos: false,
mix: None,
priming: false,
@@ -1010,6 +1021,7 @@ impl PlaybackSession {
rates,
span_rate: Rate::REAL_TIME,
span,
+ span_priming: true,
eos: false,
mix: None,
priming: false,
@@ -1332,6 +1344,9 @@ impl PlaybackSession {
frame.index = self.span.map_or(frame.index, |s| {
s.timeline_at(self.span_rate.timeline_at(frame.index))
});
+ // The first picture out of the span now decoding ends its
+ // prime ([`Self::span_priming`]).
+ self.span_priming = false;
return Some(frame);
}
Err(TryRecvError::Empty) => return None,
@@ -1426,6 +1441,17 @@ impl PlaybackSession {
self.restarts
}
+ /// Whether the picture span now decoding has yet to hand over a frame:
+ /// true from the moment a span is started -- a seek, a clip boundary, a
+ /// picture restart -- until that span's first frame arrives. Whatever
+ /// lateness that first frame carries is the span's own reopen, not a
+ /// decoder falling behind, so a front-end gating its late-picture restart
+ /// on this answers a prime with the decode already on its way rather than
+ /// with another restart of it.
+ pub fn picture_priming(&self) -> bool {
+ self.span_priming
+ }
+
/// Starved audio callbacks since the device opened, and how far into the
/// device's own playback (seconds) the last of them was -- `None` for a
/// session with no device at all. The counter the plugin prints on drop,
@@ -1498,6 +1524,10 @@ impl PlaybackSession {
Some((source, _)) => self.rates.get(source).copied().unwrap_or(Rate::REAL_TIME),
None => Rate::REAL_TIME,
};
+ // The new span owes its first picture from the moment it is asked for:
+ // every path below, the reused worker as much as a fresh one
+ // ([`Self::span_priming`]).
+ self.span_priming = true;
let opened = match span {
// The grade is the composite's at this frame -- the same clip the
// span itself came from -- and it is constant across the span, so
diff --git a/crates/engine/tests/playback.rs b/crates/engine/tests/playback.rs
index e2a4691..5dafddf 100644
--- a/crates/engine/tests/playback.rs
+++ b/crates/engine/tests/playback.rs
@@ -706,6 +706,83 @@ fn edits_traverse_cuts() {
);
}
+/// A cut small enough to land *ahead* of the decoder rather than behind it:
+/// less than half a second of file removed, which is the shape a silence cut
+/// leaves at every boundary it makes. The picture worker reaches the next
+/// span by decoding forward and dropping (the plugin's forward skip, no
+/// flush) -- and what must survive that is the exactness of the landing: the
+/// first frame past the boundary is the source frame the cut ended on, pixel
+/// for pixel, exactly as the long cut above is asserted.
+#[test]
+fn a_small_cut_lands_frame_exact_across_the_boundary() {
+ let path = asset("test_baseline.mp4");
+ let mut session = open(&path);
+ let (fps, total) = (session.meta().frame_rate, session.meta().frame_count);
+ // 0.2 s out of the middle: 6 frames at 30 fps, well inside the half a
+ // second a reposition may walk forward.
+ let (cut, hole_end) = ((1.0 * fps) as u32, (1.2 * fps) as u32);
+ assert!(session.cut_at(1.0), "cut at 1 s");
+ assert!(session.cut_at(1.2), "cut at 1.2 s");
+ assert!(session.delete_clip(Lane::V1, 1), "drop the hole");
+ let kept = total - (hole_end - cut);
+
+ // Play the whole edited timeline from the top, one frame at a time.
+ session.seek(0.0);
+ session.play();
+ let deadline = Instant::now() + Duration::from_secs(20);
+ let (mut expect, mut boundary) = (0, None);
+ loop {
+ session.tick();
+ while let Some(frame) = session.try_frame() {
+ assert_eq!(frame.index, expect, "timeline indices must be contiguous");
+ if frame.index == cut {
+ boundary = Some(frame.bgra);
+ }
+ expect += 1;
+ }
+ if session.is_eos() {
+ break;
+ }
+ assert!(Instant::now() < deadline, "still draining after 20 s");
+ sleep(Duration::from_millis(4));
+ }
+ assert_eq!(expect, kept, "the edited timeline, whole and nothing but");
+ session.pause();
+
+ let boundary = boundary.expect("no frame at the cut");
+ assert!(
+ boundary == source_frame(&path, hole_end),
+ "the boundary frame is not source {hole_end}"
+ );
+ assert!(
+ boundary != source_frame(&path, cut),
+ "the deleted range is still being decoded"
+ );
+}
+
+/// The prime a picture restart spends, as the session reports it: owed from
+/// the moment a span is started until that span's first frame arrives. A
+/// front-end gates its late-picture restart on this, so what it reads has to
+/// be exactly this and nothing looser.
+#[test]
+fn picture_priming_spans_a_restart_and_ends_at_its_first_frame() {
+ let path = asset("test_baseline.mp4");
+ let mut session = open(&path);
+ // The open itself is a span that has not delivered yet.
+ assert!(session.picture_priming(), "a fresh session is priming");
+ let first = next_frame(&mut session, "the open");
+ assert!(!session.picture_priming(), "the first frame ends the prime");
+ assert_eq!(first.index, 0);
+
+ // A seek restarts the picture at its target: a new span, a new prime --
+ // the same start every clip boundary and edit takes.
+ session.seek(2.0);
+ assert!(session.picture_priming(), "the reseek is priming again");
+ let landed = next_frame(&mut session, "the reseek");
+ assert!(!session.picture_priming());
+ assert_eq!(landed.index, (2.0 * session.meta().frame_rate) as u32);
+}
+
/// Copy and paste. A clipboard clip is a pair of *source* frame numbers, so the
/// pasted stretch has to decode its own range -- not the frames the timeline
/// used to hold at that position.