diff --git a/crates/app/src/keymap.rs b/crates/app/src/keymap.rs index 0763bbf..35cc538 100644 --- a/crates/app/src/keymap.rs +++ b/crates/app/src/keymap.rs @@ -77,13 +77,14 @@ pub enum ActionId { Equalizer, Speed, Silence, + Mix, CancelExport, } impl ActionId { /// Display order everywhere -- the editor lists them in it and /// [`Keymap::defaults`] binds them in it. - pub const ALL: [ActionId; 38] = [ + pub const ALL: [ActionId; 39] = [ ActionId::Play, ActionId::StepBack, ActionId::StepForward, @@ -121,6 +122,7 @@ impl ActionId { ActionId::Equalizer, ActionId::Speed, ActionId::Silence, + ActionId::Mix, ActionId::CancelExport, ]; @@ -164,6 +166,7 @@ impl ActionId { ActionId::Equalizer => "Equalizer", ActionId::Speed => "Speed (tape)…", ActionId::Silence => "Silences: cut or speed up…", + ActionId::Mix => "Mix: track volumes and the limiter…", ActionId::CancelExport => "Cancel export", } } @@ -209,6 +212,7 @@ impl ActionId { ActionId::Equalizer => "equalizer", ActionId::Speed => "speed", ActionId::Silence => "silence", + ActionId::Mix => "mix", ActionId::CancelExport => "cancel-export", } } @@ -265,7 +269,12 @@ impl ActionId { ActionId::ToggleMute | ActionId::VolumeUp | ActionId::VolumeDown - | ActionId::Equalizer => Category::Audio, + | ActionId::Equalizer + // The mix is the project's sound -- what every track plays at and + // what the whole of it is held under -- where the three above it + // are this machine's monitoring. Both are audio, and the card says + // which is which. + | ActionId::Mix => Category::Audio, ActionId::Save | ActionId::Export | ActionId::CancelExport => Category::File, } } @@ -631,6 +640,11 @@ impl Keymap { // delete (x and delete) -- what it opens is a card that can cut // forty places at once. b(ActionId::Silence, "u", false), + // The mix card takes "f", for the faders on it: "m" would be + // the word but it is the monitoring mute, which is this + // machine's volume and not the project's -- two things one key + // must not mean. + b(ActionId::Mix, "f", false), b(ActionId::CancelExport, "escape", false), ], } @@ -893,7 +907,7 @@ mod tests { #[test] fn every_default_stroke_reaches_its_action() { let k = Keymap::defaults(); - assert_eq!(k.entries().len(), 40); + assert_eq!(k.entries().len(), 41); assert_eq!(k.lookup("space", false), Some(ActionId::Play)); // The seek keys: bare arrows a frame, ctrl arrows a second, and the two // ends of the timeline. @@ -1127,7 +1141,7 @@ mod tests { assert_eq!(whole("edith-keys 1\n").display(ActionId::Cut), "unbound"); // 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(), 38); + assert_eq!(ActionId::ALL.len(), 39); assert_eq!(k.display(ActionId::ZoomIn), "ctrl+="); } diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index 33204d7..20be25f 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -14,6 +14,7 @@ use engine::color::ColorParams; use engine::decode::Backend; use engine::eq::{Band, BandKind, EqParams}; use engine::export::{ExportSettings, Format}; +use engine::limiter::Limiter; use engine::project::{Edge, Lane, LaneKind, Source, Speed}; use engine::scale::FitPolicy; use engine::{Clip, Codec, ExportHandle, Frame, PlaybackSession}; @@ -493,6 +494,16 @@ const SILENCE_SECS_STEP: f64 = 0.05; const SILENCE_DB_RANGE: (f32, f32) = (-80., 0.); const SILENCE_SECS_RANGE: (f64, f64) = (0., 5.); +/// One press of a nudge key on the mix card, in dB: the step every fader and +/// the limiter's ceiling moves by. A whole decibel, the smallest move anyone +/// hears as a move -- and it lands on round numbers, so a track set by ear +/// still reads as a number a person would say. +const MIX_DB_STEP: f32 = 1.; + +/// The mix card's rows below the faders: the limiter's ceiling and its switch. +/// One fader per audio track comes first, however many there are. +const MIX_MASTER_ROWS: usize = 2; + /// The speed-up rate is bounded *below* by real time: a "speed-up" that slows /// the silence down would make the timeline longer, which is the one thing /// neither button may do. The top is [`Speed::MAX`]. @@ -790,6 +801,14 @@ struct Player { /// The bar is being dragged. On the root like the colour card's, for the /// same reason: the pointer leaves a 4 px bar on the first move. speed_dragging: bool, + /// The mix card is up: every audio track's own volume and the master + /// limiter, which are project settings and not any clip's -- so unlike the + /// four clip cards there is no handle to hold, only whether it is open. + mix_open: bool, + /// Which of its rows the arrow keys move -- a fader, the limiter's ceiling + /// or its switch. The card's own focus, since nothing in it takes gpui's + /// (ledger:182). + mix_field: usize, /// The silence card is up on this clip -- the lane it is on and its index /// there, exactly as the speed card's handle is. silence_open: Option<(Lane, usize)>, @@ -1000,6 +1019,7 @@ impl Player { ActionId::Equalizer => self.open_eq(cx), ActionId::Speed => self.open_speed(cx), ActionId::Silence => self.open_silence(cx), + ActionId::Mix => self.open_mix(None, cx), // Nothing to cancel while nothing is exporting; the export guard in // the key handler is what answers this one while there is. ActionId::CancelExport => {} @@ -1408,6 +1428,82 @@ impl Player { cx.notify(); } + /// Opens the mix card. `lane` is the row it lands on -- the track whose + /// header was clicked -- and `None` starts at the top, which is what the + /// stroke means. + /// + /// Nothing here is a clip's, so nothing is refused for want of a selection: + /// a timeline with no audio track at all still has a limiter to set, and a + /// fader on an empty track is the level the next take lands at. + fn open_mix(&mut self, lane: Option, cx: &mut Context) { + if self.exporting().is_some() { + return; + } + self.mix_open = true; + self.mix_field = lane + .and_then(|lane| self.mix_lanes().iter().position(|&l| l == lane)) + .unwrap_or(0); + // One card at a time, the rule the other five follow. + self.keys_open = false; + self.export_open = false; + self.eq_open = None; + self.color_open = None; + self.speed_open = None; + self.close_silence(); + self.context_menu = None; + cx.notify(); + } + + /// The audio tracks the card shows a fader for, top to bottom: *every* one + /// of them, empty ones included -- what the timeline lays out, not what the + /// mixer happens to open (`Project::audio_lanes` leaves an empty track out, + /// and a fader that disappeared when a track was cleared would be a setting + /// nobody could reach). + fn mix_lanes(&self) -> Vec { + self.session.as_ref().map_or_else(Vec::new, |session| { + session + .lanes() + .into_iter() + .filter(|l| l.kind == LaneKind::Audio) + .collect() + }) + } + + /// Moves the row the card has picked: a fader by [`MIX_DB_STEP`], the + /// ceiling by the same, and the switch either way (a ring of two, like the + /// silence card's unit row). + /// + /// Every one of them goes through the session, so it reseeks: what the ear + /// hears while the arrow is held is the mix that is being set. + fn nudge_mix(&mut self, steps: i32, cx: &mut Context) { + let lanes = self.mix_lanes(); + let Some(session) = self.session.as_mut() else { + return; + }; + match lanes.get(self.mix_field) { + Some(&lane) => { + let at = session.lane_gain_db(lane) + steps as f32 * MIX_DB_STEP; + session.set_lane_gain_db(lane, at); + } + None => { + let limiter = session.limiter(); + let at = match self.mix_field - lanes.len() { + 0 => Limiter { + on: limiter.on, + ..limiter + } + .with_ceiling(limiter.ceiling_db + steps as f32 * MIX_DB_STEP), + _ => Limiter { + on: !limiter.on, + ..limiter + }, + }; + session.set_limiter(at); + } + } + cx.notify(); + } + /// Closes it and drops the preview with it: marks left on the lane after /// the card is gone would name frames the next edit has already moved. fn close_silence(&mut self) { @@ -1670,6 +1766,7 @@ impl Player { || self.color_open.is_some() || self.speed_open.is_some() || self.silence_open.is_some() + || self.mix_open || self.exporting().is_some() } @@ -1689,6 +1786,7 @@ impl Player { || self.color_open.is_some() || self.speed_open.is_some() || self.silence_open.is_some() + || self.mix_open { Repeat::Card } else { @@ -3556,6 +3654,25 @@ impl Render for Player { cx.notify(); return; } + // The mix card, the same way again: ↑↓ pick a row -- a track's + // fader, the limiter's ceiling or its switch -- and ←→ move it, + // held or pressed. Card-local like the four above it. + if this.mix_open { + let rows = this.mix_lanes().len() + MIX_MASTER_ROWS; + if key == ESCAPE { + this.mix_open = false; + } else if key == "down" { + this.mix_field = (this.mix_field + 1) % rows; + } else if key == "up" { + this.mix_field = (this.mix_field + rows - 1) % rows; + } else if key == "right" { + this.nudge_mix(1, cx); + } else if key == "left" { + this.nudge_mix(-1, cx); + } + cx.notify(); + return; + } // A clip menu names an index, and every edit below moves // indices -- so a stroke closes it before it acts. Escape means // that and nothing else, which is the `esc` the keys menu @@ -3782,6 +3899,7 @@ impl Render for Player { .children(self.color_card(cx)) .children(self.speed_card(cx)) .children(self.silence_card(cx)) + .children(self.mix_card(cx)) } } @@ -5727,6 +5845,174 @@ impl Player { ) } + /// The mix card: one fader per audio track and the master limiter under + /// them -- the two settings that belong to the *sound of the whole + /// timeline* rather than to any clip on it. + /// + /// A track's fader moves everything on that track by the same amount, + /// every frequency of it: it is not the equalizer (one take, one band) and + /// it is not the volume in the panel, which is what this machine monitors + /// at and is written to no file. The limiter is over the sum of them all, + /// which is where a mix can pass full scale and where a clamp used to + /// square it off. + /// + /// The silence card's shape, down to the steppers: a row is a label, a + /// value and the two presses that move it, and the arrows pick a row and + /// move it too. The rows scroll rather than the card growing past the + /// window -- a timeline may hold more tracks than a 360 px window has room + /// for faders. + fn mix_card(&self, cx: &mut Context) -> Option { + if !self.mix_open { + return None; + } + let session = self.session.as_ref(); + let lanes = self.mix_lanes(); + let limiter = session.map_or_else(Limiter::default, PlaybackSession::limiter); + let mut rows: Vec<(String, String)> = lanes + .iter() + .map(|&lane| { + let db = session.map_or(0., |s| s.lane_gain_db(lane)); + (format!("{} plays at", lane.label()), format!("{db:+.0} dB")) + }) + .collect(); + // The ceiling in dBFS and the faders in dB, the silence card's rule: + // a ceiling is a level below full scale, a fader is a change. + rows.push(( + "Limiter ceiling".into(), + format!("{:+.0} dBFS", limiter.ceiling_db), + )); + rows.push(( + "Limiter".into(), + match limiter.on { + true => "on".into(), + false => "off".into(), + }, + )); + let rows: Vec<_> = rows + .into_iter() + .enumerate() + .map(|(n, (label, value))| { + div() + .id(("mix-row", n)) + .flex() + .flex_none() + .min_h(px(KEYS_ROW_H)) + .items_center() + .justify_between() + .px(px(6.)) + .rounded(px(3.)) + .bg(rgb(match n == self.mix_field { + true => SELECTED, + false => CHROME, + })) + .cursor_pointer() + .hover(|s| s.bg(rgb(HOVER))) + .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + this.mix_field = n; + cx.notify(); + })) + .child(div().text_color(rgb(INK_DIM)).child(label)) + .child( + div() + .flex() + .items_center() + .gap(px(4.)) + .child(value) + .children([-1, 1].map(|steps: i32| { + div() + .id(("mix-step", n * 2 + usize::from(steps > 0))) + .flex_none() + .w(px(HIT_MIN)) + .h(px(KEYS_ROW_H)) + .flex() + .items_center() + .justify_center() + .rounded(px(3.)) + .bg(rgb(CHROME)) + .cursor_pointer() + .hover(|s| s.bg(rgb(HOVER))) + .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + // Picked as well as moved, the silence + // card's rule: the row a press lands on + // is the row the arrows carry on from. + this.mix_field = n; + this.nudge_mix(steps, cx); + })) + .child(match steps > 0 { + true => "+", + false => "−", + }) + })), + ) + }) + .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(COLOR_W)) + .max_h(px(360. - 24.)) + .flex() + .flex_col() + .gap(px(6.)) + .p(px(12.)) + .rounded(px(6.)) + .bg(rgb(SURFACE)) + .child( + div() + .flex_none() + .px(px(6.)) + .child("Mix — track volumes and the master limiter"), + ) + .child( + div() + .flex_none() + .px(px(6.)) + .text_size(px(11.)) + .text_color(rgb(INK_DIM)) + .child( + "− and + move a setting, or ↑↓ picks one and ←→ moves it (hold to run it) — a track fader moves everything on that track; esc closes", + ), + ) + .child( + div() + .id("mix-rows") + .flex() + .flex_col() + .gap(px(6.)) + .overflow_y_scroll() + .children(rows), + ) + .child( + div() + .flex_none() + .px(px(6.)) + .text_size(px(11.)) + .text_color(rgb(INK_DIM)) + // What the choice *is*: the limiter's own line, + // because "on" alone says nothing about what it + // does to a mix that never reaches the ceiling. + .child(match limiter.on { + true => format!( + "the mix is held under {:+.0} dBFS — quieter passages are untouched", + limiter.ceiling_db + ), + false => "the limiter is out of circuit — a hot mix clips at full scale".to_string(), + }), + ), + ), + ) + } + /// The silence card: what the scan is looking for, what it found, and the /// two things that can be done about it. /// @@ -6344,6 +6630,19 @@ impl Player { .map_or(&[][..], PlaybackSession::sources); let (sel, sel_link) = (self.selected, self.selected_link()); let audio = lane.kind == LaneKind::Audio; + // What this track plays at, on the header it belongs to: shown only + // when it is not unity, because a column 40 px wide has room for a + // number or for a name, and the name is what a header is for. The + // press opens the mix card on this very track. + let gain_db = self + .session + .as_ref() + .map_or(0., |session| session.lane_gain_db(lane)); + let gain_tip: SharedString = format!( + "{name} plays at {gain_db:+.0} dB — opens the mix ({}); the whole track, every frequency, unlike the equalizer", + self.keymap.display(ActionId::Mix) + ) + .into(); let tip: SharedString = format!( "Select (or {} under the playhead, {}/{} along the lane) — drag it to move it, an end to trim, {} removes the take, {} leaves a gap, {} rejoins a cut", self.keymap.display(ActionId::Select), @@ -6374,7 +6673,35 @@ impl Player { .bg(rgb(SURFACE)) .text_size(px(11.)) .text_color(rgb(INK_DIM)) - .child(div().flex_1().flex().items_center().child(name)) + .child(match audio { + // A button, not a label: the one setting a track has of + // its own used to be reachable from nowhere. + true => div() + .id(("mix-lane", lane.ord)) + .flex_1() + .w_full() + .flex() + .items_center() + .justify_center() + .rounded(px(3.)) + .cursor_pointer() + .hover(|s| s.bg(rgb(HOVER))) + .tooltip(move |_, cx| cx.new(|_| Tip(gain_tip.clone())).into()) + .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + this.open_mix(Some(lane), cx) + })) + .child(match gain_db == 0. { + true => name.clone(), + false => format!("{name} {gain_db:+.0}"), + }) + .into_any_element(), + false => div() + .flex_1() + .flex() + .items_center() + .child(name.clone()) + .into_any_element(), + }) // The one thing a header does: take this track away again. // A `HIT_MIN` target rather than a glyph-sized one, and it // stays put on a track holding clips instead of hiding -- @@ -8961,6 +9288,9 @@ mod tests { source.contains("this.remove_lane(lane, cx)") } ActionId::ToggleMute => element("volume"), + // The fader on every audio track's own header, which is + // also what opens the card the limiter is on. + ActionId::Mix => element("mix-lane"), ActionId::VolumeUp | ActionId::VolumeDown => element("volume-bar"), // The ruler seeks anywhere the pointer points; the frame and // the second are the keyboard's finer grain of that move. @@ -8992,6 +9322,8 @@ mod tests { "speed-preset", "silence-row", "silence-step", + "mix-row", + "mix-step", "silence-apply", "export-confirm", ] { @@ -11414,6 +11746,8 @@ fn main() { speed_open: None, speed_bar: Rc::default(), speed_dragging: false, + mix_open: false, + mix_field: 0, silence_open: None, // The conservative defaults the engine documents: a first // scan that leaves a little too much is one nobody undoes. diff --git a/crates/engine/src/audio.rs b/crates/engine/src/audio.rs index ef4885d..b958807 100644 --- a/crates/engine/src/audio.rs +++ b/crates/engine/src/audio.rs @@ -50,6 +50,7 @@ use symphonia_core::units; use symphonia_core::units::{Time, TimeBase}; use crate::eq::{EqParams, EqState}; +use crate::limiter::{Limiter, LimiterState}; /// ffmpeg's AAC-LC encoder delay, used when the file carries no edit list. /// (HE-AAC/iTunes files use 2112, but those are rejected as unsupported here.) @@ -453,11 +454,41 @@ impl AudioSession { lanes: &[Vec<(Option, f64, f64)>], eqs: &[Vec>], speeds: &[Vec>], + ) -> crate::Result)>> { + Self::open_mixed_streams_master(sources, lanes, eqs, speeds, &[], Limiter::default()) + } + + /// [`open_mixed_streams_speed`](Self::open_mixed_streams_speed) with the two + /// settings that belong to the *mix* rather than to a clip: what each lane + /// is turned up or down by on its way into the sum (`gains[i]`, an + /// amplitude, [`crate::Project::audio_gains`] builds it) and the master + /// limiter the sum comes out through. + /// + /// Both live at the sum and nowhere else, which is what makes a lane volume + /// a *lane* volume and a limiter a master one: a gain applied per segment + /// would have to agree with itself across a lane's cuts, and a limiter + /// applied per lane would pump each lane against the others. A short or + /// empty gain list means the rest play as they are, exactly as a short eq + /// list means flat. + /// + /// Flat settings take the same path the mixer always took, down to the bit: + /// one lane at unity with the limiter off is still `open_multi_streams` + /// verbatim, with no mixer thread at all. A lane that is *not* at unity, or + /// a limiter that is on, is what puts a single-lane timeline through the + /// mixer -- a sum of one, which is where both settings live. + pub fn open_mixed_streams_master( + sources: &[(PathBuf, usize)], + lanes: &[Vec<(Option, f64, f64)>], + eqs: &[Vec>], + speeds: &[Vec>], + gains: &[f32], + limiter: Limiter, ) -> crate::Result)>> { let [first, rest @ ..] = lanes else { return Ok(None); }; - if rest.is_empty() { + let mastered = limiter.is_active() || gains.iter().any(|&g| g != 1.0); + if rest.is_empty() && !mastered { let flat = Vec::new(); let plain = Vec::new(); return Self::open_multi_streams_speed( @@ -487,12 +518,20 @@ impl AudioSession { meta = Some(lane_meta); rxs.push(rx); } - let meta = meta.expect("at least two lanes opened above"); + let meta = meta.expect("at least one lane opened above"); let (tx, rx) = sync_channel(32); let channels = usize::from(meta.channels); + // One per lane, in the lanes' own order, padded with unity: a short + // list is "as it is from here on", the eq list's rule. + let mut gains = gains.to_vec(); + gains.resize(lanes.len(), 1.0); + // Built here, off the thread that will run it, where the rate is known. + let limiter = limiter + .is_active() + .then(|| LimiterState::new(&limiter, meta.sample_rate, channels)); thread::Builder::new() .name("audio-mix".into()) - .spawn(move || mix(&rxs, channels, &tx))?; + .spawn(move || mix(&rxs, channels, &gains, limiter, &tx))?; Ok(Some((meta, rx))) } @@ -1855,7 +1894,13 @@ struct Worker { /// The accumulator is reused across turns; the one allocation per chunk is the /// buffer the channel takes ownership of, and none of this is the RT path (the /// device callback reads the ring the feeder has already filled). -fn mix(rxs: &[Receiver], channels: usize, tx: &SyncSender) { +fn mix( + rxs: &[Receiver], + channels: usize, + gains: &[f32], + mut limiter: Option, + tx: &SyncSender, +) { let mut pending: Vec> = rxs.iter().map(|_| Vec::new()).collect(); let mut live: Vec = rxs.iter().map(|_| true).collect(); // Numbering follows lane 0, whose first chunk says where it starts. @@ -1890,11 +1935,31 @@ fn mix(rxs: &[Receiver], channels: usize, tx: &SyncSender `: how loud that whole lane plays, +//! everything on it and every frequency of it -- a different thing from a +//! clip's `eq` line, which is one take and one band. It names its lane the way +//! a clip line does and comes *after* the lanes, because a lane is declared by +//! its clips and a gain declares nothing. Only a lane somebody has turned gets +//! one; the rest are at 0 dB, which is where every lane of every dialect before +//! v9 is. +//! //! The `resolution` line is the **project's** picture size, which is a //! different thing from any source's: media of other sizes are placed on it. //! It belongs once, beside the playhead, and a file without one (every dialect @@ -58,7 +79,10 @@ //! is the only way an empty lane could still be there on the way back. A lane //! number may not skip one of its kind. //! -//! **Version 7** was this without the clip's speed field -- every clip of such +//! **Version 8** was this without the `fps` and `limiter` lines and without +//! the `gain` ones: such a project mixes every lane at unity, limits nothing, +//! and comes back at the rate its scaffolding source runs at. +//! **Version 7** was that without the clip's speed field -- every clip of such //! a project plays at real time, which is the only rate there was. //! **Version 6** was that without the `resolution` line and without the clip's //! fit field -- such a project is the size of its first source and letterboxes @@ -72,9 +96,9 @@ //! `. All six still load -- a v1 file's clips are laid out //! cumulatively and copied onto both lanes as one group each, which is exactly //! what a v1 timeline meant, and an older file simply equalizes and grades -//! nothing, and an older one plays everything at real time -- and saving any of -//! them writes v8. An older reader refuses a newer -//! file by name. +//! nothing, and an older one plays everything at real time, and an older one +//! mixes flat -- and saving any of them writes v9. An older reader refuses a +//! newer file by name. //! //! Text because an edit list is a few integers and a path, and a path is //! *bytes* on this platform -- a JSON string would have to lossily decode one. @@ -102,12 +126,14 @@ use std::path::{Path, PathBuf}; use crate::color::ColorParams; use crate::eq::{Band, BandKind, EqParams}; +use crate::limiter::Limiter; use crate::project::{Clip, Lane, LaneKind, Source, Speed}; use crate::scale::FitPolicy; /// What [`save`] writes. Read support goes back to `edith 1`; see the module /// docs for what those dialects looked like. -const MAGIC: &[u8] = b"edith 8"; +const MAGIC: &[u8] = b"edith 9"; +const MAGIC_V8: &[u8] = b"edith 8"; const MAGIC_V7: &[u8] = b"edith 7"; const MAGIC_V6: &[u8] = b"edith 6"; const MAGIC_V5: &[u8] = b"edith 5"; @@ -136,18 +162,37 @@ pub struct Document { /// The project's own picture size. `None` for every dialect before v7 and /// for a v7 file that leaves it out, which both mean "source 0's picture". pub resolution: Option<(u32, u32)>, + /// Every lane's own volume in dB, in the order `lanes` is in and as long as + /// it; `0.0` for a lane nobody has turned, which is every lane of every + /// dialect before v9. + pub gains: Vec, + /// The master limiter. Off for every dialect before v9, and for a v9 file + /// that leaves the line out. + pub limiter: Limiter, + /// The timeline's frame rate. `None` for every dialect before v9 and for a + /// v9 file that leaves it out, which both mean "whatever the scaffolding + /// source runs at" -- the inference a project of nothing but stills and + /// songs has no answer for (see + /// [`crate::PlaybackSession::open_project`]). + pub fps: Option, pub playhead: u32, } /// Writes the project to `path`, atomically. `sources`, `eq` and `color` should -/// already be orphan-free ([`crate::Project::without_orphan_sources`]). +/// already be orphan-free ([`crate::Project::without_orphan_sources`]); +/// `gains` is one dB per lane in the same order the lanes are in +/// ([`crate::Project::lane_gains`]). +#[allow(clippy::too_many_arguments)] pub fn save( path: &Path, sources: &[Source], lanes: &[(LaneKind, Vec)], + gains: &[f32], eq: &[EqParams], color: &[ColorParams], resolution: (u32, u32), + fps: Option, + limiter: Limiter, playhead: u32, ) -> crate::Result<()> { let dir = project_dir(path); @@ -160,7 +205,9 @@ pub fn save( // the second one puts the name itself there. let result = std::fs::File::create(&part) .and_then(|mut f| { - f.write_all(&emit(&dir, sources, lanes, eq, color, resolution, playhead))?; + f.write_all(&emit( + &dir, sources, lanes, gains, eq, color, resolution, fps, limiter, playhead, + ))?; f.sync_all() }) .and_then(|()| std::fs::rename(&part, path)) @@ -190,13 +237,17 @@ fn project_dir(path: &Path) -> PathBuf { dir.canonicalize().unwrap_or_else(|_| dir.to_path_buf()) } +#[allow(clippy::too_many_arguments)] fn emit( dir: &Path, sources: &[Source], lanes: &[(LaneKind, Vec)], + gains: &[f32], eq: &[EqParams], color: &[ColorParams], resolution: (u32, u32), + fps: Option, + limiter: Limiter, playhead: u32, ) -> Vec { let mut out = Vec::new(); @@ -204,6 +255,26 @@ fn emit( out.push(b'\n'); out.extend_from_slice(format!("playhead {playhead}\n").as_bytes()); out.extend_from_slice(format!("resolution {} {}\n", resolution.0, resolution.1).as_bytes()); + // `{:?}`, the eq table's rule: the rate a timeline was cut at has to read + // back as the very number, or every clip on it lands on another frame. + if let Some(fps) = fps.filter(|f| f.is_finite() && *f > 0.0) { + out.extend_from_slice(format!("fps {fps:?}\n").as_bytes()); + } + // Written only when it is not the default, so a project nobody has limited + // is the same bytes it was in v8 bar the version line. + if limiter != Limiter::default() { + out.extend_from_slice( + format!( + "limiter {:?} {}\n", + limiter.ceiling_db, + match limiter.on { + true => "on", + false => "off", + } + ) + .as_bytes(), + ); + } for s in sources { out.extend_from_slice(format!("source {} ", s.audio_stream).as_bytes()); escape(s.path.strip_prefix(dir).unwrap_or(&s.path), &mut out); @@ -276,6 +347,25 @@ fn emit( ); } } + // After the lanes, not before them: a gain line names a lane that has to be + // there already, and a lane is declared by its own lines. Only the lanes + // somebody has turned get one. + let (mut video, mut audio) = (0, 0); + for ((kind, _), &db) in lanes.iter().zip(gains) { + let (keyword, ord) = match kind { + LaneKind::Video => { + video += 1; + ("video", video) + } + LaneKind::Audio => { + audio += 1; + ("audio", audio) + } + }; + if db != 0.0 { + out.extend_from_slice(format!("gain {keyword} {ord} {db:?}\n").as_bytes()); + } + } out } @@ -289,8 +379,11 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result { // The dialects that wrote a source line without its stream field. Reading // one is the whole of what "an old project still opens" means here. let streamless = v1 || first == MAGIC_V2; - // The one that carries a per-clip speed... - let v8 = first == MAGIC; + // The one that carries the mix -- lane volumes, the master limiter and the + // rate the timeline was cut at... + let v9 = first == MAGIC; + // ...the ones that carry a per-clip speed... + let v8 = v9 || first == MAGIC_V8; // ...the ones that carry a project resolution and per-clip fit policies... let v7 = v8 || first == MAGIC_V7; // ...the ones that carry colour grades... @@ -322,6 +415,11 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result { // Nothing before v7 has a resolution of its own: source 0's picture is // what those projects were, and `None` is how the loader is told so. resolution: None, + // ...and nothing before v9 carries a mix or a rate: every lane at unity, + // no limiter, and the rate inferred from the scaffold as it always was. + gains: Vec::new(), + limiter: Limiter::default(), + fps: None, playhead: 0, }; let mut playhead_seen = false; @@ -360,6 +458,76 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result { } doc.resolution = Some((width, height)); } + b"fps" if v9 => { + if doc.fps.is_some() || !doc.sources.is_empty() { + return Err(format!("line {n}: fps belongs once, before the sources").into()); + } + let f = fields(rest, 1, "fps", n)?; + let fps = std::str::from_utf8(f[0]) + .ok() + .and_then(|s| s.parse::().ok()) + .filter(|f| f.is_finite() && *f > 0.0 && *f <= 1000.0) + .ok_or_else(|| { + format!( + "line {n}: {:?} is not a frame rate", + String::from_utf8_lossy(f[0]) + ) + })?; + doc.fps = Some(fps); + } + b"limiter" if v9 => { + if !doc.sources.is_empty() { + return Err( + format!("line {n}: limiter belongs once, before the sources").into(), + ); + } + let f = fields(rest, 2, "limiter", n)?; + let on = match f[1] { + b"on" => true, + b"off" => false, + other => { + return Err(format!( + "line {n}: limiter is on or off, not {:?}", + String::from_utf8_lossy(other) + ) + .into()); + } + }; + // Through the same clamp a nudge goes through: a hand-written + // ceiling above full scale is a ceiling that limits nothing. + doc.limiter = Limiter { + on, + ..Limiter::default() + } + .with_ceiling(float(f[0], n)?); + } + // After the lanes it names, which is where `emit` writes it: a lane + // is declared by its own lines, and a gain declares nothing. + b"gain" if v9 => { + let f = fields(rest, 3, "gain", n)?; + let kind = match f[0] { + b"video" => LaneKind::Video, + b"audio" => LaneKind::Audio, + other => { + return Err(format!( + "line {n}: gain names {:?}, not a lane kind", + String::from_utf8_lossy(other) + ) + .into()); + } + }; + let ord = number(f[1], n)?; + let at = doc + .lanes + .iter() + .enumerate() + .filter(|(_, (k, _))| *k == kind) + .nth(ord.saturating_sub(1) as usize) + .map(|(at, _)| at) + .ok_or_else(|| format!("line {n}: gain names a lane that is not there"))?; + doc.gains.resize(doc.lanes.len(), 0.0); + doc.gains[at] = float(f[2], n)?; + } b"source" => { if doc.lanes.iter().any(|(_, clips)| !clips.is_empty()) { return Err(format!("line {n}: source after a clip").into()); @@ -518,6 +686,8 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result { } } } + // One per lane whatever the file said, so a caller may zip the two. + doc.gains.resize(doc.lanes.len(), 0.0); // A file whose lanes are all empty *is* a project -- the emptied timeline, // saved. What it may not be is laneless; [`crate::Project::from_parts`] // refuses that one, by the name it has there. @@ -773,6 +943,35 @@ fn unescape(field: &[u8], line: usize) -> crate::Result { mod tests { use super::*; + /// [`super::emit`] for a project whose mix is flat: every lane at unity, no + /// limiter, no rate written. Shadows the real one for the tests that were + /// written before there was a mix to write -- the dialect they are about is + /// the one this emits, and a v9 file with flat settings is a v8 file bar + /// its version line, which is exactly what they assert. + #[allow(clippy::too_many_arguments)] + fn emit( + dir: &Path, + sources: &[Source], + lanes: &[(LaneKind, Vec)], + eq: &[EqParams], + color: &[ColorParams], + resolution: (u32, u32), + playhead: u32, + ) -> Vec { + super::emit( + dir, + sources, + lanes, + &[], + eq, + color, + resolution, + None, + Limiter::default(), + playhead, + ) + } + fn clip(start: u32, in_frame: u32, out_frame: u32, source: usize, link: Option) -> Clip { Clip { start, @@ -833,7 +1032,7 @@ mod tests { let bytes = flat(&dir, &sources, &lanes, 12); assert_eq!( String::from_utf8_lossy(&bytes), - "edith 8\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\ + "edith 9\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\ source 2 /elsewhere/b.mp4\n\ video 1 0 0 30 0 0 - - fit 1000\nvideo 1 30 10 20 1 1 - - fit 1000\n\ audio 1 0 0 30 0 0 - - fit 1000\n", @@ -870,7 +1069,7 @@ mod tests { let bytes = flat(&dir, &sources, &lanes, 7); assert_eq!( String::from_utf8_lossy(&bytes), - "edith 8\nplayhead 7\nresolution 1280 720\nsource 0 a.mp4\n\ + "edith 9\nplayhead 7\nresolution 1280 720\nsource 0 a.mp4\n\ video 1 0 0 30 0 4 - - fit 1000\naudio 1\n\ video 2 40 0 10 0 - - - fit 1000\naudio 2 0 0 30 0 4 - - fit 1000\n", "an empty lane is a line of its own; everything else is its clips" @@ -978,7 +1177,7 @@ mod tests { let bytes = emit(&dir, &sources, &lanes, &eq, &[], (1280, 720), 0); assert_eq!( String::from_utf8_lossy(&bytes), - "edith 8\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ + "edith 9\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk\n\ eq 16777215.0:-0.1:3.918315e-39:hs\n\ eq\n\ @@ -1082,7 +1281,7 @@ mod tests { let bytes = emit(&dir, &sources, &lanes, &[], &color, (1280, 720), 0); assert_eq!( String::from_utf8_lossy(&bytes), - "edith 8\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ + "edith 9\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ color 0.1:1.2:0.9:-0.3\n\ color -1e-7:16777215.0:3.918315e-39:-0.0\n\ color 0.0:1.0:1.0:0.0\n\ @@ -1147,7 +1346,7 @@ mod tests { (1280, 720), old.playhead )), - "edith 8\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\ + "edith 9\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\ eq 80.0:-3.0:0.707:ls\n\ video 1 0 0 30 0 0 0 - fit 1000\naudio 1 0 0 30 0 0 - - fit 1000\n" ); @@ -1185,7 +1384,7 @@ mod tests { let bytes = emit(&dir, &sources, &lanes, &[], &[], (1280, 720), 0); assert_eq!( String::from_utf8_lossy(&bytes), - "edith 8\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ + "edith 9\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ video 1 0 0 30 0 - - - fit 2000\nvideo 1 15 30 40 0 - - - fit 250\n\ audio 1 0 0 30 0 - - - fit 2000\n", "the rate is the clip line's last field, in thousandths" @@ -1214,7 +1413,7 @@ mod tests { (1280, 720), old.playhead )), - "edith 8\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\ + "edith 9\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\ video 1 0 0 30 0 0 - - fit 1000\naudio 1 0 0 30 0 0 - - fit 1000\n" ); // A rate outside what the editor can set is a corrupt line, by name. @@ -1225,6 +1424,105 @@ mod tests { ); } + /// The whole of the v9 bump, the speed test's twin: the mix a project was + /// left at -- every track's own volume and the master limiter -- plus the + /// rate it was cut at, all written, all read back as the very numbers, and + /// a v8 file (which has none of them) loading flat and unlimited. + #[test] + fn the_mix_and_the_rate_round_trip_and_a_v8_file_is_flat() { + let dir = PathBuf::from("/proj"); + let sources = vec![Source::new("/proj/a.mp4", 0)]; + let lanes = vec![ + (LaneKind::Video, vec![clip(0, 0, 30, 0, None)]), + (LaneKind::Audio, vec![clip(0, 0, 30, 0, None)]), + // A second audio track, turned down: the gain lines are per lane, + // so the two must not run into one another. + (LaneKind::Audio, vec![clip(0, 0, 30, 0, None)]), + ]; + let limiter = Limiter { + ceiling_db: -1.5, + on: true, + }; + let bytes = super::emit( + &dir, + &sources, + &lanes, + &[0.0, 3.0, -6.5], + &[], + &[], + (1280, 720), + Some(23.976023976023978), + limiter, + 0, + ); + assert_eq!( + String::from_utf8_lossy(&bytes), + "edith 9\nplayhead 0\nresolution 1280 720\nfps 23.976023976023978\n\ + limiter -1.5 on\nsource 0 a.mp4\n\ + video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n\ + audio 2 0 0 30 0 - - - fit 1000\n\ + gain audio 1 3.0\ngain audio 2 -6.5\n", + "the mix is lines of its own, the gains after the lanes they name" + ); + let back = parse(&bytes, &dir).expect("parse"); + assert_eq!(back.lanes, lanes); + assert_eq!(back.gains, vec![0.0, 3.0, -6.5], "one per lane, in order"); + assert_eq!(back.limiter, limiter); + assert_eq!(back.fps, Some(23.976023976023978), "bit-exact, not 23.976"); + + // ...and the dialect before it, which carried none of the three: a v8 + // file mixes flat, limits nothing, and says nothing about its rate. + let v8 = b"edith 8\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\ + video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n"; + let old = parse(v8, &dir).expect("v8 parses"); + assert_eq!(old.gains, vec![0.0, 0.0], "one per lane, all at unity"); + assert_eq!(old.limiter, Limiter::default()); + assert_eq!(old.fps, None); + // A v9 file may leave all three out too, and means the same thing. + assert_eq!( + String::from_utf8_lossy(&emit( + &dir, + &old.sources, + &old.lanes, + &old.eq, + &old.color, + (1280, 720), + old.playhead + )), + "edith 9\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\ + video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n" + ); + + // Each of the three refuses by name, on its own line. + for (text, want) in [ + ( + "edith 9\nfps nope\nsource 0 a.mp4\n", + "line 2: \"nope\" is not a frame rate", + ), + ( + "edith 9\nlimiter -1.0 maybe\nsource 0 a.mp4\n", + "line 2: limiter is on or off, not \"maybe\"", + ), + ( + "edith 9\nsource 0 a.mp4\nvideo 1 0 0 30 0 - - - fit 1000\ngain audio 1 -3.0\n", + "line 4: gain names a lane that is not there", + ), + ( + "edith 9\nsource 0 a.mp4\nvideo 1 0 0 30 0 - - - fit 1000\ngain lane 1 -3.0\n", + "line 4: gain names \"lane\", not a lane kind", + ), + ] { + assert_eq!( + parse(text.as_bytes(), &dir).unwrap_err().to_string(), + want, + "{text:?}" + ); + } + // A hand-written ceiling nothing could limit at is clamped, not taken. + let loud = parse(b"edith 9\nlimiter 12.0 on\nsource 0 a.mp4\n", &dir).expect("parses"); + assert_eq!(loud.limiter.ceiling_db, Limiter::MAX_DB); + } + /// The refusals the colour grammar adds, each naming its line. #[test] fn a_malformed_colour_names_its_line() { @@ -1355,7 +1653,7 @@ mod tests { assert!(old.eq.is_empty(), "nothing before v5 equalizes anything"); assert_eq!( String::from_utf8_lossy(&flat(&dir, &old.sources, &old.lanes, old.playhead)), - "edith 8\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\ + "edith 9\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\ source 2 /elsewhere/b.mp4\n\ video 1 0 0 30 0 0 - - fit 1000\nvideo 1 30 10 20 1 1 - - fit 1000\n\ audio 1 0 0 30 0 0 - - fit 1000\n" @@ -1408,7 +1706,7 @@ mod tests { let v5 = flat(&dir, &back.sources, &back.lanes, back.playhead); assert_eq!( String::from_utf8_lossy(&v5), - "edith 8\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\ + "edith 9\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\ source 0 /elsewhere/b.mp4\n\ video 1 0 0 30 0 0 - - fit 1000\nvideo 1 30 10 20 1 1 - - fit 1000\n\ audio 1 0 0 30 0 0 - - fit 1000\n", @@ -1440,7 +1738,7 @@ mod tests { // Saved again it is the current version, which round-trips to the // same document. let v5 = flat(&dir, &back.sources, &back.lanes, back.playhead); - assert!(v5.starts_with(b"edith 8\n")); + assert!(v5.starts_with(b"edith 9\n")); let again = parse(&v5, &dir).expect("v5 parses"); assert_eq!(again.lanes, back.lanes); // A dialect may not be mixed: lane lines under v1, `clip` under v2. @@ -1535,14 +1833,17 @@ mod tests { &two(one.to_vec(), one.to_vec()), &[], &[], + &[], (1280, 720), + None, + Limiter::default(), 0, ) .expect("save"); let bytes = std::fs::read(&path).expect("read back"); assert_eq!( String::from_utf8_lossy(&bytes), - "edith 8\nplayhead 0\nresolution 1280 720\nsource 1 a.mp4\n\ + "edith 9\nplayhead 0\nresolution 1280 720\nsource 1 a.mp4\n\ video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n" ); // Loading rejoins the *given* directory, so the file is reached by the @@ -1587,10 +1888,10 @@ mod tests { #[test] fn a_wrong_first_line_is_refused_by_name() { let dir = PathBuf::from("/proj"); - let err = parse(b"edith 9\nsource 0 a.mp4\nvideo 0 0 5 0 -\n", &dir) + let err = parse(b"edith 10\nsource 0 a.mp4\nvideo 0 0 5 0 -\n", &dir) .unwrap_err() .to_string(); - assert_eq!(err, "line 1: unsupported version 9"); + assert_eq!(err, "line 1: unsupported version 10"); for junk in [&b""[..], b"{}\n", b"source a.mp4\n"] { assert_eq!( parse(junk, &dir).unwrap_err().to_string(), diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index ade9f98..08aa301 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -360,6 +360,15 @@ fn equalized(project: &Project) -> bool { }) } +/// Whether the *mix* is doing something -- a lane turned off unity, or a +/// limiter in circuit. [`equalized`]'s pair, and a copy cannot carry either of +/// them: both live where the lanes are summed +/// ([`AudioSession::open_mixed_streams_master`]), and a copied packet was never +/// summed at all. An mp4 whose timeline is mixed is decoded and re-encoded. +fn mastered(project: &Project) -> bool { + project.limiter().is_active() || project.audio_gains().iter().any(|&g| g != 1.0) +} + /// The bitrate an export codes at: the caller's number through the same clamp /// as the computed one, for the reason [`Enc::open`] states. fn bitrate_of(meta: &VideoMeta, settings: &ExportSettings) -> u64 { @@ -425,6 +434,7 @@ fn forces_encode(project: &Project) -> bool { .iter() .any(|&lane| project.lane(lane).iter().any(|c| !c.speed.is_normal())) || equalized(project) + || mastered(project) } /// What the sound is written by. Every audio encoder here is software -- there @@ -564,8 +574,11 @@ fn copy_audio(project: &Project, meta: &VideoMeta) -> crate::Result crate::Result Self { + Self { + ceiling_db: -1.0, + on: false, + } + } +} + +impl Limiter { + /// The ceilings a front-end may set, and what a file may name: a limiter + /// above full scale would limit nothing, and one 24 dB down is already a + /// fader. + pub const MIN_DB: f32 = -24.0; + pub const MAX_DB: f32 = 0.0; + + /// The setting with `ceiling_db` put inside the range above, which is what + /// a nudge and a parsed line both go through. Not finite means the default. + pub fn with_ceiling(self, ceiling_db: f32) -> Self { + Self { + ceiling_db: match ceiling_db.is_finite() { + true => ceiling_db.clamp(Self::MIN_DB, Self::MAX_DB), + false => Self::default().ceiling_db, + }, + ..self + } + } + + /// Whether it is doing anything to the sound -- what an export asks before + /// it decides a packet copy would be a lie. + pub fn is_active(self) -> bool { + self.on + } +} + +/// dBFS as an amplitude. `db_to_linear(0.0)` is exactly 1.0, which is what +/// keeps a flat setting a bit-exact passthrough. +pub fn db_to_linear(db: f32) -> f32 { + match db == 0.0 { + true => 1.0, + false => 10f32.powf(db / 20.0), + } +} + +/// One running limiter: the delay line, the peak window and the gain. +pub struct LimiterState { + channels: usize, + /// The delayed mix, one frame per slot, `lookahead + 1` frames round. + line: Vec, + /// The loudest channel of each frame in `line`, same indexing. + peaks: Vec, + /// Where the next frame is written; the frame read out is the one after it. + at: usize, + /// Frames still to be swallowed before anything is emitted -- the empty + /// delay line, which is how the latency is paid back (module docs). + warm: usize, + gain: f32, + ceiling: f32, + /// Where the knee starts, as an amplitude: under this the fast path runs + /// and no logarithm is taken. + knee_floor: f32, + release: f32, +} + +impl LimiterState { + pub fn new(params: &Limiter, sample_rate: u32, channels: usize) -> Self { + let channels = channels.max(1); + let frames = ((LOOKAHEAD_MS / 1000.0 * sample_rate as f32) as usize).max(1) + 1; + let ceiling_db = params.with_ceiling(params.ceiling_db).ceiling_db; + Self { + channels, + line: vec![0.0; frames * channels], + peaks: vec![0.0; frames], + at: 0, + warm: frames - 1, + gain: 1.0, + ceiling: db_to_linear(ceiling_db), + knee_floor: db_to_linear(ceiling_db - KNEE_DB / 2.0), + // One time constant per sample: the gain covers 63% of the way back + // in `RELEASE_MS`. + release: 1.0 - (-1000.0 / (RELEASE_MS * sample_rate as f32)).exp(), + } + } + + /// Rewrites `buf` -- interleaved frames -- as the limited mix. Shorter than + /// what came in by the delay line's length, once, at the first call. + pub fn process(&mut self, buf: &mut Vec) { + let channels = self.channels; + let frames = buf.len() / channels; + let mut out: Vec = Vec::with_capacity(buf.len()); + for f in 0..frames { + let frame = &buf[f * channels..(f + 1) * channels]; + let peak = frame.iter().fold(0.0f32, |m, s| m.max(s.abs())); + self.line[self.at * channels..(self.at + 1) * channels].copy_from_slice(frame); + self.peaks[self.at] = peak; + self.at = (self.at + 1) % self.peaks.len(); + + // Every frame still in the line, the one about to leave included: + // the gain below is therefore never larger than what the *emitted* + // frame needs, which is the whole no-overshoot guarantee. + let window = self.peaks.iter().fold(0.0f32, |m, &p| m.max(p)); + let want = match window <= self.knee_floor { + true => 1.0, + false => self.reduction(window), + }; + // Up is the release, down is instant -- and instant is safe here + // only because the frame it is for has not been emitted yet. + self.gain += (want - self.gain).max(0.0) * self.release; + self.gain = self.gain.min(want); + + if self.warm > 0 { + self.warm -= 1; + continue; + } + for c in 0..channels { + out.push(self.line[self.at * channels + c] * self.gain); + } + } + *buf = out; + } + + /// The gain the loudest frame in the window needs: 1.0 under the knee, the + /// knee's own curve across it, `ceiling/peak` above it. + fn reduction(&self, peak: f32) -> f32 { + let level = 20.0 * peak.log10(); + let ceiling = 20.0 * self.ceiling.log10(); + let over = level - ceiling; + let out = match over >= KNEE_DB / 2.0 { + true => ceiling, + // The cookbook's quadratic knee. At `over == 0` this is already + // `KNEE_DB/8` under the ceiling and it never crosses it, so nothing + // the knee passes needs a clamp behind it. + false => level - (over + KNEE_DB / 2.0).powi(2) / (2.0 * KNEE_DB), + }; + 10f32.powf((out - level) / 20.0) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The promise the whole file exists for: a sum well past full scale comes + /// out under the ceiling, sample for sample, and the quiet part of the same + /// stream is left where it was. + #[test] + fn a_hot_mix_comes_out_under_the_ceiling() { + let rate = 48_000; + let params = Limiter { + ceiling_db: -3.0, + on: true, + }; + let mut state = LimiterState::new(¶ms, rate, 2); + // Half a second of quiet, then half a second at 4x full scale: the + // join is where an attack overshoot would show. + let mut buf: Vec = (0..rate) + .flat_map(|i| { + let t = i as f32 / rate as f32; + let amp = match i < rate / 2 { + true => 0.05, + false => 4.0, + }; + let s = amp * (t * 440.0 * std::f32::consts::TAU).sin(); + [s, s] + }) + .collect(); + let quiet_in = buf[..rate as usize / 2].to_vec(); + state.process(&mut buf); + let ceiling = db_to_linear(-3.0); + let peak = buf.iter().fold(0.0f32, |m, s| m.max(s.abs())); + assert!( + peak <= ceiling + 1e-6, + "peak {peak} passed the {ceiling} ceiling" + ); + // ...and it is not simply silence: the loud half is right at the wall. + assert!( + peak > ceiling * 0.99, + "peak {peak} is nowhere near the wall" + ); + // The quiet half is untouched, bar the frames the lookahead eats and + // the ones where the gain has already started coming down for the loud + // part that is about to arrive. + let head = quiet_in.len() / 2; + for (a, b) in buf[..head].iter().zip(&quiet_in[..head]) { + assert!((a - b).abs() < 1e-6, "{a} != {b} under the knee"); + } + // The delay line is paid back, not carried: the output is shorter by + // exactly the lookahead and nothing else. + assert_eq!(buf.len(), rate as usize * 2 - (state.peaks.len() - 1) * 2); + } + + /// Flat settings are a passthrough, which is what the export invariant + /// rests on: 0 dB is exactly 1.0, never 0.9999999. + #[test] + fn zero_db_is_exactly_unity() { + assert_eq!(db_to_linear(0.0), 1.0); + assert!((db_to_linear(-6.0) - 0.5011872).abs() < 1e-6); + assert!(!Limiter::default().is_active(), "off until asked for"); + assert_eq!( + Limiter::default().with_ceiling(-99.0).ceiling_db, + Limiter::MIN_DB + ); + assert_eq!( + Limiter::default().with_ceiling(f32::NAN).ceiling_db, + Limiter::default().ceiling_db + ); + } +} diff --git a/crates/engine/src/playback.rs b/crates/engine/src/playback.rs index 45bbc2c..12b149d 100644 --- a/crates/engine/src/playback.rs +++ b/crates/engine/src/playback.rs @@ -496,11 +496,14 @@ impl PlaybackSession { // then refuses every file on it for not matching. The rule this and // [`audio_source_of`] share: nothing may assume what source 0 *is*. // - // ponytail: a timeline of nothing but stills, or of stills and songs, - // still comes back at the rate its scaffold implies rather than the one - // it was cut at -- the rate is written nowhere in the file. The upgrade - // path is a dialect that writes it (`crate::edith`), which is also what - // a project naming no file at all would need. + // A v9 file says what rate it was cut at, and that answer beats the + // scaffold's *where the scaffold has none to give*: a still and a song + // are both given a made-up rate (`IMAGE_ONLY_RATE`, + // `AUDIO_ONLY_CANVAS`), so a timeline of nothing but those used to come + // back at 30 fps however it was cut. A scaffold with a picture keeps + // defining the timeline as it always did -- it is the file every clip + // on the lane was conformed to, and the two agree by construction. + let saved_fps = doc.fps.filter(|f| f.is_finite() && *f > 0.0); let scaffold = doc .sources .iter() @@ -530,7 +533,8 @@ impl PlaybackSession { // like every other worker opened here. let (mut meta, stream) = match crate::is_audio(&first.path) { true => { - let (width, height, frame_rate) = AUDIO_ONLY_CANVAS; + let (width, height, canvas_fps) = AUDIO_ONLY_CANVAS; + let frame_rate = saved_fps.unwrap_or(canvas_fps); let meta = VideoMeta { width, height, @@ -547,11 +551,12 @@ impl PlaybackSession { false if crate::is_image(&first.path) => { let still = crate::decode::Still::open(&first.path) .map_err(|e| format!("source {}: {e}", first.path.display()))?; + let frame_rate = saved_fps.unwrap_or(IMAGE_ONLY_RATE); let meta = VideoMeta { width: still.width, height: still.height, - frame_rate: IMAGE_ONLY_RATE, - frame_count: image_frames(IMAGE_ONLY_RATE), + frame_rate, + frame_count: image_frames(frame_rate), codec: Codec::H264, }; let stream = DecodeSession::open_still( @@ -668,7 +673,8 @@ impl PlaybackSession { } let playhead = doc.playhead; - let project = Project::from_parts(doc.sources, doc.lanes, doc.eq, doc.color)?; + let project = Project::from_parts(doc.sources, doc.lanes, doc.eq, doc.color)? + .with_mix(&doc.gains, doc.limiter); 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 @@ -769,9 +775,19 @@ impl PlaybackSession { path, &sources, &lanes, + // The lane volumes and the limiter with them: a mix that vanished + // on a reload would be a mix nobody could keep, and both are the + // project's, not this machine's (the monitoring volume is not + // written and never will be). + &self.project.lane_gains(), &eq, &color, (self.meta.width, self.meta.height), + // ...and the rate it was cut at, which nothing else in the file + // says: a timeline of stills and songs used to come back at + // whatever its scaffold implied (`open_project`). + Some(self.meta.frame_rate), + self.project.limiter(), playhead, ) } @@ -1094,6 +1110,31 @@ impl PlaybackSession { self.edit(|p| p.set_eq(lane, idx, params)) } + /// How loud that lane plays, in dB -- everything on it, every frequency of + /// it. See [`Project::lane_gain_db`] for what it is *not*. + pub fn lane_gain_db(&self, lane: Lane) -> f32 { + self.project.lane_gain_db(lane) + } + + /// Sets it. One undo step and a reseek, the equalizer's rule for the + /// equalizer's reason: the mixer is rebuilt from the new volumes right + /// where the playhead is, so a track turned down during playback is heard + /// turned down from the next chunk on. + pub fn set_lane_gain_db(&mut self, lane: Lane, db: f32) -> bool { + self.edit(|p| p.set_lane_gain_db(lane, db)) + } + + /// The master limiter the whole mix is summed through. + pub fn limiter(&self) -> crate::limiter::Limiter { + self.project.limiter() + } + + /// Sets it, live like a lane volume and for the same reason -- the ceiling + /// a person is dragging has to be the ceiling they are hearing. + pub fn set_limiter(&mut self, limiter: crate::limiter::Limiter) -> bool { + self.edit(|p| p.set_limiter(limiter)) + } + /// Lifts one lane's clip out, leaving a gap: black frames on the video lane, /// silence on the audio one, and nothing else moves. Reseeks, because what /// the playhead sits on has changed. `false` for a bad index -- the lift of @@ -1797,11 +1838,18 @@ impl PlaybackSession { // Each source on the stream it was placed with: what plays is what // the library row said, and what an export copies (`export::run`). let sources = self.project.audio_sources(); - audio_running = - match AudioSession::open_mixed_streams_speed(&sources, &segs, &eqs, &speeds) { - Ok(Some((_, rx))) => audio.spawn_feeder(rx), - _ => false, - }; + // ...and the mix settings over the lot: each lane's own volume on + // its way into the sum and the master limiter over the sum, both + // rebuilt here like the curves above, which is what makes a lane + // fader and a ceiling audible while the timeline runs. + let gains = self.project.audio_gains(); + let limiter = self.project.limiter(); + audio_running = match AudioSession::open_mixed_streams_master( + &sources, &segs, &eqs, &speeds, &gains, limiter, + ) { + Ok(Some((_, rx))) => audio.spawn_feeder(rx), + _ => false, + }; if !audio_running { // Nothing will ever be fed again; let `tick` fall to wall time // instead of waiting on a device that has no more work coming. diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index e87dd41..818741e 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -66,8 +66,18 @@ use std::path::{Path, PathBuf}; use crate::color::ColorParams; use crate::eq::EqParams; +use crate::limiter::{Limiter, db_to_linear}; use crate::scale::FitPolicy; +/// How far down a lane's own volume goes ([`Project::set_lane_gain_db`]). +/// -60 dB is a thousandth of the amplitude -- a track that is out of the mix +/// for every purpose but the honest one, which is that it is still a level and +/// not a mute. +pub const MIN_GAIN_DB: f32 = -60.0; +/// ...and how far up. +12 dB is four times the amplitude, which is as much as +/// a mix bus can take before the limiter is doing all the work. +pub const MAX_GAIN_DB: f32 = 12.0; + /// How fast a clip plays, in **thousandths of real time**: 1000 is the speed it /// was shot at, 2000 twice that, 500 half. An integer and not an `f32` for /// [`Clip`]'s sake -- a clip is `Copy` *and* `Eq`, a float is neither exactly @@ -477,21 +487,29 @@ struct LaneData { kind: LaneKind, /// Sorted by `start` and disjoint ([`sorted_disjoint`]). clips: Vec, + /// How loud this lane plays, in dB, `0.0` for one nobody has touched -- + /// [`Project::lane_gain_db`]. Whole-lane and whole-band, which is what + /// makes it a different thing from a clip's equalizer: it moves everything + /// on the track by the same amount, cuts included. Meaningless on a video + /// lane, where it is kept at 0 and asked by nothing. + gain_db: f32, } impl LaneData { + fn new(kind: LaneKind, clips: Vec) -> Self { + Self { + kind, + clips, + gain_db: 0.0, + } + } + /// The two lanes a project starts with: `V1` then `A1`, in display order. /// One place, because a freshly opened file is exactly this pair. fn two_lanes(video: Vec, audio: Vec) -> Vec { vec![ - LaneData { - kind: LaneKind::Video, - clips: video, - }, - LaneData { - kind: LaneKind::Audio, - clips: audio, - }, + LaneData::new(LaneKind::Video, video), + LaneData::new(LaneKind::Audio, audio), ] } } @@ -600,6 +618,12 @@ pub struct Project { /// Never rolled back by an undo: an id retired by an undone split must not /// come back and group two clips that were never together. next_link: u32, + /// The master limiter every lane's sound is summed *through* + /// ([`Project::limiter`]). Off by default, and not in the lane list, which + /// is what the history snapshots hold: it is a setting on the mix, like the + /// project's resolution is a setting on the picture, and neither is an undo + /// step. + limiter: Limiter, } impl Project { @@ -628,6 +652,7 @@ impl Project { color: Vec::new(), history: Vec::new(), next_link: 1, + limiter: Limiter::default(), } } @@ -665,7 +690,7 @@ impl Project { } let lanes: Vec = lanes .into_iter() - .map(|(kind, clips)| LaneData { kind, clips }) + .map(|(kind, clips)| LaneData::new(kind, clips)) .collect(); for (data, lane) in lanes.iter().zip(handles(&lanes)) { let name = lane.label(); @@ -735,6 +760,7 @@ impl Project { color, history: Vec::new(), next_link, + limiter: Limiter::default(), }) } @@ -770,10 +796,7 @@ impl Project { /// ([`Project::from_parts`]); nothing plays until something is placed. pub fn add_lane(&mut self, kind: LaneKind) -> Lane { self.snapshot(); - self.lanes.push(LaneData { - kind, - clips: Vec::new(), - }); + self.lanes.push(LaneData::new(kind, Vec::new())); Lane::new(kind, self.lane_count(kind) - 1) } @@ -1053,6 +1076,92 @@ impl Project { ) } + /// How loud `lane` plays, in dB: `0.0` for one nobody has touched, and for + /// a lane that is not there. Whole-lane and whole-band -- every clip on the + /// track moves by it, which is what makes it a different control from a + /// clip's equalizer (one frequency range of one take) and from the master + /// volume (what this machine monitors at, which no file carries). + pub fn lane_gain_db(&self, lane: Lane) -> f32 { + self.index(lane).map_or(0.0, |i| self.lanes[i].gain_db) + } + + /// Sets that lane's volume, clamped to [`MIN_GAIN_DB`]..=[`MAX_GAIN_DB`]. + /// One undo step like every other edit -- it is in the lane list, so an + /// undo restores it with the rest. `false`, and no history, for a lane that + /// is not there, for a value that is not finite, and for one already set. + pub fn set_lane_gain_db(&mut self, lane: Lane, db: f32) -> bool { + let Some(i) = self.index(lane) else { + return false; + }; + if !db.is_finite() { + return false; + } + let db = db.clamp(MIN_GAIN_DB, MAX_GAIN_DB); + if self.lanes[i].gain_db == db { + return false; + } + self.snapshot(); + self.lanes[i].gain_db = db; + true + } + + /// Every lane's volume in dB, in display order -- what a save writes, + /// beside the lanes [`Project::without_orphan_sources`] hands back. + pub fn lane_gains(&self) -> Vec { + self.lanes.iter().map(|l| l.gain_db).collect() + } + + /// The mix settings a *load* puts back: lane volumes in display order (a + /// short list leaves the rest at unity) and the master limiter, both + /// clamped as their setters clamp them. + /// + /// The load's own door, beside [`from_parts`](Project::from_parts): the + /// setters push an undo step, and a project that arrives one undo away from + /// a state it was never in is a project whose first ctrl+z is a surprise. + pub fn with_mix(mut self, gains: &[f32], limiter: Limiter) -> Self { + for (data, &db) in self.lanes.iter_mut().zip(gains) { + if db.is_finite() { + data.gain_db = db.clamp(MIN_GAIN_DB, MAX_GAIN_DB); + } + } + self.limiter = limiter.with_ceiling(limiter.ceiling_db); + self + } + + /// What each of [`audio_segments_from`](Project::audio_segments_from)'s + /// lanes is multiplied by on its way into the mix: the same lanes in the + /// same order, as *amplitudes*, so the mixer never sees a decibel. `1.0` + /// for a lane nobody has turned, which is a multiply f32 leaves alone -- + /// the bit-exact path. + pub fn audio_gains(&self) -> Vec { + self.audio_lanes() + .into_iter() + .map(|lane| db_to_linear(self.lane_gain_db(lane))) + .collect() + } + + /// The master limiter the mix is summed through. A project setting, not a + /// clip's and not a lane's: there is one mix. + pub fn limiter(&self) -> Limiter { + self.limiter + } + + /// Sets it, with the ceiling clamped to what [`Limiter`] allows. `false` + /// for a setting already in force. + /// + /// ponytail: not an undo step, for the reason the project resolution is not + /// one ([`crate::PlaybackSession::set_resolution`]) -- it is not in the + /// lane list the history snapshots. Upgrade path is a history entry that + /// holds the mix settings beside the lanes. + pub fn set_limiter(&mut self, limiter: Limiter) -> bool { + let limiter = limiter.with_ceiling(limiter.ceiling_db); + if self.limiter == limiter { + return false; + } + self.limiter = limiter; + true + } + /// What the clip at `idx` of `lane` plays through, or `None` for one that /// plays flat (and for an index that is not there) -- what a feeder and an /// export ask before they build an [`crate::eq::EqState`]. @@ -5342,14 +5451,8 @@ mod tests { speed: Speed::NORMAL, }; let lanes = vec![ - LaneData { - kind: LaneKind::Video, - clips: vec![linked(3, 4)], - }, - LaneData { - kind: LaneKind::Video, - clips: vec![linked(5, 4)], - }, + LaneData::new(LaneKind::Video, vec![linked(3, 4)]), + LaneData::new(LaneKind::Video, vec![linked(5, 4)]), ]; assert_eq!( links_are_consistent(&lanes).unwrap_err().to_string(), @@ -5364,7 +5467,7 @@ mod tests { /// checked at the untrusted door and no edit can produce these. #[test] fn a_group_may_span_any_lane() { - let lane = |kind, clips: Vec| LaneData { kind, clips }; + let lane = |kind, clips: Vec| LaneData::new(kind, clips); let one = |start: u32, end: u32, link| Clip { start, in_frame: start, diff --git a/crates/engine/tests/audio_export.rs b/crates/engine/tests/audio_export.rs index 587c19e..550a80d 100644 --- a/crates/engine/tests/audio_export.rs +++ b/crates/engine/tests/audio_export.rs @@ -15,7 +15,7 @@ use std::path::{Path, PathBuf}; use std::time::{Duration, Instant}; use engine::export::{ExportSettings, Format}; -use engine::project::{LaneKind, Source, Speed}; +use engine::project::{Lane, LaneKind, Source, Speed}; use engine::scale::FitPolicy; use engine::{AudioSession, Clip, ExportHandle, Project}; @@ -365,6 +365,126 @@ fn a_still_and_a_song_export_as_an_mp4_with_sound() { /// Cancel leaves nothing behind -- not the output, not the `.part`. The /// timeline is long enough (a minute of audio) that the escape lands mid-decode /// rather than after the file is already closed. +/// What the two mix settings do to a *written file*, which is the only place +/// the claim can be checked: a track's fader is that track's alone, and the +/// master limiter holds the sum of them under its ceiling instead of letting it +/// square off at full scale. +/// +/// Four audio tracks of the same second, so the sum is four times one file and +/// well past what a sample can hold. Measured as the peak of the WAV read back +/// through the engine's own reader -- a level, not a shape, because that is +/// exactly what a limiter promises. +#[test] +fn a_fader_is_one_tracks_own_and_the_limiter_holds_the_sum() { + let clip = Clip { + start: 0, + in_frame: 0, + out_frame: 30, + source: 0, + link: None, + eq: None, + color: None, + fit: FitPolicy::default(), + speed: Speed::NORMAL, + }; + let four = || { + Project::from_parts( + vec![Source::new(asset("test_av.mp4"), 0)], + vec![ + (LaneKind::Video, vec![clip]), + (LaneKind::Audio, vec![clip]), + (LaneKind::Audio, vec![clip]), + (LaneKind::Audio, vec![clip]), + (LaneKind::Audio, vec![clip]), + ], + Vec::new(), + Vec::new(), + ) + .expect("one second on four audio tracks") + }; + let write = |project: Project, name: &str| { + let out = out_path(name, "wav"); + let handle = engine::export::start( + project, + meta(), + &out, + &ExportSettings { + format: Format::Wav, + ..Default::default() + }, + ); + wait(&handle, Duration::from_secs(60)).unwrap_or_else(|e| panic!("{name}: {e}")); + let (audio, samples) = decode(&out); + let peak = samples.iter().fold(0.0f32, |m, s| m.max(s.abs())); + let level = rms(&samples, usize::from(audio.channels), 0.05, 0.95); + let _ = std::fs::remove_file(&out); + (peak, level) + }; + + // Four copies of one file, each fader all the way up: the sum is well past + // what a sample can hold, and with no limiter it is clamped at full scale + // by the mixer's own backstop -- which is the clipping this exists for. + let hot = || { + let mut project = four(); + for ord in 0..4 { + assert!(project.set_lane_gain_db( + Lane::new(LaneKind::Audio, ord), + engine::project::MAX_GAIN_DB + )); + } + project + }; + let (flat_peak, flat_level) = write(hot(), "mix_flat"); + println!("flat: peak {flat_peak:.4} rms {flat_level:.4}"); + + // One track's fader, and one track's only: A2, A3 and A4 all the way down + // leaves a quarter of the sum, so the level drops by ~12 dB against the + // four of them at the same setting. A whole-band + // change -- there is no frequency in this claim, which is what makes it a + // different control from the equalizer. + let (unity_peak, unity_level) = write(four(), "mix_unity"); + let mut down = four(); + for ord in 1..4 { + assert!(down.set_lane_gain_db( + Lane::new(LaneKind::Audio, ord), + engine::project::MIN_GAIN_DB + )); + } + let (_, quiet_level) = write(down, "mix_fader"); + let drop_db = 20.0 * (quiet_level / unity_level).log10(); + println!("one track alone: rms {quiet_level:.4} ({drop_db:.1} dB)"); + assert!( + (drop_db + 12.0).abs() < 1.5, + "three of four tracks down left {drop_db:.1} dB, not ~-12" + ); + + // The limiter over the same hot sum: the peak lands under the ceiling, and + // the sound is still there (a limiter that silenced the mix would pass a + // peak test and fail every ear). + let ceiling_db = -3.0; + let mut limited = hot(); + assert!(limited.set_limiter(engine::limiter::Limiter { + ceiling_db, + on: true, + })); + let (peak, level) = write(limited, "mix_limited"); + let ceiling = 10f32.powf(ceiling_db / 20.0); + println!("limited: peak {peak:.4} vs ceiling {ceiling:.4} rms {level:.4}"); + assert!( + flat_peak > ceiling, + "the flat mix was not hot to begin with" + ); + assert!( + peak <= ceiling + 1e-3, + "peak {peak:.4} passed the {ceiling:.4} ceiling" + ); + assert!(level > unity_level, "the limiter took the mix out"); + assert!( + unity_peak < 1.0, + "four at unity fit; the +12 dB four did not" + ); +} + #[test] fn a_cancelled_audio_export_leaves_no_file() { let source = asset("test_av.mp4"); diff --git a/crates/engine/tests/backends.rs b/crates/engine/tests/backends.rs index bc24508..484d927 100644 --- a/crates/engine/tests/backends.rs +++ b/crates/engine/tests/backends.rs @@ -204,6 +204,70 @@ fn audio_only_job_names_its_encoder(format: Format) { assert_eq!(opened, planned, "{}", format.ext()); } +/// A mixed timeline cannot be copied, and the card must say so *before* the +/// export: a fader and a limiter both live where the lanes are summed, and a +/// copied AAC packet was never summed at all -- so an mp4 of such a timeline is +/// decoded and re-encoded, and the line names the encoder that will do it. +/// +/// The truthfulness rule of this whole file, applied to the one edit that used +/// to be invisible to it. +#[test] +fn a_mixed_timeline_says_it_re_encodes_and_then_does() { + let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); + assert_eq!( + session.planned_audio(Format::Mp4), + "AAC copy", + "a timeline nobody has mixed is still a copy" + ); + // A fader off unity... + assert!(session.set_lane_gain_db(engine::project::Lane::A1, -3.0)); + let planned = session.planned_audio(Format::Mp4); + assert!(planned.contains("encode"), "a faded lane: {planned}"); + // ...and back at unity it is a copy again: the answer follows the edit, it + // is not a latch. + assert!(session.set_lane_gain_db(engine::project::Lane::A1, 0.0)); + assert_eq!(session.planned_audio(Format::Mp4), "AAC copy"); + // ...and the limiter alone does it too. + assert!(session.set_limiter(engine::limiter::Limiter { + ceiling_db: -1.0, + on: true, + })); + assert_eq!(session.planned_audio(Format::Mp4), planned); + + // ...and the job opens exactly that, which is the pin the whole file is + // about: the encoders line published by the running export. + let out = out_path("mixed", "mp4"); + let handle = session.export_to_with( + &out, + &ExportSettings { + format: Format::Mp4, + ..ExportSettings::default() + }, + ); + let started = Instant::now(); + let opened = loop { + if let Some(line) = handle.encoders() { + break line; + } + assert!( + !handle.is_finished(), + "the export settled before it opened an encoder: {:?}", + handle.result().map(|r| r.err()) + ); + assert!( + started.elapsed() < Duration::from_secs(60), + "no encoder was published" + ); + std::thread::sleep(Duration::from_millis(10)); + }; + handle.cancel(); + wind_down(&handle); + assert!( + opened.ends_with(&planned), + "{opened} does not end in {planned}" + ); +} + /// Waits for a cancelled job to settle, so its `.part` is gone before the test /// ends -- and so no worker outlives the process holding a VA-API session. fn wind_down(handle: &ExportHandle) { diff --git a/crates/engine/tests/saveload.rs b/crates/engine/tests/saveload.rs index 3c287c1..314f8e9 100644 --- a/crates/engine/tests/saveload.rs +++ b/crates/engine/tests/saveload.rs @@ -209,7 +209,7 @@ fn a_version_1_project_loads_fully_grouped_and_saves_as_version_7() { let v2 = dir.join("new.edith"); loaded.save_project(&v2).expect("save"); let text = std::fs::read_to_string(&v2).expect("read back"); - assert!(text.starts_with("edith 8\n"), "{text}"); + assert!(text.starts_with("edith 9\n"), "{text}"); assert!( text.contains("\nresolution 1280 720\n"), "a project with no resolution of its own is saved at source 0's: {text}" @@ -297,7 +297,7 @@ fn a_version_4_project_holds_more_than_two_lanes() { loaded.save_project(&again).expect("save"); assert_eq!( std::fs::read_to_string(&again).expect("read back"), - "edith 8\nplayhead 0\nresolution 1280 720\nsource 0 test_av.mp4\n\ + "edith 9\nplayhead 0\nresolution 1280 720\nfps 30.0\nsource 0 test_av.mp4\n\ video 1 0 0 30 0 3 - - fit 1000\naudio 1\n\ video 2 40 0 20 0 - - - fit 1000\naudio 2 0 0 30 0 3 - - fit 1000\n", "a four-lane project is written as it was read, three versions on" @@ -327,7 +327,7 @@ fn a_version_5_project_carries_per_clip_equalizers() { loaded.save_project(&again).expect("save"); assert_eq!( std::fs::read_to_string(&again).expect("read back"), - "edith 8\nplayhead 0\nresolution 1280 720\nsource 0 test_av.mp4\n\ + "edith 9\nplayhead 0\nresolution 1280 720\nfps 30.0\nsource 0 test_av.mp4\n\ eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk\n\ eq 12000.0:6.25:0.5:hs\n\ video 1 0 0 30 0 - 0 - fit 1000\nvideo 1 30 30 60 0 - 1 - fit 1000\n\ @@ -362,7 +362,7 @@ fn a_version_6_project_carries_per_clip_colours() { loaded.save_project(&again).expect("save"); assert_eq!( std::fs::read_to_string(&again).expect("read back"), - "edith 8\nplayhead 0\nresolution 1280 720\nsource 0 test_av.mp4\n\ + "edith 9\nplayhead 0\nresolution 1280 720\nfps 30.0\nsource 0 test_av.mp4\n\ eq 80.0:-3.0:0.707:ls\n\ color 0.1:1.2:0.9:-0.3\n\ color -0.25:1.0:0.0:0.5\n\ @@ -412,7 +412,7 @@ fn a_version_7_project_carries_a_resolution_and_fit_policies() { loaded.save_project(&again).expect("save"); assert_eq!( std::fs::read_to_string(&again).expect("read back"), - "edith 8\nplayhead 0\nresolution 960 720\nsource 0 test_av.mp4\n\ + "edith 9\nplayhead 0\nresolution 960 720\nfps 30.0\nsource 0 test_av.mp4\n\ video 1 0 0 30 0 - - - fill 1000\nvideo 1 30 30 60 0 - - - center 1000\n\ audio 1 0 0 60 0 - - - fit 1000\n", "a v7 project is written back as the v8 it now is: the same clips, each \ @@ -670,7 +670,7 @@ fn malformed_files_are_numbered_errors_and_never_panics() { for (text, want) in [ ( - "edith 9\nsource 0 test_av.mp4\nvideo 1 0 0 30 0 - - - fit\n", + "edith 10\nsource 0 test_av.mp4\nvideo 1 0 0 30 0 - - - fit\n", "line 1", ), // An eq index the table does not hold, and a band shape there is none. @@ -755,3 +755,74 @@ fn a_source_that_no_longer_matches_the_timeline_is_refused_in_import_words() { ) ); } + +/// The mix a project was left at comes back with it: a track's fader, the +/// master limiter and the rate the timeline was cut at. A fader that vanished +/// on a reload would be a setting nobody could keep. +#[test] +fn the_mix_survives_a_save_and_an_open() { + use engine::project::{Lane, LaneKind}; + let dir = scratch("mix"); + let source = copy_in(&dir, "test_av.mp4"); + let mut saved = PlaybackSession::open(&source).expect("open the fixture"); + let a2 = saved.add_lane(LaneKind::Audio); + assert!(saved.set_lane_gain_db(Lane::A1, -6.0)); + assert!(saved.set_lane_gain_db(a2, 3.0)); + let limiter = engine::limiter::Limiter { + ceiling_db: -2.0, + on: true, + }; + assert!(saved.set_limiter(limiter)); + let path = dir.join("mix.edith"); + saved.save_project(&path).expect("save"); + + let mut loaded = PlaybackSession::open_project(&path).expect("open the project"); + assert_eq!(loaded.lane_gain_db(Lane::A1), -6.0, "A1's fader"); + assert_eq!(loaded.lane_gain_db(a2), 3.0, "A2's own, not A1's"); + assert_eq!(loaded.limiter(), limiter); + assert!(!loaded.undo(), "a loaded mix is not an undo step"); + // ...and saving it again is the same bytes: the format holds all of it. + let again = dir.join("again.edith"); + loaded + .save_project(&again) + .expect("save the loaded project"); + assert_eq!( + std::fs::read(&path).unwrap(), + std::fs::read(&again).unwrap(), + "save -> load -> save is not a fixed point" + ); +} + +/// The other half of the v9 bump, and the debt it pays: a timeline holding +/// nothing but a song has no file to take a frame rate from, so it used to come +/// back at the canvas rate whatever it was cut at. The written `fps` is now +/// preferred over that inference -- and a project whose scaffold *does* have a +/// picture still takes the rate from the file, which is what every clip on it +/// was conformed to. +#[test] +fn a_song_only_project_comes_back_at_the_rate_it_names() { + let dir = scratch("song_fps"); + copy_in(&dir, "test_tone.mp3"); + let path = dir.join("song.edith"); + std::fs::write( + &path, + "edith 9\nplayhead 0\nresolution 1920 1080\nfps 24.0\nsource 0 test_tone.mp3\n\ + video 1\naudio 1 0 0 24 0 - - - fit 1000\n", + ) + .expect("write a v9 song project"); + let loaded = PlaybackSession::open_project(&path).expect("a song-only project opens"); + assert_eq!(loaded.meta().frame_rate, 24.0, "the rate the file names"); + assert_eq!(loaded.timeline_duration(), 1.0, "one second at 24 fps"); + + // The same file without the line -- which is every dialect before v9 -- + // still comes back at the canvas rate, so an old project is unchanged. + let old = dir.join("song8.edith"); + std::fs::write( + &old, + "edith 8\nplayhead 0\nresolution 1920 1080\nsource 0 test_tone.mp3\n\ + video 1\naudio 1 0 0 24 0 - - - fit 1000\n", + ) + .expect("write a v8 song project"); + let loaded = PlaybackSession::open_project(&old).expect("a v8 song project opens"); + assert_eq!(loaded.meta().frame_rate, 30.0, "the canvas rate, as before"); +} diff --git a/crates/engine/tests/silence.rs b/crates/engine/tests/silence.rs index fc5a181..735a2d6 100644 --- a/crates/engine/tests/silence.rs +++ b/crates/engine/tests/silence.rs @@ -360,10 +360,22 @@ fn scanning_a_clip_and_cutting_what_it_finds() { std::fs::create_dir_all(&dir).expect("a place to save"); let file = dir.join("cut.edith"); let (sources, lanes, eq, color) = p.without_orphan_sources(); - engine::edith::save(&file, &sources, &lanes, &eq, &color, (1920, 1080), 0).expect("save"); + engine::edith::save( + &file, + &sources, + &lanes, + &p.lane_gains(), + &eq, + &color, + (1920, 1080), + None, + p.limiter(), + 0, + ) + .expect("save"); let text = std::fs::read_to_string(&file).expect("read it back"); assert!( - text.starts_with("edith 8"), + text.starts_with("edith 9"), "{:?}", &text[..16.min(text.len())] );