diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index 7d91cb8..93759a9 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -536,7 +536,11 @@ struct Player { /// than in the session so it survives closing one file and opening the /// next -- it is a setting of the player, not of the timeline, which is /// also why it is not written to the project file and cannot reach an - /// export. [`Player::apply_volume`] is what pushes it at a session. + /// export. This is the *owner*: the engine holds the level per session, on + /// the device that runs it, and restores it when that device is replaced + /// ([`engine::PlaybackSession::set_gain`]), so every session is a + /// follower of this one copy and none of them can answer for it. + /// [`Player::apply_volume`] is what pushes it, at every session there is. volume: Volume, /// Where the volume slider was last painted, and whether a hand is on it -- /// the speed bar's pair, for the speed bar's reason: the pointer moves diff --git a/crates/app/src/player/library.rs b/crates/app/src/player/library.rs index 55f147f..5f9388c 100644 --- a/crates/app/src/player/library.rs +++ b/crates/app/src/player/library.rs @@ -668,11 +668,16 @@ impl Player { match PlaybackSession::open_with_audio_stream(path, stream) { Ok(mut session) => { session.drop_late_pictures(true); - session.set_gain(self.volume.gain()); // The button says "plays it" -- a preview that opens paused // reads as a frozen picture, not as a player awaiting a click. session.play(); self.preview_session = Some(session); + // The one place the window's level reaches a session + // ([`Player::apply_volume`]) -- and it goes at the timeline + // under the preview too, which is what makes closing the + // preview hand back a session already at the shown level + // rather than the one it had before the preview opened. + self.apply_volume(); self.session_swapped(); self.notify_user( format!( @@ -711,6 +716,13 @@ impl Player { cx.notify(); } } + // The session on screen is the timeline's again, and it is told the + // window's level here rather than being trusted to have kept it: a + // level changed while the preview was up reaches every session + // ([`Player::apply_volume`]), and this is the belt to that pair of + // braces -- the session that takes the picture is the one that must be + // heard at the level the control shows. + self.apply_volume(); // The picture swaps back to the timeline's, so everything keyed to a // session hears it (`Player::session_swapped`) -- the sound watch among // them, or the timeline's own unchanged reason would read as a device diff --git a/crates/app/src/player/transport.rs b/crates/app/src/player/transport.rs index 1e51a14..7f49623 100644 --- a/crates/app/src/player/transport.rs +++ b/crates/app/src/player/transport.rs @@ -396,15 +396,28 @@ impl Player { /// The play binding and the transport button share it: once the timeline is finished /// the only sensible "play" is from the top. - /// Pushes the current volume at the session, which is the only place it is - /// ever pushed: after a change here, and after a session arrives. A session - /// starts at full volume, so a file opened while muted has to be told -- - /// that is the whole reason this is not just called from the key handler. - /// Silent no-op with no timeline, or with a run that has no audio device. + /// Pushes the current volume at every session that is up, which is the only + /// place it is ever pushed: after a change here, and after a session + /// arrives. A session starts at full volume, so a file opened while muted + /// has to be told -- that is the whole reason this is not just called from + /// the key handler. + /// + /// *Every* session, not [`active_session`](Player::active_session): a + /// preview and the timeline under it are both live output, and pushing only + /// the active one left the level the window showed belonging to whichever + /// session happened to be on screen. Muting during a preview and closing it + /// then handed the timeline back the level from before the preview, at full + /// volume, with the control still reading "muted". The engine holds the + /// level per session and restores it when a device is replaced underneath + /// it ([`PlaybackSession::set_gain`]), so the app's one copy of the level is + /// the owner and every session is a follower of it. + /// + /// Silent no-op with no session at all, or on one with no audio device. pub(crate) fn apply_volume(&self) { - if let Some(session) = self.active_session() { - session.set_gain(self.volume.gain()); - } + push_gain( + self.volume.gain(), + [self.session.as_ref(), self.preview_session.as_ref()], + ); } /// The mute key and the two volume keys, and the click on the button. The @@ -488,6 +501,22 @@ pub(crate) fn crosses_into_loop(was: Transport, now: Transport, loop_on: bool) - now == Transport::Ended && was != Transport::Ended && loop_on } +/// The window's monitoring level, pushed at *every* session handed in -- the +/// timeline and a preview over it are both live output, and pushing only the +/// one on screen left the level belonging to whichever session happened to be +/// active: muting during a preview and closing it handed the timeline back the +/// level from before the preview opened, at full volume, with the control still +/// reading "muted". +/// +/// A free function over the sessions rather than a `&self` method so the round +/// trip can be driven without a `Player` -- which takes a gpui `Context` this +/// test binary has no `TestAppContext` to build. +pub(crate) fn push_gain(gain: f32, sessions: [Option<&PlaybackSession>; N]) { + for session in sessions.into_iter().flatten() { + session.set_gain(gain); + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/app/src/tests/media.rs b/crates/app/src/tests/media.rs index e70b2b3..6e58f91 100644 --- a/crates/app/src/tests/media.rs +++ b/crates/app/src/tests/media.rs @@ -6,8 +6,8 @@ use crate::player::library::{ auto_proxies_pref_path, load_auto_proxies_pref, save_auto_proxies_pref, }; use crate::subs::{ - audio_import_tail, load_subtitle_style, save_subtitle_style, sub_line_h_for, - subtitle_style_path, SUB_SIZE_RANGE, + SUB_SIZE_RANGE, audio_import_tail, load_subtitle_style, save_subtitle_style, sub_line_h_for, + subtitle_style_path, }; use crate::ui::preview::{bgra_to_rgba, screenshot_path}; @@ -106,7 +106,7 @@ fn a_device_that_dies_under_an_open_file_says_so_and_unsays_it() { /// speaks. #[test] fn a_preview_flip_is_not_a_device_that_came_back() { - use crate::notices::{audio_step, AudioStep}; + use crate::notices::{AudioStep, audio_step}; // A swap, every way round: seeded, never announced. assert_eq!(audio_step(7, 8, None, Some("AUDIO_LOST")), AudioStep::Seed); assert_eq!(audio_step(7, 8, Some("AUDIO_LOST"), None), AudioStep::Seed); @@ -152,8 +152,8 @@ fn an_audio_import_names_its_rate_channels_and_length() { /// stuck read and never as a frozen window. #[test] fn an_import_line_says_a_stage_has_stopped_moving_and_only_then() { - use std::sync::atomic::{AtomicU8, Ordering::Relaxed}; use std::sync::Arc; + use std::sync::atomic::{AtomicU8, Ordering::Relaxed}; let stage = Arc::new(AtomicU8::new(ImportStage::Header as u8)); let started = Instant::now() - Duration::from_secs(9); let mut import = Import { @@ -364,8 +364,8 @@ fn the_wheel_draws_the_sample_a_drag_is_holding() { #[test] fn the_strand_slot_starts_at_the_complement_and_the_write_chooses_it() { use engine::decode::{ - viz_hue_ui, viz_sat_ui, viz_strand_hue_ui, viz_strand_sat_ui, viz_strand_set, - with_viz_paint_hue, with_viz_paint_strands, VIZ_PAINT_AZURE, + VIZ_PAINT_AZURE, viz_hue_ui, viz_sat_ui, viz_strand_hue_ui, viz_strand_sat_ui, + viz_strand_set, with_viz_paint_hue, with_viz_paint_strands, }; let paint = with_viz_paint_strands(VIZ_PAINT_AZURE, 2); @@ -407,8 +407,8 @@ fn the_strand_slot_starts_at_the_complement_and_the_write_chooses_it() { #[test] fn a_strand_slot_on_a_single_strand_clip_is_the_clip_s_own_colour() { use engine::decode::{ - viz_hue_ui, viz_sat_ui, viz_strand_set, viz_strands_of, with_viz_paint_hue, - with_viz_paint_sat, with_viz_paint_strands, VIZ_PAINT_AZURE, + VIZ_PAINT_AZURE, viz_hue_ui, viz_sat_ui, viz_strand_set, viz_strands_of, + with_viz_paint_hue, with_viz_paint_sat, with_viz_paint_strands, }; let one = with_viz_paint_strands( @@ -449,8 +449,8 @@ fn a_seek_says_so_only_once_it_has_stood() { /// fifty-one seconds on a 25 GB film. #[test] fn a_silence_card_is_up_while_its_scan_runs_and_says_where_it_has_got_to() { - use std::sync::atomic::Ordering::Relaxed; use std::sync::Arc; + use std::sync::atomic::Ordering::Relaxed; let progress = Arc::new(engine::silence::Progress::default()); // Two hours and eight minutes, as the header claims it. progress.total.store(7680, Relaxed); @@ -880,9 +880,11 @@ fn every_codec_row_is_offered_or_says_why_not() { detail.contains("ec-vorbis"), "the row names the encoder like every other live one: {detail}" ); - assert!(FORMATS - .into_iter() - .any(|(row, _, _, detail)| row.contains(&Format::Hevc) && detail.contains("intra"))); + assert!( + FORMATS + .into_iter() + .any(|(row, _, _, detail)| row.contains(&Format::Hevc) && detail.contains("intra")) + ); // The destination follows the format and keeps the stem, mp4 included. assert_eq!( retarget(std::path::Path::new("/a/take.export.mp4"), Format::Wav), @@ -1459,6 +1461,94 @@ fn ticking_the_preview_session_never_moves_the_timeline() { ); } +/// The monitoring level is the *window's*, and a preview closing must not hand +/// the timeline back the level it had before the preview opened: muting during +/// a preview and pressing `esc` used to leave the timeline playing at full +/// volume with the control still reading "muted" -- the shown level and the +/// heard level disagreed and nothing said so. +/// +/// What is driven is the real push, [`push_gain`] -- the function +/// [`apply_volume`](crate::player::transport::Player::apply_volume) is nothing +/// but a call to, over the same two session slots a `Player` holds -- and the +/// answer is read back out of the *device* ([`PlaybackSession::gain`]), not +/// out of the window. `Player` itself cannot be built here (it takes a gpui +/// `Context` this binary has no `TestAppContext` to build; the sibling preview +/// tests say the same), so the door that calls the push is pinned by the scan +/// below rather than executed. +#[test] +fn a_preview_close_leaves_the_timeline_at_the_level_the_window_shows() { + let timeline = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); + // The control: an untouched session is at full volume, so a level read back + // as 1.0 is a real answer and not a default this test could pass on. + assert_eq!( + timeline.gain(), + Some(1.0), + "a fresh session is not at full volume" + ); + + // Stands in for `open_preview`: a second session arrives, and the window is + // muted while it is the one on screen. + let preview = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); + let muted = 0.0; + push_gain(muted, [Some(&timeline), Some(&preview)]); + + // The preview goes away -- `close_preview` takes it and pushes at what is + // left. The session that takes the picture must be the session heard at + // the level the control shows. + drop(preview); + push_gain(muted, [Some(&timeline), None]); + assert_eq!( + timeline.gain(), + Some(muted), + "closing a preview handed the timeline back a level the window is not showing" + ); + + // The other half of the regression, and the half a single-session test can + // never see: a push that reached only the *active* session (the preview) + // left the timeline exactly where it was, which is the reported bug. The + // pre-fix shape is therefore the control that makes the assertion above + // mean something. + let control = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); + let other = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); + push_gain(muted, [Some(&other), None]); + assert_eq!( + control.gain(), + Some(1.0), + "a session outside the push followed it, so the read above proves nothing" + ); + assert_eq!( + other.gain(), + Some(muted), + "the pushed session ignored the level" + ); +} + +/// The wiring the round trip above cannot build a `Player` for: the level +/// reaches *both* session slots, and both doors that install or drop a session +/// push it. A push at the active session alone is the regression, and it is +/// invisible to any test that only ever holds one session. +#[test] +fn the_window_level_is_pushed_at_every_session_and_on_every_swap() { + let apply = fn_body("apply_volume"); + assert!( + apply.contains("self.session.as_ref()") && apply.contains("self.preview_session.as_ref()"), + "the level is pushed at one session only, so a preview closing hands the \ + timeline back the level from before the preview opened" + ); + assert!( + !apply.contains("self.active_session()"), + "the push still goes through the active session, which is the one-session \ + rule this replaced" + ); + for door in ["open_preview", "close_preview"] { + assert!( + fn_body(door).contains("self.apply_volume();"), + "{door} swaps the session on screen without telling the new one what \ + level the window is showing" + ); + } +} + /// [`bgra_to_rgba`] and [`save_screenshot`]'s own PNG write, round-tripped: a /// synthetic 2x2 frame -- one pixel per corner, alpha and channel order all /// distinct -- decodes back to the same pixels a viewer would see, in RGBA. diff --git a/crates/app/src/tests/mod.rs b/crates/app/src/tests/mod.rs index 8661872..8d78bb8 100644 --- a/crates/app/src/tests/mod.rs +++ b/crates/app/src/tests/mod.rs @@ -77,6 +77,8 @@ fn config_env_lock() -> MutexGuard<'static, ()> { .expect("config environment lock poisoned") } +use crate::player::transport::push_gain; + /// Tests never open PipeWire. The output seam also refuses a cargo-test /// binary under `target/*/deps/`; this pin is the documented door and the /// source-scan guard below. diff --git a/crates/engine-audio/src/lib.rs b/crates/engine-audio/src/lib.rs index c492f54..45b52b0 100644 --- a/crates/engine-audio/src/lib.rs +++ b/crates/engine-audio/src/lib.rs @@ -626,6 +626,27 @@ pub unsafe extern "C" fn ao_set_volume(session: *mut c_void, gain: f32) -> i32 { .unwrap_or(-1) } +/// Reads back the gain [`ao_set_volume`] last set: what the stream is actually +/// multiplying by, which is not the same question as what a caller last asked +/// for once the device has been replaced (a re-armed stream comes up at 1.0). +/// -1.0 for a session that cannot answer -- never a real gain, which is 0.0 to +/// 1.0. +/// +/// # Safety +/// `session` must come from [`ao_open`]. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn ao_gain(session: *mut c_void) -> f32 { + catch_unwind(AssertUnwindSafe(|| { + if session.is_null() { + return -1.0; + } + // SAFETY: caller-guaranteed live session. + let session = unsafe { &*(session as *const Session) }; + f32::from_bits(session.shared.gain.load(Ordering::Relaxed)) + })) + .unwrap_or(-1.0) +} + /// Drops every queued sample, so playback resumes from whatever is written /// next: what a seek needs. Takes effect on the next process callback (or the /// first one after a resume), and leaves the played position alone -- the @@ -751,7 +772,10 @@ mod tests { flush.store(true, Ordering::Release); let mut out = [0u8; 16]; assert_eq!(consume(&flush, &ring, &mut out, 2), 0, "the flush landed"); - assert!(!primed.load(Ordering::Acquire), "the restart counts as late"); + assert!( + !primed.load(Ordering::Acquire), + "the restart counts as late" + ); // ...until its own first sample lands, from where it counts again -- // which is also what makes the tail work: `ao_stream_ended` unprimes diff --git a/crates/engine/src/ao.rs b/crates/engine/src/ao.rs index f2b1d94..c00b00f 100644 --- a/crates/engine/src/ao.rs +++ b/crates/engine/src/ao.rs @@ -12,7 +12,7 @@ use std::ffi::c_void; use std::path::Path; -use std::sync::atomic::{AtomicI64, AtomicU64, Ordering}; +use std::sync::atomic::{AtomicI64, AtomicU32, AtomicU64, Ordering}; use std::sync::{LazyLock, OnceLock}; use std::time::Instant; @@ -54,6 +54,11 @@ struct Plugin { /// did and only counts the tail of a played-out stream as lateness, which /// is a worse diagnostic rather than a worse session. stream_ended: Option i32>, + /// Optional, unlike its neighbours: without it a session plays and is + /// silenced exactly as before, it just cannot be *asked* what gain it is + /// running -- and asking is the only way to see that a device replaced + /// under it came back at the wrong level. + gain: Option f32>, close: unsafe extern "C" fn(*mut c_void), // Never dropped (lives in a static), so the fn pointers above stay valid. _lib: Library, @@ -102,6 +107,7 @@ fn load() -> Option { // reads zero underruns is worse than a run that says the // plugin is the wrong one. underruns: *lib.get(b"ao_underruns\0").ok()?, + gain: lib.get(b"ao_gain\0").ok().map(|f| *f), stream_ended: lib.get(b"ao_stream_ended\0").ok().map(|f| *f), close: *lib.get(b"ao_close\0").ok()?, _lib: lib, @@ -137,6 +143,11 @@ struct Silent { base: AtomicI64, /// 0 = paused; otherwise milliseconds from [`epoch`] at the last resume. origin_ms: AtomicU64, + /// The gain last pushed, so the silent sink answers the same question the + /// plugin does: what is this stream actually multiplying by. Without it + /// every gain read back as a shrug, and a device that had been re-armed at + /// full volume looked exactly like one that had kept its level. + gain: AtomicU32, } fn epoch() -> Instant { @@ -154,9 +165,18 @@ impl Silent { rate: f64::from(sample_rate), base: AtomicI64::new(-1), origin_ms: AtomicU64::new(0), + gain: AtomicU32::new(1.0f32.to_bits()), } } + fn gain(&self) -> f32 { + f32::from_bits(self.gain.load(Ordering::Relaxed)) + } + + fn set_gain(&self, gain: f32) { + self.gain.store(gain.to_bits(), Ordering::Relaxed); + } + fn extra(&self) -> i64 { match self.origin_ms.load(Ordering::Relaxed) { 0 => 0, @@ -308,7 +328,10 @@ impl AoSession { return false; } match &self.backend { - Backend::Silent(_) => true, + Backend::Silent(s) => { + s.set_gain(gain); + true + } Backend::Plugin { plugin, handle } => { // SAFETY: `handle` came from `ao_open` and is still open. unsafe { (plugin.set_volume)(*handle, gain) == 0 } @@ -316,6 +339,25 @@ impl AoSession { } } + /// The gain this stream is actually running at, read back from the device + /// rather than remembered by the caller: the two come apart the moment the + /// device object is replaced (a fresh stream comes up at 1.0), and a + /// remembered answer would report the level that was asked for rather than + /// the one in force. `None` with no device, or a plugin too old to answer. + pub fn gain(&self) -> Option { + match &self.backend { + Backend::Silent(s) => Some(s.gain()), + Backend::Plugin { plugin, handle } => { + let read = plugin.gain?; + // SAFETY: `handle` came from `ao_open` and is still open. + match unsafe { read(*handle) } { + gain if gain < 0.0 => None, + gain => Some(gain), + } + } + } + } + /// Drops everything still queued, so the next samples written play right /// away -- what a seek needs. The played position keeps counting. pub fn flush(&self) -> bool { diff --git a/crates/engine/src/limiter.rs b/crates/engine/src/limiter.rs index 75b4107..72205fd 100644 --- a/crates/engine/src/limiter.rs +++ b/crates/engine/src/limiter.rs @@ -140,14 +140,24 @@ 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. + /// except that it swallows nothing to fill its delay line -- the line is + /// zeroed and emitting from the first frame, where [`new`] would have eaten + /// that much of the mix at the front 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. + /// the sound by the lookahead, once per switch-on. + /// + /// The price, stated as it measures rather than as it was hoped: not a + /// momentary hair of silence the stream grows back from, but a **permanent** + /// shift of [`LOOKAHEAD_MS`] for the rest of the stream -- the output is + /// the input delayed by the whole line, every block, because nothing ever + /// re-aligns it. That is at most 2 ms, which is under the perceptual + /// threshold, and it is paid once per stream rather than growing; it is + /// pinned by + /// `tests::an_engaged_limiter_shifts_the_stream_by_the_lookahead_for_good`. + /// Changing it is a design call about the export's A/V alignment, not a + /// bug fix. pub fn engaged(params: &Limiter, sample_rate: u32, channels: usize) -> Self { Self { warm: 0, @@ -314,7 +324,10 @@ mod tests { 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 <= 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 @@ -330,6 +343,85 @@ mod tests { assert!(raw > 1.0, "bypassed, the mix is untouched: peak {raw}"); } + /// What engaging a limiter mid-stream actually costs, measured rather than + /// described: not a momentary hair of silence that the stream then grows + /// back from, but a **permanent** shift. `engaged` starts its delay line + /// empty and swallows nothing, so from the first block onward the output is + /// the input delayed by the whole lookahead -- for the rest of the stream. + /// `new` is head-aligned instead: it swallows the lookahead once, at the + /// front, and is a block shorter for it. + /// + /// The two are measured against each other because the difference is the + /// whole claim: same tone, same settings, one index offset and one block + /// length apart. A permanent offset of at most [`LOOKAHEAD_MS`] is below + /// the perceptual threshold, so this pins the *measured* behaviour the doc + /// comment on [`LimiterState::engaged`] describes rather than ruling on + /// whether it should be changed -- that is a design call, not a bug fix. + #[test] + fn an_engaged_limiter_shifts_the_stream_by_the_lookahead_for_good() { + let rate = 48_000; + let params = Limiter { + ceiling_db: -3.0, + on: true, + }; + let lookahead = ((LOOKAHEAD_MS / 1000.0 * rate as f32) as usize).max(1); + // Under the knee throughout, so what comes out is the input and the + // only thing being measured is *when* each frame appears. + let tone: Vec = (0..4_000) + .flat_map(|i| { + let s = 0.1 * (i as f32 / rate as f32 * 440.0 * std::f32::consts::TAU).sin(); + [s, s] + }) + .collect(); + + // `new`: head-aligned, and a block shorter by exactly the lookahead. + let mut fresh = LimiterState::new(¶ms, rate, 2); + let mut head = tone.clone(); + fresh.process(&mut head); + assert_eq!( + head.len(), + tone.len() - lookahead * 2, + "a fresh limiter is not head-aligned by exactly the lookahead" + ); + + // `engaged`: the same count, the same samples -- one lookahead later. + let mut live = LimiterState::engaged(¶ms, rate, 2); + let mut shifted = tone.clone(); + live.process(&mut shifted); + assert_eq!( + shifted.len(), + tone.len(), + "an engaged limiter ate samples, which is the thing it exists not to do" + ); + assert_eq!( + &shifted[lookahead * 2..], + &head[..], + "an engaged limiter is not the fresh one delayed by exactly the \ + lookahead, so what it costs mid-stream is not what the doc claims" + ); + // And the shift is the *stream's*, not one block's. A second block of a + // marker the first did not contain comes out *still* delayed by the + // lookahead: the head of it is still the tail of the tone, and the + // marker itself only appears from the lookahead on. Nothing re-aligns + // the line, which is what makes the cost permanent rather than a one-off + // at the moment of engaging. + let marker = vec![0.5; tone.len()]; + let mut next = marker.clone(); + live.process(&mut next); + assert!( + next[..lookahead * 2].iter().any(|s| *s != 0.5), + "the second block is aligned where the first was not, so the cost is \ + a one-off rather than a permanent shift" + ); + assert!( + next[lookahead * 2..] + .iter() + .all(|s| (*s - 0.5).abs() < 1e-6), + "the marker is not behind by exactly the lookahead: the stream is not \ + delayed by a fixed amount from here on" + ); + } + /// 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 338db52..10f753d 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, PathBuf}; -use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU64, AtomicUsize, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU32, AtomicU64, AtomicUsize, Ordering}; use std::sync::mpsc::{Receiver, TryRecvError}; use std::sync::{Arc, Mutex}; use std::thread; @@ -26,8 +26,9 @@ use crate::colorspace::{ColorDescription, ContentLight}; use crate::decode::{Backend, BackendCell, DecodeSession, Frame, Worker}; use crate::demux::{Codec, Demuxer, NoVideoTrack, Rotation, VideoMeta}; use crate::eq::EqParams; -use crate::project::{ProjectSettings, - Clip, Edge, GapSweep, Lane, LaneKind, Project, Rate, Source, Span, Speed, SubClip, +use crate::project::{ + Clip, Edge, GapSweep, Lane, LaneKind, Project, ProjectSettings, Rate, Source, Span, Speed, + SubClip, }; use crate::scale::{Composer, FitPolicy}; use crate::transform::TransformParams; @@ -140,6 +141,18 @@ struct Audio { /// 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 monitoring gain this session's device is running at, as f32 bits. + /// + /// The device is the owner -- [`PlaybackSession::gain`] reads the level + /// back out of it -- and this is the *only* reason a session knows what to + /// restore: the device object is replaced from under the session whenever + /// the output dies ([`Self::rearm_audio`]) or is armed late + /// ([`Self::arm_audio`]), and a fresh one comes up at 1.0. Without this a + /// muted session that lost its device came back at full volume while the + /// control still said muted. Written by [`PlaybackSession::set_gain`] + /// alone, so it cannot drift from the knob: whatever the caller last + /// pushed is exactly what the next device is told. + gain: Arc, /// The timeline is *meant* to be playing: what a play or a seek-while-playing /// asks for, and what the feeder turns into a running device the moment it /// has a real sample to play ([`Audio::set_playing`], [`feed`]). @@ -638,7 +651,9 @@ impl PlaybackSession { // hands it back out. The same trade the audio header cache above this // makes -- a second container open, paid once at open rather than never // -- since nothing here decodes a single picture. - let content_light = Demuxer::open(&path).map(|(_, d)| d.light()).unwrap_or_default(); + let content_light = Demuxer::open(&path) + .map(|(_, d)| d.light()) + .unwrap_or_default(); Ok(Self { meta, content_light, @@ -980,7 +995,9 @@ impl PlaybackSession { let content_light = if crate::is_audio(&first.path) || crate::is_image(&first.path) { ContentLight::default() } else { - Demuxer::open(&first.path).map(|(_, d)| d.light()).unwrap_or_default() + Demuxer::open(&first.path) + .map(|(_, d)| d.light()) + .unwrap_or_default() }; // The extension's word, corrected below the moment the header disagrees // with it (`NoVideoTrack`, the same fallback `open_stream` takes): every @@ -1001,11 +1018,11 @@ impl PlaybackSession { codec: Codec::H264, color: ColorDescription::default(), rotation: Rotation::None, - // No container said anything about these: the canvas this engine drew - // itself is square pixels at the size it was drawn at. - coded_width: width, - coded_height: height, - pixel_aspect: crate::demux::PixelAspect::SQUARE, + // No container said anything about these: the canvas this engine drew + // itself is square pixels at the size it was drawn at. + coded_width: width, + coded_height: height, + pixel_aspect: crate::demux::PixelAspect::SQUARE, }; (meta, DecodeSession::open_black(width, height, 1)) } @@ -1071,11 +1088,11 @@ impl PlaybackSession { codec: Codec::H264, color: ColorDescription::default(), rotation: Rotation::None, - // No container said anything about these: the canvas this engine drew - // itself is square pixels at the size it was drawn at. - coded_width: width, - coded_height: height, - pixel_aspect: crate::demux::PixelAspect::SQUARE, + // No container said anything about these: the canvas this engine drew + // itself is square pixels at the size it was drawn at. + coded_width: width, + coded_height: height, + pixel_aspect: crate::demux::PixelAspect::SQUARE, }; (meta, DecodeSession::open_black(width, height, 1)) } @@ -1207,24 +1224,24 @@ impl PlaybackSession { let subtitles = crate::subtitle::open_all(&doc.subtitles); let project = Project::from_parts(doc.sources, doc.lanes, doc.eq, doc.color, doc.transform)? - .with_mix(&doc.gains, doc.limiter) - .with_tone(doc.tone) - // The palette before what is placed on it: a caption names a row of - // it, and [`Project::with_subs`] refuses one naming a row that is - // not there. - .with_subtitles(subtitles) - .with_subs(doc.subs)? - // The header a load puts back: the canvas and rate above, which a - // save's own `resolution`/`fps` lines may have moved off the - // scaffold's, and the switches the literal below carries -- handed - // in here because they are the project's own and a door that moved - // one after this would snapshot whatever copy it holds, which until - // this line is the placeholder's. No undo step for - // [`Project::with_mix`]'s reason: a project that arrived one `z` - // from a state it was never in is a project whose first undo is a - // surprise. - .with_canvas(meta.width, meta.height, meta.frame_rate) - .with_switches(doc.proxy, doc.auto_proxy, doc.encoder, doc.sample_rate); + .with_mix(&doc.gains, doc.limiter) + .with_tone(doc.tone) + // The palette before what is placed on it: a caption names a row of + // it, and [`Project::with_subs`] refuses one naming a row that is + // not there. + .with_subtitles(subtitles) + .with_subs(doc.subs)? + // The header a load puts back: the canvas and rate above, which a + // save's own `resolution`/`fps` lines may have moved off the + // scaffold's, and the switches the literal below carries -- handed + // in here because they are the project's own and a door that moved + // one after this would snapshot whatever copy it holds, which until + // this line is the placeholder's. No undo step for + // [`Project::with_mix`]'s reason: a project that arrived one `z` + // from a state it was never in is a project whose first undo is a + // surprise. + .with_canvas(meta.width, meta.height, meta.frame_rate) + .with_switches(doc.proxy, doc.auto_proxy, doc.encoder, doc.sample_rate); let span = project.composite_span_at(0); // Last, because it is the one thing here that cannot be taken back: the // feeder thread outlives the `Audio` value (it holds its own clones) and @@ -1248,7 +1265,11 @@ impl PlaybackSession { // source's silence is not worth reporting over an earlier one's). let (audio, audio_disabled) = { let mut opened = (None, None); - for source in project.sources().iter().filter(|s| !crate::is_image(&s.path)) { + for source in project + .sources() + .iter() + .filter(|s| !crate::is_image(&s.path)) + { opened = open_audio(&source.path, source.audio_stream); if opened.0.is_some() { break; @@ -1713,8 +1734,10 @@ impl PlaybackSession { }; let now = secs_to_frame(self.clock.now(), self.meta.frame_rate); let offset = now.saturating_sub(span.start).min(span.len); - self.worker - .playhead(self.span_rate.source_at(in_frame + span.speed.source_at(offset))); + self.worker.playhead( + self.span_rate + .source_at(in_frame + span.speed.source_at(offset)), + ); } /// Installs `replacement` as the decode worker, parking the outgoing one in @@ -1908,11 +1931,7 @@ impl PlaybackSession { .composite_transform_at(start) .copied() .unwrap_or_default(), - Composer::new( - canvas_w, - canvas_h, - self.project.composite_fit_at(start), - ), + Composer::new(canvas_w, canvas_h, self.project.composite_fit_at(start)), ) .inspect_err(|e| eprintln!("timeline frame {start}: image open failed: {e}")) } @@ -1941,17 +1960,11 @@ impl PlaybackSession { .composite_transform_at(start) .copied() .unwrap_or_default(), - Composer::new( - canvas_w, - canvas_h, - self.project.composite_fit_at(start), - ), + Composer::new(canvas_w, canvas_h, self.project.composite_fit_at(start)), self.project.composite_visualizer_at(start), self.project.composite_viz_paint_at(start), ) - .inspect_err(|e| { - eprintln!("timeline frame {start}: visualizer open failed: {e}") - }) + .inspect_err(|e| eprintln!("timeline frame {start}: visualizer open failed: {e}")) } Some(Span { start, @@ -2119,11 +2132,7 @@ impl PlaybackSession { .composite_transform_at(b_start) .copied() .unwrap_or_default(); - let canvas = Composer::new( - canvas_w, - canvas_h, - self.project.composite_fit_at(b_start), - ); + let canvas = Composer::new(canvas_w, canvas_h, self.project.composite_fit_at(b_start)); let tone = self.project.tone(); let stream = DecodeSession::open_worker_deferred( &path, @@ -2301,7 +2310,9 @@ impl PlaybackSession { /// changes only the words, which are drawn over whatever is decoded. pub fn trim_sub(&mut self, lane: Lane, idx: usize, edge: Edge, to: u32) -> crate::Result<()> { let grouped = self.caption_grouped_with_clips(lane, idx); - let trimmed = self.project.trim_sub(lane, idx, edge, to, self.meta.frame_rate); + let trimmed = self + .project + .trim_sub(lane, idx, edge, to, self.meta.frame_rate); if trimmed.is_ok() && grouped { self.invalidate(Dirty::Both); } @@ -2312,7 +2323,8 @@ impl PlaybackSession { /// ([`Project::trim_sub_room`]) -- what a front-end drawing the box during /// a drag asks, at this timeline's rate. pub fn trim_sub_room(&self, lane: Lane, idx: usize, edge: Edge) -> Option<(u32, u32)> { - self.project.trim_sub_room(lane, idx, edge, self.meta.frame_rate) + self.project + .trim_sub_room(lane, idx, edge, self.meta.frame_rate) } /// Takes one placement off a subtitle lane, leaving a gap @@ -2390,7 +2402,11 @@ impl PlaybackSession { // one this dispatch needs; a caption carries a link at all only once // grouped (`place_sub` always starts one at `None`), so that alone is // "this delete ripples more than its own lane". - match self.sub_lane(lane).get(idx).is_some_and(|s| s.link.is_some()) { + match self + .sub_lane(lane) + .get(idx) + .is_some_and(|s| s.link.is_some()) + { true => self.edit(Dirty::Both, |p| p.delete_sub_in(lane, idx)), // A caption in no group is the plain lift that touches nothing // else: no reseek owed. @@ -2555,7 +2571,9 @@ impl PlaybackSession { to: Lane, start: u32, ) -> bool { - self.edit(Dirty::Both, |p| p.move_selection(picks, from, idx, to, start)) + self.edit(Dirty::Both, |p| { + p.move_selection(picks, from, idx, to, start) + }) } /// Drags one end of that clip to timeline frame `to`, changing how much of @@ -2738,6 +2756,10 @@ impl PlaybackSession { // A device that is there but *dead* is not a device: the walk below // opens another one, which is also what clears the notice a death put up // ([`Self::tick`]). + let carried = self + .audio + .as_ref() + .map(|audio| audio.gain.load(Ordering::Acquire)); if let Some(audio) = &self.audio && !audio.died.load(Ordering::Acquire) { @@ -2750,8 +2772,16 @@ impl PlaybackSession { .filter(|s| !crate::is_image(&s.path)) { let (audio, disabled) = open_audio(&source.path, source.audio_stream); - if audio.is_some() { - self.audio = audio; + if let Some(audio) = audio { + // The device is being replaced under a session that may already + // be running at a level the user chose, so that level comes + // across with it ([`Audio::gain`]) rather than the fresh + // stream's 1.0. + if let Some(bits) = carried { + audio.gain.store(bits, Ordering::Release); + audio.ao.lock().unwrap().set_volume(f32::from_bits(bits)); + } + self.audio = Some(audio); self.audio_disabled = disabled; return; } @@ -2800,6 +2830,11 @@ impl PlaybackSession { // is silenced until the seek that feeds it says otherwise, which is the // same two steps [`open_audio`] takes on the way in. ao.set_active(false); + // A fresh stream comes up at full volume, so the level this session was + // already running at is put back onto it before it is installed: a + // muted session that lost its device to a daemon restart would + // otherwise come back loud while the window still reads "muted". + ao.set_volume(f32::from_bits(audio.gain.load(Ordering::Acquire))); // Replacing the session is what closes the dead stream, so it is done // under the device lock the feeder writes through. *audio.ao.lock().unwrap() = ao; @@ -3267,8 +3302,8 @@ impl PlaybackSession { // end is an append, never a clip with black in front of it. The frame // itself is honoured in [`Project::paste`], because a *drop* names a // place on the bed and means it. - let at = secs_to_frame(timeline_secs, self.meta.frame_rate) - .min(self.project.timeline_frames()); + let at = + secs_to_frame(timeline_secs, self.meta.frame_rate).min(self.project.timeline_frames()); self.edit(Dirty::Both, |p| p.paste(at, clip)) } @@ -3277,8 +3312,8 @@ impl PlaybackSession { /// past the last frame lands there rather than carrying black in front of /// it, exactly as a lone clip's paste does. pub fn paste_set_at(&mut self, timeline_secs: f64, items: &[(Lane, Clip)]) -> bool { - let at = secs_to_frame(timeline_secs, self.meta.frame_rate) - .min(self.project.timeline_frames()); + let at = + secs_to_frame(timeline_secs, self.meta.frame_rate).min(self.project.timeline_frames()); self.edit(Dirty::Both, |p| p.paste_set(at, items)) } @@ -3982,21 +4017,44 @@ impl PlaybackSession { self.clock.seek_to(self.timeline_duration()); } + /// The gain this session's device is running at, read back from the device + /// rather than remembered here: `None` with no audio output, or a plugin + /// too old to answer -- the two cases where a remembered answer would be a + /// claim nothing can check. + pub fn gain(&self) -> Option { + self.audio.as_ref()?.ao.lock().unwrap().gain() + } + /// Sets the monitoring gain, 0.0 (silent) to 1.0. Mute is a gain of 0.0: /// one knob, because muting and turning it down are the same thing to the /// device, and *which* the user meant is a question only the UI can answer /// -- it keeps the level to come back to. /// - /// Deliberately not session state: nothing here remembers it, so a caller - /// pushes it once per session and an export -- which renders the file - /// rather than what the speakers are doing -- can never pick it up. Silent - /// with no audio device, which is also the only honest answer there. + /// The level is remembered for as long as this session lives + /// ([`Audio::gain`]) and only so that a device which is *replaced* under + /// the session -- re-armed after a death, armed by a late import -- comes + /// back at the level the session was already running at. It is still not + /// project state: a fresh session starts at 1.0, so a caller still pushes + /// it once per session, and an export -- which renders the file rather + /// than what the speakers are doing -- can never pick it up. Silent with + /// no audio device, which is also the only honest answer there. /// /// Mute is not pause: the samples are still consumed and the device clock /// still runs, so the picture keeps playing against it. pub fn set_gain(&self, gain: f32) -> bool { match &self.audio { - Some(audio) => audio.ao.lock().unwrap().set_volume(gain), + Some(audio) => { + // The device is the owner and is told first: a remembered level + // that says something the device does not agree with is worse + // than no memory at all, because the next replacement would + // restore the wrong number. + if audio.ao.lock().unwrap().set_volume(gain) { + audio.gain.store(gain.to_bits(), Ordering::Release); + true + } else { + false + } + } None => false, } } @@ -4692,6 +4750,7 @@ fn open_audio(path: &Path, stream: usize) -> (Option