From 8b784e6ace779fce2ce3c4e64230619a1ef3d2bb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 30 Sep 2026 15:57:54 +0300 Subject: [PATCH] fix(player): one owner for the monitoring level, so a preview close cannot undo it The level is the *window's*, but it was pushed at whichever session happened to be on screen (`apply_volume` went through `active_session()`, preview-or-timeline). Open a preview, press M, press Esc: the preview is quiet, the notice goes, and the timeline plays at the level from before the preview -- usually full -- while the control still reads "Muted". Shown level and heard level disagreed and nothing said so. `open_preview` pushed at the preview directly rather than through the one door, which is the same defect wearing a different hat. The app keeps exactly one copy of the level (`Player::volume`, a setting of the window and not of any session) and every session is a follower of it. The engine cannot own it: a preview and the timeline are two sessions with two devices, and the level has to outlive both, so the owner is above them. * `push_gain(gain, sessions)`: the push, over every session handed in. 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. * `apply_volume` is a call to it with both session slots; `open_preview` and `close_preview` call it, so no door can swap the session on screen without telling the new one what the window is showing. Witnesses: `a_preview_close_leaves_the_timeline_at_the_level_the_window_shows` round-trips the level through the real push and reads it back out of the device (`PlaybackSession::gain`), with a control that a session outside the push is untouched. `the_window_level_is_pushed_at_every_session_and_on_every_swap` pins the wiring the first cannot execute; reverting the push to the active session alone fails it. --- crates/app/src/main.rs | 16 +- crates/app/src/player/library.rs | 27 ++- crates/app/src/player/transport.rs | 45 +++- crates/app/src/tests/media.rs | 114 +++++++++- crates/app/src/tests/mod.rs | 61 ++--- crates/engine/src/playback.rs | 353 +++++++++++++++++++++-------- 6 files changed, 457 insertions(+), 159 deletions(-) diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index 0656641..9317443 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -68,11 +68,11 @@ use engine::transform::TransformParams; use engine::{Clip, Codec, ExportHandle, Frame, MediaBitrate, PlaybackSession}; use gpui::{ AnyElement, App, Application, Bounds, ClickEvent, Context, Corners, CursorStyle, Div, - DragMoveEvent, FocusHandle, KeyDownEvent, MouseButton, MouseDownEvent, - MouseExitEvent, MouseMoveEvent, MouseUpEvent, PathBuilder, Pixels, Point, RenderImage, - ScrollDelta, ScrollHandle, ScrollWheelEvent, SharedString, Size, Stateful, TextAlign, - TitlebarOptions, Window, WindowBounds, WindowOptions, canvas, div, point, prelude::*, px, - relative, rgb, rgba, size, + DragMoveEvent, FocusHandle, KeyDownEvent, MouseButton, MouseDownEvent, MouseExitEvent, + MouseMoveEvent, MouseUpEvent, PathBuilder, Pixels, Point, RenderImage, ScrollDelta, + ScrollHandle, ScrollWheelEvent, SharedString, Size, Stateful, TextAlign, TitlebarOptions, + Window, WindowBounds, WindowOptions, canvas, div, point, prelude::*, px, relative, rgb, rgba, + size, }; struct Player { @@ -535,7 +535,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 6a5de06..7dc6618 100644 --- a/crates/app/src/player/library.rs +++ b/crates/app/src/player/library.rs @@ -177,9 +177,7 @@ impl Player { self.reset_after_reseek(); } Err(e) => self.notify_user(format!("NO VISUALIZER — {e}").into()), - Ok(false) => { - self.notify_user("NO VISUALIZER — that clip could not be placed".into()) - } + Ok(false) => self.notify_user("NO VISUALIZER — that clip could not be placed".into()), } cx.notify(); } @@ -453,10 +451,7 @@ impl Player { { true => { self.close_session(); - format!( - "REMOVED {} — the library is empty", - file_name(path) - ) + format!("REMOVED {} — the library is empty", file_name(path)) } // The undo stack goes with it (`Project::remove_source`): // said here, because a `z` that does nothing afterwards @@ -673,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!( @@ -716,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 @@ -1196,9 +1203,7 @@ impl Player { .count(); let text = match (on, ready, making) { (false, ..) => "PROXIES OFF — the films themselves are what play".to_string(), - (true, 0, 0) => { - "PROXIES ON — no film here has one".to_string() - } + (true, 0, 0) => "PROXIES ON — no film here has one".to_string(), (true, 0, n) => format!("PROXIES ON — {n} still being made"), (true, n, 0) => format!("PROXIES ON — cutting on {n}"), (true, n, m) => format!("PROXIES ON — cutting on {n}, {m} still being made"), 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 ce51f9e..8ad8d78 100644 --- a/crates/app/src/tests/mod.rs +++ b/crates/app/src/tests/mod.rs @@ -10,55 +10,56 @@ mod media; mod view; use super::{ - active_lane, auto_bps, band_label, bitrate_detail, clipboard_after_remove, color_snap, - containers, destructive, enable, enable_lane, envelope, eq_card_w, eq_freq, eq_freq_label, - eq_graph_h, eq_spectrum, eq_x, eq_y, estimated_bytes, export_path, export_settings, - format_refusal, fps_choices, fps_label, frac_along, frac_down, frame_at, frame_rate_ladder, - histogram, inserted_band, is_project, keymap, keys_rows, keys_rows_matching, lane_items, - lanes_h, marked, menu_at, menu_items, menu_rows_h, next_container, normalise, nothing_to_play, - notice_tone, panel_h, parse_budget, project_path, proxies_to_start, push_notice, px_below, - range_word, rate_label, retarget, row_enable, row_items, scrub_due, secs_label, should_resync, + ACCENT_PRIMARY, AUDIO_KBPS, BENCH_ITEMS, BG_RAISED, BPS_COARSE, BPS_FINE, BPS_MAX, BPS_MIN, + COLOR_BANDS, COLOR_BAR_W, COLOR_STEP, COLOR_W, CONTROL_H, Clip, ColorEdit, Ctx, + DEFAULT_AUDIO_KBPS, EQ_BANDS_MAX, EQ_CURVE_STEPS, EQ_FFT, EQ_FREQ_HIGH, EQ_FREQ_LOW, + EQ_FREQ_STEP, EQ_GAIN_LIMIT, EQ_GRAPH_H, EQ_HANDLE, EQ_Q_HIGH, EQ_Q_LOW, EQ_Q_STEP, + EQ_SPECTRUM_DB, EQ_TICKS, EQ_W_MAX, ESCAPE, EXPORT_DONE, EXPORT_MOMENT_H, Enable, EncoderSeat, + FORMATS, Format, HEADER_H, HIST_BINS, HIST_H, HIST_SAMPLES, HIT_MIN, KEYS_ROW_H, KEYS_W, + KeyRow, LABEL_H, LANE_H, LANES_MAX, LATE_RESYNC, LIBRARY_MAX_W, LIBRARY_MIN_W, Lane, MB_FLOOR, + MENU_ITEMS, MENU_PAD, MENU_ROW_H, MENU_W, NO_FILE, NOTICES_MAX, NumberEdit, OVERLAID, PANEL_H, + RESYNC_GAP, ROW_ITEMS, RULER_HIT_H, RowCtx, RowItem, SCROLL_NOTCH_SHARE, SILENCE_ROWS, + SOURCE_TINTS, SPEED_PRESETS, SPEED_STEP, STATUS_ERROR, STATUS_SUCCESS, STATUS_WARNING, + SUB_PLAN_CHARS, Source, Speed, StreamInfo, SubPickKey, TIMELINE_SHARE, Transport, VOLUME_W, + VizSlot, Volume, WAVE_BPS, WAVE_COL, WAVE_COLS_MAX, Wave, ZOOM_MIN_FRAMES, active_lane, + auto_bps, band_label, bitrate_detail, clipboard_after_remove, color_snap, containers, + destructive, enable, enable_lane, envelope, eq_card_w, eq_freq, eq_freq_label, eq_graph_h, + eq_spectrum, eq_x, eq_y, estimated_bytes, export_path, export_settings, format_refusal, + fps_choices, fps_label, frac_along, frac_down, frame_at, frame_rate_ladder, histogram, + inserted_band, is_project, keymap, keys_rows, keys_rows_matching, lane_items, lanes_h, marked, + menu_at, menu_items, menu_rows_h, next_container, normalise, nothing_to_play, notice_tone, + panel_h, parse_budget, project_path, proxies_to_start, push_notice, px_below, range_word, + rate_label, retarget, row_enable, row_items, scrub_due, secs_label, should_resync, silence_rate, size_label, snap_cue, snap_marks, snapped, source_tint, span_partner, speed_at, sub_pick_after_removal, sub_pick_after_restore, subtitle_plan, timecode, timeline_fixed_h, tip_may_paint, transport, typed, unseen_paths, unseen_sources, viz_held_paint, whole_take, - window_title, Clip, ColorEdit, Ctx, Enable, EncoderSeat, Format, KeyRow, Lane, NumberEdit, - RowCtx, RowItem, Source, Speed, StreamInfo, SubPickKey, Transport, VizSlot, Volume, Wave, - ACCENT_PRIMARY, AUDIO_KBPS, BENCH_ITEMS, BG_RAISED, BPS_COARSE, BPS_FINE, BPS_MAX, BPS_MIN, - COLOR_BANDS, COLOR_BAR_W, COLOR_STEP, COLOR_W, CONTROL_H, DEFAULT_AUDIO_KBPS, EQ_BANDS_MAX, - EQ_CURVE_STEPS, EQ_FFT, EQ_FREQ_HIGH, EQ_FREQ_LOW, EQ_FREQ_STEP, EQ_GAIN_LIMIT, EQ_GRAPH_H, - EQ_HANDLE, EQ_Q_HIGH, EQ_Q_LOW, EQ_Q_STEP, EQ_SPECTRUM_DB, EQ_TICKS, EQ_W_MAX, ESCAPE, - EXPORT_DONE, EXPORT_MOMENT_H, FORMATS, HEADER_H, HIST_BINS, HIST_H, HIST_SAMPLES, HIT_MIN, - KEYS_ROW_H, KEYS_W, LABEL_H, LANES_MAX, LANE_H, LATE_RESYNC, LIBRARY_MAX_W, LIBRARY_MIN_W, - MB_FLOOR, MENU_ITEMS, MENU_PAD, MENU_ROW_H, MENU_W, NOTICES_MAX, NO_FILE, OVERLAID, PANEL_H, - RESYNC_GAP, ROW_ITEMS, RULER_HIT_H, SCROLL_NOTCH_SHARE, SILENCE_ROWS, SOURCE_TINTS, - SPEED_PRESETS, SPEED_STEP, STATUS_ERROR, STATUS_SUCCESS, STATUS_WARNING, SUB_PLAN_CHARS, - TIMELINE_SHARE, VOLUME_W, WAVE_BPS, WAVE_COL, WAVE_COLS_MAX, ZOOM_MIN_FRAMES, + window_title, }; use super::{ - arrival, audio_rate_choices, av1_hw_warning, clip_width, clock, encoder_choices, encoder_label, + ActionId, Choice, EDGE_W, ETA_SPAN, Edge, FITS, FRAME_RATES, IMPORT_STALL, Import, ImportStage, + Landing, LaneKind, PPS_DEFAULT, PPS_MIN, Preset, RESOLUTIONS, Repeat, SAMPLE_RATES, SEEK_STALL, + Scale, ScanKey, ScanPlan, SilenceScan, SubClip, View, ZOOM_OUT_MARGIN, ZOOM_STEP, arrival, + audio_rate_choices, av1_hw_warning, clip_width, clock, encoder_choices, encoder_label, eta_secs, file_name, file_uri, fit_choices, frames_of_us, full_scan_key, import_line, landing, lane_refuses, launch_queue, library_rows, live_idx, next_fit, next_resolution, note_progress, pending_fps_choices, pending_resolution_choices, px_along, read_ahead, repeats, resolution_choices, resolution_ladder, sample_rate_choices, scan_plan, seek_line, silence_cached, silence_line, slice_whole_levels, source_secs, stash_or_write, tone_choices, - tone_label, trimmed_clip, trimmed_sub, trims, unscannable, unusable, ActionId, Choice, Edge, - Import, ImportStage, Landing, LaneKind, Preset, Repeat, Scale, ScanKey, ScanPlan, SilenceScan, - SubClip, View, EDGE_W, ETA_SPAN, FITS, FRAME_RATES, IMPORT_STALL, PPS_DEFAULT, PPS_MIN, - RESOLUTIONS, SAMPLE_RATES, SEEK_STALL, ZOOM_OUT_MARGIN, ZOOM_STEP, + tone_label, trimmed_clip, trimmed_sub, trims, unscannable, unusable, }; use super::{ - carries_subtitles, cue_box, cues_at, file_tint, is_subtitle, lang_human, sub_bottom, - sub_pick_name, subtitle_detail, subtitle_notice, subtitle_rows, subtitle_tail, - subtitle_toggle_notice, walk_subtitles, Subs, SUB_BOTTOM, SUB_CUE_MIN_W, SUB_LINE_H, SUB_TEXT, + SUB_BOTTOM, SUB_CUE_MIN_W, SUB_LINE_H, SUB_TEXT, Subs, carries_subtitles, cue_box, cues_at, + file_tint, is_subtitle, lang_human, sub_bottom, sub_pick_name, subtitle_detail, + subtitle_notice, subtitle_rows, subtitle_tail, subtitle_toggle_notice, walk_subtitles, }; use engine::PlaybackSession; use engine::scale::FitPolicy; -use gpui::{point, px, size, Bounds, Pixels}; +use gpui::{Bounds, Pixels, point, px, size}; use std::collections::HashMap; @@ -76,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/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