forge
Explore
Log in

Don't you dare go Hollow

An edit rebuilds what it dirtied, and nothing else

Browse files at this commit

c2e62a3fcc493eaa96f78fd54fe81e1757abe767Ahmet Kaan GümüşParent: 680220d
  • feat
    • an edit rebuilds what it dirtied, and nothing else
Show full message
✨ feat(engine): an edit rebuilds what it dirtied, and nothing else

Every param change went through one funnel -- edit() -> seek() -- which
flushed the audio ring, reopened every track, respawned the feeder and
rebuilt the video decoder. Dragging a colour slider therefore cut the
sound ~40 times across one gesture, and every restart re-anchored the
clock onto an empty ring, so the silence of the restart was counted as
timeline time: a permanent A/V offset, re-rolled by every edit made
while playing (the resolution-change desync).

Edits are classified by what they dirty now. A grade, a fit policy and
the project resolution rebuild the picture where it stands and never
touch a sample. An equalizer rebuilds the sound and never touches the
picture. A fader and the master ceiling rebuild nothing at all: they
live at the mix sum, so the running mixer picks them up between two
blocks (MixControls), and the limiter is retuned rather than restarted
so its delay line -- and the sample count the master clock is made of --
keeps running. Only a structural edit still reseeks both halves.

And a restart no longer costs an offset: the feeder stamps the device
position its first real sample was queued at, and the clock anchors
there instead of on the first poll after the seek, so the silence before
the content is never timeline time.

Also: a span whose source will not open no longer presents the old
channel's frames under the new mapping, and the feeder stops parking
10 ms on a ring that is merely waiting out a flush.
crates/engine/src/audio.rsmodified+117 -3
@@ -28,7 +28,9 @@
28 use std::fs::File;28 use std::fs::File;
29 use std::io::BufReader;29 use std::io::BufReader;
30 use std::path::{Path, PathBuf};30 use std::path::{Path, PathBuf};
31+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
31 use std::sync::mpsc::{Receiver, SyncSender, sync_channel};32 use std::sync::mpsc::{Receiver, SyncSender, sync_channel};
33+use std::sync::{Arc, Mutex};
32 use std::thread;34 use std::thread;
33 35
34 use mp4::{AudioObjectType, ChannelConfig, MediaType, Mp4Reader, Mp4Track, TrackType};36 use mp4::{AudioObjectType, ChannelConfig, MediaType, Mp4Reader, Mp4Track, TrackType};
@@ -152,6 +154,67 @@ pub struct StreamInfo {
152 pub decodable: bool,154 pub decodable: bool,
153 }155 }
154 156
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+
155 pub struct AudioSession;218 pub struct AudioSession;
156 219
157 impl AudioSession {220 impl AudioSession {
@@ -497,6 +560,26 @@ impl AudioSession {
497 speeds: &[Vec<Option<crate::project::Stretch>>],560 speeds: &[Vec<Option<crate::project::Stretch>>],
498 gains: &[f32],561 gains: &[f32],
499 limiter: Limiter,562 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>>,
500 ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> {583 ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> {
501 let [first, rest @ ..] = lanes else {584 let [first, rest @ ..] = lanes else {
502 return Ok(None);585 return Ok(None);
@@ -540,12 +623,20 @@ impl AudioSession {
540 let mut gains = gains.to_vec();623 let mut gains = gains.to_vec();
541 gains.resize(lanes.len(), 1.0);624 gains.resize(lanes.len(), 1.0);
542 // Built here, off the thread that will run it, where the rate is known.625 // Built here, off the thread that will run it, where the rate is known.
543- let limiter = limiter626+ let state = limiter
544 .is_active()627 .is_active()
545 .then(|| LimiterState::new(&limiter, meta.sample_rate, channels));628 .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;
546 thread::Builder::new()637 thread::Builder::new()
547 .name("audio-mix".into())638 .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))?;
549 Ok(Some((meta, rx)))640 Ok(Some((meta, rx)))
550 }641 }
551 642
@@ -2114,10 +2205,15 @@ struct Worker {
2114 fn mix(2205 fn mix(
2115 rxs: &[Receiver<AudioChunk>],2206 rxs: &[Receiver<AudioChunk>],
2116 channels: usize,2207 channels: usize,
2117- gains: &[f32],2208+ mut gains: Vec<f32>,
2118 mut limiter: Option<LimiterState>,2209 mut limiter: Option<LimiterState>,
2210+ rate: u32,
2211+ controls: Option<&MixControls>,
2119 tx: &SyncSender<AudioChunk>,2212 tx: &SyncSender<AudioChunk>,
2120 ) {2213 ) {
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;
2121 let mut pending: Vec<Vec<f32>> = rxs.iter().map(|_| Vec::new()).collect();2217 let mut pending: Vec<Vec<f32>> = rxs.iter().map(|_| Vec::new()).collect();
2122 let mut live: Vec<bool> = rxs.iter().map(|_| true).collect();2218 let mut live: Vec<bool> = rxs.iter().map(|_| true).collect();
2123 // Numbering follows lane 0, whose first chunk says where it starts.2219 // Numbering follows lane 0, whose first chunk says where it starts.
@@ -2125,6 +2221,24 @@ fn mix(
2125 let mut emitted = 0;2221 let mut emitted = 0;
2126 let mut out: Vec<f32> = Vec::new();2222 let mut out: Vec<f32> = Vec::new();
2127 loop {2223 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+ }
2128 for (i, rx) in rxs.iter().enumerate() {2242 for (i, rx) in rxs.iter().enumerate() {
2129 while live[i] && pending[i].is_empty() {2243 while live[i] && pending[i].is_empty() {
2130 match rx.recv() {2244 match rx.recv() {
crates/engine/src/decode.rsmodified+1 -1
@@ -87,7 +87,7 @@ impl Backend {
87 pub struct BackendCell(Arc<AtomicU8>);87 pub struct BackendCell(Arc<AtomicU8>);
88 88
89 impl BackendCell {89 impl BackendCell {
90- fn new(backend: Backend) -> Self {90+ pub(crate) fn new(backend: Backend) -> Self {
91 Self(Arc::new(AtomicU8::new(backend.code())))91 Self(Arc::new(AtomicU8::new(backend.code())))
92 }92 }
93 93
crates/engine/src/limiter.rsmodified+91 -1
@@ -106,6 +106,11 @@ pub struct LimiterState {
106 /// delay line, which is how the latency is paid back (module docs).106 /// delay line, which is how the latency is paid back (module docs).
107 warm: usize,107 warm: usize,
108 gain: f32,108 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,
109 ceiling: f32,114 ceiling: f32,
110 /// Where the knee starts, as an amplitude: under this the fast path runs115 /// Where the knee starts, as an amplitude: under this the fast path runs
111 /// and no logarithm is taken.116 /// and no logarithm is taken.
@@ -125,6 +130,7 @@ impl LimiterState {
125 at: 0,130 at: 0,
126 warm: frames - 1,131 warm: frames - 1,
127 gain: 1.0,132 gain: 1.0,
133+ bypass: !params.on,
128 ceiling: db_to_linear(ceiling_db),134 ceiling: db_to_linear(ceiling_db),
129 knee_floor: db_to_linear(ceiling_db - KNEE_DB / 2.0),135 knee_floor: db_to_linear(ceiling_db - KNEE_DB / 2.0),
130 // One time constant per sample: the gain covers 63% of the way back136 // One time constant per sample: the gain covers 63% of the way back
@@ -133,6 +139,34 @@ impl LimiterState {
133 }139 }
134 }140 }
135 141
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+
136 /// Rewrites `buf` -- interleaved frames -- as the limited mix. Shorter than170 /// Rewrites `buf` -- interleaved frames -- as the limited mix. Shorter than
137 /// what came in by the delay line's length, once, at the first call.171 /// what came in by the delay line's length, once, at the first call.
138 pub fn process(&mut self, buf: &mut Vec<f32>) {172 pub fn process(&mut self, buf: &mut Vec<f32>) {
@@ -163,8 +197,14 @@ impl LimiterState {
163 self.warm -= 1;197 self.warm -= 1;
164 continue;198 continue;
165 }199 }
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+ };
166 for c in 0..channels {206 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);
168 }208 }
169 }209 }
170 *buf = out;210 *buf = out;
@@ -240,6 +280,56 @@ mod tests {
240 assert_eq!(buf.len(), rate as usize * 2 - (state.peaks.len() - 1) * 2);280 assert_eq!(buf.len(), rate as usize * 2 - (state.peaks.len() - 1) * 2);
241 }281 }
242 282
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+
243 /// Flat settings are a passthrough, which is what the export invariant333 /// Flat settings are a passthrough, which is what the export invariant
244 /// rests on: 0 dB is exactly 1.0, never 0.9999999.334 /// rests on: 0 dB is exactly 1.0, never 0.9999999.
245 #[test]335 #[test]
crates/engine/src/playback.rsmodified+321 -74
@@ -12,7 +12,7 @@
12 //! the renderer decides which frame that means.12 //! the renderer decides which frame that means.
13 13
14 use std::path::Path;14 use std::path::Path;
15-use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};15+use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU64, Ordering};
16 use std::sync::mpsc::{Receiver, TryRecvError};16 use std::sync::mpsc::{Receiver, TryRecvError};
17 use std::sync::{Arc, Mutex};17 use std::sync::{Arc, Mutex};
18 use std::thread;18 use std::thread;
@@ -32,6 +32,13 @@ use crate::scale::{Composer, FitPolicy};
32 /// only has to be short next to that; it costs one wakeup per 10 ms of audio.32 /// only has to be short next to that; it costs one wakeup per 10 ms of audio.
33 const RING_FULL_WAIT: Duration = Duration::from_millis(10);33 const RING_FULL_WAIT: Duration = Duration::from_millis(10);
34 34
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+
35 /// The timeline a file with no picture scaffolds: 1080p at 30 fps, H.264 --42 /// The timeline a file with no picture scaffolds: 1080p at 30 fps, H.264 --
36 /// nothing was shot on it, so it is the canvas a *later* import meets rather43 /// nothing was shot on it, so it is the canvas a *later* import meets rather
37 /// than a description of the song. H.264 because it is the one codec that44 /// than a description of the song. H.264 because it is the one codec that
@@ -91,6 +98,18 @@ struct Audio {
91 /// Bumped by every seek. A feeder only owns the device while this still98 /// Bumped by every seek. A feeder only owns the device while this still
92 /// matches the value it started with; see [`feed`].99 /// matches the value it started with; see [`feed`].
93 epoch: Arc<AtomicU64>,100 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>,
94 /// The last [`TAP_SAMPLES`] mono samples handed to the device, oldest113 /// The last [`TAP_SAMPLES`] mono samples handed to the device, oldest
95 /// first: what a meter or an analyser draws. Written by the feeder, which114 /// first: what a meter or an analyser draws. Written by the feeder, which
96 /// is not the device's own callback -- the plugin's RT thread never sees115 /// is not the device's own callback -- the plugin's RT thread never sees
@@ -228,6 +247,39 @@ pub struct PlaybackSession {
228 span: Option<Span>,247 span: Option<Span>,
229 /// The last clip has been played out; see [`PlaybackSession::is_eos`].248 /// The last clip has been played out; see [`PlaybackSession::is_eos`].
230 eos: bool,249 eos: bool,
250+ /// The mix the running mixer is reading, when there is one: what lets a
251+ /// fader and the master ceiling move without rebuilding the audio pipeline
252+ /// at all ([`crate::audio::MixControls`]). `None` for a timeline that is
253+ /// not mixed -- one audio lane at unity with the limiter off, which is the
254+ /// bit-exact single-stream path -- and the first move off that reopens the
255+ /// stream once, mixed, and lives from there.
256+ mix: Option<Arc<crate::audio::MixControls>>,
257+ /// An audio stream has been started and has not yet played a sample: the
258+ /// window [`tick`](Self::tick) holds the clock still through, so the silence
259+ /// of a restart is never counted as timeline time. See
260+ /// [`Audio::content_at`].
261+ priming: bool,
262+}
263+
264+/// What an edit dirtied -- which half of the pipeline has to be rebuilt for the
265+/// change to be seen or heard, and, far more to the point, which half must not
266+/// be.
267+///
268+/// Rebuilding a half is expensive and *audible*: the video worker costs a
269+/// decoder open (98 ms of VA-API init, worst case, measured) and the audio one
270+/// costs a flush, a re-open and a hole in the sound. A grade changes no sample
271+/// and a fader changes no picture, so neither may pay the other's price -- that
272+/// is the whole of this type.
273+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
274+enum Dirty {
275+ /// The picture only: a grade, a fit policy, the project resolution. The
276+ /// sound keeps playing, untouched, and the clock never moves.
277+ Picture,
278+ /// The sound only: a clip's equalizer. The picture keeps playing.
279+ Sound,
280+ /// The timeline itself -- what is where, how long, how fast. Both halves
281+ /// are rebuilt, because both are decoding the wrong thing.
282+ Both,
231 }283 }
232 284
233 impl PlaybackSession {285 impl PlaybackSession {
@@ -291,6 +343,8 @@ impl PlaybackSession {
291 span_rate: Rate::REAL_TIME,343 span_rate: Rate::REAL_TIME,
292 span,344 span,
293 eos: false,345 eos: false,
346+ mix: None,
347+ priming: false,
294 })348 })
295 }349 }
296 350
@@ -395,6 +449,8 @@ impl PlaybackSession {
395 span_rate: Rate::REAL_TIME,449 span_rate: Rate::REAL_TIME,
396 span,450 span,
397 eos: false,451 eos: false,
452+ mix: None,
453+ priming: false,
398 })454 })
399 }455 }
400 456
@@ -465,6 +521,8 @@ impl PlaybackSession {
465 span_rate: Rate::REAL_TIME,521 span_rate: Rate::REAL_TIME,
466 span,522 span,
467 eos: false,523 eos: false,
524+ mix: None,
525+ priming: false,
468 })526 })
469 }527 }
470 528
@@ -720,6 +778,8 @@ impl PlaybackSession {
720 span_rate: Rate::REAL_TIME,778 span_rate: Rate::REAL_TIME,
721 span,779 span,
722 eos: false,780 eos: false,
781+ mix: None,
782+ priming: false,
723 };783 };
724 // The scaffolding above opened source 0 from its first frame and the784 // The scaffolding above opened source 0 from its first frame and the
725 // whole of its audio; this puts both onto the clip the playhead is785 // whole of its audio; this puts both onto the clip the playhead is
@@ -1024,15 +1084,29 @@ impl PlaybackSession {
1024 gap.map_or(1, |s| s.len),1084 gap.map_or(1, |s| s.len),
1025 )),1085 )),
1026 };1086 };
1027- if let Ok(stream) = opened {1087+ let Ok(stream) = opened else {
1028- // Receiver first, worker second: the drop of the *old* receiver is1088+ // The file would not open. The span still goes in -- the timeline
1029- // what wakes the outgoing worker if it is parked in `send`, and only1089+ // moves on, there are simply no more pictures -- but the *frames*
1030- // then can it return and be reaped by a later sweep. Nothing here1090+ // must not: the old channel's pictures are numbered in the old
1031- // joins, so this ordering costs the seek nothing.1091+ // source's frames, and presenting them under the new mapping would
1032- self.frames = stream.frames;1092+ // put the wrong picture at the wrong time (and leave
1033- self.backend = stream.backend;1093+ // [`decode_backend`](Self::decode_backend) describing a worker that
1034- self.retire(stream.worker);1094+ // is no longer feeding anything). A dead receiver instead, which is
1035- }1095+ // what carries the session on to the next span. The old worker stays
1096+ // parked in `self.worker` where the caller already cancelled it; the
1097+ // next span retires it.
1098+ self.frames = std::sync::mpsc::channel().1;
1099+ self.backend = BackendCell::new(Backend::Gap);
1100+ self.span = span;
1101+ return;
1102+ };
1103+ // Receiver first, worker second: the drop of the *old* receiver is
1104+ // what wakes the outgoing worker if it is parked in `send`, and only
1105+ // then can it return and be reaped by a later sweep. Nothing here
1106+ // joins, so this ordering costs the seek nothing.
1107+ self.frames = stream.frames;
1108+ self.backend = stream.backend;
1109+ self.retire(stream.worker);
1036 self.span = span;1110 self.span = span;
1037 }1111 }
1038 1112
@@ -1151,18 +1225,20 @@ impl PlaybackSession {
1151 }1225 }
1152 1226
1153 /// Gives that clip an equalizer, or takes it off with `None`. One undo step,1227 /// Gives that clip an equalizer, or takes it off with `None`. One undo step,
1154- /// like every other edit -- and, like every other edit, it *reseeks*: the1228+ /// like every other edit -- and it rebuilds the **sound** where the playhead
1155- /// audio workers are rebuilt from the new curves right where the playhead
1156 /// is, so a band changed during playback is heard from the next chunk on1229 /// is, so a band changed during playback is heard from the next chunk on
1157- /// rather than at the next play. `false` for a bad index or a non-finite1230+ /// rather than at the next play. The picture is not touched: the video
1158- /// band, and nothing changes.1231+ /// worker keeps decoding through it ([`Dirty`]). `false` for a bad index or
1232+ /// a non-finite band, and nothing changes.
1159 ///1233 ///
1160- /// ponytail: the reseek is what makes it live, so the cost of a change is a1234+ /// ponytail: the audio rebuild is what makes it live, so the cost of a
1161- /// decoder restart -- inaudible at a drag's end, but too much to call once1235+ /// change is a decoder restart -- inaudible at a drag's end, but too much to
1162- /// per pointer sample (a caller commits one change per gesture). Upgrade1236+ /// call once per pointer sample (a caller commits one change per gesture).
1163- /// path is an `Arc` swap the running worker polls per chunk.1237+ /// Upgrade path is the per-segment twin of [`crate::audio::MixControls`],
1238+ /// which the lane worker would poll per chunk the way the mixer polls the
1239+ /// gains.
1164 pub fn set_eq(&mut self, lane: Lane, idx: usize, params: Option<EqParams>) -> bool {1240 pub fn set_eq(&mut self, lane: Lane, idx: usize, params: Option<EqParams>) -> bool {
1165- self.edit(|p| p.set_eq(lane, idx, params))1241+ self.edit(Dirty::Sound, |p| p.set_eq(lane, idx, params))
1166 }1242 }
1167 1243
1168 /// How loud that lane plays, in dB -- everything on it, every frequency of1244 /// How loud that lane plays, in dB -- everything on it, every frequency of
@@ -1171,12 +1247,36 @@ impl PlaybackSession {
1171 self.project.lane_gain_db(lane)1247 self.project.lane_gain_db(lane)
1172 }1248 }
1173 1249
1174- /// Sets it. One undo step and a reseek, the equalizer's rule for the1250+ /// Sets it. One undo step -- and **nothing is rebuilt**: a lane's volume
1175- /// equalizer's reason: the mixer is rebuilt from the new volumes right1251+ /// lives at the sum, so the running mixer is handed the new number and
1176- /// where the playhead is, so a track turned down during playback is heard1252+ /// picks it up at its next block ([`crate::audio::MixControls`]). A fader
1177- /// turned down from the next chunk on.1253+ /// held down under an arrow key therefore moves the level and nothing else:
1254+ /// no flush, no decoder restart, no hole in the sound and no blink in the
1255+ /// picture.
1256+ ///
1257+ /// The one exception is the timeline that is not mixed at all -- a single
1258+ /// audio lane at unity with the limiter off, which plays through the
1259+ /// bit-exact single-stream path and has no mixer to talk to. Moving *that*
1260+ /// off unity opens one, once; every move after it is live.
1178 pub fn set_lane_gain_db(&mut self, lane: Lane, db: f32) -> bool {1261 pub fn set_lane_gain_db(&mut self, lane: Lane, db: f32) -> bool {
1179- self.edit(|p| p.set_lane_gain_db(lane, db))1262+ if !self.project.set_lane_gain_db(lane, db) {
1263+ return false;
1264+ }
1265+ self.push_mix();
1266+ true
1267+ }
1268+
1269+ /// Hands the mix the running mixer is reading its new settings -- the whole
1270+ /// of what a fader and a ceiling cost. With no mixer listening (the
1271+ /// single-lane flat path, and a session with no sound at all) the sound is
1272+ /// rebuilt instead, which is what opens one.
1273+ fn push_mix(&mut self) {
1274+ let gains = self.project.audio_gains();
1275+ let limiter = self.project.limiter();
1276+ match &self.mix {
1277+ Some(mix) => mix.set(gains, limiter),
1278+ None => self.reseek_audio(),
1279+ }
1180 }1280 }
1181 1281
1182 /// The master limiter the whole mix is summed through.1282 /// The master limiter the whole mix is summed through.
@@ -1185,9 +1285,25 @@ impl PlaybackSession {
1185 }1285 }
1186 1286
1187 /// Sets it, live like a lane volume and for the same reason -- the ceiling1287 /// Sets it, live like a lane volume and for the same reason -- the ceiling
1188- /// a person is dragging has to be the ceiling they are hearing.1288+ /// a person is dragging has to be the ceiling they are hearing. Nothing is
1289+ /// rebuilt: the running limiter is *retuned* between two blocks
1290+ /// ([`crate::limiter::LimiterState::retune`]), so its delay line keeps
1291+ /// running and the sample count the master clock is made of does not move.
1292+ ///
1293+ /// ponytail: not an undo step, and deliberately -- [`Project::undo`]
1294+ /// restores the lane list, and the limiter is not in it, so snapshotting
1295+ /// here would push a step whose undo changes nothing a person can see or
1296+ /// hear (the twin [`set_lane_gain_db`](Self::set_lane_gain_db) *is*
1297+ /// undoable only because a lane volume lives in that list). The project
1298+ /// resolution is outside undo for the same reason and says so. Upgrade path
1299+ /// is a history that carries the mix beside the lanes, which every existing
1300+ /// snapshot site would then have to fill in.
1189 pub fn set_limiter(&mut self, limiter: crate::limiter::Limiter) -> bool {1301 pub fn set_limiter(&mut self, limiter: crate::limiter::Limiter) -> bool {
1190- self.edit(|p| p.set_limiter(limiter))1302+ if !self.project.set_limiter(limiter) {
1303+ return false;
1304+ }
1305+ self.push_mix();
1306+ true
1191 }1307 }
1192 1308
1193 /// Lifts one lane's clip out, leaving a gap: black frames on the video lane,1309 /// Lifts one lane's clip out, leaving a gap: black frames on the video lane,
@@ -1196,7 +1312,7 @@ impl PlaybackSession {
1196 /// the last placement there is empties the timeline, which is a state1312 /// the last placement there is empties the timeline, which is a state
1197 /// ([`is_empty`](Self::is_empty)) and one undo away.1313 /// ([`is_empty`](Self::is_empty)) and one undo away.
1198 pub fn lift_clip(&mut self, lane: Lane, idx: usize) -> bool {1314 pub fn lift_clip(&mut self, lane: Lane, idx: usize) -> bool {
1199- self.edit(|p| p.lift(lane, idx))1315+ self.edit(Dirty::Both, |p| p.lift(lane, idx))
1200 }1316 }
1201 1317
1202 /// Moves that clip onto lane `to` with its head at timeline frame `start` --1318 /// Moves that clip onto lane `to` with its head at timeline frame `start` --
@@ -1212,7 +1328,7 @@ impl PlaybackSession {
1212 /// pointer on a frame, and converting it back through seconds would be a1328 /// pointer on a frame, and converting it back through seconds would be a
1213 /// rounding step between the box let go of and the box committed.1329 /// rounding step between the box let go of and the box committed.
1214 pub fn move_clip_to(&mut self, from: Lane, idx: usize, to: Lane, start: u32) -> bool {1330 pub fn move_clip_to(&mut self, from: Lane, idx: usize, to: Lane, start: u32) -> bool {
1215- self.edit(|p| p.move_clip(from, idx, to, start))1331+ self.edit(Dirty::Both, |p| p.move_clip(from, idx, to, start))
1216 }1332 }
1217 1333
1218 /// Drags one end of that clip to timeline frame `to`, changing how much of1334 /// Drags one end of that clip to timeline frame `to`, changing how much of
@@ -1394,7 +1510,7 @@ impl PlaybackSession {
1394 /// without the caller having to nudge the playhead itself. `false` for an1510 /// without the caller having to nudge the playhead itself. `false` for an
1395 /// index that is not there and for a value that is not finite.1511 /// index that is not there and for a value that is not finite.
1396 pub fn set_color(&mut self, lane: Lane, idx: usize, params: Option<ColorParams>) -> bool {1512 pub fn set_color(&mut self, lane: Lane, idx: usize, params: Option<ColorParams>) -> bool {
1397- self.edit(|p| p.set_color(lane, idx, params))1513+ self.edit(Dirty::Picture, |p| p.set_color(lane, idx, params))
1398 }1514 }
1399 1515
1400 /// The same grade and the same reseek without the undo step1516 /// The same grade and the same reseek without the undo step
@@ -1402,7 +1518,7 @@ impl PlaybackSession {
1402 /// through, so the frame regrades under the hand and the whole gesture is1518 /// through, so the frame regrades under the hand and the whole gesture is
1403 /// still a single `z`.1519 /// still a single `z`.
1404 pub fn set_color_live(&mut self, lane: Lane, idx: usize, params: Option<ColorParams>) -> bool {1520 pub fn set_color_live(&mut self, lane: Lane, idx: usize, params: Option<ColorParams>) -> bool {
1405- self.edit(|p| p.set_color_live(lane, idx, params))1521+ self.edit(Dirty::Picture, |p| p.set_color_live(lane, idx, params))
1406 }1522 }
1407 1523
1408 /// The project's resolution: what every clip is composed onto, what the1524 /// The project's resolution: what every clip is composed onto, what the
@@ -1419,10 +1535,13 @@ impl PlaybackSession {
1419 self.native1535 self.native
1420 }1536 }
1421 1537
1422- /// Sets it. Reseeks like an edit, so the frame on screen is recomposed at1538+ /// Sets it. Rebuilds the **picture** where the playhead is, so the frame on
1423- /// the new size at once, paused or playing. `false` for a size that is not a1539+ /// screen is recomposed at the new size at once, paused or playing -- and
1424- /// picture -- zero either way, or past 8K, which is where the per-frame1540+ /// the sound is not touched at all: the size of the canvas is not something
1425- /// buffers stop being a sane thing to allocate from a keystroke.1541+ /// a sample can carry, so resizing a 4K film mid-play costs neither a hole
1542+ /// in the audio nor an offset against it ([`Dirty`]). `false` for a size
1543+ /// that is not a picture -- zero either way, or past 8K, which is where the
1544+ /// per-frame buffers stop being a sane thing to allocate from a keystroke.
1426 ///1545 ///
1427 /// ponytail: not an undo step. The project resolution is not in the lane1546 /// ponytail: not an undo step. The project resolution is not in the lane
1428 /// snapshots [`Project::undo`] restores, so cycling it back is one more1547 /// snapshots [`Project::undo`] restores, so cycling it back is one more
@@ -1437,8 +1556,7 @@ impl PlaybackSession {
1437 }1556 }
1438 self.meta.width = width;1557 self.meta.width = width;
1439 self.meta.height = height;1558 self.meta.height = height;
1440- let now = self.now();1559+ self.invalidate(Dirty::Picture);
1441- self.seek(now);
1442 true1560 true
1443 }1561 }
1444 1562
@@ -1451,7 +1569,7 @@ impl PlaybackSession {
1451 /// grade: the picture on screen is recomposed through the new policy without1569 /// grade: the picture on screen is recomposed through the new policy without
1452 /// the caller nudging the playhead. `false` for an index that is not there.1570 /// the caller nudging the playhead. `false` for an index that is not there.
1453 pub fn set_fit(&mut self, lane: Lane, idx: usize, fit: FitPolicy) -> bool {1571 pub fn set_fit(&mut self, lane: Lane, idx: usize, fit: FitPolicy) -> bool {
1454- self.edit(|p| p.set_fit(lane, idx, fit))1572+ self.edit(Dirty::Picture, |p| p.set_fit(lane, idx, fit))
1455 }1573 }
1456 1574
1457 /// The clip at `idx` -- what a caller copies. It is a pair of source frame1575 /// The clip at `idx` -- what a caller copies. It is a pair of source frame
@@ -1466,7 +1584,7 @@ impl PlaybackSession {
1466 /// the end of the timeline the clip is appended. One undo step.1584 /// the end of the timeline the clip is appended. One undo step.
1467 pub fn paste_at(&mut self, timeline_secs: f64, clip: Clip) -> bool {1585 pub fn paste_at(&mut self, timeline_secs: f64, clip: Clip) -> bool {
1468 let at = secs_to_frame(timeline_secs, self.meta.frame_rate);1586 let at = secs_to_frame(timeline_secs, self.meta.frame_rate);
1469- self.edit(|p| p.paste(at, clip))1587+ self.edit(Dirty::Both, |p| p.paste(at, clip))
1470 }1588 }
1471 1589
1472 /// Places the whole of `path` played on its audio `stream` at1590 /// Places the whole of `path` played on its audio `stream` at
@@ -1625,7 +1743,7 @@ impl PlaybackSession {
1625 /// and it reseeks like every other edit.1743 /// and it reseeks like every other edit.
1626 pub fn place_at(&mut self, lane: Lane, timeline_secs: f64, clip: Clip) -> bool {1744 pub fn place_at(&mut self, lane: Lane, timeline_secs: f64, clip: Clip) -> bool {
1627 let at = secs_to_frame(timeline_secs, self.meta.frame_rate);1745 let at = secs_to_frame(timeline_secs, self.meta.frame_rate);
1628- self.edit(|p| p.place(lane, at, clip))1746+ self.edit(Dirty::Both, |p| p.place(lane, at, clip))
1629 }1747 }
1630 1748
1631 /// Removes `lane`'s clip at `idx` and everything under it, closing the gap1749 /// Removes `lane`'s clip at `idx` and everything under it, closing the gap
@@ -1639,12 +1757,12 @@ impl PlaybackSession {
1639 /// not `V1`'s, and a front-end that could only say "the third clip" would1757 /// not `V1`'s, and a front-end that could only say "the third clip" would
1640 /// delete the wrong one the moment a second lane exists.1758 /// delete the wrong one the moment a second lane exists.
1641 pub fn delete_clip(&mut self, lane: Lane, idx: usize) -> bool {1759 pub fn delete_clip(&mut self, lane: Lane, idx: usize) -> bool {
1642- self.edit(|p| p.delete_in(lane, idx))1760+ self.edit(Dirty::Both, |p| p.delete_in(lane, idx))
1643 }1761 }
1644 1762
1645 /// Undoes the last successful edit, and reseeks like a delete.1763 /// Undoes the last successful edit, and reseeks like a delete.
1646 pub fn undo(&mut self) -> bool {1764 pub fn undo(&mut self) -> bool {
1647- self.edit(Project::undo)1765+ self.edit(Dirty::Both, Project::undo)
1648 }1766 }
1649 1767
1650 /// Takes `path` into the **library**: it becomes a source of this session,1768 /// Takes `path` into the **library**: it becomes a source of this session,
@@ -1736,18 +1854,36 @@ impl PlaybackSession {
1736 Ok(source)1854 Ok(source)
1737 }1855 }
1738 1856
1739- /// Applies an edit and, if it took, reseeks onto the new mapping. `seek`1857+ /// Applies an edit and, if it took, rebuilds **what it dirtied** and nothing
1740- /// clamps to the new duration and keeps playing playing, so a delete that1858+ /// else ([`Dirty`]). A structural edit reseeks: `seek` clamps to the new
1741- /// shortens the timeline past the playhead lands on the last frame.1859+ /// duration and keeps playing playing, so a delete that shortens the
1742- fn edit(&mut self, f: impl FnOnce(&mut Project) -> bool) -> bool {1860+ /// timeline past the playhead lands on the last frame. A grade or a fit
1861+ /// policy rebuilds the picture where it stands, with the sound running
1862+ /// through it untouched -- no flush, no re-open, no hole -- and an
1863+ /// equalizer the other way round.
1864+ fn edit(&mut self, dirty: Dirty, f: impl FnOnce(&mut Project) -> bool) -> bool {
1743 if !f(&mut self.project) {1865 if !f(&mut self.project) {
1744 return false;1866 return false;
1745 }1867 }
1746- let now = self.now();1868+ self.invalidate(dirty);
1747- self.seek(now);
1748 true1869 true
1749 }1870 }
1750 1871
1872+ /// Rebuilds the dirtied half (or both) at the playhead.
1873+ fn invalidate(&mut self, dirty: Dirty) {
1874+ match dirty {
1875+ Dirty::Picture => {
1876+ let (_, target) = self.landing(self.now());
1877+ self.start_picture(target);
1878+ }
1879+ Dirty::Sound => self.reseek_audio(),
1880+ Dirty::Both => {
1881+ let now = self.now();
1882+ self.seek(now);
1883+ }
1884+ }
1885+ }
1886+
1751 /// Current timeline position in seconds.1887 /// Current timeline position in seconds.
1752 pub fn now(&self) -> f64 {1888 pub fn now(&self) -> f64 {
1753 self.clock.now()1889 self.clock.now()
@@ -1849,12 +1985,51 @@ impl PlaybackSession {
1849 /// Playing stays playing and paused stays paused -- but a paused seek still1985 /// Playing stays playing and paused stays paused -- but a paused seek still
1850 /// decodes, so the caller can show the frame it landed on.1986 /// decodes, so the caller can show the frame it landed on.
1851 pub fn seek(&mut self, secs: f64) {1987 pub fn seek(&mut self, secs: f64) {
1988+ let (t, target) = self.landing(secs);
1989+ let was_playing = self.clock.is_playing();
1990+ self.stop_audio();
1991+ self.start_picture(target);
1992+ let audio_running = self.start_audio(target);
1993+ // Same invariant as `play`: position the clock before audio restarts.
1994+ if audio_running && self.clock.source() != ClockSource::Audio {
1995+ self.clock.switch_to_audio();
1996+ }
1997+ self.clock.seek_to(t);
1998+ self.resume(was_playing);
1999+ }
2000+
2001+ /// Where a seek to `secs` lands: the clamped timeline position and the
2002+ /// timeline frame it means. The one place the clamp lives, so every
2003+ /// invalidation below lands on the same frame a seek would.
2004+ fn landing(&self, secs: f64) -> (f64, u32) {
1852 let fps = self.meta.frame_rate;2005 let fps = self.meta.frame_rate;
1853 let total = self.project.timeline_frames();2006 let total = self.project.timeline_frames();
1854 let t = secs.clamp(0.0, f64::from(total) / fps);2007 let t = secs.clamp(0.0, f64::from(total) / fps);
1855- let target = secs_to_frame(t, fps).min(total.saturating_sub(1));2008+ (t, secs_to_frame(t, fps).min(total.saturating_sub(1)))
1856- let was_playing = self.clock.is_playing();2009+ }
1857 2010
2011+ /// Rebuilds the **picture** at `target` and touches nothing else: the sound
2012+ /// keeps playing out of the same stream, the clock keeps running, and a
2013+ /// grade dragged during playback is therefore silent.
2014+ fn start_picture(&mut self, target: u32) {
2015+ // Cancel first, drop second: the old worker may be parked in `send` on
2016+ // the bounded channel, where only the disconnect wakes it -- and it
2017+ // then finds the flag already set. It is then parked, not joined; see
2018+ // [`retire`](Self::retire), which is what keeps a scrub off the price
2019+ // of a VA-API init.
2020+ self.worker.cancel();
2021+ // The span runs from `target` to the end of whatever it landed in -- a
2022+ // clip, or a gap, which starts a black-frame worker instead. `None` is
2023+ // the emptied timeline, black too, and `start_span` says so.
2024+ self.start_span(self.project.composite_span_at(target));
2025+ self.eos = false;
2026+ }
2027+
2028+ /// Silences the device and supersedes whatever is feeding it: the first half
2029+ /// of every audio restart, and the only thing that ever discards queued
2030+ /// sound.
2031+ fn stop_audio(&mut self) {
2032+ self.mix = None;
1858 if let Some(audio) = &self.audio {2033 if let Some(audio) = &self.audio {
1859 let ao = audio.ao.lock().unwrap();2034 let ao = audio.ao.lock().unwrap();
1860 ao.set_active(false);2035 ao.set_active(false);
@@ -1862,25 +2037,31 @@ impl PlaybackSession {
1862 // feeder re-checks the epoch inside that same lock: whatever it is2037 // feeder re-checks the epoch inside that same lock: whatever it is
1863 // carrying can no longer reach the ring after this point.2038 // carrying can no longer reach the ring after this point.
1864 audio.epoch.fetch_add(1, Ordering::Release);2039 audio.epoch.fetch_add(1, Ordering::Release);
2040+ // Nothing of the new stream has been played yet, by definition.
2041+ audio.content_at.store(-1, Ordering::Release);
1865 ao.flush();2042 ao.flush();
1866 // The flushed samples are not being played any more, so nothing may2043 // The flushed samples are not being played any more, so nothing may
1867 // still be drawn from them.2044 // still be drawn from them.
1868 audio.tap.lock().unwrap().clear();2045 audio.tap.lock().unwrap().clear();
1869 }2046 }
2047+ }
1870 2048
1871- // Cancel first, drop second: the old worker may be parked in `send` on2049+ /// Puts the device back where it was: playing if it was playing, and with
1872- // the bounded channel, where only the disconnect wakes it -- and it2050+ /// the clock held until the new stream is really audible (see
1873- // then finds the flag already set. It is then parked, not joined; see2051+ /// [`Audio::content_at`]).
1874- // [`retire`](Self::retire), which is what keeps a scrub off the price2052+ fn resume(&mut self, was_playing: bool) {
1875- // of a VA-API init.2053+ self.priming = true;
1876- self.worker.cancel();2054+ if was_playing && let Some(audio) = &self.audio {
1877- // The span runs from `target` to the end of whatever it landed in -- a2055+ audio.ao.lock().unwrap().set_active(true);
1878- // clip, or a gap, which starts a black-frame worker instead. `None` is2056+ }
1879- // the emptied timeline, black too, and `start_span` says so.2057+ }
1880- self.start_span(self.project.composite_span_at(target));
1881- self.eos = false;
1882 2058
2059+ /// Rebuilds the **sound** from `target` -- the second half of a restart --
2060+ /// and says whether anything will be fed.
2061+ fn start_audio(&mut self, target: u32) -> bool {
2062+ let fps = self.meta.frame_rate;
1883 let mut audio_running = false;2063 let mut audio_running = false;
2064+ let mut live = None;
1884 if let Some(audio) = &self.audio2065 if let Some(audio) = &self.audio
1885 && !audio.died.load(Ordering::Acquire)2066 && !audio.died.load(Ordering::Acquire)
1886 {2067 {
@@ -1914,32 +2095,54 @@ impl PlaybackSession {
1914 // the library row said, and what an export copies (`export::run`).2095 // the library row said, and what an export copies (`export::run`).
1915 let sources = self.project.audio_sources();2096 let sources = self.project.audio_sources();
1916 // ...and the mix settings over the lot: each lane's own volume on2097 // ...and the mix settings over the lot: each lane's own volume on
1917- // its way into the sum and the master limiter over the sum, both2098+ // its way into the sum and the master limiter over the sum. These
1918- // rebuilt here like the curves above, which is what makes a lane2099+ // two are handed over *live* as well as at the open: they sit at
1919- // fader and a ceiling audible while the timeline runs.2100+ // the sum, where nothing is decoded, so a fader moved later is a
2101+ // number the running mixer picks up rather than a stream rebuilt
2102+ // under the ear ([`crate::audio::MixControls`]).
1920 let gains = self.project.audio_gains();2103 let gains = self.project.audio_gains();
1921 let limiter = self.project.limiter();2104 let limiter = self.project.limiter();
1922- audio_running = match AudioSession::open_mixed_streams_master(2105+ let controls = crate::audio::MixControls::new(gains.clone(), limiter);
1923- &sources, &segs, &eqs, &speeds, &gains, limiter,2106+ audio_running = match AudioSession::open_mixed_streams_live(
2107+ &sources,
2108+ &segs,
2109+ &eqs,
2110+ &speeds,
2111+ &gains,
2112+ limiter,
2113+ Some(&controls),
1924 ) {2114 ) {
1925 Ok(Some((_, rx))) => audio.spawn_feeder(rx),2115 Ok(Some((_, rx))) => audio.spawn_feeder(rx),
1926 _ => false,2116 _ => false,
1927 };2117 };
2118+ // Only a mixed timeline has a mixer to talk to; the single-lane
2119+ // flat path is the bit-exact one and has none.
2120+ live = (audio_running && controls.is_live()).then_some(controls);
1928 if !audio_running {2121 if !audio_running {
1929 // Nothing will ever be fed again; let `tick` fall to wall time2122 // Nothing will ever be fed again; let `tick` fall to wall time
1930 // instead of waiting on a device that has no more work coming.2123 // instead of waiting on a device that has no more work coming.
1931 audio.fed_all.store(true, Ordering::Release);2124 audio.fed_all.store(true, Ordering::Release);
1932 }2125 }
1933 }2126 }
2127+ self.mix = live;
2128+ audio_running
2129+ }
1934 2130
1935- // Same invariant as `play`: position the clock before audio restarts.2131+ /// Rebuilds the sound alone, from where the playhead is: what a change that
2132+ /// no picture can show goes through. The video worker is left decoding, so
2133+ /// the picture does not blink -- and the clock, held still by
2134+ /// [`resume`](Self::resume) until the new stream is audible, puts the sound
2135+ /// back exactly where the picture already is.
2136+ fn reseek_audio(&mut self) {
2137+ let (t, target) = self.landing(self.now());
2138+ let was_playing = self.clock.is_playing();
2139+ self.stop_audio();
2140+ let audio_running = self.start_audio(target);
1936 if audio_running && self.clock.source() != ClockSource::Audio {2141 if audio_running && self.clock.source() != ClockSource::Audio {
1937 self.clock.switch_to_audio();2142 self.clock.switch_to_audio();
1938 }2143 }
1939 self.clock.seek_to(t);2144 self.clock.seek_to(t);
1940- if was_playing && let Some(audio) = &self.audio {2145+ self.resume(was_playing);
1941- audio.ao.lock().unwrap().set_active(true);
1942- }
1943 }2146 }
1944 2147
1945 /// Renders the edited timeline to `out` on a worker thread. The session is2148 /// Renders the edited timeline to `out` on a worker thread. The session is
@@ -1993,10 +2196,35 @@ impl PlaybackSession {
1993 // Audio EOF. Wall time carries the same timeline on from here, with2196 // Audio EOF. Wall time carries the same timeline on from here, with
1994 // no jump, and this branch cannot be reached again.2197 // no jump, and this branch cannot be reached again.
1995 self.clock.switch_to_wall();2198 self.clock.switch_to_wall();
1996- } else {2199+ return;
2200+ }
2201+ if self.priming {
2202+ // A stream that has been started and has not been heard yet: the
2203+ // device is playing the silence of its own restart, and none of it
2204+ // is timeline time ([`Audio::content_at`]). The clock holds where
2205+ // the seek left it -- so the picture holds too, on the frame it
2206+ // landed on, rather than sliding ahead of a sound that has not
2207+ // started.
2208+ let started = audio.content_at.load(Ordering::Acquire);
2209+ if started < 0 {
2210+ return;
2211+ }
2212+ // ...and then the *first sample of the stream* becomes the
2213+ // reference, not whatever position this poll happened to catch: the
2214+ // clock's own anchor is its first report ([`PlaybackClock`]), and
2215+ // anchoring it here is what makes a mid-play edit cost no offset.
2216+ //
2217+ // ponytail: `started` is the position when the sample was queued,
2218+ // and it is heard at the next callback -- up to one quantum (5-21
2219+ // ms) later, so that much of the restart is still counted. Upgrade
2220+ // path is the position at the first *pop* of real audio, which only
2221+ // the plugin's RT thread can see.
1997 self.clock2222 self.clock
1998- .set_audio_position(position as u64, audio.sample_rate);2223+ .set_audio_position(started as u64, audio.sample_rate);
2224+ self.priming = false;
1999 }2225 }
2226+ self.clock
2227+ .set_audio_position(position as u64, audio.sample_rate);
2000 }2228 }
2001 }2229 }
2002 2230
@@ -2225,6 +2453,7 @@ fn open_audio(path: &Path, stream: usize) -> (Option<Audio>, Option<String>) {
2225 fed_all: Arc::new(AtomicBool::new(false)),2453 fed_all: Arc::new(AtomicBool::new(false)),
2226 died: Arc::new(AtomicBool::new(false)),2454 died: Arc::new(AtomicBool::new(false)),
2227 epoch: Arc::new(AtomicU64::new(0)),2455 epoch: Arc::new(AtomicU64::new(0)),
2456+ content_at: Arc::new(AtomicI64::new(-1)),
2228 tap: Arc::new(Mutex::new(Vec::with_capacity(TAP_SAMPLES))),2457 tap: Arc::new(Mutex::new(Vec::with_capacity(TAP_SAMPLES))),
2229 };2458 };
2230 (audio.spawn_feeder(rx).then_some(audio), None)2459 (audio.spawn_feeder(rx).then_some(audio), None)
@@ -2250,21 +2479,39 @@ fn feed(rx: Receiver<AudioChunk>, audio: &Audio, epoch: u64) {
2250 if audio.epoch.load(Ordering::Acquire) != epoch {2479 if audio.epoch.load(Ordering::Acquire) != epoch {
2251 return;2480 return;
2252 }2481 }
2253- match ao.write(&pending) {2482+ let accepted = match ao.write(&pending) {
2254 Some(n) => n,2483 Some(n) => n,
2255 None => {2484 None => {
2256 // Output died; flag it so `tick` moves the clock to wall time.2485 // Output died; flag it so `tick` moves the clock to wall time.
2257 audio.died.store(true, Ordering::Release);2486 audio.died.store(true, Ordering::Release);
2258 return;2487 return;
2259 }2488 }
2489+ };
2490+ // The first sample of this stream to reach the ring, stamped with
2491+ // what the device had played by then: everything before it was the
2492+ // silence of the restart, and [`PlaybackSession::tick`] anchors the
2493+ // clock here so that silence is never timeline time. Under the
2494+ // device lock, with the epoch already checked, so the stamp and the
2495+ // sample belong to the same stream.
2496+ if accepted > 0 && audio.content_at.load(Ordering::Acquire) < 0 {
2497+ let at = ao.position().unwrap_or(0).max(0);
2498+ audio.content_at.store(at, Ordering::Release);
2260 }2499 }
2500+ accepted
2261 };2501 };
2262 audio.fed.fetch_add(accepted as u64, Ordering::Relaxed);2502 audio.fed.fetch_add(accepted as u64, Ordering::Relaxed);
2263 audio.note_tap(&pending[..accepted]);2503 audio.note_tap(&pending[..accepted]);
2264 pending.drain(..accepted);2504 pending.drain(..accepted);
2265 if !pending.is_empty() {2505 if !pending.is_empty() {
2266- // Ring full: nothing to do but let the device drain it.2506+ // Ring full: nothing to do but let the device drain it. Except when
2267- thread::sleep(RING_FULL_WAIT);2507+ // *nothing* was taken, which after a flush means the ring is still
2508+ // waiting for the device to consume the flush flag rather than
2509+ // being full: that is the head of a restart, and every millisecond
2510+ // spent parked there is a millisecond of silence.
2511+ match accepted {
2512+ 0 => thread::sleep(FLUSH_WAIT),
2513+ _ => thread::sleep(RING_FULL_WAIT),
2514+ }
2268 }2515 }
2269 }2516 }
2270 }2517 }
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+}