diff --git a/crates/app/src/keymap.rs b/crates/app/src/keymap.rs index 4d7da28..12c454a 100644 --- a/crates/app/src/keymap.rs +++ b/crates/app/src/keymap.rs @@ -46,13 +46,16 @@ pub enum ActionId { Cut, Delete, Undo, + ToggleMute, + VolumeUp, + VolumeDown, CancelExport, } impl ActionId { /// Display order everywhere -- the editor lists them in it and /// [`Keymap::defaults`] binds them in it. - pub const ALL: [ActionId; 9] = [ + pub const ALL: [ActionId; 12] = [ ActionId::Play, ActionId::Export, ActionId::Save, @@ -61,6 +64,9 @@ impl ActionId { ActionId::Cut, ActionId::Delete, ActionId::Undo, + ActionId::ToggleMute, + ActionId::VolumeUp, + ActionId::VolumeDown, ActionId::CancelExport, ]; @@ -75,6 +81,9 @@ impl ActionId { ActionId::Cut => "Cut", ActionId::Delete => "Delete", ActionId::Undo => "Undo", + ActionId::ToggleMute => "Mute / Unmute", + ActionId::VolumeUp => "Volume up", + ActionId::VolumeDown => "Volume down", ActionId::CancelExport => "Cancel export", } } @@ -91,6 +100,9 @@ impl ActionId { ActionId::Cut => "cut", ActionId::Delete => "delete", ActionId::Undo => "undo", + ActionId::ToggleMute => "toggle-mute", + ActionId::VolumeUp => "volume-up", + ActionId::VolumeDown => "volume-down", ActionId::CancelExport => "cancel-export", } } @@ -199,6 +211,12 @@ impl Keymap { b(ActionId::Delete, "delete", false), b(ActionId::Undo, "z", false), b(ActionId::Undo, "z", true), + b(ActionId::ToggleMute, "m", false), + // The unshifted pair, which is what gpui reports for those two + // keys ("=" and "-", platform.rs:862): the volume keys every + // player has, without asking for shift to make the "+". + b(ActionId::VolumeUp, "=", false), + b(ActionId::VolumeDown, "-", false), b(ActionId::CancelExport, "escape", false), ], } @@ -425,7 +443,7 @@ mod tests { #[test] fn every_default_stroke_reaches_its_action() { let k = Keymap::defaults(); - assert_eq!(k.entries().len(), 11); + assert_eq!(k.entries().len(), 14); assert_eq!(k.lookup("space", false), Some(ActionId::Play)); assert_eq!(k.lookup("e", false), Some(ActionId::Export)); assert_eq!(k.lookup("s", true), Some(ActionId::Save)); @@ -436,6 +454,12 @@ mod tests { assert_eq!(k.lookup("delete", false), Some(ActionId::Delete)); assert_eq!(k.lookup("z", false), Some(ActionId::Undo)); assert_eq!(k.lookup("z", true), Some(ActionId::Undo)); + assert_eq!(k.lookup("m", false), Some(ActionId::ToggleMute)); + // The volume pair is the unshifted one, so neither needs a modifier + // and neither is the "+" gpui reports for shift+=. + assert_eq!(k.lookup("=", false), Some(ActionId::VolumeUp)); + assert_eq!(k.lookup("-", false), Some(ActionId::VolumeDown)); + assert_eq!(k.lookup("+", false), None); assert_eq!(k.lookup("escape", false), Some(ActionId::CancelExport)); // The modifier is half the chord: ctrl+e is not e. assert_eq!(k.lookup("e", true), None); @@ -564,7 +588,7 @@ mod tests { ); // The label is the editor's column, and never the file's word for it. assert_eq!(ActionId::CancelExport.label(), "Cancel export"); - assert_eq!(ActionId::ALL.len(), 9); + assert_eq!(ActionId::ALL.len(), 12); } #[test] diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index e0fe874..55cde5e 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -8,6 +8,7 @@ use std::rc::Rc; use std::sync::Arc; use std::time::{Duration, Instant}; +use engine::export::ExportSettings; use engine::{Clip, ExportHandle, Frame, PlaybackSession}; use gpui::{ AnyElement, App, Application, Bounds, ClickEvent, Context, FocusHandle, KeyDownEvent, @@ -59,6 +60,10 @@ const TIME_W: f32 = 200.; /// 360 px tall window. The rows are click targets, so `HIT_MIN` binds them too. const KEYS_W: f32 = 320.; const KEYS_ROW_H: f32 = HIT_MIN; +/// How much of the row list is on screen at once; past this it scrolls. What +/// keeps the card inside the smallest window no matter how many actions the +/// editor grows -- ten rows fit here, and the eleventh is a scroll away. +const KEYS_ROWS_H: f32 = 10. * KEYS_ROW_H; /// The one key name this file still spells out, and gpui's spelling of it: it /// is the way out of a capture and out of the overlay, and both have to work @@ -66,6 +71,68 @@ const KEYS_ROW_H: f32 = HIT_MIN; /// through the keymap to find it. const ESCAPE: &str = "escape"; +/// What the monitoring output is set to. Two things, not one: the level the +/// user picked, and whether it is being held silent -- so unmuting comes back +/// to the level rather than to a guess. +/// +/// The level counts steps rather than carrying an `f32`, because 5% at a time +/// down and back up again through a float would not land on the number it +/// started from, and the label would eventually read `79%`. +/// +/// Volume and mute stay independent on purpose: turning the level down while +/// muted must not be what makes sound come out. Only the mute key unmutes, and +/// the button says both things at once ("Muted 80%") so neither is a surprise. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +struct Volume { + steps: u8, + muted: bool, +} + +impl Volume { + /// 5% a press: twenty of them across the range. + const MAX_STEPS: u8 = 20; + + /// What the device is set to: mute wins, and the level is what it returns + /// to. `0.0..=1.0`, which is the range the plugin's ABI accepts. + fn gain(self) -> f32 { + if self.muted { + 0. + } else { + f32::from(self.steps) / f32::from(Self::MAX_STEPS) + } + } + + /// One press up or down, clamped at both ends -- saturating, so the count + /// cannot wrap past silence into full volume. + fn step(&mut self, up: bool) { + self.steps = if up { + self.steps.saturating_add(1).min(Self::MAX_STEPS) + } else { + self.steps.saturating_sub(1) + }; + } + + /// What the button reads. The level shows while muted too: it is what the + /// next press of the mute key brings back. + fn label(self) -> String { + let percent = u32::from(self.steps) * 100 / u32::from(Self::MAX_STEPS); + if self.muted { + format!("Muted {percent}%") + } else { + format!("Vol {percent}%") + } + } +} + +impl Default for Volume { + fn default() -> Self { + Self { + steps: Self::MAX_STEPS, + muted: false, + } + } +} + struct Player { /// The timeline, once there is one. A run with no file opens without it and /// waits: the first media import or project load is what fills it, and @@ -116,10 +183,26 @@ struct Player { /// Which stroke means what, and what every shortcut on screen is called. /// The one place either question is answered. keymap: Keymap, + /// How loud the monitoring is, and whether it is muted. Lives here rather + /// 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. + volume: Volume, /// The keybindings overlay is up. While it is, it owns the keyboard and the /// pointer: a stroke or a click meant for a row must not also cut the /// timeline. keys_open: bool, + /// The export options card is up: what the export action opens now, so + /// nothing is written until the card's own button says so. One card at a + /// time -- opening either closes the other, since both are the whole window + /// and two stacked scrims say nothing about which one is listening. + export_open: bool, + /// Which quality row the card has picked, and the megabits typed against + /// the custom one. Kept across closes, so a second export offers what the + /// first one chose. + quality: Quality, + custom_mbps: u32, /// The action whose row is waiting for a stroke. The next key that is /// neither escape nor a lone modifier becomes the whole of what reaches it. rebinding: Option, @@ -311,6 +394,9 @@ impl Player { Ok(session) => { self.fps = session.meta().frame_rate; self.session = Some(session); + // A fresh session comes up at full volume; the player's own + // setting outlives the file, so it is pushed at every new one. + self.apply_volume(); self.export_path = export_path(path); self.project_path = project_path(path); self.name = file_name(path).into(); @@ -365,6 +451,7 @@ impl Player { // media: that is the only place an export has ever landed. self.export_path = export_path(&session.sources()[0]); self.session = Some(session); + self.apply_volume(); self.project_path = path.to_path_buf(); self.name = file_name(path).into(); // A copied clip names its source by index, which means a @@ -461,6 +548,26 @@ 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. + fn apply_volume(&self) { + if let Some(session) = &self.session { + session.set_gain(self.volume.gain()); + } + } + + /// The mute key and the two volume keys, and the click on the button. The + /// picture is not touched: silencing the output is not pausing it, so the + /// clock -- which the device still drives -- runs straight through. + fn set_volume(&mut self, change: impl FnOnce(&mut Volume), cx: &mut Context) { + change(&mut self.volume); + self.apply_volume(); + cx.notify(); + } + fn toggle_or_restart(&mut self, cx: &mut Context) { if self.exporting().is_some() { return; @@ -483,24 +590,82 @@ impl Player { self.export.as_ref().filter(|_| !self.cancelling) } - /// Writes the edit list out beside the source. Playback stops first: the - /// exporter opens its own decoder -- and, on the hardware path, an encoder -- - /// so a running player would only compete with it for the GPU. A cancelled - /// export still winding down holds this off for the frame it takes to - /// notice, which is what keeps its `remove_file` off the new output. - fn start_export(&mut self, cx: &mut Context) { + /// What the export action does now: opens the card, which is where the + /// quality, the destination and the decision to write at all are. Nothing + /// is encoded until the button in it is pressed. + fn open_export(&mut self, cx: &mut Context) { if self.export.is_some() { return; } - // Nothing to write out, and a refusal rather than a silent button: the + // Nothing to write out, and a refusal rather than a card about it: the // window is empty and the export path is not even chosen yet. + if self.session.is_none() { + self.notice = Some("NOTHING TO EXPORT — open a file first".into()); + cx.notify(); + return; + } + self.export_open = true; + // One card at a time, and a waiting row must not outlive the card it + // was waiting in. + self.keys_open = false; + self.rebinding = None; + cx.notify(); + } + + /// The card's Destination row: the desktop's save dialog, on a background + /// thread like the import chooser -- the user may sit in it and the window + /// behind must not freeze. No chooser at all leaves the default path, which + /// is what the refusal says. + fn pick_destination(&mut self, cx: &mut Context) { + let default = self.export_path.clone(); + let picked = cx + .background_executor() + .spawn(async move { pick_save(&default) }); + cx.spawn(async move |this, cx| { + let picked = picked.await; + this.update(cx, |this, cx| { + // The dialog outlives the card: an export started meanwhile + // took the old path and its notice must name what it wrote. + if this.export.is_some() { + return; + } + match picked { + Ok(Some(path)) => this.export_path = path, + // Cancelled: the default stands, as it did before. + Ok(None) => {} + Err(text) => { + eprintln!("{text}"); + this.notice = Some(text.into()); + } + } + cx.notify(); + }) + .ok(); + }) + .detach(); + } + + /// Writes the edit list out, at the settings the card was left at. Playback + /// stops first: the exporter opens its own decoder -- and, on the hardware + /// path, an encoder -- so a running player would only compete with it for + /// the GPU. A cancelled export still winding down holds this off for the + /// frame it takes to notice, which is what keeps its `remove_file` off the + /// new output. + fn start_export(&mut self, cx: &mut Context) { + if self.export.is_some() { + return; + } + let settings = export_settings(self.quality, self.custom_mbps); let Some(session) = &mut self.session else { self.notice = Some("NOTHING TO EXPORT — open a file first".into()); cx.notify(); return; }; session.pause(); - self.export = Some(session.export_to(&self.export_path)); + self.export = Some(session.export_to_with(&self.export_path, &settings)); + // The card has been answered; the progress line takes the panel from + // here, and it is the running export's escape that matters now. + self.export_open = false; cx.notify(); } @@ -632,15 +797,39 @@ impl Render for Player { } return; } + // The export card owns it the same way, and for the same + // reason. Escape closes it -- nothing has been written yet, so + // there is nothing here to cancel -- and a digit is the custom + // bitrate being typed: the card has no text field (nothing in + // it takes focus, ledger:182) so this listener is its input, + // exactly as it is a waiting row's. + if this.export_open { + if key == ESCAPE { + this.export_open = false; + } else if let Ok(digit) = key.parse::() { + this.custom_mbps = push_digit(this.custom_mbps, digit); + this.quality = Quality::Custom; + } else if key == "backspace" { + this.custom_mbps /= 10; + this.quality = Quality::Custom; + } + cx.notify(); + return; + } match action { Some(ActionId::Play) => this.toggle_or_restart(cx), - Some(ActionId::Export) => this.start_export(cx), + Some(ActionId::Export) => this.open_export(cx), Some(ActionId::Save) => this.save_project(cx), Some(ActionId::Copy) => this.copy_selected(), Some(ActionId::Paste) => this.paste(cx), Some(ActionId::Cut) => this.cut(cx), Some(ActionId::Delete) => this.delete_selected(cx), Some(ActionId::Undo) => this.undo(cx), + Some(ActionId::ToggleMute) => { + this.set_volume(|volume| volume.muted = !volume.muted, cx) + } + Some(ActionId::VolumeUp) => this.set_volume(|volume| volume.step(true), cx), + Some(ActionId::VolumeDown) => this.set_volume(|volume| volume.step(false), cx), // Nothing to cancel while nothing is exporting. Some(ActionId::CancelExport) | None => {} } @@ -653,8 +842,10 @@ impl Render for Player { // The overlay owns the pointer as well as the keyboard, and a // drop is a click the scrim cannot swallow: gpui delivers it to // the root's hitbox, which is under the scrim but is not a - // sibling it can stop. - if this.keys_open { + // sibling it can stop. The export card is over the timeline for + // the same reason: importing under it would change the very + // edit list the card is about to write out. + if this.keys_open || this.export_open { return; } for path in paths.paths() { @@ -738,8 +929,10 @@ impl Render for Player { // the picture nothing the rest of the time. .children(self.notice_bar(cx)) .child(self.panel(position, duration, playing, cx)) - // Last, so it is over everything -- it takes no room in the column. + // Last, so they are over everything -- they take no room in the + // column, and only one of the two is ever up. .children(self.keys_overlay(cx)) + .children(self.export_card(cx)) } } @@ -839,6 +1032,24 @@ impl Player { live && self.selected.is_some(), cx.listener(|this, _: &ClickEvent, _, cx| this.delete_selected(cx)), )) + // With the transport, not the edit group: it changes what + // the file sounds like, never what it is. Reads as its own + // state, so muted is legible without a tooltip. + .child(control( + "volume", + None, + self.volume.label(), + format!( + "{} mutes · {} louder · {} quieter", + key(ActionId::ToggleMute), + key(ActionId::VolumeUp), + key(ActionId::VolumeDown) + ), + live, + cx.listener(|this, _: &ClickEvent, _, cx| { + this.set_volume(|volume| volume.muted = !volume.muted, cx) + }), + )) .child(separator()) .child(control( "import", @@ -853,11 +1064,11 @@ impl Player { None, "Export", format!( - "{} — writes the timeline out beside the source", + "{} — quality and destination, then writes the timeline out", key(ActionId::Export) ), live && self.export.is_none(), - cx.listener(|this, _: &ClickEvent, _, cx| this.start_export(cx)), + cx.listener(|this, _: &ClickEvent, _, cx| this.open_export(cx)), )) .child(control( "save", @@ -879,6 +1090,8 @@ impl Player { cx.listener(|this, _: &ClickEvent, _, cx| { this.keys_open = !this.keys_open; this.rebinding = None; + // One card at a time, both ways round. + this.export_open = false; cx.notify(); }), )), @@ -1070,9 +1283,9 @@ impl Player { // two, and the notice bar it would otherwise appear in is // under the scrim. // - // ponytail: a refusal long enough to wrap to three lines - // pushes the card past a 360 px tall window. The upgrade - // path is a scrolling row list, not a shorter message. + // The row list below is capped and scrolls, so neither a + // wrapped refusal here nor another action added to `ALL` + // can push the card past a 360 px window any more. .child( div() .flex_none() @@ -1085,7 +1298,146 @@ impl Player { .unwrap_or_else(|| "click a row, then press a key".into()), ), ) - .children(rows), + // Capped and scrolling rather than as tall as the action + // list happens to be: the list grows with the editor, + // the smallest window does not. + .child( + div() + .id("keys-rows") + .flex() + .flex_col() + .gap(px(2.)) + .max_h(px(KEYS_ROWS_H)) + .overflow_y_scroll() + .children(rows), + ), + ), + ) + } + + /// What an export is going to be, before there is one: the destination, the + /// quality rows, and the two things that are not a choice at all. The same + /// scrim, width and row shape as the keybindings overlay -- two cards of + /// different builds over one window read as two different programs -- and + /// the same plain divs, so the root keeps the keyboard and a typed digit + /// reaches the custom row. + fn export_card(&self, cx: &mut Context) -> Option { + if !self.export_open { + return None; + } + let row = |id: (&'static str, usize)| { + div() + .id(id) + .flex() + // The floor, not the height: the destination's path wraps on a + // long name and must not paint over the row under it. + .min_h(px(KEYS_ROW_H)) + .items_center() + .justify_between() + .gap(px(12.)) + .px(px(6.)) + .rounded(px(3.)) + .cursor_pointer() + .hover(|s| s.bg(rgb(HOVER))) + }; + let rows: Vec<_> = Quality::ALL + .into_iter() + .enumerate() + .map(|(i, quality)| { + row(("quality", i)) + .when(self.quality == quality, |d| d.bg(rgb(SELECTED))) + .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + this.quality = quality; + cx.notify(); + })) + .child(quality.label()) + .child( + div() + .text_size(px(11.)) + .text_color(rgb(INK_DIM)) + .child(quality.detail(self.custom_mbps)), + ) + }) + .collect(); + Some( + div() + .absolute() + .inset_0() + .flex() + .justify_center() + .items_center() + .bg(rgba(0x101010cc)) + .on_mouse_down(MouseButton::Left, |_: &MouseDownEvent, _, cx| { + cx.stop_propagation() + }) + .child( + div() + .w(px(KEYS_W)) + .flex() + .flex_col() + .gap(px(2.)) + .p(px(12.)) + .rounded(px(6.)) + .bg(rgb(SURFACE)) + .child(div().flex_none().px(px(6.)).child("Export")) + // The status line, where a refusal from the save dialog + // lands: the notice bar it would otherwise take is under + // the scrim. + .child( + div() + .flex_none() + .px(px(6.)) + .text_size(px(11.)) + .text_color(rgb(INK_DIM)) + .child(self.notice.clone().unwrap_or_else(|| { + "pick a quality, then Export — esc closes".into() + })), + ) + .child( + row(("destination", 0)) + .on_click(cx.listener(|this, _: &ClickEvent, _, cx| { + this.pick_destination(cx) + })) + .child("Destination") + .child( + div() + .text_size(px(11.)) + .text_color(rgb(INK_DIM)) + .child(file_name(&self.export_path)), + ), + ) + .children(rows) + // Not offered, so said: these are what this program can + // write, and a menu of one is a lie about the other + // entries. `moov` last is the muxer's own shape -- the + // file is playable only once it is finished. + .child( + div() + .flex_none() + .px(px(6.)) + .text_size(px(11.)) + .text_color(rgb(INK_DIM)) + .child("H.264 · MP4 · moov at end"), + ) + .child( + div() + .id("export-confirm") + .mt(px(4.)) + .flex() + .h(px(CONTROL_H)) + .items_center() + .justify_center() + .rounded(px(3.)) + .bg(rgb(SELECTED)) + .cursor_pointer() + .hover(|s| s.bg(rgb(HOVER))) + .on_click( + cx.listener(|this, _: &ClickEvent, _, cx| { + this.start_export(cx) + }), + ) + .child("Export"), + ), ), ) } @@ -1147,31 +1499,62 @@ fn scrub_due(target: u32, last_target: u32, since: Duration) -> bool { target != last_target && since >= SCRUB_GAP } -/// The desktop's own file choosers, best first. Asked for by name because gpui -/// 0.2 has no file dialog of its own and none of these is worth a dependency. -const PICKERS: [(&str, &[&str]); 2] = [ - ("zenity", &["--file-selection", "--title=edith — import"]), - ("kdialog", &["--getopenfilename"]), -]; - -/// Runs the first chooser that is installed. `Ok(None)` is a cancelled dialog; -/// the error is for a machine with no chooser at all, which still has the drop -/// target -- the import path that never depended on another program. -fn pick_file() -> Result, &'static str> { - for (bin, args) in PICKERS { +/// Runs the first chooser that is installed. `Some(None)` is a cancelled +/// dialog; `None` is a machine with no chooser at all, and what still works +/// without one differs per dialog, so the caller words that refusal. +/// +/// The desktop's own choosers, asked for by name because gpui 0.2 has no file +/// dialog of its own and none of these is worth a dependency. +fn run_picker(pickers: [(&str, Vec); 2]) -> Option> { + for (bin, args) in pickers { // Not installed: try the next one. Anything else (a cancel, a refusal) // is that chooser's answer and is taken as final. let Ok(out) = std::process::Command::new(bin).args(args).output() else { continue; }; let path = String::from_utf8_lossy(&out.stdout).trim().to_string(); - return Ok((!path.is_empty()).then(|| PathBuf::from(path))); + return Some((!path.is_empty()).then(|| PathBuf::from(path))); } - Err( + None +} + +fn pick_file() -> Result, &'static str> { + run_picker([ + ( + "zenity", + vec!["--file-selection".into(), "--title=edith — import".into()], + ), + ("kdialog", vec!["--getopenfilename".into()]), + ]) + .ok_or( "NO FILE CHOOSER — install zenity or kdialog, or drag the file onto this window to import it", ) } +/// The save-side dialog, opened on where the export would land anyway: with no +/// chooser installed that default is still what gets written, so this refusal +/// costs the export nothing and says so. +fn pick_save(default: &std::path::Path) -> Result, &'static str> { + let default = default.to_string_lossy().into_owned(); + run_picker([ + ( + "zenity", + vec![ + "--file-selection".into(), + // No `--confirm-overwrite`: zenity 4.2 lists it as deprecated + // and does the confirming itself. + "--save".into(), + "--title=edith — export to".into(), + format!("--filename={default}"), + ], + ), + ("kdialog", vec!["--getsavefilename".into(), default]), + ]) + .ok_or( + "NO FILE CHOOSER — install zenity or kdialog to choose where; exporting beside the source", + ) +} + /// Where an export goes: the source path with `.export.mp4` for an extension, /// so it lands beside the original and can never be the original. fn export_path(source: impl Into) -> PathBuf { @@ -1213,6 +1596,81 @@ fn source_tint(source: usize) -> u32 { SOURCE_TINTS[source % SOURCE_TINTS.len()] } +/// What the export card offers, top to bottom. Bitrate is the only thing the +/// encoder actually takes: the codec and the container are what this program +/// can write and nothing else, so the card states them rather than offering +/// them. +#[derive(Clone, Copy, PartialEq, Debug)] +enum Quality { + Auto, + Low, + Medium, + High, + Custom, +} + +impl Quality { + const ALL: [Quality; 5] = [ + Quality::Auto, + Quality::Low, + Quality::Medium, + Quality::High, + Quality::Custom, + ]; + + fn label(self) -> &'static str { + match self { + Quality::Auto => "Auto", + Quality::Low => "Low", + Quality::Medium => "Medium", + Quality::High => "High", + Quality::Custom => "Custom", + } + } + + /// The figure the row stands for, said in the units the row is chosen by. + fn detail(self, custom_mbps: u32) -> String { + match self { + Quality::Auto => "from the picture size and frame rate".to_string(), + Quality::Custom => format!("{custom_mbps} Mbps — type a number, 1–20"), + other => format!( + "{} Mbps", + export_settings(other, 0).bitrate.unwrap_or_default() / 1_000_000 + ), + } + } +} + +/// The card's rows as the engine takes them. `Auto` leaves the bitrate to the +/// exporter, which derives it from the picture; the fixed rows are figures that +/// hold from 720p to 1080p, and a typed one is passed exactly as typed -- the +/// engine clamps every explicit bitrate to 1..20 Mbps (export.rs:290), so this +/// must not clamp it a second time and disagree about where the edge is. +fn export_settings(quality: Quality, custom_mbps: u32) -> ExportSettings { + ExportSettings { + bitrate: match quality { + Quality::Auto => None, + Quality::Low => Some(2_000_000), + Quality::Medium => Some(6_000_000), + Quality::High => Some(12_000_000), + Quality::Custom => Some(u64::from(custom_mbps) * 1_000_000), + }, + // No row of its own: the software pin is for a driver that encodes + // badly, which is a thing about the machine and not about the output -- + // `VE_SW_ENC` already says it, and to the whole run rather than once. + force_sw: false, + } +} + +/// A digit typed against the custom row, appended to what is already there. +/// Refused rather than truncated past two digits: the engine's ceiling is +/// 20 Mbps, so a third digit can only be a mistake, and a silently dropped one +/// would leave the card showing a number nobody typed. +fn push_digit(mbps: u32, digit: u32) -> u32 { + let next = mbps * 10 + digit; + if next <= 99 { next } else { mbps } +} + /// Whether a stroke gets out of a running export. Escape does, whatever /// modifiers are held with it, for the same reason it gets out of a capture and /// out of the overlay: it is this window's way out, and a way out that only @@ -1249,11 +1707,13 @@ fn width_frac(len: f64, total: f64) -> f32 { fn control( id: &'static str, glyph: Option, - label: &'static str, + // Not `&'static str`: the volume button's label is its state. + label: impl Into, shortcut: String, enabled: bool, on_click: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static, ) -> impl IntoElement { + let label = label.into(); let tip: SharedString = format!("{label} — {shortcut}").into(); div() .id(id) @@ -1435,9 +1895,10 @@ fn timecode(t: f64, fps: f64) -> String { #[cfg(test)] mod tests { use super::{ - CONTROL_H, HIT_MIN, KEYS_ROW_H, KEYS_W, LANE_H, RULER_HIT_H, SOURCE_TINTS, SURFACE, - cancels_export, export_path, frac_along, is_bare_modifier, is_project, keymap, - project_path, scrub_due, source_tint, timecode, width_frac, + CONTROL_H, HIT_MIN, KEYS_ROW_H, KEYS_ROWS_H, KEYS_W, LANE_H, Quality, RULER_HIT_H, + SOURCE_TINTS, SURFACE, Volume, cancels_export, export_path, export_settings, frac_along, + is_bare_modifier, is_project, keymap, project_path, push_digit, scrub_due, source_tint, + timecode, width_frac, }; use gpui::{Bounds, Pixels, point, px, size}; use std::time::Duration; @@ -1581,24 +2042,142 @@ mod tests { #[test] fn the_keybindings_card_fits_the_smallest_window() { - // A row per action -- not per binding, which is why the count is - // `ALL` -- under a title and a status line, inside the 640x360 the rest - // of the layout is already sized for. - let rows = keymap::ActionId::ALL.len() as f32; + // The row list is capped and scrolls, so the card's height no longer + // depends on how many actions there are: a title, a status line and the + // viewport, inside the 640x360 the rest of the layout is sized for. let title = 17.; // 13 px text on its own line let status = 28.; // 11 px text, two lines: a refusal wraps - let gaps = (rows + 1.) * 2.; + let gaps = 3. * 2.; let padding = 24.; assert!( - title + status + rows * KEYS_ROW_H + gaps + padding <= 360., + title + status + KEYS_ROWS_H + gaps + padding <= 360., "card too tall" ); + // The cap is only honest if it is the taller list that scrolls, not the + // card that grows: every action must be reachable by scrolling, and + // enough of them visible that the list reads as a list. + assert!( + KEYS_ROWS_H / KEYS_ROW_H >= 8., + "too few rows visible to scan" + ); assert!(KEYS_W <= 640., "card too wide"); // The rows are clickable, so WCAG 2.5.8 binds them like every other // target in this window. assert!(KEYS_ROW_H >= HIT_MIN); } + /// Mute and level are one control with two states, and the whole point is + /// that mute keeps the level: the user gets back what they had, not 100%. + #[test] + fn muting_keeps_the_level_it_comes_back_to() { + let mut volume = Volume::default(); + assert_eq!(volume.gain(), 1.0); + assert_eq!(volume.label(), "Vol 100%"); + + // Four presses down, then muted: the gain is silence but the level is + // still what it was, and the button keeps saying so. + for _ in 0..4 { + volume.step(false); + } + assert_eq!(volume.gain(), 0.8); + volume.muted = true; + assert_eq!(volume.gain(), 0.0); + assert_eq!(volume.label(), "Muted 80%"); + + // Turning it down while muted stays muted -- the one thing a mute + // button must never do is get louder because you asked for quieter. + volume.step(false); + assert_eq!(volume.gain(), 0.0); + assert!(volume.muted); + + // Unmute returns to the level, including the step taken while silent. + volume.muted = false; + assert_eq!(volume.gain(), 0.75); + } + + /// Both ends hold under a key held down: the ABI only accepts `0.0..=1.0`, + /// and a wrapped step count would hand it something else. + #[test] + fn the_volume_stops_at_both_ends() { + let mut volume = Volume::default(); + for _ in 0..40 { + volume.step(true); + } + assert_eq!(volume.gain(), 1.0); + assert_eq!(volume.steps, Volume::MAX_STEPS); + + for _ in 0..40 { + volume.step(false); + } + assert_eq!(volume.gain(), 0.0); + assert_eq!(volume.label(), "Vol 0%"); + + // Silent by the level rather than by the flag is still not muted: the + // button says which, because only one of them survives a step up. + assert!(!volume.muted); + volume.step(true); + assert_eq!(volume.gain(), 0.05); + } + + #[test] + fn a_quality_row_is_the_bitrate_it_promises() { + // Auto is the one row that says nothing: the exporter derives it, and + // a number typed against the custom row must not leak into it. + assert_eq!(export_settings(Quality::Auto, 7).bitrate, None); + assert_eq!(export_settings(Quality::Low, 0).bitrate, Some(2_000_000)); + assert_eq!(export_settings(Quality::Medium, 0).bitrate, Some(6_000_000)); + assert_eq!(export_settings(Quality::High, 0).bitrate, Some(12_000_000)); + // Megabits as typed, and as the row says it back. + assert_eq!(export_settings(Quality::Custom, 7).bitrate, Some(7_000_000)); + assert_eq!(Quality::Low.detail(0), "2 Mbps"); + // Every fixed row sits inside the engine's clamp (export.rs:290), so no + // row can promise a bitrate the exporter silently changes. + for quality in Quality::ALL { + let settings = export_settings(quality, 7); + if let Some(bitrate) = settings.bitrate { + assert!( + (1_000_000..=20_000_000).contains(&bitrate), + "{quality:?} outside the engine clamp" + ); + } + // The software pin is the environment's to set, never a row's. + assert!(!settings.force_sw); + } + } + + #[test] + fn a_typed_bitrate_stops_at_two_digits() { + assert_eq!(push_digit(0, 8), 8); + assert_eq!(push_digit(1, 2), 12); + // A third digit is refused whole: the ceiling is 20 Mbps, so it can + // only be a mistake, and dropping it silently would leave the card + // showing a number nobody typed. + assert_eq!(push_digit(12, 3), 12); + assert_eq!(push_digit(99, 9), 99); + // Never past what the clamp can take back to a real bitrate. + assert!(u64::from(push_digit(99, 9)) * 1_000_000 < u64::from(u32::MAX)); + } + + #[test] + fn the_export_card_fits_the_smallest_window() { + // Same 640x360 floor the keybindings card is measured against: a + // destination row, one row per quality, the fixed-format line and the + // confirm button, under a title and a status line. + let rows = Quality::ALL.len() as f32 + 1.; + let title = 17.; + let status = 28.; + let fixed = 17.; + let gaps = (rows + 3.) * 2.; + let padding = 24.; + assert!( + title + status + rows * KEYS_ROW_H + fixed + CONTROL_H + 4. + gaps + padding <= 360., + "card too tall" + ); + // Clickable rows, so WCAG 2.5.8 binds them as it binds the panel's. + assert!(KEYS_ROW_H >= HIT_MIN); + assert!(CONTROL_H >= HIT_MIN); + } + #[test] fn nothing_clickable_is_smaller_than_the_wcag_minimum() { // Every hit target in the panel, including the scrub strip -- whose bar @@ -1720,6 +2299,9 @@ fn main() { // screen. An empty window has none to wait for. pending_seek: session.is_some(), session, + // Full and unmuted, which is what the session it was just + // handed is already set to: nothing to push at startup. + volume: Volume::default(), // Only ever used with a timeline; 30 keeps the empty // timecode reading in frames rather than in NaN. fps: meta.map_or(30., |meta| meta.frame_rate), @@ -1740,6 +2322,11 @@ fn main() { project_path: project.clone(), keymap: keymap.clone(), keys_open: false, + export_open: false, + // What an export is until someone says otherwise: the + // bitrate the picture asks for. + quality: Quality::Auto, + custom_mbps: 0, rebinding: None, notice: notice.clone().map(SharedString::from), displayed: 0, diff --git a/crates/engine-audio/src/lib.rs b/crates/engine-audio/src/lib.rs index 014ef5a..c6f24b2 100644 --- a/crates/engine-audio/src/lib.rs +++ b/crates/engine-audio/src/lib.rs @@ -91,6 +91,27 @@ impl Ring { } } +/// Multiplies the little-endian f32 samples in `dst` by `gain`, in place. +/// +/// This is how the editor's volume and mute are applied, rather than through +/// the stream's PipeWire volume control: the session manager persists every +/// change to a node's Props into its restore state (measured: WirePlumber +/// writes the bucket ~2 s after the change), so a mute keypress here would +/// become "edith is muted" in the system mixer tomorrow, and a quit while +/// muted would come back muted with nothing in the app to explain it. Scaling +/// the samples is invisible to the daemon, costs one multiply each, and -- +/// because the frames are still consumed and still handed over -- leaves the +/// device clock, and so the whole A/V sync, exactly where it was. +fn scale(dst: &mut [u8], gain: f32) { + if gain == 1.0 { + return; + } + for sample in dst.chunks_exact_mut(4) { + let scaled = f32::from_le_bytes(sample.try_into().unwrap_or([0; 4])) * gain; + sample.copy_from_slice(&scaled.to_le_bytes()); + } +} + /// The consumer half of a flush: drops everything queued, then pops as usual. /// Doing it here rather than in `ao_flush` keeps the ring single-consumer -- /// only the RT thread ever moves `read` -- and means a flush asked for while @@ -132,6 +153,9 @@ struct Shared { /// graph clock keeps ticking while the stream is inactive, and that time /// was never played. resumed: AtomicBool, + /// Output gain as f32 bits, 1.0 until the caller says otherwise. Read once + /// per callback on the RT thread, so it is an atomic rather than a lock. + gain: AtomicU32, underruns: AtomicU64, } @@ -228,6 +252,13 @@ fn run( slice[got * 4..want * 4].fill(0); shared.underruns.fetch_add(1, Ordering::Relaxed); } + // After the fill, so the silence stays silent whatever + // the gain is, and the underrun count keeps meaning + // "the decoder was late" rather than "the user muted". + scale( + &mut slice[..want * 4], + f32::from_bits(shared.gain.load(Ordering::Relaxed)), + ); frames } None => 0, @@ -377,6 +408,7 @@ pub extern "C" fn ao_open(sample_rate: u32, channels: u32) -> *mut c_void { dead: AtomicBool::new(false), flush: AtomicBool::new(false), resumed: AtomicBool::new(false), + gain: AtomicU32::new(1.0f32.to_bits()), underruns: AtomicU64::new(0), }); let (ready_tx, ready_rx) = mpsc::channel(); @@ -471,6 +503,32 @@ pub unsafe extern "C" fn ao_set_active(session: *mut c_void, active: u32) -> i32 .unwrap_or(-1) } +/// Sets the output gain: 0.0 is silence, 1.0 is the samples as written. One +/// knob for both the editor's volume and its mute -- mute is a gain of 0.0 +/// pushed down, and which of the two the user is looking at is the caller's +/// business. Takes effect on the next callback (~23 ms), and the position keeps +/// advancing throughout: this silences the output, it does not pause it. +/// 0 on success, negative on failure or a gain that is not in `0.0..=1.0`. +/// +/// # Safety +/// `session` must come from [`ao_open`]. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn ao_set_volume(session: *mut c_void, gain: f32) -> i32 { + catch_unwind(AssertUnwindSafe(|| { + // A NaN would compare false against every bound and then multiply every + // sample into a NaN, which is a loud fault in a speaker: refuse it here, + // at the ABI, rather than let it reach the RT thread. + if session.is_null() || !(0.0..=1.0).contains(&gain) { + return -1; + } + // SAFETY: caller-guaranteed live session. + let session = unsafe { &*(session as *const Session) }; + session.shared.gain.store(gain.to_bits(), Ordering::Relaxed); + 0 + })) + .unwrap_or(-1) +} + /// Drops every queued sample, so playback resumes from whatever is written /// next: what a seek needs. Takes effect on the next process callback (or the /// first one after a resume), and leaves the played position alone -- the @@ -509,7 +567,35 @@ pub unsafe extern "C" fn ao_close(session: *mut c_void) { #[cfg(test)] mod tests { - use super::{AtomicBool, Ordering, Ring, accept, consume}; + use super::{AtomicBool, Ordering, Ring, accept, consume, scale}; + + /// The gain is applied to the bytes the device is about to play, so silence + /// really is silence and a partial gain really is quieter -- and 1.0 must + /// leave the samples bit-identical, since that is every callback's path. + #[test] + fn gain_scales_the_samples_the_device_sees() { + let sample = + |bytes: &[u8], i: usize| f32::from_le_bytes(bytes[i..i + 4].try_into().unwrap()); + + let mut buf = Vec::new(); + for v in [1.0f32, -0.5, 0.25] { + buf.extend_from_slice(&v.to_le_bytes()); + } + + // Unity is the no-op the common case walks through. + let untouched = buf.clone(); + scale(&mut buf, 1.0); + assert_eq!(buf, untouched); + + // Half volume, sign kept. + scale(&mut buf, 0.5); + assert_eq!(sample(&buf, 0), 0.5); + assert_eq!(sample(&buf, 4), -0.25); + + // Mute is a gain of zero: every sample gone, none left ringing. + scale(&mut buf, 0.0); + assert!(buf.chunks_exact(4).all(|s| sample(s, 0) == 0.0)); + } /// The paused-seek ordering: a flush requested with no RT callbacks running /// must not let the writer queue new audio behind the pending discard. diff --git a/crates/engine/src/ao.rs b/crates/engine/src/ao.rs index 056f2c0..00bded0 100644 --- a/crates/engine/src/ao.rs +++ b/crates/engine/src/ao.rs @@ -18,6 +18,7 @@ struct Plugin { write: unsafe extern "C" fn(*mut c_void, *const f32, usize) -> isize, position: unsafe extern "C" fn(*mut c_void) -> i64, set_active: unsafe extern "C" fn(*mut c_void, u32) -> i32, + set_volume: unsafe extern "C" fn(*mut c_void, f32) -> i32, flush: unsafe extern "C" fn(*mut c_void) -> i32, close: unsafe extern "C" fn(*mut c_void), // Never dropped (lives in a static), so the fn pointers above stay valid. @@ -56,7 +57,11 @@ fn load() -> Option { position: *lib.get(b"ao_position\0").ok()?, set_active: *lib.get(b"ao_set_active\0").ok()?, // Required, so a plugin predating seek is rejected whole - // and we play muted rather than half-working. + // and we play muted rather than half-working. Volume is + // required on the same terms: the two ship from one build, + // and a mute button that does nothing is worse than a run + // with no sound at all, which at least says so. + set_volume: *lib.get(b"ao_set_volume\0").ok()?, flush: *lib.get(b"ao_flush\0").ok()?, close: *lib.get(b"ao_close\0").ok()?, _lib: lib, @@ -123,6 +128,15 @@ impl AoSession { unsafe { (self.plugin.set_active)(self.handle, active as u32) == 0 } } + /// Sets the output gain, 0.0 (silent) to 1.0 (as written): the editor's + /// volume and its mute are the same knob by the time they get here. The + /// clock is unaffected -- a silenced stream still plays, so the picture + /// keeps running against it. `false` for a gain outside the range. + pub fn set_volume(&self, gain: f32) -> bool { + // SAFETY: `handle` came from `ao_open` and is still open. + unsafe { (self.plugin.set_volume)(self.handle, gain) == 0 } + } + /// Drops everything still queued, so the next samples written play right /// away -- what a seek needs. The played position keeps counting. pub fn flush(&self) -> bool { diff --git a/crates/engine/src/playback.rs b/crates/engine/src/playback.rs index 1c7c04f..aba05ef 100644 --- a/crates/engine/src/playback.rs +++ b/crates/engine/src/playback.rs @@ -507,6 +507,25 @@ impl PlaybackSession { } } + /// 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. + /// + /// 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), + None => false, + } + } + /// Repositions the timeline to `secs`, clamped to the *timeline*. Both decode /// workers are replaced rather than steered: a fresh channel cannot hold a /// stale frame, and it works just as well after EOF, where the old workers diff --git a/crates/engine/tests/ao_output.rs b/crates/engine/tests/ao_output.rs index 04b1c4f..8338fac 100644 --- a/crates/engine/tests/ao_output.rs +++ b/crates/engine/tests/ao_output.rs @@ -88,6 +88,51 @@ fn plays_and_tracks_position() { ); } +/// Muting is not pausing: the device keeps consuming and the master clock keeps +/// running, which is the whole reason the picture can play on through a mute. +/// That the samples really go quiet is the plugin's own `scale` unit test -- +/// nothing out here can hear the device. +#[test] +#[ignore = "needs libengine_audio.so and a PipeWire daemon"] +fn muting_silences_without_stopping_the_clock() { + assert!(AoSession::probe(), "plugin not loadable"); + let mut ao = AoSession::open(RATE, CHANNELS).expect("no PipeWire playback available"); + + let samples = tone(); + assert_eq!(ao.write(&samples), Some(samples.len()), "short write"); + let first = wait_for_playback(&ao, Duration::from_secs(2)); + + // Mute, then keep it fed: the position must move exactly as it would have. + assert!(ao.set_volume(0.0), "mute rejected"); + assert_eq!(ao.write(&samples), Some(samples.len()), "short write"); + std::thread::sleep(Duration::from_millis(300)); + let muted = ao.position().expect("position went unknown"); + let advanced = muted - first; + let expected = RATE as i64 * 300 / 1000; + eprintln!("clock advanced {advanced} samples in 300 ms while muted (expected ~{expected})"); + assert!( + (advanced - expected).abs() < expected / 5, + "the clock stalled while muted: {advanced} samples in 300 ms" + ); + + // Every level in range is taken, and the two ends are in range. + for gain in [0.0, 0.5, 1.0] { + assert!(ao.set_volume(gain), "gain {gain} rejected"); + } + // Out of range is refused at the ABI rather than multiplied into the + // speakers -- a NaN would otherwise reach the RT thread and stay there. + for gain in [-0.1, 1.5, f32::NAN, f32::INFINITY] { + assert!(!ao.set_volume(gain), "gain {gain} accepted"); + } + // ...and a refusal changes nothing: the last accepted gain still stands. + assert_eq!(ao.write(&samples), Some(samples.len()), "short write"); + std::thread::sleep(Duration::from_millis(100)); + assert!( + ao.position().expect("position went unknown") > muted, + "clock stopped after a refused gain" + ); +} + /// No reachable daemon must fail the open cleanly and quickly, never hang. #[test] #[ignore = "needs libengine_audio.so and a PipeWire daemon"]