diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index a41ea33..379f186 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -2084,8 +2084,11 @@ impl Player { /// ceiling by the same, and the switch either way (a ring of two, like the /// silence card's unit row). /// - /// Every one of them goes through the session, so it reseeks: what the ear - /// hears while the arrow is held is the mix that is being set. + /// Every one of them goes through the session, which hands it straight to + /// the running mixer: what the ear hears while the arrow is held is the mix + /// that is being set, and nothing is rebuilt to make that true -- no reseek, + /// so no `reset_after_reseek` and no blink in the picture behind the card + /// ([`engine::PlaybackSession::set_lane_gain_db`]). fn nudge_mix(&mut self, steps: i32, cx: &mut Context) { let lanes = self.mix_lanes(); let Some(session) = self.session.as_mut() else { diff --git a/crates/engine/src/audio.rs b/crates/engine/src/audio.rs index ab4f99e..921bf8a 100644 --- a/crates/engine/src/audio.rs +++ b/crates/engine/src/audio.rs @@ -28,7 +28,9 @@ use std::fs::File; use std::io::BufReader; use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::mpsc::{Receiver, SyncSender, sync_channel}; +use std::sync::{Arc, Mutex}; use std::thread; use mp4::{AudioObjectType, ChannelConfig, MediaType, Mp4Reader, Mp4Track, TrackType}; @@ -152,6 +154,67 @@ pub struct StreamInfo { pub decodable: bool, } +/// The mix settings a *running* mixer reads: what each lane is turned by on its +/// way into the sum and the ceiling the sum comes out through, both swappable +/// while the stream plays. +/// +/// This is what keeps a fader off the reseek path. Everything else a timeline +/// says lives inside a decode worker -- a segment's window, its curve, its rate +/// -- and can only be changed by rebuilding it, which is a flush, a re-open and +/// a hole in the sound. These two live at the sum, where nothing is decoded, so +/// the mixer can pick them up between one block and the next: an arrow key held +/// down on a fader moves the level and nothing else moves at all. +/// +/// One of these belongs to one mixer thread. [`is_live`](MixControls::is_live) +/// is what says whether a mixer is actually reading it -- a single lane at +/// unity with the limiter off is not mixed at all +/// ([`AudioSession::open_mixed_streams_master`]), and a caller that finds this +/// dead has to reopen the stream to be heard. +pub struct MixControls { + /// Bumped by every change; the mixer reloads when the number it last saw + /// is not this one, so an unchanged mix costs one relaxed load per block. + version: AtomicU64, + /// The lane amplitudes and the limiter, together: they are set together and + /// a mixer that read half of one change and half of the next would be + /// mixing a state nobody asked for. + state: Mutex<(Vec, Limiter)>, + /// A mixer thread has these; see the type docs. + live: AtomicBool, +} + +impl MixControls { + pub fn new(gains: Vec, limiter: Limiter) -> Arc { + Arc::new(Self { + version: AtomicU64::new(0), + state: Mutex::new((gains, limiter)), + live: AtomicBool::new(false), + }) + } + + /// Hands the running mixer a new mix. Cheap enough for a key repeat: a lock + /// held for a `Vec` swap and an atomic. + pub fn set(&self, gains: Vec, limiter: Limiter) { + *self.state.lock().unwrap() = (gains, limiter); + self.version.fetch_add(1, Ordering::Release); + } + + /// Whether a mixer thread is reading this at all. + pub fn is_live(&self) -> bool { + self.live.load(Ordering::Acquire) + } + + /// The mix, if it has moved since `seen`. `None` -- the every-block case -- + /// takes no lock. + fn changed(&self, seen: &mut u64) -> Option<(Vec, Limiter)> { + let now = self.version.load(Ordering::Acquire); + if now == *seen { + return None; + } + *seen = now; + Some(self.state.lock().unwrap().clone()) + } +} + pub struct AudioSession; impl AudioSession { @@ -497,6 +560,26 @@ impl AudioSession { speeds: &[Vec>], gains: &[f32], limiter: Limiter, + ) -> crate::Result)>> { + Self::open_mixed_streams_live(sources, lanes, eqs, speeds, gains, limiter, None) + } + + /// [`open_mixed_streams_master`](Self::open_mixed_streams_master) with the + /// mix left *reachable*: `live` is the handle the mixer picks its gains and + /// its limiter off between blocks, so a fader moved while the stream plays + /// is heard without the stream being rebuilt ([`MixControls`]). + /// + /// `gains`/`limiter` still say what it starts as -- they are what decides + /// whether there is a mixer at all -- and the handle is marked live only + /// when there is one. An export passes `None`: nothing can move under it. + pub fn open_mixed_streams_live( + sources: &[(PathBuf, usize)], + lanes: &[Vec<(Option, f64, f64)>], + eqs: &[Vec>], + speeds: &[Vec>], + gains: &[f32], + limiter: Limiter, + live: Option<&Arc>, ) -> crate::Result)>> { let [first, rest @ ..] = lanes else { return Ok(None); @@ -540,12 +623,20 @@ impl AudioSession { let mut gains = gains.to_vec(); gains.resize(lanes.len(), 1.0); // Built here, off the thread that will run it, where the rate is known. - let limiter = limiter + let state = limiter .is_active() .then(|| LimiterState::new(&limiter, meta.sample_rate, channels)); + // Marked before the spawn rather than inside it: a caller asks this the + // moment the open returns, and a flag set on the far thread would still + // read dead. + let live = live.map(|live| { + live.live.store(true, Ordering::Release); + live.clone() + }); + let rate = meta.sample_rate; thread::Builder::new() .name("audio-mix".into()) - .spawn(move || mix(&rxs, channels, &gains, limiter, &tx))?; + .spawn(move || mix(&rxs, channels, gains, state, rate, live.as_deref(), &tx))?; Ok(Some((meta, rx))) } @@ -2114,10 +2205,15 @@ struct Worker { fn mix( rxs: &[Receiver], channels: usize, - gains: &[f32], + mut gains: Vec, mut limiter: Option, + rate: u32, + controls: Option<&MixControls>, tx: &SyncSender, ) { + // The version of the mix these gains and this limiter came from; see the + // reload at the head of the loop. + let mut seen = 0; let mut pending: Vec> = rxs.iter().map(|_| Vec::new()).collect(); let mut live: Vec = rxs.iter().map(|_| true).collect(); // Numbering follows lane 0, whose first chunk says where it starts. @@ -2125,6 +2221,24 @@ fn mix( let mut emitted = 0; let mut out: Vec = Vec::new(); loop { + // A mix moved while the stream plays, picked up between two blocks: + // the levels change at a block boundary and nothing else changes at + // all -- no flush, no re-open, no hole. The limiter is *retuned* rather + // than rebuilt, so its delay line keeps running and the sample count + // the master clock is made of does not move ([`LimiterState::retune`]). + if let Some((next, params)) = controls.and_then(|c| c.changed(&mut seen)) { + gains = next; + gains.resize(rxs.len(), 1.0); + match limiter.as_mut() { + Some(state) => state.retune(¶ms), + // First time it has ever been switched in on this stream: the + // one that swallows nothing, for the count's sake. + None if params.is_active() => { + limiter = Some(LimiterState::engaged(¶ms, rate, channels)); + } + None => {} + } + } for (i, rx) in rxs.iter().enumerate() { while live[i] && pending[i].is_empty() { match rx.recv() { diff --git a/crates/engine/src/decode.rs b/crates/engine/src/decode.rs index c26256e..98edef9 100644 --- a/crates/engine/src/decode.rs +++ b/crates/engine/src/decode.rs @@ -87,7 +87,7 @@ impl Backend { pub struct BackendCell(Arc); impl BackendCell { - fn new(backend: Backend) -> Self { + pub(crate) fn new(backend: Backend) -> Self { Self(Arc::new(AtomicU8::new(backend.code()))) } diff --git a/crates/engine/src/limiter.rs b/crates/engine/src/limiter.rs index 61c5765..75b4107 100644 --- a/crates/engine/src/limiter.rs +++ b/crates/engine/src/limiter.rs @@ -106,6 +106,11 @@ pub struct LimiterState { /// delay line, which is how the latency is paid back (module docs). warm: usize, gain: f32, + /// Switched out while the mix runs ([`LimiterState::retune`]): the line + /// still delays and still emits a frame per frame, only nothing is held + /// down. Dropping the state instead would drop the frames still inside the + /// line, and those frames are what the master clock counts. + bypass: bool, ceiling: f32, /// Where the knee starts, as an amplitude: under this the fast path runs /// and no logarithm is taken. @@ -125,6 +130,7 @@ impl LimiterState { at: 0, warm: frames - 1, gain: 1.0, + bypass: !params.on, ceiling: db_to_linear(ceiling_db), knee_floor: db_to_linear(ceiling_db - KNEE_DB / 2.0), // One time constant per sample: the gain covers 63% of the way back @@ -133,6 +139,34 @@ impl LimiterState { } } + /// One switched in **while the mix is already running**: the same limiter, + /// except that it swallows nothing to fill its delay line -- what comes out + /// first is the line's own [`LOOKAHEAD_MS`] of silence and the mix behind + /// it, where a fresh state would have eaten that much of the mix instead. + /// + /// Which matters because the count *is* the clock: a mixer that emitted + /// fewer samples than the timeline asked for would slide the picture off + /// the sound by the lookahead, once per switch-on. A hair of silence at the + /// moment somebody engages a limiter is the honest price. + pub fn engaged(params: &Limiter, sample_rate: u32, channels: usize) -> Self { + Self { + warm: 0, + ..Self::new(params, sample_rate, channels) + } + } + + /// Points a running limiter at another setting -- a ceiling dragged, the + /// switch flipped -- without touching the delay line, the peak window or + /// the gain it is holding. That is what makes the ceiling a live control: + /// rebuilding the state would restart the window (a pump) and lose the + /// frames inside the line (a slip against the picture). + pub fn retune(&mut self, params: &Limiter) { + let ceiling_db = params.with_ceiling(params.ceiling_db).ceiling_db; + self.bypass = !params.on; + self.ceiling = db_to_linear(ceiling_db); + self.knee_floor = db_to_linear(ceiling_db - KNEE_DB / 2.0); + } + /// Rewrites `buf` -- interleaved frames -- as the limited mix. Shorter than /// what came in by the delay line's length, once, at the first call. pub fn process(&mut self, buf: &mut Vec) { @@ -163,8 +197,14 @@ impl LimiterState { self.warm -= 1; continue; } + // Bypassed, the line is a delay and nothing else: the frames come + // out as they went in, one for one. + let gain = match self.bypass { + true => 1.0, + false => self.gain, + }; for c in 0..channels { - out.push(self.line[self.at * channels + c] * self.gain); + out.push(self.line[self.at * channels + c] * gain); } } *buf = out; @@ -240,6 +280,56 @@ mod tests { assert_eq!(buf.len(), rate as usize * 2 - (state.peaks.len() - 1) * 2); } + /// A ceiling dragged while the mix runs: the new one is honoured from the + /// next block, the delay line keeps running -- so the block is as long as + /// it would have been, which is what the master clock counts -- and + /// switching the limiter out leaves the samples alone rather than dropping + /// the ones still inside the line. + #[test] + fn a_retune_moves_the_ceiling_and_costs_no_samples() { + let rate = 48_000; + let mut state = LimiterState::engaged( + &Limiter { + ceiling_db: -3.0, + on: true, + }, + rate, + 2, + ); + let block: Vec = (0..2_000).map(|i| 2.0 * ((i % 7) as f32 - 3.0)).collect(); + + // Engaged mid-stream: nothing is swallowed, so the count is the count. + let mut buf = block.clone(); + state.process(&mut buf); + assert_eq!(buf.len(), block.len(), "an engaged limiter ate samples"); + let hot = buf.iter().fold(0.0f32, |m, s| m.max(s.abs())); + assert!(hot <= db_to_linear(-3.0) + 1e-6, "peak {hot} passed -3 dB"); + + // Down to -12: the same length again, and quieter. + state.retune(&Limiter { + ceiling_db: -12.0, + on: true, + }); + let mut buf = block.clone(); + state.process(&mut buf); + assert_eq!(buf.len(), block.len(), "a retune ate samples"); + let quiet = buf.iter().fold(0.0f32, |m, s| m.max(s.abs())); + assert!(quiet <= db_to_linear(-12.0) + 1e-6, "peak {quiet} passed -12 dB"); + assert!(quiet < hot, "the ceiling did not move: {hot} -> {quiet}"); + + // Switched out: the line still delays, so the count still holds, and + // what comes out is the mix as it was written. + state.retune(&Limiter { + ceiling_db: -12.0, + on: false, + }); + let mut buf = block.clone(); + state.process(&mut buf); + assert_eq!(buf.len(), block.len(), "a bypass ate samples"); + let raw = buf.iter().fold(0.0f32, |m, s| m.max(s.abs())); + assert!(raw > 1.0, "bypassed, the mix is untouched: peak {raw}"); + } + /// Flat settings are a passthrough, which is what the export invariant /// rests on: 0 dB is exactly 1.0, never 0.9999999. #[test] diff --git a/crates/engine/src/playback.rs b/crates/engine/src/playback.rs index 76db235..1942814 100644 --- a/crates/engine/src/playback.rs +++ b/crates/engine/src/playback.rs @@ -12,7 +12,7 @@ //! the renderer decides which frame that means. use std::path::Path; -use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU64, Ordering}; use std::sync::mpsc::{Receiver, TryRecvError}; use std::sync::{Arc, Mutex}; use std::thread; @@ -32,6 +32,13 @@ use crate::scale::{Composer, FitPolicy}; /// only has to be short next to that; it costs one wakeup per 10 ms of audio. const RING_FULL_WAIT: Duration = Duration::from_millis(10); +/// How long the feeder waits out a ring that took *nothing*: the flush of a +/// restart, which only the device's own callback can clear (`engine-audio` +/// refuses a write queued behind one). Short, because this is the gap at the +/// head of every restart and the ear is in it -- one wakeup per millisecond, +/// for the millisecond or two it lasts. +const FLUSH_WAIT: Duration = Duration::from_millis(1); + /// The timeline a file with no picture scaffolds: 1080p at 30 fps, H.264 -- /// nothing was shot on it, so it is the canvas a *later* import meets rather /// than a description of the song. H.264 because it is the one codec that @@ -91,6 +98,18 @@ struct Audio { /// Bumped by every seek. A feeder only owns the device while this still /// matches the value it started with; see [`feed`]. epoch: Arc, + /// The device position the *current* stream's first real sample was queued + /// at, `-1` until the feeder has queued one. Written by the feeder under the + /// device lock, read by [`tick`](PlaybackSession::tick). + /// + /// This is what keeps a restart out of the timeline. Between a flush and the + /// first sample of the new stream the device plays silence -- a decoder open + /// is tens of milliseconds -- and that silence is elapsed *device* time + /// ([`crate::ao`] counts it, as it must: it really was played). It is not + /// elapsed *timeline* time, and a clock anchored on the first poll after a + /// seek counts it as such, which is a permanent offset between the picture + /// and the sound, re-rolled by every edit made while playing. + content_at: Arc, /// The last [`TAP_SAMPLES`] mono samples handed to the device, oldest /// first: what a meter or an analyser draws. Written by the feeder, which /// is not the device's own callback -- the plugin's RT thread never sees @@ -233,6 +252,39 @@ pub struct PlaybackSession { span: Option, /// The last clip has been played out; see [`PlaybackSession::is_eos`]. eos: bool, + /// The mix the running mixer is reading, when there is one: what lets a + /// fader and the master ceiling move without rebuilding the audio pipeline + /// at all ([`crate::audio::MixControls`]). `None` for a timeline that is + /// not mixed -- one audio lane at unity with the limiter off, which is the + /// bit-exact single-stream path -- and the first move off that reopens the + /// stream once, mixed, and lives from there. + mix: Option>, + /// An audio stream has been started and has not yet played a sample: the + /// window [`tick`](Self::tick) holds the clock still through, so the silence + /// of a restart is never counted as timeline time. See + /// [`Audio::content_at`]. + priming: bool, +} + +/// What an edit dirtied -- which half of the pipeline has to be rebuilt for the +/// change to be seen or heard, and, far more to the point, which half must not +/// be. +/// +/// Rebuilding a half is expensive and *audible*: the video worker costs a +/// decoder open (98 ms of VA-API init, worst case, measured) and the audio one +/// costs a flush, a re-open and a hole in the sound. A grade changes no sample +/// and a fader changes no picture, so neither may pay the other's price -- that +/// is the whole of this type. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum Dirty { + /// The picture only: a grade, a fit policy, the project resolution. The + /// sound keeps playing, untouched, and the clock never moves. + Picture, + /// The sound only: a clip's equalizer. The picture keeps playing. + Sound, + /// The timeline itself -- what is where, how long, how fast. Both halves + /// are rebuilt, because both are decoding the wrong thing. + Both, } impl PlaybackSession { @@ -297,6 +349,8 @@ impl PlaybackSession { span_rate: Rate::REAL_TIME, span, eos: false, + mix: None, + priming: false, }) } @@ -402,6 +456,8 @@ impl PlaybackSession { span_rate: Rate::REAL_TIME, span, eos: false, + mix: None, + priming: false, }) } @@ -473,6 +529,8 @@ impl PlaybackSession { span_rate: Rate::REAL_TIME, span, eos: false, + mix: None, + priming: false, }) } @@ -755,6 +813,8 @@ impl PlaybackSession { span_rate: Rate::REAL_TIME, span, eos: false, + mix: None, + priming: false, }; // The scaffolding above opened source 0 from its first frame and the // whole of its audio; this puts both onto the clip the playhead is @@ -1074,15 +1134,29 @@ impl PlaybackSession { gap.map_or(1, |s| s.len), )), }; - if let Ok(stream) = opened { - // Receiver first, worker second: the drop of the *old* receiver is - // what wakes the outgoing worker if it is parked in `send`, and only - // then can it return and be reaped by a later sweep. Nothing here - // joins, so this ordering costs the seek nothing. - self.frames = stream.frames; - self.backend = stream.backend; - self.retire(stream.worker); - } + let Ok(stream) = opened else { + // The file would not open. The span still goes in -- the timeline + // moves on, there are simply no more pictures -- but the *frames* + // must not: the old channel's pictures are numbered in the old + // source's frames, and presenting them under the new mapping would + // put the wrong picture at the wrong time (and leave + // [`decode_backend`](Self::decode_backend) describing a worker that + // is no longer feeding anything). A dead receiver instead, which is + // what carries the session on to the next span. The old worker stays + // parked in `self.worker` where the caller already cancelled it; the + // next span retires it. + self.frames = std::sync::mpsc::channel().1; + self.backend = BackendCell::new(Backend::Gap); + self.span = span; + return; + }; + // Receiver first, worker second: the drop of the *old* receiver is + // what wakes the outgoing worker if it is parked in `send`, and only + // then can it return and be reaped by a later sweep. Nothing here + // joins, so this ordering costs the seek nothing. + self.frames = stream.frames; + self.backend = stream.backend; + self.retire(stream.worker); self.span = span; } @@ -1201,18 +1275,20 @@ impl PlaybackSession { } /// Gives that clip an equalizer, or takes it off with `None`. One undo step, - /// like every other edit -- and, like every other edit, it *reseeks*: the - /// audio workers are rebuilt from the new curves right where the playhead + /// like every other edit -- and it rebuilds the **sound** where the playhead /// is, so a band changed during playback is heard from the next chunk on - /// rather than at the next play. `false` for a bad index or a non-finite - /// band, and nothing changes. + /// rather than at the next play. The picture is not touched: the video + /// worker keeps decoding through it ([`Dirty`]). `false` for a bad index or + /// a non-finite band, and nothing changes. /// - /// ponytail: the reseek is what makes it live, so the cost of a change is a - /// decoder restart -- inaudible at a drag's end, but too much to call once - /// per pointer sample (a caller commits one change per gesture). Upgrade - /// path is an `Arc` swap the running worker polls per chunk. + /// ponytail: the audio rebuild is what makes it live, so the cost of a + /// change is a decoder restart -- inaudible at a drag's end, but too much to + /// call once per pointer sample (a caller commits one change per gesture). + /// Upgrade path is the per-segment twin of [`crate::audio::MixControls`], + /// which the lane worker would poll per chunk the way the mixer polls the + /// gains. pub fn set_eq(&mut self, lane: Lane, idx: usize, params: Option) -> bool { - self.edit(|p| p.set_eq(lane, idx, params)) + self.edit(Dirty::Sound, |p| p.set_eq(lane, idx, params)) } /// How loud that lane plays, in dB -- everything on it, every frequency of @@ -1221,12 +1297,36 @@ impl PlaybackSession { self.project.lane_gain_db(lane) } - /// Sets it. One undo step and a reseek, the equalizer's rule for the - /// equalizer's reason: the mixer is rebuilt from the new volumes right - /// where the playhead is, so a track turned down during playback is heard - /// turned down from the next chunk on. + /// Sets it. One undo step -- and **nothing is rebuilt**: a lane's volume + /// lives at the sum, so the running mixer is handed the new number and + /// picks it up at its next block ([`crate::audio::MixControls`]). A fader + /// held down under an arrow key therefore moves the level and nothing else: + /// no flush, no decoder restart, no hole in the sound and no blink in the + /// picture. + /// + /// The one exception is the timeline that is not mixed at all -- a single + /// audio lane at unity with the limiter off, which plays through the + /// bit-exact single-stream path and has no mixer to talk to. Moving *that* + /// off unity opens one, once; every move after it is live. pub fn set_lane_gain_db(&mut self, lane: Lane, db: f32) -> bool { - self.edit(|p| p.set_lane_gain_db(lane, db)) + if !self.project.set_lane_gain_db(lane, db) { + return false; + } + self.push_mix(); + true + } + + /// Hands the mix the running mixer is reading its new settings -- the whole + /// of what a fader and a ceiling cost. With no mixer listening (the + /// single-lane flat path, and a session with no sound at all) the sound is + /// rebuilt instead, which is what opens one. + fn push_mix(&mut self) { + let gains = self.project.audio_gains(); + let limiter = self.project.limiter(); + match &self.mix { + Some(mix) => mix.set(gains, limiter), + None => self.reseek_audio(), + } } /// The master limiter the whole mix is summed through. @@ -1235,9 +1335,25 @@ impl PlaybackSession { } /// Sets it, live like a lane volume and for the same reason -- the ceiling - /// a person is dragging has to be the ceiling they are hearing. + /// a person is dragging has to be the ceiling they are hearing. Nothing is + /// rebuilt: the running limiter is *retuned* between two blocks + /// ([`crate::limiter::LimiterState::retune`]), so its delay line keeps + /// running and the sample count the master clock is made of does not move. + /// + /// ponytail: not an undo step, and deliberately -- [`Project::undo`] + /// restores the lane list, and the limiter is not in it, so snapshotting + /// here would push a step whose undo changes nothing a person can see or + /// hear (the twin [`set_lane_gain_db`](Self::set_lane_gain_db) *is* + /// undoable only because a lane volume lives in that list). The project + /// resolution is outside undo for the same reason and says so. Upgrade path + /// is a history that carries the mix beside the lanes, which every existing + /// snapshot site would then have to fill in. pub fn set_limiter(&mut self, limiter: crate::limiter::Limiter) -> bool { - self.edit(|p| p.set_limiter(limiter)) + if !self.project.set_limiter(limiter) { + return false; + } + self.push_mix(); + true } /// Lifts one lane's clip out, leaving a gap: black frames on the video lane, @@ -1246,7 +1362,7 @@ impl PlaybackSession { /// the last placement there is empties the timeline, which is a state /// ([`is_empty`](Self::is_empty)) and one undo away. pub fn lift_clip(&mut self, lane: Lane, idx: usize) -> bool { - self.edit(|p| p.lift(lane, idx)) + self.edit(Dirty::Both, |p| p.lift(lane, idx)) } /// Moves that clip onto lane `to` with its head at timeline frame `start` -- @@ -1262,7 +1378,7 @@ impl PlaybackSession { /// pointer on a frame, and converting it back through seconds would be a /// rounding step between the box let go of and the box committed. pub fn move_clip_to(&mut self, from: Lane, idx: usize, to: Lane, start: u32) -> bool { - self.edit(|p| p.move_clip(from, idx, to, start)) + self.edit(Dirty::Both, |p| p.move_clip(from, idx, to, start)) } /// Drags one end of that clip to timeline frame `to`, changing how much of @@ -1444,7 +1560,7 @@ impl PlaybackSession { /// without the caller having to nudge the playhead itself. `false` for an /// index that is not there and for a value that is not finite. pub fn set_color(&mut self, lane: Lane, idx: usize, params: Option) -> bool { - self.edit(|p| p.set_color(lane, idx, params)) + self.edit(Dirty::Picture, |p| p.set_color(lane, idx, params)) } /// The same grade and the same reseek without the undo step @@ -1452,7 +1568,7 @@ impl PlaybackSession { /// through, so the frame regrades under the hand and the whole gesture is /// still a single `z`. pub fn set_color_live(&mut self, lane: Lane, idx: usize, params: Option) -> bool { - self.edit(|p| p.set_color_live(lane, idx, params)) + self.edit(Dirty::Picture, |p| p.set_color_live(lane, idx, params)) } /// The project's resolution: what every clip is composed onto, what the @@ -1469,10 +1585,13 @@ impl PlaybackSession { self.native } - /// Sets it. Reseeks like an edit, so the frame on screen is recomposed at - /// the new size at once, paused or playing. `false` for a size that is not a - /// picture -- zero either way, or past 8K, which is where the per-frame - /// buffers stop being a sane thing to allocate from a keystroke. + /// Sets it. Rebuilds the **picture** where the playhead is, so the frame on + /// screen is recomposed at the new size at once, paused or playing -- and + /// the sound is not touched at all: the size of the canvas is not something + /// a sample can carry, so resizing a 4K film mid-play costs neither a hole + /// in the audio nor an offset against it ([`Dirty`]). `false` for a size + /// that is not a picture -- zero either way, or past 8K, which is where the + /// per-frame buffers stop being a sane thing to allocate from a keystroke. /// /// ponytail: not an undo step. The project resolution is not in the lane /// snapshots [`Project::undo`] restores, so cycling it back is one more @@ -1487,8 +1606,7 @@ impl PlaybackSession { } self.meta.width = width; self.meta.height = height; - let now = self.now(); - self.seek(now); + self.invalidate(Dirty::Picture); true } @@ -1557,7 +1675,7 @@ impl PlaybackSession { /// grade: the picture on screen is recomposed through the new policy without /// the caller nudging the playhead. `false` for an index that is not there. pub fn set_fit(&mut self, lane: Lane, idx: usize, fit: FitPolicy) -> bool { - self.edit(|p| p.set_fit(lane, idx, fit)) + self.edit(Dirty::Picture, |p| p.set_fit(lane, idx, fit)) } /// The clip at `idx` -- what a caller copies. It is a pair of source frame @@ -1572,7 +1690,7 @@ impl PlaybackSession { /// the end of the timeline the clip is appended. One undo step. pub fn paste_at(&mut self, timeline_secs: f64, clip: Clip) -> bool { let at = secs_to_frame(timeline_secs, self.meta.frame_rate); - self.edit(|p| p.paste(at, clip)) + self.edit(Dirty::Both, |p| p.paste(at, clip)) } /// Places the whole of `path` played on its audio `stream` at @@ -1731,7 +1849,7 @@ impl PlaybackSession { /// and it reseeks like every other edit. pub fn place_at(&mut self, lane: Lane, timeline_secs: f64, clip: Clip) -> bool { let at = secs_to_frame(timeline_secs, self.meta.frame_rate); - self.edit(|p| p.place(lane, at, clip)) + self.edit(Dirty::Both, |p| p.place(lane, at, clip)) } /// Removes `lane`'s clip at `idx` and everything under it, closing the gap @@ -1745,12 +1863,12 @@ impl PlaybackSession { /// not `V1`'s, and a front-end that could only say "the third clip" would /// delete the wrong one the moment a second lane exists. pub fn delete_clip(&mut self, lane: Lane, idx: usize) -> bool { - self.edit(|p| p.delete_in(lane, idx)) + self.edit(Dirty::Both, |p| p.delete_in(lane, idx)) } /// Undoes the last successful edit, and reseeks like a delete. pub fn undo(&mut self) -> bool { - self.edit(Project::undo) + self.edit(Dirty::Both, Project::undo) } /// Takes `path` into the **library**: it becomes a source of this session, @@ -1842,18 +1960,36 @@ impl PlaybackSession { Ok(source) } - /// Applies an edit and, if it took, reseeks onto the new mapping. `seek` - /// clamps to the new duration and keeps playing playing, so a delete that - /// shortens the timeline past the playhead lands on the last frame. - fn edit(&mut self, f: impl FnOnce(&mut Project) -> bool) -> bool { + /// Applies an edit and, if it took, rebuilds **what it dirtied** and nothing + /// else ([`Dirty`]). A structural edit reseeks: `seek` clamps to the new + /// duration and keeps playing playing, so a delete that shortens the + /// timeline past the playhead lands on the last frame. A grade or a fit + /// policy rebuilds the picture where it stands, with the sound running + /// through it untouched -- no flush, no re-open, no hole -- and an + /// equalizer the other way round. + fn edit(&mut self, dirty: Dirty, f: impl FnOnce(&mut Project) -> bool) -> bool { if !f(&mut self.project) { return false; } - let now = self.now(); - self.seek(now); + self.invalidate(dirty); true } + /// Rebuilds the dirtied half (or both) at the playhead. + fn invalidate(&mut self, dirty: Dirty) { + match dirty { + Dirty::Picture => { + let (_, target) = self.landing(self.now()); + self.start_picture(target); + } + Dirty::Sound => self.reseek_audio(), + Dirty::Both => { + let now = self.now(); + self.seek(now); + } + } + } + /// Current timeline position in seconds. pub fn now(&self) -> f64 { self.clock.now() @@ -1955,12 +2091,51 @@ impl PlaybackSession { /// Playing stays playing and paused stays paused -- but a paused seek still /// decodes, so the caller can show the frame it landed on. pub fn seek(&mut self, secs: f64) { + let (t, target) = self.landing(secs); + let was_playing = self.clock.is_playing(); + self.stop_audio(); + self.start_picture(target); + let audio_running = self.start_audio(target); + // Same invariant as `play`: position the clock before audio restarts. + if audio_running && self.clock.source() != ClockSource::Audio { + self.clock.switch_to_audio(); + } + self.clock.seek_to(t); + self.resume(was_playing); + } + + /// Where a seek to `secs` lands: the clamped timeline position and the + /// timeline frame it means. The one place the clamp lives, so every + /// invalidation below lands on the same frame a seek would. + fn landing(&self, secs: f64) -> (f64, u32) { let fps = self.meta.frame_rate; let total = self.project.timeline_frames(); let t = secs.clamp(0.0, f64::from(total) / fps); - let target = secs_to_frame(t, fps).min(total.saturating_sub(1)); - let was_playing = self.clock.is_playing(); + (t, secs_to_frame(t, fps).min(total.saturating_sub(1))) + } + /// Rebuilds the **picture** at `target` and touches nothing else: the sound + /// keeps playing out of the same stream, the clock keeps running, and a + /// grade dragged during playback is therefore silent. + fn start_picture(&mut self, target: u32) { + // Cancel first, drop second: the old worker may be parked in `send` on + // the bounded channel, where only the disconnect wakes it -- and it + // then finds the flag already set. It is then parked, not joined; see + // [`retire`](Self::retire), which is what keeps a scrub off the price + // of a VA-API init. + self.worker.cancel(); + // The span runs from `target` to the end of whatever it landed in -- a + // clip, or a gap, which starts a black-frame worker instead. `None` is + // the emptied timeline, black too, and `start_span` says so. + self.start_span(self.project.composite_span_at(target)); + self.eos = false; + } + + /// Silences the device and supersedes whatever is feeding it: the first half + /// of every audio restart, and the only thing that ever discards queued + /// sound. + fn stop_audio(&mut self) { + self.mix = None; if let Some(audio) = &self.audio { let ao = audio.ao.lock().unwrap(); ao.set_active(false); @@ -1968,25 +2143,31 @@ impl PlaybackSession { // feeder re-checks the epoch inside that same lock: whatever it is // carrying can no longer reach the ring after this point. audio.epoch.fetch_add(1, Ordering::Release); + // Nothing of the new stream has been played yet, by definition. + audio.content_at.store(-1, Ordering::Release); ao.flush(); // The flushed samples are not being played any more, so nothing may // still be drawn from them. audio.tap.lock().unwrap().clear(); } + } - // Cancel first, drop second: the old worker may be parked in `send` on - // the bounded channel, where only the disconnect wakes it -- and it - // then finds the flag already set. It is then parked, not joined; see - // [`retire`](Self::retire), which is what keeps a scrub off the price - // of a VA-API init. - self.worker.cancel(); - // The span runs from `target` to the end of whatever it landed in -- a - // clip, or a gap, which starts a black-frame worker instead. `None` is - // the emptied timeline, black too, and `start_span` says so. - self.start_span(self.project.composite_span_at(target)); - self.eos = false; + /// Puts the device back where it was: playing if it was playing, and with + /// the clock held until the new stream is really audible (see + /// [`Audio::content_at`]). + fn resume(&mut self, was_playing: bool) { + self.priming = true; + if was_playing && let Some(audio) = &self.audio { + audio.ao.lock().unwrap().set_active(true); + } + } + /// Rebuilds the **sound** from `target` -- the second half of a restart -- + /// and says whether anything will be fed. + fn start_audio(&mut self, target: u32) -> bool { + let fps = self.meta.frame_rate; let mut audio_running = false; + let mut live = None; if let Some(audio) = &self.audio && !audio.died.load(Ordering::Acquire) { @@ -2020,32 +2201,54 @@ impl PlaybackSession { // the library row said, and what an export copies (`export::run`). let sources = self.project.audio_sources(); // ...and the mix settings over the lot: each lane's own volume on - // its way into the sum and the master limiter over the sum, both - // rebuilt here like the curves above, which is what makes a lane - // fader and a ceiling audible while the timeline runs. + // its way into the sum and the master limiter over the sum. These + // two are handed over *live* as well as at the open: they sit at + // the sum, where nothing is decoded, so a fader moved later is a + // number the running mixer picks up rather than a stream rebuilt + // under the ear ([`crate::audio::MixControls`]). let gains = self.project.audio_gains(); let limiter = self.project.limiter(); - audio_running = match AudioSession::open_mixed_streams_master( - &sources, &segs, &eqs, &speeds, &gains, limiter, + let controls = crate::audio::MixControls::new(gains.clone(), limiter); + audio_running = match AudioSession::open_mixed_streams_live( + &sources, + &segs, + &eqs, + &speeds, + &gains, + limiter, + Some(&controls), ) { Ok(Some((_, rx))) => audio.spawn_feeder(rx), _ => false, }; + // Only a mixed timeline has a mixer to talk to; the single-lane + // flat path is the bit-exact one and has none. + live = (audio_running && controls.is_live()).then_some(controls); if !audio_running { // Nothing will ever be fed again; let `tick` fall to wall time // instead of waiting on a device that has no more work coming. audio.fed_all.store(true, Ordering::Release); } } + self.mix = live; + audio_running + } - // Same invariant as `play`: position the clock before audio restarts. + /// Rebuilds the sound alone, from where the playhead is: what a change that + /// no picture can show goes through. The video worker is left decoding, so + /// the picture does not blink -- and the clock, held still by + /// [`resume`](Self::resume) until the new stream is audible, puts the sound + /// back exactly where the picture already is. + fn reseek_audio(&mut self) { + let (t, target) = self.landing(self.now()); + let was_playing = self.clock.is_playing(); + self.stop_audio(); + let audio_running = self.start_audio(target); if audio_running && self.clock.source() != ClockSource::Audio { self.clock.switch_to_audio(); } self.clock.seek_to(t); - if was_playing && let Some(audio) = &self.audio { - audio.ao.lock().unwrap().set_active(true); - } + self.resume(was_playing); } /// Renders the edited timeline to `out` on a worker thread. The session is @@ -2099,10 +2302,35 @@ impl PlaybackSession { // Audio EOF. Wall time carries the same timeline on from here, with // no jump, and this branch cannot be reached again. self.clock.switch_to_wall(); - } else { + return; + } + if self.priming { + // A stream that has been started and has not been heard yet: the + // device is playing the silence of its own restart, and none of it + // is timeline time ([`Audio::content_at`]). The clock holds where + // the seek left it -- so the picture holds too, on the frame it + // landed on, rather than sliding ahead of a sound that has not + // started. + let started = audio.content_at.load(Ordering::Acquire); + if started < 0 { + return; + } + // ...and then the *first sample of the stream* becomes the + // reference, not whatever position this poll happened to catch: the + // clock's own anchor is its first report ([`PlaybackClock`]), and + // anchoring it here is what makes a mid-play edit cost no offset. + // + // ponytail: `started` is the position when the sample was queued, + // and it is heard at the next callback -- up to one quantum (5-21 + // ms) later, so that much of the restart is still counted. Upgrade + // path is the position at the first *pop* of real audio, which only + // the plugin's RT thread can see. self.clock - .set_audio_position(position as u64, audio.sample_rate); + .set_audio_position(started as u64, audio.sample_rate); + self.priming = false; } + self.clock + .set_audio_position(position as u64, audio.sample_rate); } } @@ -2331,6 +2559,7 @@ fn open_audio(path: &Path, stream: usize) -> (Option