forge
Explore
Log in

Don't you dare go Hollow

🔀 merge(D2): edits invalidate what they dirty and nothing more — color drags stay audible, the clock anchors on real sound

Browse files at this commit

874f7620b85072da4f5b8c102c76a5ecfa18d4c7Ahmet Kaan GümüşParent: 288629adb1affe
crates/app/src/main.rsmodified+5 -2
@@ -2084,8 +2084,11 @@ impl Player {
20842084 /// ceiling by the same, and the switch either way (a ring of two, like the
20852085 /// silence card's unit row).
20862086 ///
2087- /// Every one of them goes through the session, so it reseeks: what the ear
2088- /// hears while the arrow is held is the mix that is being set.
2087+ /// Every one of them goes through the session, which hands it straight to
2088+ /// the running mixer: what the ear hears while the arrow is held is the mix
2089+ /// that is being set, and nothing is rebuilt to make that true -- no reseek,
2090+ /// so no `reset_after_reseek` and no blink in the picture behind the card
2091+ /// ([`engine::PlaybackSession::set_lane_gain_db`]).
20892092 fn nudge_mix(&mut self, steps: i32, cx: &mut Context<Self>) {
20902093 let lanes = self.mix_lanes();
20912094 let Some(session) = self.session.as_mut() else {
crates/engine/src/audio.rsmodified+117 -3
@@ -28,7 +28,9 @@
2828 use std::fs::File;
2929 use std::io::BufReader;
3030 use std::path::{Path, PathBuf};
31+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
3132 use std::sync::mpsc::{Receiver, SyncSender, sync_channel};
33+use std::sync::{Arc, Mutex};
3234 use std::thread;
3335
3436 use mp4::{AudioObjectType, ChannelConfig, MediaType, Mp4Reader, Mp4Track, TrackType};
@@ -152,6 +154,67 @@ pub struct StreamInfo {
152154 pub decodable: bool,
153155 }
154156
157+/// The mix settings a *running* mixer reads: what each lane is turned by on its
158+/// way into the sum and the ceiling the sum comes out through, both swappable
159+/// while the stream plays.
160+///
161+/// This is what keeps a fader off the reseek path. Everything else a timeline
162+/// says lives inside a decode worker -- a segment's window, its curve, its rate
163+/// -- and can only be changed by rebuilding it, which is a flush, a re-open and
164+/// a hole in the sound. These two live at the sum, where nothing is decoded, so
165+/// the mixer can pick them up between one block and the next: an arrow key held
166+/// down on a fader moves the level and nothing else moves at all.
167+///
168+/// One of these belongs to one mixer thread. [`is_live`](MixControls::is_live)
169+/// is what says whether a mixer is actually reading it -- a single lane at
170+/// unity with the limiter off is not mixed at all
171+/// ([`AudioSession::open_mixed_streams_master`]), and a caller that finds this
172+/// dead has to reopen the stream to be heard.
173+pub struct MixControls {
174+ /// Bumped by every change; the mixer reloads when the number it last saw
175+ /// is not this one, so an unchanged mix costs one relaxed load per block.
176+ version: AtomicU64,
177+ /// The lane amplitudes and the limiter, together: they are set together and
178+ /// a mixer that read half of one change and half of the next would be
179+ /// mixing a state nobody asked for.
180+ state: Mutex<(Vec<f32>, Limiter)>,
181+ /// A mixer thread has these; see the type docs.
182+ live: AtomicBool,
183+}
184+
185+impl MixControls {
186+ pub fn new(gains: Vec<f32>, limiter: Limiter) -> Arc<Self> {
187+ Arc::new(Self {
188+ version: AtomicU64::new(0),
189+ state: Mutex::new((gains, limiter)),
190+ live: AtomicBool::new(false),
191+ })
192+ }
193+
194+ /// Hands the running mixer a new mix. Cheap enough for a key repeat: a lock
195+ /// held for a `Vec` swap and an atomic.
196+ pub fn set(&self, gains: Vec<f32>, limiter: Limiter) {
197+ *self.state.lock().unwrap() = (gains, limiter);
198+ self.version.fetch_add(1, Ordering::Release);
199+ }
200+
201+ /// Whether a mixer thread is reading this at all.
202+ pub fn is_live(&self) -> bool {
203+ self.live.load(Ordering::Acquire)
204+ }
205+
206+ /// The mix, if it has moved since `seen`. `None` -- the every-block case --
207+ /// takes no lock.
208+ fn changed(&self, seen: &mut u64) -> Option<(Vec<f32>, Limiter)> {
209+ let now = self.version.load(Ordering::Acquire);
210+ if now == *seen {
211+ return None;
212+ }
213+ *seen = now;
214+ Some(self.state.lock().unwrap().clone())
215+ }
216+}
217+
155218 pub struct AudioSession;
156219
157220 impl AudioSession {
@@ -497,6 +560,26 @@ impl AudioSession {
497560 speeds: &[Vec<Option<crate::project::Stretch>>],
498561 gains: &[f32],
499562 limiter: Limiter,
563+ ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> {
564+ Self::open_mixed_streams_live(sources, lanes, eqs, speeds, gains, limiter, None)
565+ }
566+
567+ /// [`open_mixed_streams_master`](Self::open_mixed_streams_master) with the
568+ /// mix left *reachable*: `live` is the handle the mixer picks its gains and
569+ /// its limiter off between blocks, so a fader moved while the stream plays
570+ /// is heard without the stream being rebuilt ([`MixControls`]).
571+ ///
572+ /// `gains`/`limiter` still say what it starts as -- they are what decides
573+ /// whether there is a mixer at all -- and the handle is marked live only
574+ /// when there is one. An export passes `None`: nothing can move under it.
575+ pub fn open_mixed_streams_live(
576+ sources: &[(PathBuf, usize)],
577+ lanes: &[Vec<(Option<usize>, f64, f64)>],
578+ eqs: &[Vec<Option<EqParams>>],
579+ speeds: &[Vec<Option<crate::project::Stretch>>],
580+ gains: &[f32],
581+ limiter: Limiter,
582+ live: Option<&Arc<MixControls>>,
500583 ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> {
501584 let [first, rest @ ..] = lanes else {
502585 return Ok(None);
@@ -540,12 +623,20 @@ impl AudioSession {
540623 let mut gains = gains.to_vec();
541624 gains.resize(lanes.len(), 1.0);
542625 // Built here, off the thread that will run it, where the rate is known.
543- let limiter = limiter
626+ let state = limiter
544627 .is_active()
545628 .then(|| LimiterState::new(&limiter, meta.sample_rate, channels));
629+ // Marked before the spawn rather than inside it: a caller asks this the
630+ // moment the open returns, and a flag set on the far thread would still
631+ // read dead.
632+ let live = live.map(|live| {
633+ live.live.store(true, Ordering::Release);
634+ live.clone()
635+ });
636+ let rate = meta.sample_rate;
546637 thread::Builder::new()
547638 .name("audio-mix".into())
548- .spawn(move || mix(&rxs, channels, &gains, limiter, &tx))?;
639+ .spawn(move || mix(&rxs, channels, gains, state, rate, live.as_deref(), &tx))?;
549640 Ok(Some((meta, rx)))
550641 }
551642
@@ -2114,10 +2205,15 @@ struct Worker {
21142205 fn mix(
21152206 rxs: &[Receiver<AudioChunk>],
21162207 channels: usize,
2117- gains: &[f32],
2208+ mut gains: Vec<f32>,
21182209 mut limiter: Option<LimiterState>,
2210+ rate: u32,
2211+ controls: Option<&MixControls>,
21192212 tx: &SyncSender<AudioChunk>,
21202213 ) {
2214+ // The version of the mix these gains and this limiter came from; see the
2215+ // reload at the head of the loop.
2216+ let mut seen = 0;
21212217 let mut pending: Vec<Vec<f32>> = rxs.iter().map(|_| Vec::new()).collect();
21222218 let mut live: Vec<bool> = rxs.iter().map(|_| true).collect();
21232219 // Numbering follows lane 0, whose first chunk says where it starts.
@@ -2125,6 +2221,24 @@ fn mix(
21252221 let mut emitted = 0;
21262222 let mut out: Vec<f32> = Vec::new();
21272223 loop {
2224+ // A mix moved while the stream plays, picked up between two blocks:
2225+ // the levels change at a block boundary and nothing else changes at
2226+ // all -- no flush, no re-open, no hole. The limiter is *retuned* rather
2227+ // than rebuilt, so its delay line keeps running and the sample count
2228+ // the master clock is made of does not move ([`LimiterState::retune`]).
2229+ if let Some((next, params)) = controls.and_then(|c| c.changed(&mut seen)) {
2230+ gains = next;
2231+ gains.resize(rxs.len(), 1.0);
2232+ match limiter.as_mut() {
2233+ Some(state) => state.retune(&params),
2234+ // First time it has ever been switched in on this stream: the
2235+ // one that swallows nothing, for the count's sake.
2236+ None if params.is_active() => {
2237+ limiter = Some(LimiterState::engaged(&params, rate, channels));
2238+ }
2239+ None => {}
2240+ }
2241+ }
21282242 for (i, rx) in rxs.iter().enumerate() {
21292243 while live[i] && pending[i].is_empty() {
21302244 match rx.recv() {
crates/engine/src/decode.rsmodified+1 -1
@@ -87,7 +87,7 @@ impl Backend {
8787 pub struct BackendCell(Arc<AtomicU8>);
8888
8989 impl BackendCell {
90- fn new(backend: Backend) -> Self {
90+ pub(crate) fn new(backend: Backend) -> Self {
9191 Self(Arc::new(AtomicU8::new(backend.code())))
9292 }
9393
crates/engine/src/limiter.rsmodified+91 -1
@@ -106,6 +106,11 @@ pub struct LimiterState {
106106 /// delay line, which is how the latency is paid back (module docs).
107107 warm: usize,
108108 gain: f32,
109+ /// Switched out while the mix runs ([`LimiterState::retune`]): the line
110+ /// still delays and still emits a frame per frame, only nothing is held
111+ /// down. Dropping the state instead would drop the frames still inside the
112+ /// line, and those frames are what the master clock counts.
113+ bypass: bool,
109114 ceiling: f32,
110115 /// Where the knee starts, as an amplitude: under this the fast path runs
111116 /// and no logarithm is taken.
@@ -125,6 +130,7 @@ impl LimiterState {
125130 at: 0,
126131 warm: frames - 1,
127132 gain: 1.0,
133+ bypass: !params.on,
128134 ceiling: db_to_linear(ceiling_db),
129135 knee_floor: db_to_linear(ceiling_db - KNEE_DB / 2.0),
130136 // One time constant per sample: the gain covers 63% of the way back
@@ -133,6 +139,34 @@ impl LimiterState {
133139 }
134140 }
135141
142+ /// One switched in **while the mix is already running**: the same limiter,
143+ /// except that it swallows nothing to fill its delay line -- what comes out
144+ /// first is the line's own [`LOOKAHEAD_MS`] of silence and the mix behind
145+ /// it, where a fresh state would have eaten that much of the mix instead.
146+ ///
147+ /// Which matters because the count *is* the clock: a mixer that emitted
148+ /// fewer samples than the timeline asked for would slide the picture off
149+ /// the sound by the lookahead, once per switch-on. A hair of silence at the
150+ /// moment somebody engages a limiter is the honest price.
151+ pub fn engaged(params: &Limiter, sample_rate: u32, channels: usize) -> Self {
152+ Self {
153+ warm: 0,
154+ ..Self::new(params, sample_rate, channels)
155+ }
156+ }
157+
158+ /// Points a running limiter at another setting -- a ceiling dragged, the
159+ /// switch flipped -- without touching the delay line, the peak window or
160+ /// the gain it is holding. That is what makes the ceiling a live control:
161+ /// rebuilding the state would restart the window (a pump) and lose the
162+ /// frames inside the line (a slip against the picture).
163+ pub fn retune(&mut self, params: &Limiter) {
164+ let ceiling_db = params.with_ceiling(params.ceiling_db).ceiling_db;
165+ self.bypass = !params.on;
166+ self.ceiling = db_to_linear(ceiling_db);
167+ self.knee_floor = db_to_linear(ceiling_db - KNEE_DB / 2.0);
168+ }
169+
136170 /// Rewrites `buf` -- interleaved frames -- as the limited mix. Shorter than
137171 /// what came in by the delay line's length, once, at the first call.
138172 pub fn process(&mut self, buf: &mut Vec<f32>) {
@@ -163,8 +197,14 @@ impl LimiterState {
163197 self.warm -= 1;
164198 continue;
165199 }
200+ // Bypassed, the line is a delay and nothing else: the frames come
201+ // out as they went in, one for one.
202+ let gain = match self.bypass {
203+ true => 1.0,
204+ false => self.gain,
205+ };
166206 for c in 0..channels {
167- out.push(self.line[self.at * channels + c] * self.gain);
207+ out.push(self.line[self.at * channels + c] * gain);
168208 }
169209 }
170210 *buf = out;
@@ -240,6 +280,56 @@ mod tests {
240280 assert_eq!(buf.len(), rate as usize * 2 - (state.peaks.len() - 1) * 2);
241281 }
242282
283+ /// A ceiling dragged while the mix runs: the new one is honoured from the
284+ /// next block, the delay line keeps running -- so the block is as long as
285+ /// it would have been, which is what the master clock counts -- and
286+ /// switching the limiter out leaves the samples alone rather than dropping
287+ /// the ones still inside the line.
288+ #[test]
289+ fn a_retune_moves_the_ceiling_and_costs_no_samples() {
290+ let rate = 48_000;
291+ let mut state = LimiterState::engaged(
292+ &Limiter {
293+ ceiling_db: -3.0,
294+ on: true,
295+ },
296+ rate,
297+ 2,
298+ );
299+ let block: Vec<f32> = (0..2_000).map(|i| 2.0 * ((i % 7) as f32 - 3.0)).collect();
300+
301+ // Engaged mid-stream: nothing is swallowed, so the count is the count.
302+ let mut buf = block.clone();
303+ state.process(&mut buf);
304+ assert_eq!(buf.len(), block.len(), "an engaged limiter ate samples");
305+ let hot = buf.iter().fold(0.0f32, |m, s| m.max(s.abs()));
306+ assert!(hot <= db_to_linear(-3.0) + 1e-6, "peak {hot} passed -3 dB");
307+
308+ // Down to -12: the same length again, and quieter.
309+ state.retune(&Limiter {
310+ ceiling_db: -12.0,
311+ on: true,
312+ });
313+ let mut buf = block.clone();
314+ state.process(&mut buf);
315+ assert_eq!(buf.len(), block.len(), "a retune ate samples");
316+ let quiet = buf.iter().fold(0.0f32, |m, s| m.max(s.abs()));
317+ assert!(quiet <= db_to_linear(-12.0) + 1e-6, "peak {quiet} passed -12 dB");
318+ assert!(quiet < hot, "the ceiling did not move: {hot} -> {quiet}");
319+
320+ // Switched out: the line still delays, so the count still holds, and
321+ // what comes out is the mix as it was written.
322+ state.retune(&Limiter {
323+ ceiling_db: -12.0,
324+ on: false,
325+ });
326+ let mut buf = block.clone();
327+ state.process(&mut buf);
328+ assert_eq!(buf.len(), block.len(), "a bypass ate samples");
329+ let raw = buf.iter().fold(0.0f32, |m, s| m.max(s.abs()));
330+ assert!(raw > 1.0, "bypassed, the mix is untouched: peak {raw}");
331+ }
332+
243333 /// Flat settings are a passthrough, which is what the export invariant
244334 /// rests on: 0 dB is exactly 1.0, never 0.9999999.
245335 #[test]
crates/engine/src/playback.rsmodified+321 -74
@@ -12,7 +12,7 @@
1212 //! the renderer decides which frame that means.
1313
1414 use std::path::Path;
15-use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
15+use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU64, Ordering};
1616 use std::sync::mpsc::{Receiver, TryRecvError};
1717 use std::sync::{Arc, Mutex};
1818 use std::thread;
@@ -32,6 +32,13 @@ use crate::scale::{Composer, FitPolicy};
3232 /// only has to be short next to that; it costs one wakeup per 10 ms of audio.
3333 const RING_FULL_WAIT: Duration = Duration::from_millis(10);
3434
35+/// How long the feeder waits out a ring that took *nothing*: the flush of a
36+/// restart, which only the device's own callback can clear (`engine-audio`
37+/// refuses a write queued behind one). Short, because this is the gap at the
38+/// head of every restart and the ear is in it -- one wakeup per millisecond,
39+/// for the millisecond or two it lasts.
40+const FLUSH_WAIT: Duration = Duration::from_millis(1);
41+
3542 /// The timeline a file with no picture scaffolds: 1080p at 30 fps, H.264 --
3643 /// nothing was shot on it, so it is the canvas a *later* import meets rather
3744 /// than a description of the song. H.264 because it is the one codec that
@@ -91,6 +98,18 @@ struct Audio {
9198 /// Bumped by every seek. A feeder only owns the device while this still
9299 /// matches the value it started with; see [`feed`].
93100 epoch: Arc<AtomicU64>,
101+ /// The device position the *current* stream's first real sample was queued
102+ /// at, `-1` until the feeder has queued one. Written by the feeder under the
103+ /// device lock, read by [`tick`](PlaybackSession::tick).
104+ ///
105+ /// This is what keeps a restart out of the timeline. Between a flush and the
106+ /// first sample of the new stream the device plays silence -- a decoder open
107+ /// is tens of milliseconds -- and that silence is elapsed *device* time
108+ /// ([`crate::ao`] counts it, as it must: it really was played). It is not
109+ /// elapsed *timeline* time, and a clock anchored on the first poll after a
110+ /// seek counts it as such, which is a permanent offset between the picture
111+ /// and the sound, re-rolled by every edit made while playing.
112+ content_at: Arc<AtomicI64>,
94113 /// The last [`TAP_SAMPLES`] mono samples handed to the device, oldest
95114 /// first: what a meter or an analyser draws. Written by the feeder, which
96115 /// is not the device's own callback -- the plugin's RT thread never sees
@@ -233,6 +252,39 @@ pub struct PlaybackSession {
233252 span: Option<Span>,
234253 /// The last clip has been played out; see [`PlaybackSession::is_eos`].
235254 eos: bool,
255+ /// The mix the running mixer is reading, when there is one: what lets a
256+ /// fader and the master ceiling move without rebuilding the audio pipeline
257+ /// at all ([`crate::audio::MixControls`]). `None` for a timeline that is
258+ /// not mixed -- one audio lane at unity with the limiter off, which is the
259+ /// bit-exact single-stream path -- and the first move off that reopens the
260+ /// stream once, mixed, and lives from there.
261+ mix: Option<Arc<crate::audio::MixControls>>,
262+ /// An audio stream has been started and has not yet played a sample: the
263+ /// window [`tick`](Self::tick) holds the clock still through, so the silence
264+ /// of a restart is never counted as timeline time. See
265+ /// [`Audio::content_at`].
266+ priming: bool,
267+}
268+
269+/// What an edit dirtied -- which half of the pipeline has to be rebuilt for the
270+/// change to be seen or heard, and, far more to the point, which half must not
271+/// be.
272+///
273+/// Rebuilding a half is expensive and *audible*: the video worker costs a
274+/// decoder open (98 ms of VA-API init, worst case, measured) and the audio one
275+/// costs a flush, a re-open and a hole in the sound. A grade changes no sample
276+/// and a fader changes no picture, so neither may pay the other's price -- that
277+/// is the whole of this type.
278+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
279+enum Dirty {
280+ /// The picture only: a grade, a fit policy, the project resolution. The
281+ /// sound keeps playing, untouched, and the clock never moves.
282+ Picture,
283+ /// The sound only: a clip's equalizer. The picture keeps playing.
284+ Sound,
285+ /// The timeline itself -- what is where, how long, how fast. Both halves
286+ /// are rebuilt, because both are decoding the wrong thing.
287+ Both,
236288 }
237289
238290 impl PlaybackSession {
@@ -297,6 +349,8 @@ impl PlaybackSession {
297349 span_rate: Rate::REAL_TIME,
298350 span,
299351 eos: false,
352+ mix: None,
353+ priming: false,
300354 })
301355 }
302356
@@ -402,6 +456,8 @@ impl PlaybackSession {
402456 span_rate: Rate::REAL_TIME,
403457 span,
404458 eos: false,
459+ mix: None,
460+ priming: false,
405461 })
406462 }
407463
@@ -473,6 +529,8 @@ impl PlaybackSession {
473529 span_rate: Rate::REAL_TIME,
474530 span,
475531 eos: false,
532+ mix: None,
533+ priming: false,
476534 })
477535 }
478536
@@ -755,6 +813,8 @@ impl PlaybackSession {
755813 span_rate: Rate::REAL_TIME,
756814 span,
757815 eos: false,
816+ mix: None,
817+ priming: false,
758818 };
759819 // The scaffolding above opened source 0 from its first frame and the
760820 // whole of its audio; this puts both onto the clip the playhead is
@@ -1074,15 +1134,29 @@ impl PlaybackSession {
10741134 gap.map_or(1, |s| s.len),
10751135 )),
10761136 };
1077- if let Ok(stream) = opened {
1078- // Receiver first, worker second: the drop of the *old* receiver is
1079- // what wakes the outgoing worker if it is parked in `send`, and only
1080- // then can it return and be reaped by a later sweep. Nothing here
1081- // joins, so this ordering costs the seek nothing.
1082- self.frames = stream.frames;
1083- self.backend = stream.backend;
1084- self.retire(stream.worker);
1085- }
1137+ let Ok(stream) = opened else {
1138+ // The file would not open. The span still goes in -- the timeline
1139+ // moves on, there are simply no more pictures -- but the *frames*
1140+ // must not: the old channel's pictures are numbered in the old
1141+ // source's frames, and presenting them under the new mapping would
1142+ // put the wrong picture at the wrong time (and leave
1143+ // [`decode_backend`](Self::decode_backend) describing a worker that
1144+ // is no longer feeding anything). A dead receiver instead, which is
1145+ // what carries the session on to the next span. The old worker stays
1146+ // parked in `self.worker` where the caller already cancelled it; the
1147+ // next span retires it.
1148+ self.frames = std::sync::mpsc::channel().1;
1149+ self.backend = BackendCell::new(Backend::Gap);
1150+ self.span = span;
1151+ return;
1152+ };
1153+ // Receiver first, worker second: the drop of the *old* receiver is
1154+ // what wakes the outgoing worker if it is parked in `send`, and only
1155+ // then can it return and be reaped by a later sweep. Nothing here
1156+ // joins, so this ordering costs the seek nothing.
1157+ self.frames = stream.frames;
1158+ self.backend = stream.backend;
1159+ self.retire(stream.worker);
10861160 self.span = span;
10871161 }
10881162
@@ -1201,18 +1275,20 @@ impl PlaybackSession {
12011275 }
12021276
12031277 /// Gives that clip an equalizer, or takes it off with `None`. One undo step,
1204- /// like every other edit -- and, like every other edit, it *reseeks*: the
1205- /// audio workers are rebuilt from the new curves right where the playhead
1278+ /// like every other edit -- and it rebuilds the **sound** where the playhead
12061279 /// is, so a band changed during playback is heard from the next chunk on
1207- /// rather than at the next play. `false` for a bad index or a non-finite
1208- /// band, and nothing changes.
1280+ /// rather than at the next play. The picture is not touched: the video
1281+ /// worker keeps decoding through it ([`Dirty`]). `false` for a bad index or
1282+ /// a non-finite band, and nothing changes.
12091283 ///
1210- /// ponytail: the reseek is what makes it live, so the cost of a change is a
1211- /// decoder restart -- inaudible at a drag's end, but too much to call once
1212- /// per pointer sample (a caller commits one change per gesture). Upgrade
1213- /// path is an `Arc` swap the running worker polls per chunk.
1284+ /// ponytail: the audio rebuild is what makes it live, so the cost of a
1285+ /// change is a decoder restart -- inaudible at a drag's end, but too much to
1286+ /// call once per pointer sample (a caller commits one change per gesture).
1287+ /// Upgrade path is the per-segment twin of [`crate::audio::MixControls`],
1288+ /// which the lane worker would poll per chunk the way the mixer polls the
1289+ /// gains.
12141290 pub fn set_eq(&mut self, lane: Lane, idx: usize, params: Option<EqParams>) -> bool {
1215- self.edit(|p| p.set_eq(lane, idx, params))
1291+ self.edit(Dirty::Sound, |p| p.set_eq(lane, idx, params))
12161292 }
12171293
12181294 /// How loud that lane plays, in dB -- everything on it, every frequency of
@@ -1221,12 +1297,36 @@ impl PlaybackSession {
12211297 self.project.lane_gain_db(lane)
12221298 }
12231299
1224- /// Sets it. One undo step and a reseek, the equalizer's rule for the
1225- /// equalizer's reason: the mixer is rebuilt from the new volumes right
1226- /// where the playhead is, so a track turned down during playback is heard
1227- /// turned down from the next chunk on.
1300+ /// Sets it. One undo step -- and **nothing is rebuilt**: a lane's volume
1301+ /// lives at the sum, so the running mixer is handed the new number and
1302+ /// picks it up at its next block ([`crate::audio::MixControls`]). A fader
1303+ /// held down under an arrow key therefore moves the level and nothing else:
1304+ /// no flush, no decoder restart, no hole in the sound and no blink in the
1305+ /// picture.
1306+ ///
1307+ /// The one exception is the timeline that is not mixed at all -- a single
1308+ /// audio lane at unity with the limiter off, which plays through the
1309+ /// bit-exact single-stream path and has no mixer to talk to. Moving *that*
1310+ /// off unity opens one, once; every move after it is live.
12281311 pub fn set_lane_gain_db(&mut self, lane: Lane, db: f32) -> bool {
1229- self.edit(|p| p.set_lane_gain_db(lane, db))
1312+ if !self.project.set_lane_gain_db(lane, db) {
1313+ return false;
1314+ }
1315+ self.push_mix();
1316+ true
1317+ }
1318+
1319+ /// Hands the mix the running mixer is reading its new settings -- the whole
1320+ /// of what a fader and a ceiling cost. With no mixer listening (the
1321+ /// single-lane flat path, and a session with no sound at all) the sound is
1322+ /// rebuilt instead, which is what opens one.
1323+ fn push_mix(&mut self) {
1324+ let gains = self.project.audio_gains();
1325+ let limiter = self.project.limiter();
1326+ match &self.mix {
1327+ Some(mix) => mix.set(gains, limiter),
1328+ None => self.reseek_audio(),
1329+ }
12301330 }
12311331
12321332 /// The master limiter the whole mix is summed through.
@@ -1235,9 +1335,25 @@ impl PlaybackSession {
12351335 }
12361336
12371337 /// Sets it, live like a lane volume and for the same reason -- the ceiling
1238- /// a person is dragging has to be the ceiling they are hearing.
1338+ /// a person is dragging has to be the ceiling they are hearing. Nothing is
1339+ /// rebuilt: the running limiter is *retuned* between two blocks
1340+ /// ([`crate::limiter::LimiterState::retune`]), so its delay line keeps
1341+ /// running and the sample count the master clock is made of does not move.
1342+ ///
1343+ /// ponytail: not an undo step, and deliberately -- [`Project::undo`]
1344+ /// restores the lane list, and the limiter is not in it, so snapshotting
1345+ /// here would push a step whose undo changes nothing a person can see or
1346+ /// hear (the twin [`set_lane_gain_db`](Self::set_lane_gain_db) *is*
1347+ /// undoable only because a lane volume lives in that list). The project
1348+ /// resolution is outside undo for the same reason and says so. Upgrade path
1349+ /// is a history that carries the mix beside the lanes, which every existing
1350+ /// snapshot site would then have to fill in.
12391351 pub fn set_limiter(&mut self, limiter: crate::limiter::Limiter) -> bool {
1240- self.edit(|p| p.set_limiter(limiter))
1352+ if !self.project.set_limiter(limiter) {
1353+ return false;
1354+ }
1355+ self.push_mix();
1356+ true
12411357 }
12421358
12431359 /// Lifts one lane's clip out, leaving a gap: black frames on the video lane,
@@ -1246,7 +1362,7 @@ impl PlaybackSession {
12461362 /// the last placement there is empties the timeline, which is a state
12471363 /// ([`is_empty`](Self::is_empty)) and one undo away.
12481364 pub fn lift_clip(&mut self, lane: Lane, idx: usize) -> bool {
1249- self.edit(|p| p.lift(lane, idx))
1365+ self.edit(Dirty::Both, |p| p.lift(lane, idx))
12501366 }
12511367
12521368 /// Moves that clip onto lane `to` with its head at timeline frame `start` --
@@ -1262,7 +1378,7 @@ impl PlaybackSession {
12621378 /// pointer on a frame, and converting it back through seconds would be a
12631379 /// rounding step between the box let go of and the box committed.
12641380 pub fn move_clip_to(&mut self, from: Lane, idx: usize, to: Lane, start: u32) -> bool {
1265- self.edit(|p| p.move_clip(from, idx, to, start))
1381+ self.edit(Dirty::Both, |p| p.move_clip(from, idx, to, start))
12661382 }
12671383
12681384 /// Drags one end of that clip to timeline frame `to`, changing how much of
@@ -1444,7 +1560,7 @@ impl PlaybackSession {
14441560 /// without the caller having to nudge the playhead itself. `false` for an
14451561 /// index that is not there and for a value that is not finite.
14461562 pub fn set_color(&mut self, lane: Lane, idx: usize, params: Option<ColorParams>) -> bool {
1447- self.edit(|p| p.set_color(lane, idx, params))
1563+ self.edit(Dirty::Picture, |p| p.set_color(lane, idx, params))
14481564 }
14491565
14501566 /// The same grade and the same reseek without the undo step
@@ -1452,7 +1568,7 @@ impl PlaybackSession {
14521568 /// through, so the frame regrades under the hand and the whole gesture is
14531569 /// still a single `z`.
14541570 pub fn set_color_live(&mut self, lane: Lane, idx: usize, params: Option<ColorParams>) -> bool {
1455- self.edit(|p| p.set_color_live(lane, idx, params))
1571+ self.edit(Dirty::Picture, |p| p.set_color_live(lane, idx, params))
14561572 }
14571573
14581574 /// The project's resolution: what every clip is composed onto, what the
@@ -1469,10 +1585,13 @@ impl PlaybackSession {
14691585 self.native
14701586 }
14711587
1472- /// Sets it. Reseeks like an edit, so the frame on screen is recomposed at
1473- /// the new size at once, paused or playing. `false` for a size that is not a
1474- /// picture -- zero either way, or past 8K, which is where the per-frame
1475- /// buffers stop being a sane thing to allocate from a keystroke.
1588+ /// Sets it. Rebuilds the **picture** where the playhead is, so the frame on
1589+ /// screen is recomposed at the new size at once, paused or playing -- and
1590+ /// the sound is not touched at all: the size of the canvas is not something
1591+ /// a sample can carry, so resizing a 4K film mid-play costs neither a hole
1592+ /// in the audio nor an offset against it ([`Dirty`]). `false` for a size
1593+ /// that is not a picture -- zero either way, or past 8K, which is where the
1594+ /// per-frame buffers stop being a sane thing to allocate from a keystroke.
14761595 ///
14771596 /// ponytail: not an undo step. The project resolution is not in the lane
14781597 /// snapshots [`Project::undo`] restores, so cycling it back is one more
@@ -1487,8 +1606,7 @@ impl PlaybackSession {
14871606 }
14881607 self.meta.width = width;
14891608 self.meta.height = height;
1490- let now = self.now();
1491- self.seek(now);
1609+ self.invalidate(Dirty::Picture);
14921610 true
14931611 }
14941612
@@ -1557,7 +1675,7 @@ impl PlaybackSession {
15571675 /// grade: the picture on screen is recomposed through the new policy without
15581676 /// the caller nudging the playhead. `false` for an index that is not there.
15591677 pub fn set_fit(&mut self, lane: Lane, idx: usize, fit: FitPolicy) -> bool {
1560- self.edit(|p| p.set_fit(lane, idx, fit))
1678+ self.edit(Dirty::Picture, |p| p.set_fit(lane, idx, fit))
15611679 }
15621680
15631681 /// The clip at `idx` -- what a caller copies. It is a pair of source frame
@@ -1572,7 +1690,7 @@ impl PlaybackSession {
15721690 /// the end of the timeline the clip is appended. One undo step.
15731691 pub fn paste_at(&mut self, timeline_secs: f64, clip: Clip) -> bool {
15741692 let at = secs_to_frame(timeline_secs, self.meta.frame_rate);
1575- self.edit(|p| p.paste(at, clip))
1693+ self.edit(Dirty::Both, |p| p.paste(at, clip))
15761694 }
15771695
15781696 /// Places the whole of `path` played on its audio `stream` at
@@ -1731,7 +1849,7 @@ impl PlaybackSession {
17311849 /// and it reseeks like every other edit.
17321850 pub fn place_at(&mut self, lane: Lane, timeline_secs: f64, clip: Clip) -> bool {
17331851 let at = secs_to_frame(timeline_secs, self.meta.frame_rate);
1734- self.edit(|p| p.place(lane, at, clip))
1852+ self.edit(Dirty::Both, |p| p.place(lane, at, clip))
17351853 }
17361854
17371855 /// Removes `lane`'s clip at `idx` and everything under it, closing the gap
@@ -1745,12 +1863,12 @@ impl PlaybackSession {
17451863 /// not `V1`'s, and a front-end that could only say "the third clip" would
17461864 /// delete the wrong one the moment a second lane exists.
17471865 pub fn delete_clip(&mut self, lane: Lane, idx: usize) -> bool {
1748- self.edit(|p| p.delete_in(lane, idx))
1866+ self.edit(Dirty::Both, |p| p.delete_in(lane, idx))
17491867 }
17501868
17511869 /// Undoes the last successful edit, and reseeks like a delete.
17521870 pub fn undo(&mut self) -> bool {
1753- self.edit(Project::undo)
1871+ self.edit(Dirty::Both, Project::undo)
17541872 }
17551873
17561874 /// Takes `path` into the **library**: it becomes a source of this session,
@@ -1842,18 +1960,36 @@ impl PlaybackSession {
18421960 Ok(source)
18431961 }
18441962
1845- /// Applies an edit and, if it took, reseeks onto the new mapping. `seek`
1846- /// clamps to the new duration and keeps playing playing, so a delete that
1847- /// shortens the timeline past the playhead lands on the last frame.
1848- fn edit(&mut self, f: impl FnOnce(&mut Project) -> bool) -> bool {
1963+ /// Applies an edit and, if it took, rebuilds **what it dirtied** and nothing
1964+ /// else ([`Dirty`]). A structural edit reseeks: `seek` clamps to the new
1965+ /// duration and keeps playing playing, so a delete that shortens the
1966+ /// timeline past the playhead lands on the last frame. A grade or a fit
1967+ /// policy rebuilds the picture where it stands, with the sound running
1968+ /// through it untouched -- no flush, no re-open, no hole -- and an
1969+ /// equalizer the other way round.
1970+ fn edit(&mut self, dirty: Dirty, f: impl FnOnce(&mut Project) -> bool) -> bool {
18491971 if !f(&mut self.project) {
18501972 return false;
18511973 }
1852- let now = self.now();
1853- self.seek(now);
1974+ self.invalidate(dirty);
18541975 true
18551976 }
18561977
1978+ /// Rebuilds the dirtied half (or both) at the playhead.
1979+ fn invalidate(&mut self, dirty: Dirty) {
1980+ match dirty {
1981+ Dirty::Picture => {
1982+ let (_, target) = self.landing(self.now());
1983+ self.start_picture(target);
1984+ }
1985+ Dirty::Sound => self.reseek_audio(),
1986+ Dirty::Both => {
1987+ let now = self.now();
1988+ self.seek(now);
1989+ }
1990+ }
1991+ }
1992+
18571993 /// Current timeline position in seconds.
18581994 pub fn now(&self) -> f64 {
18591995 self.clock.now()
@@ -1955,12 +2091,51 @@ impl PlaybackSession {
19552091 /// Playing stays playing and paused stays paused -- but a paused seek still
19562092 /// decodes, so the caller can show the frame it landed on.
19572093 pub fn seek(&mut self, secs: f64) {
2094+ let (t, target) = self.landing(secs);
2095+ let was_playing = self.clock.is_playing();
2096+ self.stop_audio();
2097+ self.start_picture(target);
2098+ let audio_running = self.start_audio(target);
2099+ // Same invariant as `play`: position the clock before audio restarts.
2100+ if audio_running && self.clock.source() != ClockSource::Audio {
2101+ self.clock.switch_to_audio();
2102+ }
2103+ self.clock.seek_to(t);
2104+ self.resume(was_playing);
2105+ }
2106+
2107+ /// Where a seek to `secs` lands: the clamped timeline position and the
2108+ /// timeline frame it means. The one place the clamp lives, so every
2109+ /// invalidation below lands on the same frame a seek would.
2110+ fn landing(&self, secs: f64) -> (f64, u32) {
19582111 let fps = self.meta.frame_rate;
19592112 let total = self.project.timeline_frames();
19602113 let t = secs.clamp(0.0, f64::from(total) / fps);
1961- let target = secs_to_frame(t, fps).min(total.saturating_sub(1));
1962- let was_playing = self.clock.is_playing();
2114+ (t, secs_to_frame(t, fps).min(total.saturating_sub(1)))
2115+ }
19632116
2117+ /// Rebuilds the **picture** at `target` and touches nothing else: the sound
2118+ /// keeps playing out of the same stream, the clock keeps running, and a
2119+ /// grade dragged during playback is therefore silent.
2120+ fn start_picture(&mut self, target: u32) {
2121+ // Cancel first, drop second: the old worker may be parked in `send` on
2122+ // the bounded channel, where only the disconnect wakes it -- and it
2123+ // then finds the flag already set. It is then parked, not joined; see
2124+ // [`retire`](Self::retire), which is what keeps a scrub off the price
2125+ // of a VA-API init.
2126+ self.worker.cancel();
2127+ // The span runs from `target` to the end of whatever it landed in -- a
2128+ // clip, or a gap, which starts a black-frame worker instead. `None` is
2129+ // the emptied timeline, black too, and `start_span` says so.
2130+ self.start_span(self.project.composite_span_at(target));
2131+ self.eos = false;
2132+ }
2133+
2134+ /// Silences the device and supersedes whatever is feeding it: the first half
2135+ /// of every audio restart, and the only thing that ever discards queued
2136+ /// sound.
2137+ fn stop_audio(&mut self) {
2138+ self.mix = None;
19642139 if let Some(audio) = &self.audio {
19652140 let ao = audio.ao.lock().unwrap();
19662141 ao.set_active(false);
@@ -1968,25 +2143,31 @@ impl PlaybackSession {
19682143 // feeder re-checks the epoch inside that same lock: whatever it is
19692144 // carrying can no longer reach the ring after this point.
19702145 audio.epoch.fetch_add(1, Ordering::Release);
2146+ // Nothing of the new stream has been played yet, by definition.
2147+ audio.content_at.store(-1, Ordering::Release);
19712148 ao.flush();
19722149 // The flushed samples are not being played any more, so nothing may
19732150 // still be drawn from them.
19742151 audio.tap.lock().unwrap().clear();
19752152 }
2153+ }
19762154
1977- // Cancel first, drop second: the old worker may be parked in `send` on
1978- // the bounded channel, where only the disconnect wakes it -- and it
1979- // then finds the flag already set. It is then parked, not joined; see
1980- // [`retire`](Self::retire), which is what keeps a scrub off the price
1981- // of a VA-API init.
1982- self.worker.cancel();
1983- // The span runs from `target` to the end of whatever it landed in -- a
1984- // clip, or a gap, which starts a black-frame worker instead. `None` is
1985- // the emptied timeline, black too, and `start_span` says so.
1986- self.start_span(self.project.composite_span_at(target));
1987- self.eos = false;
2155+ /// Puts the device back where it was: playing if it was playing, and with
2156+ /// the clock held until the new stream is really audible (see
2157+ /// [`Audio::content_at`]).
2158+ fn resume(&mut self, was_playing: bool) {
2159+ self.priming = true;
2160+ if was_playing && let Some(audio) = &self.audio {
2161+ audio.ao.lock().unwrap().set_active(true);
2162+ }
2163+ }
19882164
2165+ /// Rebuilds the **sound** from `target` -- the second half of a restart --
2166+ /// and says whether anything will be fed.
2167+ fn start_audio(&mut self, target: u32) -> bool {
2168+ let fps = self.meta.frame_rate;
19892169 let mut audio_running = false;
2170+ let mut live = None;
19902171 if let Some(audio) = &self.audio
19912172 && !audio.died.load(Ordering::Acquire)
19922173 {
@@ -2020,32 +2201,54 @@ impl PlaybackSession {
20202201 // the library row said, and what an export copies (`export::run`).
20212202 let sources = self.project.audio_sources();
20222203 // ...and the mix settings over the lot: each lane's own volume on
2023- // its way into the sum and the master limiter over the sum, both
2024- // rebuilt here like the curves above, which is what makes a lane
2025- // fader and a ceiling audible while the timeline runs.
2204+ // its way into the sum and the master limiter over the sum. These
2205+ // two are handed over *live* as well as at the open: they sit at
2206+ // the sum, where nothing is decoded, so a fader moved later is a
2207+ // number the running mixer picks up rather than a stream rebuilt
2208+ // under the ear ([`crate::audio::MixControls`]).
20262209 let gains = self.project.audio_gains();
20272210 let limiter = self.project.limiter();
2028- audio_running = match AudioSession::open_mixed_streams_master(
2029- &sources, &segs, &eqs, &speeds, &gains, limiter,
2211+ let controls = crate::audio::MixControls::new(gains.clone(), limiter);
2212+ audio_running = match AudioSession::open_mixed_streams_live(
2213+ &sources,
2214+ &segs,
2215+ &eqs,
2216+ &speeds,
2217+ &gains,
2218+ limiter,
2219+ Some(&controls),
20302220 ) {
20312221 Ok(Some((_, rx))) => audio.spawn_feeder(rx),
20322222 _ => false,
20332223 };
2224+ // Only a mixed timeline has a mixer to talk to; the single-lane
2225+ // flat path is the bit-exact one and has none.
2226+ live = (audio_running && controls.is_live()).then_some(controls);
20342227 if !audio_running {
20352228 // Nothing will ever be fed again; let `tick` fall to wall time
20362229 // instead of waiting on a device that has no more work coming.
20372230 audio.fed_all.store(true, Ordering::Release);
20382231 }
20392232 }
2233+ self.mix = live;
2234+ audio_running
2235+ }
20402236
2041- // Same invariant as `play`: position the clock before audio restarts.
2237+ /// Rebuilds the sound alone, from where the playhead is: what a change that
2238+ /// no picture can show goes through. The video worker is left decoding, so
2239+ /// the picture does not blink -- and the clock, held still by
2240+ /// [`resume`](Self::resume) until the new stream is audible, puts the sound
2241+ /// back exactly where the picture already is.
2242+ fn reseek_audio(&mut self) {
2243+ let (t, target) = self.landing(self.now());
2244+ let was_playing = self.clock.is_playing();
2245+ self.stop_audio();
2246+ let audio_running = self.start_audio(target);
20422247 if audio_running && self.clock.source() != ClockSource::Audio {
20432248 self.clock.switch_to_audio();
20442249 }
20452250 self.clock.seek_to(t);
2046- if was_playing && let Some(audio) = &self.audio {
2047- audio.ao.lock().unwrap().set_active(true);
2048- }
2251+ self.resume(was_playing);
20492252 }
20502253
20512254 /// Renders the edited timeline to `out` on a worker thread. The session is
@@ -2099,10 +2302,35 @@ impl PlaybackSession {
20992302 // Audio EOF. Wall time carries the same timeline on from here, with
21002303 // no jump, and this branch cannot be reached again.
21012304 self.clock.switch_to_wall();
2102- } else {
2305+ return;
2306+ }
2307+ if self.priming {
2308+ // A stream that has been started and has not been heard yet: the
2309+ // device is playing the silence of its own restart, and none of it
2310+ // is timeline time ([`Audio::content_at`]). The clock holds where
2311+ // the seek left it -- so the picture holds too, on the frame it
2312+ // landed on, rather than sliding ahead of a sound that has not
2313+ // started.
2314+ let started = audio.content_at.load(Ordering::Acquire);
2315+ if started < 0 {
2316+ return;
2317+ }
2318+ // ...and then the *first sample of the stream* becomes the
2319+ // reference, not whatever position this poll happened to catch: the
2320+ // clock's own anchor is its first report ([`PlaybackClock`]), and
2321+ // anchoring it here is what makes a mid-play edit cost no offset.
2322+ //
2323+ // ponytail: `started` is the position when the sample was queued,
2324+ // and it is heard at the next callback -- up to one quantum (5-21
2325+ // ms) later, so that much of the restart is still counted. Upgrade
2326+ // path is the position at the first *pop* of real audio, which only
2327+ // the plugin's RT thread can see.
21032328 self.clock
2104- .set_audio_position(position as u64, audio.sample_rate);
2329+ .set_audio_position(started as u64, audio.sample_rate);
2330+ self.priming = false;
21052331 }
2332+ self.clock
2333+ .set_audio_position(position as u64, audio.sample_rate);
21062334 }
21072335 }
21082336
@@ -2331,6 +2559,7 @@ fn open_audio(path: &Path, stream: usize) -> (Option<Audio>, Option<String>) {
23312559 fed_all: Arc::new(AtomicBool::new(false)),
23322560 died: Arc::new(AtomicBool::new(false)),
23332561 epoch: Arc::new(AtomicU64::new(0)),
2562+ content_at: Arc::new(AtomicI64::new(-1)),
23342563 tap: Arc::new(Mutex::new(Vec::with_capacity(TAP_SAMPLES))),
23352564 };
23362565 (audio.spawn_feeder(rx).then_some(audio), None)
@@ -2356,21 +2585,39 @@ fn feed(rx: Receiver<AudioChunk>, audio: &Audio, epoch: u64) {
23562585 if audio.epoch.load(Ordering::Acquire) != epoch {
23572586 return;
23582587 }
2359- match ao.write(&pending) {
2588+ let accepted = match ao.write(&pending) {
23602589 Some(n) => n,
23612590 None => {
23622591 // Output died; flag it so `tick` moves the clock to wall time.
23632592 audio.died.store(true, Ordering::Release);
23642593 return;
23652594 }
2595+ };
2596+ // The first sample of this stream to reach the ring, stamped with
2597+ // what the device had played by then: everything before it was the
2598+ // silence of the restart, and [`PlaybackSession::tick`] anchors the
2599+ // clock here so that silence is never timeline time. Under the
2600+ // device lock, with the epoch already checked, so the stamp and the
2601+ // sample belong to the same stream.
2602+ if accepted > 0 && audio.content_at.load(Ordering::Acquire) < 0 {
2603+ let at = ao.position().unwrap_or(0).max(0);
2604+ audio.content_at.store(at, Ordering::Release);
23662605 }
2606+ accepted
23672607 };
23682608 audio.fed.fetch_add(accepted as u64, Ordering::Relaxed);
23692609 audio.note_tap(&pending[..accepted]);
23702610 pending.drain(..accepted);
23712611 if !pending.is_empty() {
2372- // Ring full: nothing to do but let the device drain it.
2373- thread::sleep(RING_FULL_WAIT);
2612+ // Ring full: nothing to do but let the device drain it. Except when
2613+ // *nothing* was taken, which after a flush means the ring is still
2614+ // waiting for the device to consume the flush flag rather than
2615+ // being full: that is the head of a restart, and every millisecond
2616+ // spent parked there is a millisecond of silence.
2617+ match accepted {
2618+ 0 => thread::sleep(FLUSH_WAIT),
2619+ _ => thread::sleep(RING_FULL_WAIT),
2620+ }
23742621 }
23752622 }
23762623 }
crates/engine/tests/invalidation.rsadded+252 -0
@@ -0,0 +1,252 @@
1+//! What an edit is allowed to tear down, and what it is not.
2+//!
3+//! Every setting a person can move while a timeline plays dirties *one* half of
4+//! the pipeline at most: a grade, a fit policy and the project resolution are
5+//! pictures, an equalizer is sound, and a fader is not even that -- it is a
6+//! number the running mixer picks up between two blocks. The tests here are the
7+//! measurement of that claim, and the thing they measure is the **audio tap**:
8+//! it is the sound the device was handed last, and a restart clears it (the
9+//! ring is flushed and nothing is fed again until a decoder has reopened, tens
10+//! of milliseconds later). An empty tap right after an edit therefore *is* the
11+//! hole in the sound the user reported hearing when they dragged a colour
12+//! slider.
13+//!
14+//! Every test runs anywhere: with no PipeWire daemon there is no device, no tap
15+//! and nothing to protect, so the audio assertions are made only when there is
16+//! sound to make them about -- the clock assertions run either way.
17+//!
18+//! ```text
19+//! cargo test -p engine --test invalidation -- --nocapture
20+//! ```
21+
22+use std::path::{Path, PathBuf};
23+use std::thread::sleep;
24+use std::time::Duration;
25+
26+use engine::PlaybackSession;
27+use engine::color::ColorParams;
28+use engine::limiter::Limiter;
29+use engine::project::Lane;
30+
31+fn asset(name: &str) -> PathBuf {
32+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))
33+ .join("../../assets")
34+ .join(name)
35+}
36+
37+/// Silent, like every other suite that plays a real file: these tests are about
38+/// whether the sound is *interrupted*, not about what it sounds like, and the
39+/// gain is the last multiply before the device -- everything measured here is
40+/// decoded, fed and counted exactly as it is when it is audible.
41+fn open(path: &Path) -> PlaybackSession {
42+ let session = PlaybackSession::open(path).expect("open");
43+ session.set_gain(0.0);
44+ session
45+}
46+
47+/// How many samples the device has been handed lately. `None` with no audio
48+/// device at all -- the machine's business, and nothing to assert about.
49+fn heard(session: &PlaybackSession) -> Option<usize> {
50+ session.audio_tap().map(|(tap, _)| tap.len())
51+}
52+
53+/// Plays until the device has really been handed something, so a later empty
54+/// tap means "this edit emptied it" rather than "it was never filled".
55+fn play_until_heard(session: &mut PlaybackSession) -> Option<usize> {
56+ session.play();
57+ for _ in 0..200 {
58+ session.tick();
59+ while session.try_frame().is_some() {}
60+ if heard(session).is_none_or(|n| n > 0) {
61+ break;
62+ }
63+ sleep(Duration::from_millis(10));
64+ }
65+ let filled = heard(session);
66+ if filled == Some(0) {
67+ panic!("the device was never fed: nothing to measure");
68+ }
69+ filled
70+}
71+
72+/// A grade dragged while the timeline plays. The slider commits per pointer
73+/// sample (`set_color_live`), which used to reseek the whole session per
74+/// sample: an audio flush, an audio re-open and a video decoder rebuild, ~40
75+/// times across one drag of the bar. The sound must not notice.
76+#[test]
77+fn a_grade_during_playback_never_touches_the_sound() {
78+ let mut session = open(&asset("test_av.mp4"));
79+ let filled = play_until_heard(&mut session);
80+ let before = session.now();
81+
82+ for step in 0..20 {
83+ let grade = ColorParams {
84+ saturation: 1.0 - step as f32 / 40.0,
85+ ..Default::default()
86+ };
87+ assert!(
88+ session.set_color_live(Lane::V1, 0, Some(grade)),
89+ "the grade takes at step {step}"
90+ );
91+ // Right now, with no wait: a flush shows up here before anything can
92+ // refill it.
93+ if let Some(n) = heard(&session) {
94+ assert!(
95+ n > 0,
96+ "step {step} of the drag emptied the device queue -- the sound was torn down by a colour change"
97+ );
98+ }
99+ session.tick();
100+ while session.try_frame().is_some() {}
101+ }
102+
103+ assert_eq!(
104+ heard(&session).is_some(),
105+ filled.is_some(),
106+ "the audio path disappeared across the drag"
107+ );
108+ let after = session.now();
109+ assert!(
110+ after >= before,
111+ "the clock went backwards across the drag: {before:.3}s -> {after:.3}s"
112+ );
113+ assert!(
114+ after - before < 0.5,
115+ "20 grade steps cost {:.3}s of timeline",
116+ after - before
117+ );
118+ eprintln!("20 live grades: clock {before:.3}s -> {after:.3}s, tap {filled:?} samples");
119+}
120+
121+/// The project resolution, changed while the timeline plays -- the 4K film the
122+/// report came from. Every clip is recomposed onto the new canvas, which is a
123+/// video decoder rebuild and nothing else: no sample changes, so no sample may
124+/// be discarded and the clock may not be re-anchored (that re-anchor, onto an
125+/// empty ring, is what put the picture permanently ahead of the sound).
126+#[test]
127+fn a_resolution_change_during_playback_never_touches_the_sound() {
128+ let mut session = open(&asset("test_av.mp4"));
129+ let filled = play_until_heard(&mut session);
130+ let native = session.native_resolution();
131+ let before = session.now();
132+
133+ for (w, h) in [(1920, 1080), (640, 360), (3840, 2160)] {
134+ assert!(session.set_resolution(w, h), "resize to {w}x{h}");
135+ if let Some(n) = heard(&session) {
136+ assert!(
137+ n > 0,
138+ "resizing to {w}x{h} emptied the device queue -- the sound was torn down by a picture setting"
139+ );
140+ }
141+ let at = session.now();
142+ assert!(
143+ at >= before && at - before < 0.5,
144+ "the clock jumped across the resize: {before:.3}s -> {at:.3}s"
145+ );
146+ assert_eq!(session.resolution(), (w, h));
147+ session.tick();
148+ while session.try_frame().is_some() {}
149+ }
150+ assert_eq!(
151+ session.native_resolution(),
152+ native,
153+ "the media's own size is not the project's"
154+ );
155+ assert_eq!(
156+ heard(&session).is_some(),
157+ filled.is_some(),
158+ "the audio path disappeared across the resizes"
159+ );
160+
161+ // ...and it is still running afterwards, at real speed.
162+ let mark = session.now();
163+ for _ in 0..30 {
164+ session.tick();
165+ while session.try_frame().is_some() {}
166+ sleep(Duration::from_millis(10));
167+ }
168+ let ran = session.now() - mark;
169+ eprintln!("after three resizes the clock ran {ran:.3}s in 0.3s of real time");
170+ assert!(ran > 0.05, "the clock stalled after the resize: {ran:.3}s");
171+}
172+
173+/// A fader and the master ceiling, moved while the timeline plays. Both live at
174+/// the mix and nowhere else, so a running mixer picks them up between blocks --
175+/// nothing is flushed, nothing is reopened, and the picture does not blink.
176+///
177+/// The *first* move is allowed one restart: a single audio lane at unity with
178+/// the limiter off is not mixed at all (the bit-exact path), so moving off it
179+/// is what opens a mixer. Every move after that is live, which is what an arrow
180+/// key held down on the mix card actually does.
181+#[test]
182+fn a_fader_during_playback_stops_restarting_the_sound() {
183+ let mut session = open(&asset("test_av.mp4"));
184+ let filled = play_until_heard(&mut session);
185+ if filled.is_none() {
186+ eprintln!("no audio device: nothing to mix");
187+ return;
188+ }
189+
190+ // The move that opens the mixer, and the refill after it.
191+ assert!(session.set_lane_gain_db(Lane::A1, -3.0), "turn A1 down");
192+ play_until_heard(&mut session);
193+
194+ for step in 1..=20 {
195+ let db = -3.0 - step as f32 * 0.5;
196+ assert!(session.set_lane_gain_db(Lane::A1, db), "fader to {db} dB");
197+ assert_eq!(
198+ heard(&session),
199+ filled,
200+ "nudge {step} emptied the device queue -- a fader restarted the stream"
201+ );
202+ }
203+ // ...and the ceiling beside it, which is retuned rather than rebuilt.
204+ for step in 0..8 {
205+ let limiter = Limiter {
206+ on: step % 2 == 0,
207+ ..Limiter::default()
208+ }
209+ .with_ceiling(-1.0 - step as f32);
210+ assert!(session.set_limiter(limiter), "ceiling {step}");
211+ assert_eq!(
212+ heard(&session),
213+ filled,
214+ "limiter step {step} emptied the device queue"
215+ );
216+ }
217+ assert_eq!(session.lane_gain_db(Lane::A1), -13.0);
218+ eprintln!("20 fader nudges and 8 limiter moves: not one restart");
219+}
220+
221+/// The other half of the rule, and the one that makes it a *classification*
222+/// rather than a blanket "never rebuild": an equalizer really is a change to
223+/// the samples, so it does restart the audio -- and must leave the picture
224+/// alone while it does.
225+#[test]
226+fn an_equalizer_rebuilds_the_sound_and_only_the_sound() {
227+ let mut session = open(&asset("test_av.mp4"));
228+ play_until_heard(&mut session);
229+ let before = session.now();
230+
231+ let params = engine::eq::EqParams::default_layout();
232+ let mut curve = params.clone();
233+ curve.bands[0].gain_db = 6.0;
234+ assert!(session.set_eq(Lane::A1, 0, Some(curve)), "equalize A1's clip");
235+
236+ let after = session.now();
237+ assert!(
238+ after >= before && after - before < 0.5,
239+ "the equalizer moved the playhead: {before:.3}s -> {after:.3}s"
240+ );
241+ // The picture keeps coming: the video worker was never cancelled.
242+ let mut frames = 0;
243+ for _ in 0..60 {
244+ session.tick();
245+ while session.try_frame().is_some() {
246+ frames += 1;
247+ }
248+ sleep(Duration::from_millis(10));
249+ }
250+ eprintln!("{frames} frames across an equalizer change, clock at {:.3}s", session.now());
251+ assert!(frames > 0, "the picture stopped when the sound was rebuilt");
252+}
crates/engine/tests/playback.rsmodified+15 -3
@@ -284,15 +284,27 @@ fn seek_keeps_the_audio_clock() {
284284 "clock at {}",
285285 session.now()
286286 );
287+ // From here on the *sound* is what the clock counts, and the sound restarts
288+ // at once -- the video decoder's reopen (up to a VA-API init) happens
289+ // underneath a stream that is already playing, so the window `next_index`
290+ // spends waiting for the first picture is time the timeline really moved
291+ // through. Measured against the wall rather than assumed free: counting it
292+ // is the fix for the offset an edit-while-playing used to leave behind
293+ // (`invalidation.rs`), where the clock re-anchored onto an empty ring and
294+ // the picture stayed that far behind the sound for good.
295+ let from = Instant::now();
287296 let first = next_index(&mut session, "seek(3.0)");
288297 assert_eq!(first, (3.0 * meta.frame_rate) as u32);
289298 let mut after_seek = None;
290299 run_for(&mut session, &mut after_seek, Duration::from_millis(600));
291300 let advanced = session.now();
292- eprintln!("seek(3.0) -> {advanced:.3}s, frames {first}..={after_seek:?}");
301+ let real = from.elapsed().as_secs_f64();
302+ eprintln!(
303+ "seek(3.0) -> {advanced:.3}s after {real:.3}s of real time, frames {first}..={after_seek:?}"
304+ );
293305 assert!(
294- (3.3..3.9).contains(&advanced),
295- "clock did not run at real speed after the seek: {advanced:.3}s"
306+ (3.0 + real - 0.35..3.0 + real + 0.35).contains(&advanced),
307+ "clock did not run at real speed after the seek: {advanced:.3}s after {real:.3}s"
296308 );
297309
298310 // Everything from the target on, and nothing before it: ~2 s of frames.