forge
Explore
Log in

Don't you dare go Hollow

🔀 merge(gain): monitoring owns the gain and re-arms the device

Browse files at this commit

8c1aee4f412ce0213ba4a0894c258c2a5e6100cfAhmet Kaan GümüşParent: fbc29d14156093
# Conflicts:
#	crates/app/src/tests/mod.rs
crates/app/src/main.rsmodified+5 -1
@@ -536,7 +536,11 @@ struct Player {
536 /// than in the session so it survives closing one file and opening the536 /// than in the session so it survives closing one file and opening the
537 /// next -- it is a setting of the player, not of the timeline, which is537 /// next -- it is a setting of the player, not of the timeline, which is
538 /// also why it is not written to the project file and cannot reach an538 /// also why it is not written to the project file and cannot reach an
539- /// export. [`Player::apply_volume`] is what pushes it at a session.539+ /// export. This is the *owner*: the engine holds the level per session, on
540+ /// the device that runs it, and restores it when that device is replaced
541+ /// ([`engine::PlaybackSession::set_gain`]), so every session is a
542+ /// follower of this one copy and none of them can answer for it.
543+ /// [`Player::apply_volume`] is what pushes it, at every session there is.
540 volume: Volume,544 volume: Volume,
541 /// Where the volume slider was last painted, and whether a hand is on it --545 /// Where the volume slider was last painted, and whether a hand is on it --
542 /// the speed bar's pair, for the speed bar's reason: the pointer moves546 /// the speed bar's pair, for the speed bar's reason: the pointer moves
crates/app/src/player/library.rsmodified+13 -1
@@ -668,11 +668,16 @@ impl Player {
668 match PlaybackSession::open_with_audio_stream(path, stream) {668 match PlaybackSession::open_with_audio_stream(path, stream) {
669 Ok(mut session) => {669 Ok(mut session) => {
670 session.drop_late_pictures(true);670 session.drop_late_pictures(true);
671- session.set_gain(self.volume.gain());
672 // The button says "plays it" -- a preview that opens paused671 // The button says "plays it" -- a preview that opens paused
673 // reads as a frozen picture, not as a player awaiting a click.672 // reads as a frozen picture, not as a player awaiting a click.
674 session.play();673 session.play();
675 self.preview_session = Some(session);674 self.preview_session = Some(session);
675+ // The one place the window's level reaches a session
676+ // ([`Player::apply_volume`]) -- and it goes at the timeline
677+ // under the preview too, which is what makes closing the
678+ // preview hand back a session already at the shown level
679+ // rather than the one it had before the preview opened.
680+ self.apply_volume();
676 self.session_swapped();681 self.session_swapped();
677 self.notify_user(682 self.notify_user(
678 format!(683 format!(
@@ -711,6 +716,13 @@ impl Player {
711 cx.notify();716 cx.notify();
712 }717 }
713 }718 }
719+ // The session on screen is the timeline's again, and it is told the
720+ // window's level here rather than being trusted to have kept it: a
721+ // level changed while the preview was up reaches every session
722+ // ([`Player::apply_volume`]), and this is the belt to that pair of
723+ // braces -- the session that takes the picture is the one that must be
724+ // heard at the level the control shows.
725+ self.apply_volume();
714 // The picture swaps back to the timeline's, so everything keyed to a726 // The picture swaps back to the timeline's, so everything keyed to a
715 // session hears it (`Player::session_swapped`) -- the sound watch among727 // session hears it (`Player::session_swapped`) -- the sound watch among
716 // them, or the timeline's own unchanged reason would read as a device728 // them, or the timeline's own unchanged reason would read as a device
crates/app/src/player/transport.rsmodified+37 -8
@@ -396,15 +396,28 @@ impl Player {
396 396
397 /// The play binding and the transport button share it: once the timeline is finished397 /// The play binding and the transport button share it: once the timeline is finished
398 /// the only sensible "play" is from the top.398 /// the only sensible "play" is from the top.
399- /// Pushes the current volume at the session, which is the only place it is399+ /// Pushes the current volume at every session that is up, which is the only
400- /// ever pushed: after a change here, and after a session arrives. A session400+ /// place it is ever pushed: after a change here, and after a session
401- /// starts at full volume, so a file opened while muted has to be told --401+ /// arrives. A session starts at full volume, so a file opened while muted
402- /// that is the whole reason this is not just called from the key handler.402+ /// has to be told -- that is the whole reason this is not just called from
403- /// Silent no-op with no timeline, or with a run that has no audio device.403+ /// the key handler.
404+ ///
405+ /// *Every* session, not [`active_session`](Player::active_session): a
406+ /// preview and the timeline under it are both live output, and pushing only
407+ /// the active one left the level the window showed belonging to whichever
408+ /// session happened to be on screen. Muting during a preview and closing it
409+ /// then handed the timeline back the level from before the preview, at full
410+ /// volume, with the control still reading "muted". The engine holds the
411+ /// level per session and restores it when a device is replaced underneath
412+ /// it ([`PlaybackSession::set_gain`]), so the app's one copy of the level is
413+ /// the owner and every session is a follower of it.
414+ ///
415+ /// Silent no-op with no session at all, or on one with no audio device.
404 pub(crate) fn apply_volume(&self) {416 pub(crate) fn apply_volume(&self) {
405- if let Some(session) = self.active_session() {417+ push_gain(
406- session.set_gain(self.volume.gain());418+ self.volume.gain(),
407- }419+ [self.session.as_ref(), self.preview_session.as_ref()],
420+ );
408 }421 }
409 422
410 /// The mute key and the two volume keys, and the click on the button. The423 /// 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) -
488 now == Transport::Ended && was != Transport::Ended && loop_on501 now == Transport::Ended && was != Transport::Ended && loop_on
489 }502 }
490 503
504+/// The window's monitoring level, pushed at *every* session handed in -- the
505+/// timeline and a preview over it are both live output, and pushing only the
506+/// one on screen left the level belonging to whichever session happened to be
507+/// active: muting during a preview and closing it handed the timeline back the
508+/// level from before the preview opened, at full volume, with the control still
509+/// reading "muted".
510+///
511+/// A free function over the sessions rather than a `&self` method so the round
512+/// trip can be driven without a `Player` -- which takes a gpui `Context` this
513+/// test binary has no `TestAppContext` to build.
514+pub(crate) fn push_gain<const N: usize>(gain: f32, sessions: [Option<&PlaybackSession>; N]) {
515+ for session in sessions.into_iter().flatten() {
516+ session.set_gain(gain);
517+ }
518+}
519+
491 #[cfg(test)]520 #[cfg(test)]
492 mod tests {521 mod tests {
493 use super::*;522 use super::*;
crates/app/src/tests/media.rsmodified+102 -12
@@ -6,8 +6,8 @@ use crate::player::library::{
6 auto_proxies_pref_path, load_auto_proxies_pref, save_auto_proxies_pref,6 auto_proxies_pref_path, load_auto_proxies_pref, save_auto_proxies_pref,
7 };7 };
8 use crate::subs::{8 use crate::subs::{
9- audio_import_tail, load_subtitle_style, save_subtitle_style, sub_line_h_for,9+ SUB_SIZE_RANGE, audio_import_tail, load_subtitle_style, save_subtitle_style, sub_line_h_for,
10- subtitle_style_path, SUB_SIZE_RANGE,10+ subtitle_style_path,
11 };11 };
12 use crate::ui::preview::{bgra_to_rgba, screenshot_path};12 use crate::ui::preview::{bgra_to_rgba, screenshot_path};
13 13
@@ -106,7 +106,7 @@ fn a_device_that_dies_under_an_open_file_says_so_and_unsays_it() {
106 /// speaks.106 /// speaks.
107 #[test]107 #[test]
108 fn a_preview_flip_is_not_a_device_that_came_back() {108 fn a_preview_flip_is_not_a_device_that_came_back() {
109- use crate::notices::{audio_step, AudioStep};109+ use crate::notices::{AudioStep, audio_step};
110 // A swap, every way round: seeded, never announced.110 // A swap, every way round: seeded, never announced.
111 assert_eq!(audio_step(7, 8, None, Some("AUDIO_LOST")), AudioStep::Seed);111 assert_eq!(audio_step(7, 8, None, Some("AUDIO_LOST")), AudioStep::Seed);
112 assert_eq!(audio_step(7, 8, Some("AUDIO_LOST"), None), AudioStep::Seed);112 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() {
152 /// stuck read and never as a frozen window.152 /// stuck read and never as a frozen window.
153 #[test]153 #[test]
154 fn an_import_line_says_a_stage_has_stopped_moving_and_only_then() {154 fn an_import_line_says_a_stage_has_stopped_moving_and_only_then() {
155- use std::sync::atomic::{AtomicU8, Ordering::Relaxed};
156 use std::sync::Arc;155 use std::sync::Arc;
156+ use std::sync::atomic::{AtomicU8, Ordering::Relaxed};
157 let stage = Arc::new(AtomicU8::new(ImportStage::Header as u8));157 let stage = Arc::new(AtomicU8::new(ImportStage::Header as u8));
158 let started = Instant::now() - Duration::from_secs(9);158 let started = Instant::now() - Duration::from_secs(9);
159 let mut import = Import {159 let mut import = Import {
@@ -364,8 +364,8 @@ fn the_wheel_draws_the_sample_a_drag_is_holding() {
364 #[test]364 #[test]
365 fn the_strand_slot_starts_at_the_complement_and_the_write_chooses_it() {365 fn the_strand_slot_starts_at_the_complement_and_the_write_chooses_it() {
366 use engine::decode::{366 use engine::decode::{
367- viz_hue_ui, viz_sat_ui, viz_strand_hue_ui, viz_strand_sat_ui, viz_strand_set,367+ VIZ_PAINT_AZURE, viz_hue_ui, viz_sat_ui, viz_strand_hue_ui, viz_strand_sat_ui,
368- with_viz_paint_hue, with_viz_paint_strands, VIZ_PAINT_AZURE,368+ viz_strand_set, with_viz_paint_hue, with_viz_paint_strands,
369 };369 };
370 370
371 let paint = with_viz_paint_strands(VIZ_PAINT_AZURE, 2);371 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() {
407 #[test]407 #[test]
408 fn a_strand_slot_on_a_single_strand_clip_is_the_clip_s_own_colour() {408 fn a_strand_slot_on_a_single_strand_clip_is_the_clip_s_own_colour() {
409 use engine::decode::{409 use engine::decode::{
410- viz_hue_ui, viz_sat_ui, viz_strand_set, viz_strands_of, with_viz_paint_hue,410+ VIZ_PAINT_AZURE, viz_hue_ui, viz_sat_ui, viz_strand_set, viz_strands_of,
411- with_viz_paint_sat, with_viz_paint_strands, VIZ_PAINT_AZURE,411+ with_viz_paint_hue, with_viz_paint_sat, with_viz_paint_strands,
412 };412 };
413 413
414 let one = with_viz_paint_strands(414 let one = with_viz_paint_strands(
@@ -449,8 +449,8 @@ fn a_seek_says_so_only_once_it_has_stood() {
449 /// fifty-one seconds on a 25 GB film.449 /// fifty-one seconds on a 25 GB film.
450 #[test]450 #[test]
451 fn a_silence_card_is_up_while_its_scan_runs_and_says_where_it_has_got_to() {451 fn a_silence_card_is_up_while_its_scan_runs_and_says_where_it_has_got_to() {
452- use std::sync::atomic::Ordering::Relaxed;
453 use std::sync::Arc;452 use std::sync::Arc;
453+ use std::sync::atomic::Ordering::Relaxed;
454 let progress = Arc::new(engine::silence::Progress::default());454 let progress = Arc::new(engine::silence::Progress::default());
455 // Two hours and eight minutes, as the header claims it.455 // Two hours and eight minutes, as the header claims it.
456 progress.total.store(7680, Relaxed);456 progress.total.store(7680, Relaxed);
@@ -880,9 +880,11 @@ fn every_codec_row_is_offered_or_says_why_not() {
880 detail.contains("ec-vorbis"),880 detail.contains("ec-vorbis"),
881 "the row names the encoder like every other live one: {detail}"881 "the row names the encoder like every other live one: {detail}"
882 );882 );
883- assert!(FORMATS883+ assert!(
884- .into_iter()884+ FORMATS
885- .any(|(row, _, _, detail)| row.contains(&Format::Hevc) && detail.contains("intra")));885+ .into_iter()
886+ .any(|(row, _, _, detail)| row.contains(&Format::Hevc) && detail.contains("intra"))
887+ );
886 // The destination follows the format and keeps the stem, mp4 included.888 // The destination follows the format and keeps the stem, mp4 included.
887 assert_eq!(889 assert_eq!(
888 retarget(std::path::Path::new("/a/take.export.mp4"), Format::Wav),890 retarget(std::path::Path::new("/a/take.export.mp4"), Format::Wav),
@@ -1459,6 +1461,94 @@ fn ticking_the_preview_session_never_moves_the_timeline() {
1459 );1461 );
1460 }1462 }
1461 1463
1464+/// The monitoring level is the *window's*, and a preview closing must not hand
1465+/// the timeline back the level it had before the preview opened: muting during
1466+/// a preview and pressing `esc` used to leave the timeline playing at full
1467+/// volume with the control still reading "muted" -- the shown level and the
1468+/// heard level disagreed and nothing said so.
1469+///
1470+/// What is driven is the real push, [`push_gain`] -- the function
1471+/// [`apply_volume`](crate::player::transport::Player::apply_volume) is nothing
1472+/// but a call to, over the same two session slots a `Player` holds -- and the
1473+/// answer is read back out of the *device* ([`PlaybackSession::gain`]), not
1474+/// out of the window. `Player` itself cannot be built here (it takes a gpui
1475+/// `Context` this binary has no `TestAppContext` to build; the sibling preview
1476+/// tests say the same), so the door that calls the push is pinned by the scan
1477+/// below rather than executed.
1478+#[test]
1479+fn a_preview_close_leaves_the_timeline_at_the_level_the_window_shows() {
1480+ let timeline = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
1481+ // The control: an untouched session is at full volume, so a level read back
1482+ // as 1.0 is a real answer and not a default this test could pass on.
1483+ assert_eq!(
1484+ timeline.gain(),
1485+ Some(1.0),
1486+ "a fresh session is not at full volume"
1487+ );
1488+
1489+ // Stands in for `open_preview`: a second session arrives, and the window is
1490+ // muted while it is the one on screen.
1491+ let preview = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
1492+ let muted = 0.0;
1493+ push_gain(muted, [Some(&timeline), Some(&preview)]);
1494+
1495+ // The preview goes away -- `close_preview` takes it and pushes at what is
1496+ // left. The session that takes the picture must be the session heard at
1497+ // the level the control shows.
1498+ drop(preview);
1499+ push_gain(muted, [Some(&timeline), None]);
1500+ assert_eq!(
1501+ timeline.gain(),
1502+ Some(muted),
1503+ "closing a preview handed the timeline back a level the window is not showing"
1504+ );
1505+
1506+ // The other half of the regression, and the half a single-session test can
1507+ // never see: a push that reached only the *active* session (the preview)
1508+ // left the timeline exactly where it was, which is the reported bug. The
1509+ // pre-fix shape is therefore the control that makes the assertion above
1510+ // mean something.
1511+ let control = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
1512+ let other = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
1513+ push_gain(muted, [Some(&other), None]);
1514+ assert_eq!(
1515+ control.gain(),
1516+ Some(1.0),
1517+ "a session outside the push followed it, so the read above proves nothing"
1518+ );
1519+ assert_eq!(
1520+ other.gain(),
1521+ Some(muted),
1522+ "the pushed session ignored the level"
1523+ );
1524+}
1525+
1526+/// The wiring the round trip above cannot build a `Player` for: the level
1527+/// reaches *both* session slots, and both doors that install or drop a session
1528+/// push it. A push at the active session alone is the regression, and it is
1529+/// invisible to any test that only ever holds one session.
1530+#[test]
1531+fn the_window_level_is_pushed_at_every_session_and_on_every_swap() {
1532+ let apply = fn_body("apply_volume");
1533+ assert!(
1534+ apply.contains("self.session.as_ref()") && apply.contains("self.preview_session.as_ref()"),
1535+ "the level is pushed at one session only, so a preview closing hands the \
1536+ timeline back the level from before the preview opened"
1537+ );
1538+ assert!(
1539+ !apply.contains("self.active_session()"),
1540+ "the push still goes through the active session, which is the one-session \
1541+ rule this replaced"
1542+ );
1543+ for door in ["open_preview", "close_preview"] {
1544+ assert!(
1545+ fn_body(door).contains("self.apply_volume();"),
1546+ "{door} swaps the session on screen without telling the new one what \
1547+ level the window is showing"
1548+ );
1549+ }
1550+}
1551+
1462 /// [`bgra_to_rgba`] and [`save_screenshot`]'s own PNG write, round-tripped: a1552 /// [`bgra_to_rgba`] and [`save_screenshot`]'s own PNG write, round-tripped: a
1463 /// synthetic 2x2 frame -- one pixel per corner, alpha and channel order all1553 /// synthetic 2x2 frame -- one pixel per corner, alpha and channel order all
1464 /// distinct -- decodes back to the same pixels a viewer would see, in RGBA.1554 /// distinct -- decodes back to the same pixels a viewer would see, in RGBA.
crates/app/src/tests/mod.rsmodified+2 -0
@@ -77,6 +77,8 @@ fn config_env_lock() -> MutexGuard<'static, ()> {
77 .expect("config environment lock poisoned")77 .expect("config environment lock poisoned")
78 }78 }
79 79
80+use crate::player::transport::push_gain;
81+
80 /// Tests never open PipeWire. The output seam also refuses a cargo-test82 /// Tests never open PipeWire. The output seam also refuses a cargo-test
81 /// binary under `target/*/deps/`; this pin is the documented door and the83 /// binary under `target/*/deps/`; this pin is the documented door and the
82 /// source-scan guard below.84 /// source-scan guard below.
crates/engine-audio/src/lib.rsmodified+25 -1
@@ -626,6 +626,27 @@ pub unsafe extern "C" fn ao_set_volume(session: *mut c_void, gain: f32) -> i32 {
626 .unwrap_or(-1)626 .unwrap_or(-1)
627 }627 }
628 628
629+/// Reads back the gain [`ao_set_volume`] last set: what the stream is actually
630+/// multiplying by, which is not the same question as what a caller last asked
631+/// for once the device has been replaced (a re-armed stream comes up at 1.0).
632+/// -1.0 for a session that cannot answer -- never a real gain, which is 0.0 to
633+/// 1.0.
634+///
635+/// # Safety
636+/// `session` must come from [`ao_open`].
637+#[unsafe(no_mangle)]
638+pub unsafe extern "C" fn ao_gain(session: *mut c_void) -> f32 {
639+ catch_unwind(AssertUnwindSafe(|| {
640+ if session.is_null() {
641+ return -1.0;
642+ }
643+ // SAFETY: caller-guaranteed live session.
644+ let session = unsafe { &*(session as *const Session) };
645+ f32::from_bits(session.shared.gain.load(Ordering::Relaxed))
646+ }))
647+ .unwrap_or(-1.0)
648+}
649+
629 /// Drops every queued sample, so playback resumes from whatever is written650 /// Drops every queued sample, so playback resumes from whatever is written
630 /// next: what a seek needs. Takes effect on the next process callback (or the651 /// next: what a seek needs. Takes effect on the next process callback (or the
631 /// first one after a resume), and leaves the played position alone -- the652 /// first one after a resume), and leaves the played position alone -- the
@@ -751,7 +772,10 @@ mod tests {
751 flush.store(true, Ordering::Release);772 flush.store(true, Ordering::Release);
752 let mut out = [0u8; 16];773 let mut out = [0u8; 16];
753 assert_eq!(consume(&flush, &ring, &mut out, 2), 0, "the flush landed");774 assert_eq!(consume(&flush, &ring, &mut out, 2), 0, "the flush landed");
754- assert!(!primed.load(Ordering::Acquire), "the restart counts as late");775+ assert!(
776+ !primed.load(Ordering::Acquire),
777+ "the restart counts as late"
778+ );
755 779
756 // ...until its own first sample lands, from where it counts again --780 // ...until its own first sample lands, from where it counts again --
757 // which is also what makes the tail work: `ao_stream_ended` unprimes781 // which is also what makes the tail work: `ao_stream_ended` unprimes
crates/engine/src/ao.rsmodified+44 -2
@@ -12,7 +12,7 @@
12 12
13 use std::ffi::c_void;13 use std::ffi::c_void;
14 use std::path::Path;14 use std::path::Path;
15-use std::sync::atomic::{AtomicI64, AtomicU64, Ordering};15+use std::sync::atomic::{AtomicI64, AtomicU32, AtomicU64, Ordering};
16 use std::sync::{LazyLock, OnceLock};16 use std::sync::{LazyLock, OnceLock};
17 use std::time::Instant;17 use std::time::Instant;
18 18
@@ -54,6 +54,11 @@ struct Plugin {
54 /// did and only counts the tail of a played-out stream as lateness, which54 /// did and only counts the tail of a played-out stream as lateness, which
55 /// is a worse diagnostic rather than a worse session.55 /// is a worse diagnostic rather than a worse session.
56 stream_ended: Option<unsafe extern "C" fn(*mut c_void) -> i32>,56 stream_ended: Option<unsafe extern "C" fn(*mut c_void) -> i32>,
57+ /// Optional, unlike its neighbours: without it a session plays and is
58+ /// silenced exactly as before, it just cannot be *asked* what gain it is
59+ /// running -- and asking is the only way to see that a device replaced
60+ /// under it came back at the wrong level.
61+ gain: Option<unsafe extern "C" fn(*mut c_void) -> f32>,
57 close: unsafe extern "C" fn(*mut c_void),62 close: unsafe extern "C" fn(*mut c_void),
58 // Never dropped (lives in a static), so the fn pointers above stay valid.63 // Never dropped (lives in a static), so the fn pointers above stay valid.
59 _lib: Library,64 _lib: Library,
@@ -102,6 +107,7 @@ fn load() -> Option<Plugin> {
102 // reads zero underruns is worse than a run that says the107 // reads zero underruns is worse than a run that says the
103 // plugin is the wrong one.108 // plugin is the wrong one.
104 underruns: *lib.get(b"ao_underruns\0").ok()?,109 underruns: *lib.get(b"ao_underruns\0").ok()?,
110+ gain: lib.get(b"ao_gain\0").ok().map(|f| *f),
105 stream_ended: lib.get(b"ao_stream_ended\0").ok().map(|f| *f),111 stream_ended: lib.get(b"ao_stream_ended\0").ok().map(|f| *f),
106 close: *lib.get(b"ao_close\0").ok()?,112 close: *lib.get(b"ao_close\0").ok()?,
107 _lib: lib,113 _lib: lib,
@@ -137,6 +143,11 @@ struct Silent {
137 base: AtomicI64,143 base: AtomicI64,
138 /// 0 = paused; otherwise milliseconds from [`epoch`] at the last resume.144 /// 0 = paused; otherwise milliseconds from [`epoch`] at the last resume.
139 origin_ms: AtomicU64,145 origin_ms: AtomicU64,
146+ /// The gain last pushed, so the silent sink answers the same question the
147+ /// plugin does: what is this stream actually multiplying by. Without it
148+ /// every gain read back as a shrug, and a device that had been re-armed at
149+ /// full volume looked exactly like one that had kept its level.
150+ gain: AtomicU32,
140 }151 }
141 152
142 fn epoch() -> Instant {153 fn epoch() -> Instant {
@@ -154,9 +165,18 @@ impl Silent {
154 rate: f64::from(sample_rate),165 rate: f64::from(sample_rate),
155 base: AtomicI64::new(-1),166 base: AtomicI64::new(-1),
156 origin_ms: AtomicU64::new(0),167 origin_ms: AtomicU64::new(0),
168+ gain: AtomicU32::new(1.0f32.to_bits()),
157 }169 }
158 }170 }
159 171
172+ fn gain(&self) -> f32 {
173+ f32::from_bits(self.gain.load(Ordering::Relaxed))
174+ }
175+
176+ fn set_gain(&self, gain: f32) {
177+ self.gain.store(gain.to_bits(), Ordering::Relaxed);
178+ }
179+
160 fn extra(&self) -> i64 {180 fn extra(&self) -> i64 {
161 match self.origin_ms.load(Ordering::Relaxed) {181 match self.origin_ms.load(Ordering::Relaxed) {
162 0 => 0,182 0 => 0,
@@ -308,7 +328,10 @@ impl AoSession {
308 return false;328 return false;
309 }329 }
310 match &self.backend {330 match &self.backend {
311- Backend::Silent(_) => true,331+ Backend::Silent(s) => {
332+ s.set_gain(gain);
333+ true
334+ }
312 Backend::Plugin { plugin, handle } => {335 Backend::Plugin { plugin, handle } => {
313 // SAFETY: `handle` came from `ao_open` and is still open.336 // SAFETY: `handle` came from `ao_open` and is still open.
314 unsafe { (plugin.set_volume)(*handle, gain) == 0 }337 unsafe { (plugin.set_volume)(*handle, gain) == 0 }
@@ -316,6 +339,25 @@ impl AoSession {
316 }339 }
317 }340 }
318 341
342+ /// The gain this stream is actually running at, read back from the device
343+ /// rather than remembered by the caller: the two come apart the moment the
344+ /// device object is replaced (a fresh stream comes up at 1.0), and a
345+ /// remembered answer would report the level that was asked for rather than
346+ /// the one in force. `None` with no device, or a plugin too old to answer.
347+ pub fn gain(&self) -> Option<f32> {
348+ match &self.backend {
349+ Backend::Silent(s) => Some(s.gain()),
350+ Backend::Plugin { plugin, handle } => {
351+ let read = plugin.gain?;
352+ // SAFETY: `handle` came from `ao_open` and is still open.
353+ match unsafe { read(*handle) } {
354+ gain if gain < 0.0 => None,
355+ gain => Some(gain),
356+ }
357+ }
358+ }
359+ }
360+
319 /// Drops everything still queued, so the next samples written play right361 /// Drops everything still queued, so the next samples written play right
320 /// away -- what a seek needs. The played position keeps counting.362 /// away -- what a seek needs. The played position keeps counting.
321 pub fn flush(&self) -> bool {363 pub fn flush(&self) -> bool {
crates/engine/src/limiter.rsmodified+98 -6
@@ -140,14 +140,24 @@ impl LimiterState {
140 }140 }
141 141
142 /// One switched in **while the mix is already running**: the same limiter,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 out143+ /// except that it swallows nothing to fill its delay line -- the line is
144- /// first is the line's own [`LOOKAHEAD_MS`] of silence and the mix behind144+ /// zeroed and emitting from the first frame, where [`new`] would have eaten
145- /// it, where a fresh state would have eaten that much of the mix instead.145+ /// that much of the mix at the front instead.
146 ///146 ///
147 /// Which matters because the count *is* the clock: a mixer that emitted147 /// Which matters because the count *is* the clock: a mixer that emitted
148 /// fewer samples than the timeline asked for would slide the picture off148 /// 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 the149+ /// the sound by the lookahead, once per switch-on.
150- /// moment somebody engages a limiter is the honest price.150+ ///
151+ /// The price, stated as it measures rather than as it was hoped: not a
152+ /// momentary hair of silence the stream grows back from, but a **permanent**
153+ /// shift of [`LOOKAHEAD_MS`] for the rest of the stream -- the output is
154+ /// the input delayed by the whole line, every block, because nothing ever
155+ /// re-aligns it. That is at most 2 ms, which is under the perceptual
156+ /// threshold, and it is paid once per stream rather than growing; it is
157+ /// pinned by
158+ /// `tests::an_engaged_limiter_shifts_the_stream_by_the_lookahead_for_good`.
159+ /// Changing it is a design call about the export's A/V alignment, not a
160+ /// bug fix.
151 pub fn engaged(params: &Limiter, sample_rate: u32, channels: usize) -> Self {161 pub fn engaged(params: &Limiter, sample_rate: u32, channels: usize) -> Self {
152 Self {162 Self {
153 warm: 0,163 warm: 0,
@@ -314,7 +324,10 @@ mod tests {
314 state.process(&mut buf);324 state.process(&mut buf);
315 assert_eq!(buf.len(), block.len(), "a retune ate samples");325 assert_eq!(buf.len(), block.len(), "a retune ate samples");
316 let quiet = buf.iter().fold(0.0f32, |m, s| m.max(s.abs()));326 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");327+ assert!(
328+ quiet <= db_to_linear(-12.0) + 1e-6,
329+ "peak {quiet} passed -12 dB"
330+ );
318 assert!(quiet < hot, "the ceiling did not move: {hot} -> {quiet}");331 assert!(quiet < hot, "the ceiling did not move: {hot} -> {quiet}");
319 332
320 // Switched out: the line still delays, so the count still holds, and333 // Switched out: the line still delays, so the count still holds, and
@@ -330,6 +343,85 @@ mod tests {
330 assert!(raw > 1.0, "bypassed, the mix is untouched: peak {raw}");343 assert!(raw > 1.0, "bypassed, the mix is untouched: peak {raw}");
331 }344 }
332 345
346+ /// What engaging a limiter mid-stream actually costs, measured rather than
347+ /// described: not a momentary hair of silence that the stream then grows
348+ /// back from, but a **permanent** shift. `engaged` starts its delay line
349+ /// empty and swallows nothing, so from the first block onward the output is
350+ /// the input delayed by the whole lookahead -- for the rest of the stream.
351+ /// `new` is head-aligned instead: it swallows the lookahead once, at the
352+ /// front, and is a block shorter for it.
353+ ///
354+ /// The two are measured against each other because the difference is the
355+ /// whole claim: same tone, same settings, one index offset and one block
356+ /// length apart. A permanent offset of at most [`LOOKAHEAD_MS`] is below
357+ /// the perceptual threshold, so this pins the *measured* behaviour the doc
358+ /// comment on [`LimiterState::engaged`] describes rather than ruling on
359+ /// whether it should be changed -- that is a design call, not a bug fix.
360+ #[test]
361+ fn an_engaged_limiter_shifts_the_stream_by_the_lookahead_for_good() {
362+ let rate = 48_000;
363+ let params = Limiter {
364+ ceiling_db: -3.0,
365+ on: true,
366+ };
367+ let lookahead = ((LOOKAHEAD_MS / 1000.0 * rate as f32) as usize).max(1);
368+ // Under the knee throughout, so what comes out is the input and the
369+ // only thing being measured is *when* each frame appears.
370+ let tone: Vec<f32> = (0..4_000)
371+ .flat_map(|i| {
372+ let s = 0.1 * (i as f32 / rate as f32 * 440.0 * std::f32::consts::TAU).sin();
373+ [s, s]
374+ })
375+ .collect();
376+
377+ // `new`: head-aligned, and a block shorter by exactly the lookahead.
378+ let mut fresh = LimiterState::new(&params, rate, 2);
379+ let mut head = tone.clone();
380+ fresh.process(&mut head);
381+ assert_eq!(
382+ head.len(),
383+ tone.len() - lookahead * 2,
384+ "a fresh limiter is not head-aligned by exactly the lookahead"
385+ );
386+
387+ // `engaged`: the same count, the same samples -- one lookahead later.
388+ let mut live = LimiterState::engaged(&params, rate, 2);
389+ let mut shifted = tone.clone();
390+ live.process(&mut shifted);
391+ assert_eq!(
392+ shifted.len(),
393+ tone.len(),
394+ "an engaged limiter ate samples, which is the thing it exists not to do"
395+ );
396+ assert_eq!(
397+ &shifted[lookahead * 2..],
398+ &head[..],
399+ "an engaged limiter is not the fresh one delayed by exactly the \
400+ lookahead, so what it costs mid-stream is not what the doc claims"
401+ );
402+ // And the shift is the *stream's*, not one block's. A second block of a
403+ // marker the first did not contain comes out *still* delayed by the
404+ // lookahead: the head of it is still the tail of the tone, and the
405+ // marker itself only appears from the lookahead on. Nothing re-aligns
406+ // the line, which is what makes the cost permanent rather than a one-off
407+ // at the moment of engaging.
408+ let marker = vec![0.5; tone.len()];
409+ let mut next = marker.clone();
410+ live.process(&mut next);
411+ assert!(
412+ next[..lookahead * 2].iter().any(|s| *s != 0.5),
413+ "the second block is aligned where the first was not, so the cost is \
414+ a one-off rather than a permanent shift"
415+ );
416+ assert!(
417+ next[lookahead * 2..]
418+ .iter()
419+ .all(|s| (*s - 0.5).abs() < 1e-6),
420+ "the marker is not behind by exactly the lookahead: the stream is not \
421+ delayed by a fixed amount from here on"
422+ );
423+ }
424+
333 /// Flat settings are a passthrough, which is what the export invariant425 /// Flat settings are a passthrough, which is what the export invariant
334 /// rests on: 0 dB is exactly 1.0, never 0.9999999.426 /// rests on: 0 dB is exactly 1.0, never 0.9999999.
335 #[test]427 #[test]
crates/engine/src/playback.rsmodified+260 -93
@@ -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, PathBuf};14 use std::path::{Path, PathBuf};
15-use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU64, AtomicUsize, Ordering};15+use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU32, AtomicU64, AtomicUsize, 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;
@@ -26,8 +26,9 @@ use crate::colorspace::{ColorDescription, ContentLight};
26 use crate::decode::{Backend, BackendCell, DecodeSession, Frame, Worker};26 use crate::decode::{Backend, BackendCell, DecodeSession, Frame, Worker};
27 use crate::demux::{Codec, Demuxer, NoVideoTrack, Rotation, VideoMeta};27 use crate::demux::{Codec, Demuxer, NoVideoTrack, Rotation, VideoMeta};
28 use crate::eq::EqParams;28 use crate::eq::EqParams;
29-use crate::project::{ProjectSettings,29+use crate::project::{
30- Clip, Edge, GapSweep, Lane, LaneKind, Project, Rate, Source, Span, Speed, SubClip,30+ Clip, Edge, GapSweep, Lane, LaneKind, Project, ProjectSettings, Rate, Source, Span, Speed,
31+ SubClip,
31 };32 };
32 use crate::scale::{Composer, FitPolicy};33 use crate::scale::{Composer, FitPolicy};
33 use crate::transform::TransformParams;34 use crate::transform::TransformParams;
@@ -140,6 +141,18 @@ struct Audio {
140 /// seek counts it as such, which is a permanent offset between the picture141 /// seek counts it as such, which is a permanent offset between the picture
141 /// and the sound, re-rolled by every edit made while playing.142 /// and the sound, re-rolled by every edit made while playing.
142 content_at: Arc<AtomicI64>,143 content_at: Arc<AtomicI64>,
144+ /// The monitoring gain this session's device is running at, as f32 bits.
145+ ///
146+ /// The device is the owner -- [`PlaybackSession::gain`] reads the level
147+ /// back out of it -- and this is the *only* reason a session knows what to
148+ /// restore: the device object is replaced from under the session whenever
149+ /// the output dies ([`Self::rearm_audio`]) or is armed late
150+ /// ([`Self::arm_audio`]), and a fresh one comes up at 1.0. Without this a
151+ /// muted session that lost its device came back at full volume while the
152+ /// control still said muted. Written by [`PlaybackSession::set_gain`]
153+ /// alone, so it cannot drift from the knob: whatever the caller last
154+ /// pushed is exactly what the next device is told.
155+ gain: Arc<AtomicU32>,
143 /// The timeline is *meant* to be playing: what a play or a seek-while-playing156 /// The timeline is *meant* to be playing: what a play or a seek-while-playing
144 /// asks for, and what the feeder turns into a running device the moment it157 /// asks for, and what the feeder turns into a running device the moment it
145 /// has a real sample to play ([`Audio::set_playing`], [`feed`]).158 /// has a real sample to play ([`Audio::set_playing`], [`feed`]).
@@ -638,7 +651,9 @@ impl PlaybackSession {
638 // hands it back out. The same trade the audio header cache above this651 // hands it back out. The same trade the audio header cache above this
639 // makes -- a second container open, paid once at open rather than never652 // makes -- a second container open, paid once at open rather than never
640 // -- since nothing here decodes a single picture.653 // -- since nothing here decodes a single picture.
641- let content_light = Demuxer::open(&path).map(|(_, d)| d.light()).unwrap_or_default();654+ let content_light = Demuxer::open(&path)
655+ .map(|(_, d)| d.light())
656+ .unwrap_or_default();
642 Ok(Self {657 Ok(Self {
643 meta,658 meta,
644 content_light,659 content_light,
@@ -980,7 +995,9 @@ impl PlaybackSession {
980 let content_light = if crate::is_audio(&first.path) || crate::is_image(&first.path) {995 let content_light = if crate::is_audio(&first.path) || crate::is_image(&first.path) {
981 ContentLight::default()996 ContentLight::default()
982 } else {997 } else {
983- Demuxer::open(&first.path).map(|(_, d)| d.light()).unwrap_or_default()998+ Demuxer::open(&first.path)
999+ .map(|(_, d)| d.light())
1000+ .unwrap_or_default()
984 };1001 };
985 // The extension's word, corrected below the moment the header disagrees1002 // The extension's word, corrected below the moment the header disagrees
986 // with it (`NoVideoTrack`, the same fallback `open_stream` takes): every1003 // with it (`NoVideoTrack`, the same fallback `open_stream` takes): every
@@ -1001,11 +1018,11 @@ impl PlaybackSession {
1001 codec: Codec::H264,1018 codec: Codec::H264,
1002 color: ColorDescription::default(),1019 color: ColorDescription::default(),
1003 rotation: Rotation::None,1020 rotation: Rotation::None,
1004- // No container said anything about these: the canvas this engine drew1021+ // No container said anything about these: the canvas this engine drew
1005- // itself is square pixels at the size it was drawn at.1022+ // itself is square pixels at the size it was drawn at.
1006- coded_width: width,1023+ coded_width: width,
1007- coded_height: height,1024+ coded_height: height,
1008- pixel_aspect: crate::demux::PixelAspect::SQUARE,1025+ pixel_aspect: crate::demux::PixelAspect::SQUARE,
1009 };1026 };
1010 (meta, DecodeSession::open_black(width, height, 1))1027 (meta, DecodeSession::open_black(width, height, 1))
1011 }1028 }
@@ -1071,11 +1088,11 @@ impl PlaybackSession {
1071 codec: Codec::H264,1088 codec: Codec::H264,
1072 color: ColorDescription::default(),1089 color: ColorDescription::default(),
1073 rotation: Rotation::None,1090 rotation: Rotation::None,
1074- // No container said anything about these: the canvas this engine drew1091+ // No container said anything about these: the canvas this engine drew
1075- // itself is square pixels at the size it was drawn at.1092+ // itself is square pixels at the size it was drawn at.
1076- coded_width: width,1093+ coded_width: width,
1077- coded_height: height,1094+ coded_height: height,
1078- pixel_aspect: crate::demux::PixelAspect::SQUARE,1095+ pixel_aspect: crate::demux::PixelAspect::SQUARE,
1079 };1096 };
1080 (meta, DecodeSession::open_black(width, height, 1))1097 (meta, DecodeSession::open_black(width, height, 1))
1081 }1098 }
@@ -1207,24 +1224,24 @@ impl PlaybackSession {
1207 let subtitles = crate::subtitle::open_all(&doc.subtitles);1224 let subtitles = crate::subtitle::open_all(&doc.subtitles);
1208 let project =1225 let project =
1209 Project::from_parts(doc.sources, doc.lanes, doc.eq, doc.color, doc.transform)?1226 Project::from_parts(doc.sources, doc.lanes, doc.eq, doc.color, doc.transform)?
1210- .with_mix(&doc.gains, doc.limiter)1227+ .with_mix(&doc.gains, doc.limiter)
1211- .with_tone(doc.tone)1228+ .with_tone(doc.tone)
1212- // The palette before what is placed on it: a caption names a row of1229+ // The palette before what is placed on it: a caption names a row of
1213- // it, and [`Project::with_subs`] refuses one naming a row that is1230+ // it, and [`Project::with_subs`] refuses one naming a row that is
1214- // not there.1231+ // not there.
1215- .with_subtitles(subtitles)1232+ .with_subtitles(subtitles)
1216- .with_subs(doc.subs)?1233+ .with_subs(doc.subs)?
1217- // The header a load puts back: the canvas and rate above, which a1234+ // The header a load puts back: the canvas and rate above, which a
1218- // save's own `resolution`/`fps` lines may have moved off the1235+ // save's own `resolution`/`fps` lines may have moved off the
1219- // scaffold's, and the switches the literal below carries -- handed1236+ // scaffold's, and the switches the literal below carries -- handed
1220- // in here because they are the project's own and a door that moved1237+ // in here because they are the project's own and a door that moved
1221- // one after this would snapshot whatever copy it holds, which until1238+ // one after this would snapshot whatever copy it holds, which until
1222- // this line is the placeholder's. No undo step for1239+ // this line is the placeholder's. No undo step for
1223- // [`Project::with_mix`]'s reason: a project that arrived one `z`1240+ // [`Project::with_mix`]'s reason: a project that arrived one `z`
1224- // from a state it was never in is a project whose first undo is a1241+ // from a state it was never in is a project whose first undo is a
1225- // surprise.1242+ // surprise.
1226- .with_canvas(meta.width, meta.height, meta.frame_rate)1243+ .with_canvas(meta.width, meta.height, meta.frame_rate)
1227- .with_switches(doc.proxy, doc.auto_proxy, doc.encoder, doc.sample_rate);1244+ .with_switches(doc.proxy, doc.auto_proxy, doc.encoder, doc.sample_rate);
1228 let span = project.composite_span_at(0);1245 let span = project.composite_span_at(0);
1229 // Last, because it is the one thing here that cannot be taken back: the1246 // Last, because it is the one thing here that cannot be taken back: the
1230 // feeder thread outlives the `Audio` value (it holds its own clones) and1247 // feeder thread outlives the `Audio` value (it holds its own clones) and
@@ -1248,7 +1265,11 @@ impl PlaybackSession {
1248 // source's silence is not worth reporting over an earlier one's).1265 // source's silence is not worth reporting over an earlier one's).
1249 let (audio, audio_disabled) = {1266 let (audio, audio_disabled) = {
1250 let mut opened = (None, None);1267 let mut opened = (None, None);
1251- for source in project.sources().iter().filter(|s| !crate::is_image(&s.path)) {1268+ for source in project
1269+ .sources()
1270+ .iter()
1271+ .filter(|s| !crate::is_image(&s.path))
1272+ {
1252 opened = open_audio(&source.path, source.audio_stream);1273 opened = open_audio(&source.path, source.audio_stream);
1253 if opened.0.is_some() {1274 if opened.0.is_some() {
1254 break;1275 break;
@@ -1713,8 +1734,10 @@ impl PlaybackSession {
1713 };1734 };
1714 let now = secs_to_frame(self.clock.now(), self.meta.frame_rate);1735 let now = secs_to_frame(self.clock.now(), self.meta.frame_rate);
1715 let offset = now.saturating_sub(span.start).min(span.len);1736 let offset = now.saturating_sub(span.start).min(span.len);
1716- self.worker1737+ self.worker.playhead(
1717- .playhead(self.span_rate.source_at(in_frame + span.speed.source_at(offset)));1738+ self.span_rate
1739+ .source_at(in_frame + span.speed.source_at(offset)),
1740+ );
1718 }1741 }
1719 1742
1720 /// Installs `replacement` as the decode worker, parking the outgoing one in1743 /// Installs `replacement` as the decode worker, parking the outgoing one in
@@ -1908,11 +1931,7 @@ impl PlaybackSession {
1908 .composite_transform_at(start)1931 .composite_transform_at(start)
1909 .copied()1932 .copied()
1910 .unwrap_or_default(),1933 .unwrap_or_default(),
1911- Composer::new(1934+ Composer::new(canvas_w, canvas_h, self.project.composite_fit_at(start)),
1912- canvas_w,
1913- canvas_h,
1914- self.project.composite_fit_at(start),
1915- ),
1916 )1935 )
1917 .inspect_err(|e| eprintln!("timeline frame {start}: image open failed: {e}"))1936 .inspect_err(|e| eprintln!("timeline frame {start}: image open failed: {e}"))
1918 }1937 }
@@ -1941,17 +1960,11 @@ impl PlaybackSession {
1941 .composite_transform_at(start)1960 .composite_transform_at(start)
1942 .copied()1961 .copied()
1943 .unwrap_or_default(),1962 .unwrap_or_default(),
1944- Composer::new(1963+ Composer::new(canvas_w, canvas_h, self.project.composite_fit_at(start)),
1945- canvas_w,
1946- canvas_h,
1947- self.project.composite_fit_at(start),
1948- ),
1949 self.project.composite_visualizer_at(start),1964 self.project.composite_visualizer_at(start),
1950 self.project.composite_viz_paint_at(start),1965 self.project.composite_viz_paint_at(start),
1951 )1966 )
1952- .inspect_err(|e| {1967+ .inspect_err(|e| eprintln!("timeline frame {start}: visualizer open failed: {e}"))
1953- eprintln!("timeline frame {start}: visualizer open failed: {e}")
1954- })
1955 }1968 }
1956 Some(Span {1969 Some(Span {
1957 start,1970 start,
@@ -2119,11 +2132,7 @@ impl PlaybackSession {
2119 .composite_transform_at(b_start)2132 .composite_transform_at(b_start)
2120 .copied()2133 .copied()
2121 .unwrap_or_default();2134 .unwrap_or_default();
2122- let canvas = Composer::new(2135+ let canvas = Composer::new(canvas_w, canvas_h, self.project.composite_fit_at(b_start));
2123- canvas_w,
2124- canvas_h,
2125- self.project.composite_fit_at(b_start),
2126- );
2127 let tone = self.project.tone();2136 let tone = self.project.tone();
2128 let stream = DecodeSession::open_worker_deferred(2137 let stream = DecodeSession::open_worker_deferred(
2129 &path,2138 &path,
@@ -2301,7 +2310,9 @@ impl PlaybackSession {
2301 /// changes only the words, which are drawn over whatever is decoded.2310 /// changes only the words, which are drawn over whatever is decoded.
2302 pub fn trim_sub(&mut self, lane: Lane, idx: usize, edge: Edge, to: u32) -> crate::Result<()> {2311 pub fn trim_sub(&mut self, lane: Lane, idx: usize, edge: Edge, to: u32) -> crate::Result<()> {
2303 let grouped = self.caption_grouped_with_clips(lane, idx);2312 let grouped = self.caption_grouped_with_clips(lane, idx);
2304- let trimmed = self.project.trim_sub(lane, idx, edge, to, self.meta.frame_rate);2313+ let trimmed = self
2314+ .project
2315+ .trim_sub(lane, idx, edge, to, self.meta.frame_rate);
2305 if trimmed.is_ok() && grouped {2316 if trimmed.is_ok() && grouped {
2306 self.invalidate(Dirty::Both);2317 self.invalidate(Dirty::Both);
2307 }2318 }
@@ -2312,7 +2323,8 @@ impl PlaybackSession {
2312 /// ([`Project::trim_sub_room`]) -- what a front-end drawing the box during2323 /// ([`Project::trim_sub_room`]) -- what a front-end drawing the box during
2313 /// a drag asks, at this timeline's rate.2324 /// a drag asks, at this timeline's rate.
2314 pub fn trim_sub_room(&self, lane: Lane, idx: usize, edge: Edge) -> Option<(u32, u32)> {2325 pub fn trim_sub_room(&self, lane: Lane, idx: usize, edge: Edge) -> Option<(u32, u32)> {
2315- self.project.trim_sub_room(lane, idx, edge, self.meta.frame_rate)2326+ self.project
2327+ .trim_sub_room(lane, idx, edge, self.meta.frame_rate)
2316 }2328 }
2317 2329
2318 /// Takes one placement off a subtitle lane, leaving a gap2330 /// Takes one placement off a subtitle lane, leaving a gap
@@ -2390,7 +2402,11 @@ impl PlaybackSession {
2390 // one this dispatch needs; a caption carries a link at all only once2402 // one this dispatch needs; a caption carries a link at all only once
2391 // grouped (`place_sub` always starts one at `None`), so that alone is2403 // grouped (`place_sub` always starts one at `None`), so that alone is
2392 // "this delete ripples more than its own lane".2404 // "this delete ripples more than its own lane".
2393- match self.sub_lane(lane).get(idx).is_some_and(|s| s.link.is_some()) {2405+ match self
2406+ .sub_lane(lane)
2407+ .get(idx)
2408+ .is_some_and(|s| s.link.is_some())
2409+ {
2394 true => self.edit(Dirty::Both, |p| p.delete_sub_in(lane, idx)),2410 true => self.edit(Dirty::Both, |p| p.delete_sub_in(lane, idx)),
2395 // A caption in no group is the plain lift that touches nothing2411 // A caption in no group is the plain lift that touches nothing
2396 // else: no reseek owed.2412 // else: no reseek owed.
@@ -2555,7 +2571,9 @@ impl PlaybackSession {
2555 to: Lane,2571 to: Lane,
2556 start: u32,2572 start: u32,
2557 ) -> bool {2573 ) -> bool {
2558- self.edit(Dirty::Both, |p| p.move_selection(picks, from, idx, to, start))2574+ self.edit(Dirty::Both, |p| {
2575+ p.move_selection(picks, from, idx, to, start)
2576+ })
2559 }2577 }
2560 2578
2561 /// Drags one end of that clip to timeline frame `to`, changing how much of2579 /// Drags one end of that clip to timeline frame `to`, changing how much of
@@ -2738,6 +2756,10 @@ impl PlaybackSession {
2738 // A device that is there but *dead* is not a device: the walk below2756 // A device that is there but *dead* is not a device: the walk below
2739 // opens another one, which is also what clears the notice a death put up2757 // opens another one, which is also what clears the notice a death put up
2740 // ([`Self::tick`]).2758 // ([`Self::tick`]).
2759+ let carried = self
2760+ .audio
2761+ .as_ref()
2762+ .map(|audio| audio.gain.load(Ordering::Acquire));
2741 if let Some(audio) = &self.audio2763 if let Some(audio) = &self.audio
2742 && !audio.died.load(Ordering::Acquire)2764 && !audio.died.load(Ordering::Acquire)
2743 {2765 {
@@ -2750,8 +2772,16 @@ impl PlaybackSession {
2750 .filter(|s| !crate::is_image(&s.path))2772 .filter(|s| !crate::is_image(&s.path))
2751 {2773 {
2752 let (audio, disabled) = open_audio(&source.path, source.audio_stream);2774 let (audio, disabled) = open_audio(&source.path, source.audio_stream);
2753- if audio.is_some() {2775+ if let Some(audio) = audio {
2754- self.audio = audio;2776+ // The device is being replaced under a session that may already
2777+ // be running at a level the user chose, so that level comes
2778+ // across with it ([`Audio::gain`]) rather than the fresh
2779+ // stream's 1.0.
2780+ if let Some(bits) = carried {
2781+ audio.gain.store(bits, Ordering::Release);
2782+ audio.ao.lock().unwrap().set_volume(f32::from_bits(bits));
2783+ }
2784+ self.audio = Some(audio);
2755 self.audio_disabled = disabled;2785 self.audio_disabled = disabled;
2756 return;2786 return;
2757 }2787 }
@@ -2800,6 +2830,11 @@ impl PlaybackSession {
2800 // is silenced until the seek that feeds it says otherwise, which is the2830 // is silenced until the seek that feeds it says otherwise, which is the
2801 // same two steps [`open_audio`] takes on the way in.2831 // same two steps [`open_audio`] takes on the way in.
2802 ao.set_active(false);2832 ao.set_active(false);
2833+ // A fresh stream comes up at full volume, so the level this session was
2834+ // already running at is put back onto it before it is installed: a
2835+ // muted session that lost its device to a daemon restart would
2836+ // otherwise come back loud while the window still reads "muted".
2837+ ao.set_volume(f32::from_bits(audio.gain.load(Ordering::Acquire)));
2803 // Replacing the session is what closes the dead stream, so it is done2838 // Replacing the session is what closes the dead stream, so it is done
2804 // under the device lock the feeder writes through.2839 // under the device lock the feeder writes through.
2805 *audio.ao.lock().unwrap() = ao;2840 *audio.ao.lock().unwrap() = ao;
@@ -3267,8 +3302,8 @@ impl PlaybackSession {
3267 // end is an append, never a clip with black in front of it. The frame3302 // end is an append, never a clip with black in front of it. The frame
3268 // itself is honoured in [`Project::paste`], because a *drop* names a3303 // itself is honoured in [`Project::paste`], because a *drop* names a
3269 // place on the bed and means it.3304 // place on the bed and means it.
3270- let at = secs_to_frame(timeline_secs, self.meta.frame_rate)3305+ let at =
3271- .min(self.project.timeline_frames());3306+ secs_to_frame(timeline_secs, self.meta.frame_rate).min(self.project.timeline_frames());
3272 self.edit(Dirty::Both, |p| p.paste(at, clip))3307 self.edit(Dirty::Both, |p| p.paste(at, clip))
3273 }3308 }
3274 3309
@@ -3277,8 +3312,8 @@ impl PlaybackSession {
3277 /// past the last frame lands there rather than carrying black in front of3312 /// past the last frame lands there rather than carrying black in front of
3278 /// it, exactly as a lone clip's paste does.3313 /// it, exactly as a lone clip's paste does.
3279 pub fn paste_set_at(&mut self, timeline_secs: f64, items: &[(Lane, Clip)]) -> bool {3314 pub fn paste_set_at(&mut self, timeline_secs: f64, items: &[(Lane, Clip)]) -> bool {
3280- let at = secs_to_frame(timeline_secs, self.meta.frame_rate)3315+ let at =
3281- .min(self.project.timeline_frames());3316+ secs_to_frame(timeline_secs, self.meta.frame_rate).min(self.project.timeline_frames());
3282 self.edit(Dirty::Both, |p| p.paste_set(at, items))3317 self.edit(Dirty::Both, |p| p.paste_set(at, items))
3283 }3318 }
3284 3319
@@ -3982,21 +4017,44 @@ impl PlaybackSession {
3982 self.clock.seek_to(self.timeline_duration());4017 self.clock.seek_to(self.timeline_duration());
3983 }4018 }
3984 4019
4020+ /// The gain this session's device is running at, read back from the device
4021+ /// rather than remembered here: `None` with no audio output, or a plugin
4022+ /// too old to answer -- the two cases where a remembered answer would be a
4023+ /// claim nothing can check.
4024+ pub fn gain(&self) -> Option<f32> {
4025+ self.audio.as_ref()?.ao.lock().unwrap().gain()
4026+ }
4027+
3985 /// Sets the monitoring gain, 0.0 (silent) to 1.0. Mute is a gain of 0.0:4028 /// Sets the monitoring gain, 0.0 (silent) to 1.0. Mute is a gain of 0.0:
3986 /// one knob, because muting and turning it down are the same thing to the4029 /// one knob, because muting and turning it down are the same thing to the
3987 /// device, and *which* the user meant is a question only the UI can answer4030 /// device, and *which* the user meant is a question only the UI can answer
3988 /// -- it keeps the level to come back to.4031 /// -- it keeps the level to come back to.
3989 ///4032 ///
3990- /// Deliberately not session state: nothing here remembers it, so a caller4033+ /// The level is remembered for as long as this session lives
3991- /// pushes it once per session and an export -- which renders the file4034+ /// ([`Audio::gain`]) and only so that a device which is *replaced* under
3992- /// rather than what the speakers are doing -- can never pick it up. Silent4035+ /// the session -- re-armed after a death, armed by a late import -- comes
3993- /// with no audio device, which is also the only honest answer there.4036+ /// back at the level the session was already running at. It is still not
4037+ /// project state: a fresh session starts at 1.0, so a caller still pushes
4038+ /// it once per session, and an export -- which renders the file rather
4039+ /// than what the speakers are doing -- can never pick it up. Silent with
4040+ /// no audio device, which is also the only honest answer there.
3994 ///4041 ///
3995 /// Mute is not pause: the samples are still consumed and the device clock4042 /// Mute is not pause: the samples are still consumed and the device clock
3996 /// still runs, so the picture keeps playing against it.4043 /// still runs, so the picture keeps playing against it.
3997 pub fn set_gain(&self, gain: f32) -> bool {4044 pub fn set_gain(&self, gain: f32) -> bool {
3998 match &self.audio {4045 match &self.audio {
3999- Some(audio) => audio.ao.lock().unwrap().set_volume(gain),4046+ Some(audio) => {
4047+ // The device is the owner and is told first: a remembered level
4048+ // that says something the device does not agree with is worse
4049+ // than no memory at all, because the next replacement would
4050+ // restore the wrong number.
4051+ if audio.ao.lock().unwrap().set_volume(gain) {
4052+ audio.gain.store(gain.to_bits(), Ordering::Release);
4053+ true
4054+ } else {
4055+ false
4056+ }
4057+ }
4000 None => false,4058 None => false,
4001 }4059 }
4002 }4060 }
@@ -4692,6 +4750,7 @@ fn open_audio(path: &Path, stream: usize) -> (Option<Audio>, Option<String>) {
4692 died: Arc::new(AtomicBool::new(false)),4750 died: Arc::new(AtomicBool::new(false)),
4693 epoch: Arc::new(AtomicU64::new(0)),4751 epoch: Arc::new(AtomicU64::new(0)),
4694 content_at: Arc::new(AtomicI64::new(-1)),4752 content_at: Arc::new(AtomicI64::new(-1)),
4753+ gain: Arc::new(AtomicU32::new(1.0f32.to_bits())),
4695 wants_active: Arc::new(AtomicBool::new(false)),4754 wants_active: Arc::new(AtomicBool::new(false)),
4696 tap: Arc::new(Mutex::new(Vec::with_capacity(TAP_SAMPLES))),4755 tap: Arc::new(Mutex::new(Vec::with_capacity(TAP_SAMPLES))),
4697 feeders: Arc::new(AtomicUsize::new(0)),4756 feeders: Arc::new(AtomicUsize::new(0)),
@@ -4828,8 +4887,8 @@ fn blend_bgra(a: &[u8], b: &[u8], t: f32) -> Vec<u8> {
4828 #[cfg(test)]4887 #[cfg(test)]
4829 mod tests {4888 mod tests {
4830 use super::{4889 use super::{
4831- Edge, Lane, PlaybackSession, Source, TransformParams, audio_source_of, blend_bgra, secs_to_frame,4890+ AUDIO_LOST, Edge, Lane, PlaybackSession, Source, TransformParams, audio_source_of,
4832- AUDIO_LOST,4891+ blend_bgra, secs_to_frame,
4833 };4892 };
4834 use std::path::PathBuf;4893 use std::path::PathBuf;
4835 use std::sync::atomic::Ordering;4894 use std::sync::atomic::Ordering;
@@ -4874,7 +4933,12 @@ mod tests {
4874 "a dead output went to wall time without a word"4933 "a dead output went to wall time without a word"
4875 );4934 );
4876 assert!(4935 assert!(
4877- session.audio.as_ref().expect("audio").died.load(Ordering::Acquire),4936+ session
4937+ .audio
4938+ .as_ref()
4939+ .expect("audio")
4940+ .died
4941+ .load(Ordering::Acquire),
4878 "a tick opened the output again inside the cooldown"4942 "a tick opened the output again inside the cooldown"
4879 );4943 );
4880 assert!(4944 assert!(
@@ -4900,7 +4964,12 @@ mod tests {
4900 "playing after a dead output fed nothing: the session cannot come back"4964 "playing after a dead output fed nothing: the session cannot come back"
4901 );4965 );
4902 assert!(4966 assert!(
4903- !session.audio.as_ref().expect("audio").died.load(Ordering::Acquire),4967+ !session
4968+ .audio
4969+ .as_ref()
4970+ .expect("audio")
4971+ .died
4972+ .load(Ordering::Acquire),
4904 "the death flag stood after the output was replaced"4973 "the death flag stood after the output was replaced"
4905 );4974 );
4906 assert_eq!(4975 assert_eq!(
@@ -4910,6 +4979,70 @@ mod tests {
4910 );4979 );
4911 }4980 }
4912 4981
4982+ /// A monitoring level is state, and a device replaced under the session is
4983+ /// a new object that knows nothing about it: the re-armed stream came up
4984+ /// at full volume, so a session playing muted while PipeWire restarted
4985+ /// came back loud with the toolbar still reading "muted". The gain is
4986+ /// therefore read back *from the device* ([`PlaybackSession::gain`]) and
4987+ /// put back onto the replacement.
4988+ ///
4989+ /// The silent sink is what makes this a state round-trip rather than a
4990+ /// claim about ears: it keeps the gain it was given, so the level after a
4991+ /// re-arm is a number this process can read, and a plain open with no gain
4992+ /// ever pushed is the control that says 1.0 is a real default rather than
4993+ /// a leftover.
4994+ #[test]
4995+ fn a_rearmed_output_comes_back_at_the_level_the_session_was_running() {
4996+ let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
4997+ // The control: a session nobody has pushed a level at is at full
4998+ // volume, which is what a *fresh* device is expected to be.
4999+ assert_eq!(
5000+ session.gain(),
5001+ Some(1.0),
5002+ "a session that never had a gain pushed is not at full volume"
5003+ );
5004+ assert!(
5005+ session.set_gain(0.0),
5006+ "a muted push was refused by the silent sink"
5007+ );
5008+ assert_eq!(
5009+ session.gain(),
5010+ Some(0.0),
5011+ "the push did not reach the device"
5012+ );
5013+
5014+ // The device goes away the way a daemon restart takes it: the stream is
5015+ // stopped and flagged dead, with the cooldown already spent. The
5016+ // replacement is opened by the door the sibling re-arm witness drives
5017+ // -- a play and the seek that follows, which is `start_audio`'s
5018+ // unthrottled attempt -- and the death flag clearing is what says a new
5019+ // device really was installed, rather than the read below passing over
5020+ // the old one.
5021+ session.stop_audio();
5022+ let audio = session.audio.as_ref().expect("audio");
5023+ audio.died.store(true, Ordering::Release);
5024+ *audio.rearm_at.lock().unwrap() = Some(std::time::Instant::now());
5025+ session.play();
5026+ session.seek(1.0);
5027+ assert!(
5028+ !session
5029+ .audio
5030+ .as_ref()
5031+ .expect("audio")
5032+ .died
5033+ .load(Ordering::Acquire),
5034+ "the device was never replaced, so the level below says nothing about \
5035+ a re-armed stream"
5036+ );
5037+
5038+ assert_eq!(
5039+ session.gain(),
5040+ Some(0.0),
5041+ "the replacement device came up at full volume: a muted session \
5042+ that lost its output came back loud while the window still said muted"
5043+ );
5044+ }
5045+
4913 /// The seat declares the canvas's own size; the painter masks the planes it5046 /// The seat declares the canvas's own size; the painter masks the planes it
4914 /// returns to even dimensions, and a canvas the two disagree about used to5047 /// returns to even dimensions, and a canvas the two disagree about used to
4915 /// take the picture down between them. On the revision before the seat masked5048 /// take the picture down between them. On the revision before the seat masked
@@ -4941,7 +5074,11 @@ mod tests {
4941 std::thread::sleep(std::time::Duration::from_millis(5));5074 std::thread::sleep(std::time::Duration::from_millis(5));
4942 }5075 }
4943 let frame = frame.unwrap_or_else(|| panic!("no frame from a {w}x{h} canvas"));5076 let frame = frame.unwrap_or_else(|| panic!("no frame from a {w}x{h} canvas"));
4944- assert_eq!((frame.width, frame.height), (w, h), "a frame at the canvas's own size");5077+ assert_eq!(
5078+ (frame.width, frame.height),
5079+ (w, h),
5080+ "a frame at the canvas's own size"
5081+ );
4945 }5082 }
4946 }5083 }
4947 5084
@@ -5026,18 +5163,27 @@ mod tests {
5026 let file = asset("test_av.mp4");5163 let file = asset("test_av.mp4");
5027 let sources = [(file, 0)];5164 let sources = [(file, 0)];
5028 let segs = [(Some(0), 0., 1.)];5165 let segs = [(Some(0), 0., 1.)];
5029- let derived = crate::AudioSession::open_multi_streams_speed_at(&sources, &segs, &[], &[], None)5166+ let derived =
5030- .expect("open the fixture")5167+ crate::AudioSession::open_multi_streams_speed_at(&sources, &segs, &[], &[], None)
5031- .expect("the fixture has sound")
5032- .0
5033- .sample_rate;
5034- let picked =
5035- crate::AudioSession::open_multi_streams_speed_at(&sources, &segs, &[], &[], Some(32000))
5036 .expect("open the fixture")5168 .expect("open the fixture")
5037 .expect("the fixture has sound")5169 .expect("the fixture has sound")
5038 .05170 .0
5039 .sample_rate;5171 .sample_rate;
5040- assert_ne!(derived, 32000, "a fixture at the picked rate proves nothing");5172+ let picked = crate::AudioSession::open_multi_streams_speed_at(
5173+ &sources,
5174+ &segs,
5175+ &[],
5176+ &[],
5177+ Some(32000),
5178+ )
5179+ .expect("open the fixture")
5180+ .expect("the fixture has sound")
5181+ .0
5182+ .sample_rate;
5183+ assert_ne!(
5184+ derived, 32000,
5185+ "a fixture at the picked rate proves nothing"
5186+ );
5041 assert_eq!(picked, 32000);5187 assert_eq!(picked, 32000);
5042 }5188 }
5043 5189
@@ -5099,7 +5245,8 @@ mod tests {
5099 "an import must not move the project's own canvas size"5245 "an import must not move the project's own canvas size"
5100 );5246 );
5101 assert_eq!(5247 assert_eq!(
5102- session.meta().frame_rate, picked_fps,5248+ session.meta().frame_rate,
5249+ picked_fps,
5103 "an import must not move the project's own rate"5250 "an import must not move the project's own rate"
5104 );5251 );
5105 }5252 }
@@ -5216,9 +5363,11 @@ mod tests {
5216 let zero = PlaybackSession::open_with_audio_stream(&multi, 0).expect("stream 0 opens");5363 let zero = PlaybackSession::open_with_audio_stream(&multi, 0).expect("stream 0 opens");
5217 let one = PlaybackSession::open_with_audio_stream(&multi, 1).expect("stream 1 opens");5364 let one = PlaybackSession::open_with_audio_stream(&multi, 1).expect("stream 1 opens");
5218 let default = PlaybackSession::open(&multi).expect("default open");5365 let default = PlaybackSession::open(&multi).expect("default open");
5219- let (Some(a0), Some(a1), Some(ad)) =5366+ let (Some(a0), Some(a1), Some(ad)) = (
5220- (zero.audio.as_ref(), one.audio.as_ref(), default.audio.as_ref())5367+ zero.audio.as_ref(),
5221- else {5368+ one.audio.as_ref(),
5369+ default.audio.as_ref(),
5370+ ) else {
5222 // No audio device on this machine: nothing further to check --5371 // No audio device on this machine: nothing further to check --
5223 // the device is the machine's business, not this door's.5372 // the device is the machine's business, not this door's.
5224 return;5373 return;
@@ -5226,7 +5375,10 @@ mod tests {
5226 assert_eq!(a0.channels, 2, "stream 0 is the stereo pair");5375 assert_eq!(a0.channels, 2, "stream 0 is the stereo pair");
5227 assert_eq!(a1.channels, 1, "stream 1 is the mono track");5376 assert_eq!(a1.channels, 1, "stream 1 is the mono track");
5228 assert_ne!(a0.channels, a1.channels, "the two streams must differ");5377 assert_ne!(a0.channels, a1.channels, "the two streams must differ");
5229- assert_eq!(ad.channels, a0.channels, "open() still defaults to stream 0");5378+ assert_eq!(
5379+ ad.channels, a0.channels,
5380+ "open() still defaults to stream 0"
5381+ );
5230 }5382 }
5231 5383
5232 /// The bug this regression pins: a preview paused (or scrubbed) to a5384 /// The bug this regression pins: a preview paused (or scrubbed) to a
@@ -5260,7 +5412,10 @@ mod tests {
5260 5412
5261 let fps = on.meta().frame_rate;5413 let fps = on.meta().frame_rate;
5262 let clip0_len = on.lane_clips(Lane::V1)[0].len();5414 let clip0_len = on.lane_clips(Lane::V1)[0].len();
5263- assert!(clip0_len > window, "the fixture needs to outlast the window");5415+ assert!(
5416+ clip0_len > window,
5417+ "the fixture needs to outlast the window"
5418+ );
5264 let mid_of_window = clip0_len - window / 2;5419 let mid_of_window = clip0_len - window / 2;
5265 let t = f64::from(mid_of_window) / fps;5420 let t = f64::from(mid_of_window) / fps;
5266 5421
@@ -5276,7 +5431,10 @@ mod tests {
5276 if let Some(f) = s.try_frame() {5431 if let Some(f) = s.try_frame() {
5277 return f;5432 return f;
5278 }5433 }
5279- assert!(std::time::Instant::now() < deadline, "no frame within 20s of the seek");5434+ assert!(
5435+ std::time::Instant::now() < deadline,
5436+ "no frame within 20s of the seek"
5437+ );
5280 std::thread::sleep(std::time::Duration::from_millis(10));5438 std::thread::sleep(std::time::Duration::from_millis(10));
5281 }5439 }
5282 };5440 };
@@ -5337,11 +5495,21 @@ mod tests {
5337 scale: 1.2,5495 scale: 1.2,
5338 ..Default::default()5496 ..Default::default()
5339 };5497 };
5340- assert!(s.set_transform_live(clip.0, clip.1, Some(params)), "the edit took");5498+ assert!(
5499+ s.set_transform_live(clip.0, clip.1, Some(params)),
5500+ "the edit took"
5501+ );
5341 let next = poll(&mut s);5502 let next = poll(&mut s);
5342 5503
5343- assert_eq!(before, s.restarts(), "a live transform edit must reuse the worker");5504+ assert_eq!(
5344- assert_eq!(next.index, first.index, "paused: same timeline position before and after");5505+ before,
5506+ s.restarts(),
5507+ "a live transform edit must reuse the worker"
5508+ );
5509+ assert_eq!(
5510+ next.index, first.index,
5511+ "paused: same timeline position before and after"
5512+ );
5345 }5513 }
5346 5514
5347 /// A rate undo lands the picture where the playhead is, in the rate that5515 /// A rate undo lands the picture where the playhead is, in the rate that
@@ -5413,4 +5581,3 @@ mod tests {
5413 );5581 );
5414 }5582 }
5415 }5583 }
5416-