forge
Explore
Log in

Don't you dare go Hollow

Every track has its own volume and the mix has a ceiling

Browse files at this commit

dc7d07d5abbd67608fdc205f2bac038fda21eda9Ahmet Kaan GümüşParent: 59c74e8
  • feat
    • every track has its own volume and the mix has a ceiling
Show full message
✨ feat(mix): every track has its own volume and the mix has a ceiling

A fader per audio track and one master limiter over the sum of them, both
applied where the lanes are added and nowhere else -- so what an export
writes is what the room heard, by construction rather than by two call
sites agreeing.

A track's fader moves everything on it, every frequency: it is not the
equalizer (one take, one band) and not the panel's volume (this machine's
monitoring, which no file carries). The limiter is lookahead, soft-knee
and per sample: the peak of an exported file is a measurement, not a hope,
and the hard clamp stays behind it as the backstop.

Flat settings are still the bit-exact passthrough: one lane at unity with
the limiter off never opens a mixer thread, and an mp4 of such a timeline
is still a packet copy. A mixed one re-encodes, and the card says so
before the export starts.

Both belong to the project, so `.edith` is v9: `fps`, `limiter` and `gain`
lines, every older dialect still loading flat. The rate line pays an old
debt with it -- a timeline of nothing but stills and songs now comes back
at the rate it was cut at instead of the one its scaffold implied.

UI: the mix card (f, or an audio track's own header), rows with steppers
and hold-to-run arrows, and the track's level on its header.
crates/app/src/keymap.rsmodified+18 -4
@@ -77,13 +77,14 @@ pub enum ActionId {
77 Equalizer,77 Equalizer,
78 Speed,78 Speed,
79 Silence,79 Silence,
80+ Mix,
80 CancelExport,81 CancelExport,
81 }82 }
82 83
83 impl ActionId {84 impl ActionId {
84 /// Display order everywhere -- the editor lists them in it and85 /// Display order everywhere -- the editor lists them in it and
85 /// [`Keymap::defaults`] binds them in it.86 /// [`Keymap::defaults`] binds them in it.
86- pub const ALL: [ActionId; 38] = [87+ pub const ALL: [ActionId; 39] = [
87 ActionId::Play,88 ActionId::Play,
88 ActionId::StepBack,89 ActionId::StepBack,
89 ActionId::StepForward,90 ActionId::StepForward,
@@ -121,6 +122,7 @@ impl ActionId {
121 ActionId::Equalizer,122 ActionId::Equalizer,
122 ActionId::Speed,123 ActionId::Speed,
123 ActionId::Silence,124 ActionId::Silence,
125+ ActionId::Mix,
124 ActionId::CancelExport,126 ActionId::CancelExport,
125 ];127 ];
126 128
@@ -164,6 +166,7 @@ impl ActionId {
164 ActionId::Equalizer => "Equalizer",166 ActionId::Equalizer => "Equalizer",
165 ActionId::Speed => "Speed (tape)…",167 ActionId::Speed => "Speed (tape)…",
166 ActionId::Silence => "Silences: cut or speed up…",168 ActionId::Silence => "Silences: cut or speed up…",
169+ ActionId::Mix => "Mix: track volumes and the limiter…",
167 ActionId::CancelExport => "Cancel export",170 ActionId::CancelExport => "Cancel export",
168 }171 }
169 }172 }
@@ -209,6 +212,7 @@ impl ActionId {
209 ActionId::Equalizer => "equalizer",212 ActionId::Equalizer => "equalizer",
210 ActionId::Speed => "speed",213 ActionId::Speed => "speed",
211 ActionId::Silence => "silence",214 ActionId::Silence => "silence",
215+ ActionId::Mix => "mix",
212 ActionId::CancelExport => "cancel-export",216 ActionId::CancelExport => "cancel-export",
213 }217 }
214 }218 }
@@ -265,7 +269,12 @@ impl ActionId {
265 ActionId::ToggleMute269 ActionId::ToggleMute
266 | ActionId::VolumeUp270 | ActionId::VolumeUp
267 | ActionId::VolumeDown271 | ActionId::VolumeDown
268- | ActionId::Equalizer => Category::Audio,272+ | ActionId::Equalizer
273+ // The mix is the project's sound -- what every track plays at and
274+ // what the whole of it is held under -- where the three above it
275+ // are this machine's monitoring. Both are audio, and the card says
276+ // which is which.
277+ | ActionId::Mix => Category::Audio,
269 ActionId::Save | ActionId::Export | ActionId::CancelExport => Category::File,278 ActionId::Save | ActionId::Export | ActionId::CancelExport => Category::File,
270 }279 }
271 }280 }
@@ -601,6 +610,11 @@ impl Keymap {
601 // delete (x and delete) -- what it opens is a card that can cut610 // delete (x and delete) -- what it opens is a card that can cut
602 // forty places at once.611 // forty places at once.
603 b(ActionId::Silence, "u", false),612 b(ActionId::Silence, "u", false),
613+ // The mix card takes "f", for the faders on it: "m" would be
614+ // the word but it is the monitoring mute, which is this
615+ // machine's volume and not the project's -- two things one key
616+ // must not mean.
617+ b(ActionId::Mix, "f", false),
604 b(ActionId::CancelExport, "escape", false),618 b(ActionId::CancelExport, "escape", false),
605 ],619 ],
606 }620 }
@@ -863,7 +877,7 @@ mod tests {
863 #[test]877 #[test]
864 fn every_default_stroke_reaches_its_action() {878 fn every_default_stroke_reaches_its_action() {
865 let k = Keymap::defaults();879 let k = Keymap::defaults();
866- assert_eq!(k.entries().len(), 40);880+ assert_eq!(k.entries().len(), 41);
867 assert_eq!(k.lookup("space", false), Some(ActionId::Play));881 assert_eq!(k.lookup("space", false), Some(ActionId::Play));
868 // The seek keys: bare arrows a frame, ctrl arrows a second, and the two882 // The seek keys: bare arrows a frame, ctrl arrows a second, and the two
869 // ends of the timeline.883 // ends of the timeline.
@@ -1097,7 +1111,7 @@ mod tests {
1097 assert_eq!(whole("edith-keys 1\n").display(ActionId::Cut), "unbound");1111 assert_eq!(whole("edith-keys 1\n").display(ActionId::Cut), "unbound");
1098 // The label is the editor's column, and never the file's word for it.1112 // The label is the editor's column, and never the file's word for it.
1099 assert_eq!(ActionId::CancelExport.label(), "Cancel export");1113 assert_eq!(ActionId::CancelExport.label(), "Cancel export");
1100- assert_eq!(ActionId::ALL.len(), 38);1114+ assert_eq!(ActionId::ALL.len(), 39);
1101 assert_eq!(k.display(ActionId::ZoomIn), "ctrl+=");1115 assert_eq!(k.display(ActionId::ZoomIn), "ctrl+=");
1102 }1116 }
1103 1117
crates/app/src/main.rsmodified+335 -1
@@ -14,6 +14,7 @@ use engine::color::ColorParams;
14 use engine::decode::Backend;14 use engine::decode::Backend;
15 use engine::eq::{Band, BandKind, EqParams};15 use engine::eq::{Band, BandKind, EqParams};
16 use engine::export::{ExportSettings, Format};16 use engine::export::{ExportSettings, Format};
17+use engine::limiter::Limiter;
17 use engine::project::{Edge, Lane, LaneKind, Source, Speed};18 use engine::project::{Edge, Lane, LaneKind, Source, Speed};
18 use engine::scale::FitPolicy;19 use engine::scale::FitPolicy;
19 use engine::{Clip, Codec, ExportHandle, Frame, PlaybackSession};20 use engine::{Clip, Codec, ExportHandle, Frame, PlaybackSession};
@@ -475,6 +476,16 @@ const SILENCE_SECS_STEP: f64 = 0.05;
475 const SILENCE_DB_RANGE: (f32, f32) = (-80., 0.);476 const SILENCE_DB_RANGE: (f32, f32) = (-80., 0.);
476 const SILENCE_SECS_RANGE: (f64, f64) = (0., 5.);477 const SILENCE_SECS_RANGE: (f64, f64) = (0., 5.);
477 478
479+/// One press of a nudge key on the mix card, in dB: the step every fader and
480+/// the limiter's ceiling moves by. A whole decibel, the smallest move anyone
481+/// hears as a move -- and it lands on round numbers, so a track set by ear
482+/// still reads as a number a person would say.
483+const MIX_DB_STEP: f32 = 1.;
484+
485+/// The mix card's rows below the faders: the limiter's ceiling and its switch.
486+/// One fader per audio track comes first, however many there are.
487+const MIX_MASTER_ROWS: usize = 2;
488+
478 /// The speed-up rate is bounded *below* by real time: a "speed-up" that slows489 /// The speed-up rate is bounded *below* by real time: a "speed-up" that slows
479 /// the silence down would make the timeline longer, which is the one thing490 /// the silence down would make the timeline longer, which is the one thing
480 /// neither button may do. The top is [`Speed::MAX`].491 /// neither button may do. The top is [`Speed::MAX`].
@@ -763,6 +774,14 @@ struct Player {
763 /// The bar is being dragged. On the root like the colour card's, for the774 /// The bar is being dragged. On the root like the colour card's, for the
764 /// same reason: the pointer leaves a 4 px bar on the first move.775 /// same reason: the pointer leaves a 4 px bar on the first move.
765 speed_dragging: bool,776 speed_dragging: bool,
777+ /// The mix card is up: every audio track's own volume and the master
778+ /// limiter, which are project settings and not any clip's -- so unlike the
779+ /// four clip cards there is no handle to hold, only whether it is open.
780+ mix_open: bool,
781+ /// Which of its rows the arrow keys move -- a fader, the limiter's ceiling
782+ /// or its switch. The card's own focus, since nothing in it takes gpui's
783+ /// (ledger:182).
784+ mix_field: usize,
766 /// The silence card is up on this clip -- the lane it is on and its index785 /// The silence card is up on this clip -- the lane it is on and its index
767 /// there, exactly as the speed card's handle is.786 /// there, exactly as the speed card's handle is.
768 silence_open: Option<(Lane, usize)>,787 silence_open: Option<(Lane, usize)>,
@@ -973,6 +992,7 @@ impl Player {
973 ActionId::Equalizer => self.open_eq(cx),992 ActionId::Equalizer => self.open_eq(cx),
974 ActionId::Speed => self.open_speed(cx),993 ActionId::Speed => self.open_speed(cx),
975 ActionId::Silence => self.open_silence(cx),994 ActionId::Silence => self.open_silence(cx),
995+ ActionId::Mix => self.open_mix(None, cx),
976 // Nothing to cancel while nothing is exporting; the export guard in996 // Nothing to cancel while nothing is exporting; the export guard in
977 // the key handler is what answers this one while there is.997 // the key handler is what answers this one while there is.
978 ActionId::CancelExport => {}998 ActionId::CancelExport => {}
@@ -1381,6 +1401,82 @@ impl Player {
1381 cx.notify();1401 cx.notify();
1382 }1402 }
1383 1403
1404+ /// Opens the mix card. `lane` is the row it lands on -- the track whose
1405+ /// header was clicked -- and `None` starts at the top, which is what the
1406+ /// stroke means.
1407+ ///
1408+ /// Nothing here is a clip's, so nothing is refused for want of a selection:
1409+ /// a timeline with no audio track at all still has a limiter to set, and a
1410+ /// fader on an empty track is the level the next take lands at.
1411+ fn open_mix(&mut self, lane: Option<Lane>, cx: &mut Context<Self>) {
1412+ if self.exporting().is_some() {
1413+ return;
1414+ }
1415+ self.mix_open = true;
1416+ self.mix_field = lane
1417+ .and_then(|lane| self.mix_lanes().iter().position(|&l| l == lane))
1418+ .unwrap_or(0);
1419+ // One card at a time, the rule the other five follow.
1420+ self.keys_open = false;
1421+ self.export_open = false;
1422+ self.eq_open = None;
1423+ self.color_open = None;
1424+ self.speed_open = None;
1425+ self.close_silence();
1426+ self.context_menu = None;
1427+ cx.notify();
1428+ }
1429+
1430+ /// The audio tracks the card shows a fader for, top to bottom: *every* one
1431+ /// of them, empty ones included -- what the timeline lays out, not what the
1432+ /// mixer happens to open (`Project::audio_lanes` leaves an empty track out,
1433+ /// and a fader that disappeared when a track was cleared would be a setting
1434+ /// nobody could reach).
1435+ fn mix_lanes(&self) -> Vec<Lane> {
1436+ self.session.as_ref().map_or_else(Vec::new, |session| {
1437+ session
1438+ .lanes()
1439+ .into_iter()
1440+ .filter(|l| l.kind == LaneKind::Audio)
1441+ .collect()
1442+ })
1443+ }
1444+
1445+ /// Moves the row the card has picked: a fader by [`MIX_DB_STEP`], the
1446+ /// ceiling by the same, and the switch either way (a ring of two, like the
1447+ /// silence card's unit row).
1448+ ///
1449+ /// Every one of them goes through the session, so it reseeks: what the ear
1450+ /// hears while the arrow is held is the mix that is being set.
1451+ fn nudge_mix(&mut self, steps: i32, cx: &mut Context<Self>) {
1452+ let lanes = self.mix_lanes();
1453+ let Some(session) = self.session.as_mut() else {
1454+ return;
1455+ };
1456+ match lanes.get(self.mix_field) {
1457+ Some(&lane) => {
1458+ let at = session.lane_gain_db(lane) + steps as f32 * MIX_DB_STEP;
1459+ session.set_lane_gain_db(lane, at);
1460+ }
1461+ None => {
1462+ let limiter = session.limiter();
1463+ let at = match self.mix_field - lanes.len() {
1464+ 0 => Limiter {
1465+ on: limiter.on,
1466+ ..limiter
1467+ }
1468+ .with_ceiling(limiter.ceiling_db + steps as f32 * MIX_DB_STEP),
1469+ _ => Limiter {
1470+ on: !limiter.on,
1471+ ..limiter
1472+ },
1473+ };
1474+ session.set_limiter(at);
1475+ }
1476+ }
1477+ cx.notify();
1478+ }
1479+
1384 /// Closes it and drops the preview with it: marks left on the lane after1480 /// Closes it and drops the preview with it: marks left on the lane after
1385 /// the card is gone would name frames the next edit has already moved.1481 /// the card is gone would name frames the next edit has already moved.
1386 fn close_silence(&mut self) {1482 fn close_silence(&mut self) {
@@ -1643,6 +1739,7 @@ impl Player {
1643 || self.color_open.is_some()1739 || self.color_open.is_some()
1644 || self.speed_open.is_some()1740 || self.speed_open.is_some()
1645 || self.silence_open.is_some()1741 || self.silence_open.is_some()
1742+ || self.mix_open
1646 || self.exporting().is_some()1743 || self.exporting().is_some()
1647 }1744 }
1648 1745
@@ -1662,6 +1759,7 @@ impl Player {
1662 || self.color_open.is_some()1759 || self.color_open.is_some()
1663 || self.speed_open.is_some()1760 || self.speed_open.is_some()
1664 || self.silence_open.is_some()1761 || self.silence_open.is_some()
1762+ || self.mix_open
1665 {1763 {
1666 Repeat::Card1764 Repeat::Card
1667 } else {1765 } else {
@@ -3478,6 +3576,25 @@ impl Render for Player {
3478 cx.notify();3576 cx.notify();
3479 return;3577 return;
3480 }3578 }
3579+ // The mix card, the same way again: ↑↓ pick a row -- a track's
3580+ // fader, the limiter's ceiling or its switch -- and ←→ move it,
3581+ // held or pressed. Card-local like the four above it.
3582+ if this.mix_open {
3583+ let rows = this.mix_lanes().len() + MIX_MASTER_ROWS;
3584+ if key == ESCAPE {
3585+ this.mix_open = false;
3586+ } else if key == "down" {
3587+ this.mix_field = (this.mix_field + 1) % rows;
3588+ } else if key == "up" {
3589+ this.mix_field = (this.mix_field + rows - 1) % rows;
3590+ } else if key == "right" {
3591+ this.nudge_mix(1, cx);
3592+ } else if key == "left" {
3593+ this.nudge_mix(-1, cx);
3594+ }
3595+ cx.notify();
3596+ return;
3597+ }
3481 // A clip menu names an index, and every edit below moves3598 // A clip menu names an index, and every edit below moves
3482 // indices -- so a stroke closes it before it acts. Escape means3599 // indices -- so a stroke closes it before it acts. Escape means
3483 // that and nothing else, which is the `esc` the keys menu3600 // that and nothing else, which is the `esc` the keys menu
@@ -3704,6 +3821,7 @@ impl Render for Player {
3704 .children(self.color_card(cx))3821 .children(self.color_card(cx))
3705 .children(self.speed_card(cx))3822 .children(self.speed_card(cx))
3706 .children(self.silence_card(cx))3823 .children(self.silence_card(cx))
3824+ .children(self.mix_card(cx))
3707 }3825 }
3708 }3826 }
3709 3827
@@ -5428,6 +5546,174 @@ impl Player {
5428 )5546 )
5429 }5547 }
5430 5548
5549+ /// The mix card: one fader per audio track and the master limiter under
5550+ /// them -- the two settings that belong to the *sound of the whole
5551+ /// timeline* rather than to any clip on it.
5552+ ///
5553+ /// A track's fader moves everything on that track by the same amount,
5554+ /// every frequency of it: it is not the equalizer (one take, one band) and
5555+ /// it is not the volume in the panel, which is what this machine monitors
5556+ /// at and is written to no file. The limiter is over the sum of them all,
5557+ /// which is where a mix can pass full scale and where a clamp used to
5558+ /// square it off.
5559+ ///
5560+ /// The silence card's shape, down to the steppers: a row is a label, a
5561+ /// value and the two presses that move it, and the arrows pick a row and
5562+ /// move it too. The rows scroll rather than the card growing past the
5563+ /// window -- a timeline may hold more tracks than a 360 px window has room
5564+ /// for faders.
5565+ fn mix_card(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> {
5566+ if !self.mix_open {
5567+ return None;
5568+ }
5569+ let session = self.session.as_ref();
5570+ let lanes = self.mix_lanes();
5571+ let limiter = session.map_or_else(Limiter::default, PlaybackSession::limiter);
5572+ let mut rows: Vec<(String, String)> = lanes
5573+ .iter()
5574+ .map(|&lane| {
5575+ let db = session.map_or(0., |s| s.lane_gain_db(lane));
5576+ (format!("{} plays at", lane.label()), format!("{db:+.0} dB"))
5577+ })
5578+ .collect();
5579+ // The ceiling in dBFS and the faders in dB, the silence card's rule:
5580+ // a ceiling is a level below full scale, a fader is a change.
5581+ rows.push((
5582+ "Limiter ceiling".into(),
5583+ format!("{:+.0} dBFS", limiter.ceiling_db),
5584+ ));
5585+ rows.push((
5586+ "Limiter".into(),
5587+ match limiter.on {
5588+ true => "on".into(),
5589+ false => "off".into(),
5590+ },
5591+ ));
5592+ let rows: Vec<_> = rows
5593+ .into_iter()
5594+ .enumerate()
5595+ .map(|(n, (label, value))| {
5596+ div()
5597+ .id(("mix-row", n))
5598+ .flex()
5599+ .flex_none()
5600+ .min_h(px(KEYS_ROW_H))
5601+ .items_center()
5602+ .justify_between()
5603+ .px(px(6.))
5604+ .rounded(px(3.))
5605+ .bg(rgb(match n == self.mix_field {
5606+ true => SELECTED,
5607+ false => CHROME,
5608+ }))
5609+ .cursor_pointer()
5610+ .hover(|s| s.bg(rgb(HOVER)))
5611+ .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
5612+ this.mix_field = n;
5613+ cx.notify();
5614+ }))
5615+ .child(div().text_color(rgb(INK_DIM)).child(label))
5616+ .child(
5617+ div()
5618+ .flex()
5619+ .items_center()
5620+ .gap(px(4.))
5621+ .child(value)
5622+ .children([-1, 1].map(|steps: i32| {
5623+ div()
5624+ .id(("mix-step", n * 2 + usize::from(steps > 0)))
5625+ .flex_none()
5626+ .w(px(HIT_MIN))
5627+ .h(px(KEYS_ROW_H))
5628+ .flex()
5629+ .items_center()
5630+ .justify_center()
5631+ .rounded(px(3.))
5632+ .bg(rgb(CHROME))
5633+ .cursor_pointer()
5634+ .hover(|s| s.bg(rgb(HOVER)))
5635+ .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
5636+ // Picked as well as moved, the silence
5637+ // card's rule: the row a press lands on
5638+ // is the row the arrows carry on from.
5639+ this.mix_field = n;
5640+ this.nudge_mix(steps, cx);
5641+ }))
5642+ .child(match steps > 0 {
5643+ true => "+",
5644+ false => "−",
5645+ })
5646+ })),
5647+ )
5648+ })
5649+ .collect();
5650+ Some(
5651+ div()
5652+ .absolute()
5653+ .inset_0()
5654+ .flex()
5655+ .justify_center()
5656+ .items_center()
5657+ .bg(rgba(0x101010cc))
5658+ .on_mouse_down(MouseButton::Left, |_: &MouseDownEvent, _, cx| {
5659+ cx.stop_propagation()
5660+ })
5661+ .child(
5662+ div()
5663+ .w(px(COLOR_W))
5664+ .max_h(px(360. - 24.))
5665+ .flex()
5666+ .flex_col()
5667+ .gap(px(6.))
5668+ .p(px(12.))
5669+ .rounded(px(6.))
5670+ .bg(rgb(SURFACE))
5671+ .child(
5672+ div()
5673+ .flex_none()
5674+ .px(px(6.))
5675+ .child("Mix — track volumes and the master limiter"),
5676+ )
5677+ .child(
5678+ div()
5679+ .flex_none()
5680+ .px(px(6.))
5681+ .text_size(px(11.))
5682+ .text_color(rgb(INK_DIM))
5683+ .child(
5684+ "− and + move a setting, or ↑↓ picks one and ←→ moves it (hold to run it) — a track fader moves everything on that track; esc closes",
5685+ ),
5686+ )
5687+ .child(
5688+ div()
5689+ .id("mix-rows")
5690+ .flex()
5691+ .flex_col()
5692+ .gap(px(6.))
5693+ .overflow_y_scroll()
5694+ .children(rows),
5695+ )
5696+ .child(
5697+ div()
5698+ .flex_none()
5699+ .px(px(6.))
5700+ .text_size(px(11.))
5701+ .text_color(rgb(INK_DIM))
5702+ // What the choice *is*: the limiter's own line,
5703+ // because "on" alone says nothing about what it
5704+ // does to a mix that never reaches the ceiling.
5705+ .child(match limiter.on {
5706+ true => format!(
5707+ "the mix is held under {:+.0} dBFS — quieter passages are untouched",
5708+ limiter.ceiling_db
5709+ ),
5710+ false => "the limiter is out of circuit — a hot mix clips at full scale".to_string(),
5711+ }),
5712+ ),
5713+ ),
5714+ )
5715+ }
5716+
5431 /// The silence card: what the scan is looking for, what it found, and the5717 /// The silence card: what the scan is looking for, what it found, and the
5432 /// two things that can be done about it.5718 /// two things that can be done about it.
5433 ///5719 ///
@@ -6045,6 +6331,19 @@ impl Player {
6045 .map_or(&[][..], PlaybackSession::sources);6331 .map_or(&[][..], PlaybackSession::sources);
6046 let (sel, sel_link) = (self.selected, self.selected_link());6332 let (sel, sel_link) = (self.selected, self.selected_link());
6047 let audio = lane.kind == LaneKind::Audio;6333 let audio = lane.kind == LaneKind::Audio;
6334+ // What this track plays at, on the header it belongs to: shown only
6335+ // when it is not unity, because a column 40 px wide has room for a
6336+ // number or for a name, and the name is what a header is for. The
6337+ // press opens the mix card on this very track.
6338+ let gain_db = self
6339+ .session
6340+ .as_ref()
6341+ .map_or(0., |session| session.lane_gain_db(lane));
6342+ let gain_tip: SharedString = format!(
6343+ "{name} plays at {gain_db:+.0} dB — opens the mix ({}); the whole track, every frequency, unlike the equalizer",
6344+ self.keymap.display(ActionId::Mix)
6345+ )
6346+ .into();
6048 let tip: SharedString = format!(6347 let tip: SharedString = format!(
6049 "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",6348 "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",
6050 self.keymap.display(ActionId::Select),6349 self.keymap.display(ActionId::Select),
@@ -6075,7 +6374,35 @@ impl Player {
6075 .bg(rgb(SURFACE))6374 .bg(rgb(SURFACE))
6076 .text_size(px(11.))6375 .text_size(px(11.))
6077 .text_color(rgb(INK_DIM))6376 .text_color(rgb(INK_DIM))
6078- .child(div().flex_1().flex().items_center().child(name))6377+ .child(match audio {
6378+ // A button, not a label: the one setting a track has of
6379+ // its own used to be reachable from nowhere.
6380+ true => div()
6381+ .id(("mix-lane", lane.ord))
6382+ .flex_1()
6383+ .w_full()
6384+ .flex()
6385+ .items_center()
6386+ .justify_center()
6387+ .rounded(px(3.))
6388+ .cursor_pointer()
6389+ .hover(|s| s.bg(rgb(HOVER)))
6390+ .tooltip(move |_, cx| cx.new(|_| Tip(gain_tip.clone())).into())
6391+ .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
6392+ this.open_mix(Some(lane), cx)
6393+ }))
6394+ .child(match gain_db == 0. {
6395+ true => name.clone(),
6396+ false => format!("{name} {gain_db:+.0}"),
6397+ })
6398+ .into_any_element(),
6399+ false => div()
6400+ .flex_1()
6401+ .flex()
6402+ .items_center()
6403+ .child(name.clone())
6404+ .into_any_element(),
6405+ })
6079 // The one thing a header does: take this track away again.6406 // The one thing a header does: take this track away again.
6080 // A `HIT_MIN` target rather than a glyph-sized one, and it6407 // A `HIT_MIN` target rather than a glyph-sized one, and it
6081 // stays put on a track holding clips instead of hiding --6408 // stays put on a track holding clips instead of hiding --
@@ -8583,6 +8910,9 @@ mod tests {
8583 source.contains("this.remove_lane(lane, cx)")8910 source.contains("this.remove_lane(lane, cx)")
8584 }8911 }
8585 ActionId::ToggleMute => element("volume"),8912 ActionId::ToggleMute => element("volume"),
8913+ // The fader on every audio track's own header, which is
8914+ // also what opens the card the limiter is on.
8915+ ActionId::Mix => element("mix-lane"),
8586 ActionId::VolumeUp | ActionId::VolumeDown => element("volume-bar"),8916 ActionId::VolumeUp | ActionId::VolumeDown => element("volume-bar"),
8587 // The ruler seeks anywhere the pointer points; the frame and8917 // The ruler seeks anywhere the pointer points; the frame and
8588 // the second are the keyboard's finer grain of that move.8918 // the second are the keyboard's finer grain of that move.
@@ -8614,6 +8944,8 @@ mod tests {
8614 "speed-preset",8944 "speed-preset",
8615 "silence-row",8945 "silence-row",
8616 "silence-step",8946 "silence-step",
8947+ "mix-row",
8948+ "mix-step",
8617 "silence-apply",8949 "silence-apply",
8618 "export-confirm",8950 "export-confirm",
8619 ] {8951 ] {
@@ -10820,6 +11152,8 @@ fn main() {
10820 speed_open: None,11152 speed_open: None,
10821 speed_bar: Rc::default(),11153 speed_bar: Rc::default(),
10822 speed_dragging: false,11154 speed_dragging: false,
11155+ mix_open: false,
11156+ mix_field: 0,
10823 silence_open: None,11157 silence_open: None,
10824 // The conservative defaults the engine documents: a first11158 // The conservative defaults the engine documents: a first
10825 // scan that leaves a little too much is one nobody undoes.11159 // scan that leaves a little too much is one nobody undoes.
crates/engine/src/audio.rsmodified+71 -6
@@ -50,6 +50,7 @@ use symphonia_core::units;
50 use symphonia_core::units::{Time, TimeBase};50 use symphonia_core::units::{Time, TimeBase};
51 51
52 use crate::eq::{EqParams, EqState};52 use crate::eq::{EqParams, EqState};
53+use crate::limiter::{Limiter, LimiterState};
53 54
54 /// ffmpeg's AAC-LC encoder delay, used when the file carries no edit list.55 /// ffmpeg's AAC-LC encoder delay, used when the file carries no edit list.
55 /// (HE-AAC/iTunes files use 2112, but those are rejected as unsupported here.)56 /// (HE-AAC/iTunes files use 2112, but those are rejected as unsupported here.)
@@ -453,11 +454,41 @@ impl AudioSession {
453 lanes: &[Vec<(Option<usize>, f64, f64)>],454 lanes: &[Vec<(Option<usize>, f64, f64)>],
454 eqs: &[Vec<Option<EqParams>>],455 eqs: &[Vec<Option<EqParams>>],
455 speeds: &[Vec<Option<crate::project::Stretch>>],456 speeds: &[Vec<Option<crate::project::Stretch>>],
457+ ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> {
458+ Self::open_mixed_streams_master(sources, lanes, eqs, speeds, &[], Limiter::default())
459+ }
460+
461+ /// [`open_mixed_streams_speed`](Self::open_mixed_streams_speed) with the two
462+ /// settings that belong to the *mix* rather than to a clip: what each lane
463+ /// is turned up or down by on its way into the sum (`gains[i]`, an
464+ /// amplitude, [`crate::Project::audio_gains`] builds it) and the master
465+ /// limiter the sum comes out through.
466+ ///
467+ /// Both live at the sum and nowhere else, which is what makes a lane volume
468+ /// a *lane* volume and a limiter a master one: a gain applied per segment
469+ /// would have to agree with itself across a lane's cuts, and a limiter
470+ /// applied per lane would pump each lane against the others. A short or
471+ /// empty gain list means the rest play as they are, exactly as a short eq
472+ /// list means flat.
473+ ///
474+ /// Flat settings take the same path the mixer always took, down to the bit:
475+ /// one lane at unity with the limiter off is still `open_multi_streams`
476+ /// verbatim, with no mixer thread at all. A lane that is *not* at unity, or
477+ /// a limiter that is on, is what puts a single-lane timeline through the
478+ /// mixer -- a sum of one, which is where both settings live.
479+ pub fn open_mixed_streams_master(
480+ sources: &[(PathBuf, usize)],
481+ lanes: &[Vec<(Option<usize>, f64, f64)>],
482+ eqs: &[Vec<Option<EqParams>>],
483+ speeds: &[Vec<Option<crate::project::Stretch>>],
484+ gains: &[f32],
485+ limiter: Limiter,
456 ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> {486 ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> {
457 let [first, rest @ ..] = lanes else {487 let [first, rest @ ..] = lanes else {
458 return Ok(None);488 return Ok(None);
459 };489 };
460- if rest.is_empty() {490+ let mastered = limiter.is_active() || gains.iter().any(|&g| g != 1.0);
491+ if rest.is_empty() && !mastered {
461 let flat = Vec::new();492 let flat = Vec::new();
462 let plain = Vec::new();493 let plain = Vec::new();
463 return Self::open_multi_streams_speed(494 return Self::open_multi_streams_speed(
@@ -487,12 +518,20 @@ impl AudioSession {
487 meta = Some(lane_meta);518 meta = Some(lane_meta);
488 rxs.push(rx);519 rxs.push(rx);
489 }520 }
490- let meta = meta.expect("at least two lanes opened above");521+ let meta = meta.expect("at least one lane opened above");
491 let (tx, rx) = sync_channel(32);522 let (tx, rx) = sync_channel(32);
492 let channels = usize::from(meta.channels);523 let channels = usize::from(meta.channels);
524+ // One per lane, in the lanes' own order, padded with unity: a short
525+ // list is "as it is from here on", the eq list's rule.
526+ let mut gains = gains.to_vec();
527+ gains.resize(lanes.len(), 1.0);
528+ // Built here, off the thread that will run it, where the rate is known.
529+ let limiter = limiter
530+ .is_active()
531+ .then(|| LimiterState::new(&limiter, meta.sample_rate, channels));
493 thread::Builder::new()532 thread::Builder::new()
494 .name("audio-mix".into())533 .name("audio-mix".into())
495- .spawn(move || mix(&rxs, channels, &tx))?;534+ .spawn(move || mix(&rxs, channels, &gains, limiter, &tx))?;
496 Ok(Some((meta, rx)))535 Ok(Some((meta, rx)))
497 }536 }
498 537
@@ -1855,7 +1894,13 @@ struct Worker {
1855 /// The accumulator is reused across turns; the one allocation per chunk is the1894 /// The accumulator is reused across turns; the one allocation per chunk is the
1856 /// buffer the channel takes ownership of, and none of this is the RT path (the1895 /// buffer the channel takes ownership of, and none of this is the RT path (the
1857 /// device callback reads the ring the feeder has already filled).1896 /// device callback reads the ring the feeder has already filled).
1858-fn mix(rxs: &[Receiver<AudioChunk>], channels: usize, tx: &SyncSender<AudioChunk>) {1897+fn mix(
1898+ rxs: &[Receiver<AudioChunk>],
1899+ channels: usize,
1900+ gains: &[f32],
1901+ mut limiter: Option<LimiterState>,
1902+ tx: &SyncSender<AudioChunk>,
1903+) {
1859 let mut pending: Vec<Vec<f32>> = rxs.iter().map(|_| Vec::new()).collect();1904 let mut pending: Vec<Vec<f32>> = rxs.iter().map(|_| Vec::new()).collect();
1860 let mut live: Vec<bool> = rxs.iter().map(|_| true).collect();1905 let mut live: Vec<bool> = rxs.iter().map(|_| true).collect();
1861 // Numbering follows lane 0, whose first chunk says where it starts.1906 // Numbering follows lane 0, whose first chunk says where it starts.
@@ -1890,11 +1935,31 @@ fn mix(rxs: &[Receiver<AudioChunk>], channels: usize, tx: &SyncSender<AudioChunk
1890 let block = frames * channels;1935 let block = frames * channels;
1891 out.clear();1936 out.clear();
1892 out.resize(block, 0.0);1937 out.resize(block, 0.0);
1893- for lane in pending.iter_mut().filter(|p| !p.is_empty()) {1938+ for (i, lane) in pending
1939+ .iter_mut()
1940+ .enumerate()
1941+ .filter(|(_, p)| !p.is_empty())
1942+ {
1943+ // The lane's own volume, applied on its way into the sum: this is
1944+ // the one place every lane's samples pass through, so a lane that
1945+ // is turned down is turned down in an export exactly as it is in
1946+ // the room. Unity is a multiply by 1.0, which f32 leaves alone.
1947+ let gain = gains.get(i).copied().unwrap_or(1.0);
1894 for (sum, sample) in out.iter_mut().zip(lane.drain(..block)) {1948 for (sum, sample) in out.iter_mut().zip(lane.drain(..block)) {
1895- *sum += sample;1949+ *sum += sample * gain;
1896 }1950 }
1897 }1951 }
1952+ // ...and the master limiter over the sum, before the clamp: what the
1953+ // clamp used to catch by squaring it off is held under the ceiling
1954+ // here instead ([`crate::limiter`]). Off, this is not even a branch
1955+ // per sample.
1956+ if let Some(limiter) = limiter.as_mut() {
1957+ limiter.process(&mut out);
1958+ }
1959+ let frames = out.len() / channels;
1960+ if frames == 0 {
1961+ continue; // the limiter's delay line is still filling
1962+ }
1898 let chunk = AudioChunk {1963 let chunk = AudioChunk {
1899 start_sample: base + emitted,1964 start_sample: base + emitted,
1900 // Clamped, not wrapped: two lanes at full scale are what a mix has1965 // Clamped, not wrapped: two lanes at full scale are what a mix has
crates/engine/src/edith.rsmodified+324 -23
@@ -1,9 +1,11 @@
1 //! The project file: a line of text per thing, and nothing else.1 //! The project file: a line of text per thing, and nothing else.
2 //!2 //!
3 //! ```text3 //! ```text
4-//! edith 84+//! edith 9
5 //! playhead 905 //! playhead 90
6 //! resolution 1920 10806 //! resolution 1920 1080
7+//! fps 30.0
8+//! limiter -1.0 on
7 //! source 0 test_av.mp49 //! source 0 test_av.mp4
8 //! source 1 /elsewhere/test_av2.mp410 //! source 1 /elsewhere/test_av2.mp4
9 //! eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk11 //! eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk
@@ -12,8 +14,27 @@
12 //! audio 1 0 0 120 0 0 0 - fit 100014 //! audio 1 0 0 120 0 0 0 - fit 1000
13 //! video 2 120 0 120 1 - - - fill 200015 //! video 2 120 0 120 1 - - - fill 2000
14 //! audio 216 //! audio 2
17+//! gain audio 1 -3.0
15 //! ```18 //! ```
16 //!19 //!
20+//! The `fps` line is the rate the timeline was cut at, printed so it reads back
21+//! bit-exactly. A file without one (every dialect before v9) means "whatever
22+//! the scaffolding source runs at", which is what such a project always was and
23+//! is an answer only a project holding a video has
24+//! ([`crate::PlaybackSession::open_project`]).
25+//!
26+//! The `limiter` line is the master limiter over the whole mix
27+//! ([`crate::limiter`]): its ceiling in dBFS and whether it is in circuit,
28+//! spelled `on` or `off`. Left out when it is the default, which is off.
29+//!
30+//! A `gain` line is `gain <kind> <lane> <dB>`: how loud that whole lane plays,
31+//! everything on it and every frequency of it -- a different thing from a
32+//! clip's `eq` line, which is one take and one band. It names its lane the way
33+//! a clip line does and comes *after* the lanes, because a lane is declared by
34+//! its clips and a gain declares nothing. Only a lane somebody has turned gets
35+//! one; the rest are at 0 dB, which is where every lane of every dialect before
36+//! v9 is.
37+//!
17 //! The `resolution` line is the **project's** picture size, which is a38 //! The `resolution` line is the **project's** picture size, which is a
18 //! different thing from any source's: media of other sizes are placed on it.39 //! different thing from any source's: media of other sizes are placed on it.
19 //! It belongs once, beside the playhead, and a file without one (every dialect40 //! It belongs once, beside the playhead, and a file without one (every dialect
@@ -58,7 +79,10 @@
58 //! is the only way an empty lane could still be there on the way back. A lane79 //! is the only way an empty lane could still be there on the way back. A lane
59 //! number may not skip one of its kind.80 //! number may not skip one of its kind.
60 //!81 //!
61-//! **Version 7** was this without the clip's speed field -- every clip of such82+//! **Version 8** was this without the `fps` and `limiter` lines and without
83+//! the `gain` ones: such a project mixes every lane at unity, limits nothing,
84+//! and comes back at the rate its scaffolding source runs at.
85+//! **Version 7** was that without the clip's speed field -- every clip of such
62 //! a project plays at real time, which is the only rate there was.86 //! a project plays at real time, which is the only rate there was.
63 //! **Version 6** was that without the `resolution` line and without the clip's87 //! **Version 6** was that without the `resolution` line and without the clip's
64 //! fit field -- such a project is the size of its first source and letterboxes88 //! fit field -- such a project is the size of its first source and letterboxes
@@ -72,9 +96,9 @@
72 //! <in> <out> <source>`. All six still load -- a v1 file's clips are laid out96 //! <in> <out> <source>`. All six still load -- a v1 file's clips are laid out
73 //! cumulatively and copied onto both lanes as one group each, which is exactly97 //! cumulatively and copied onto both lanes as one group each, which is exactly
74 //! what a v1 timeline meant, and an older file simply equalizes and grades98 //! what a v1 timeline meant, and an older file simply equalizes and grades
75-//! nothing, and an older one plays everything at real time -- and saving any of99+//! nothing, and an older one plays everything at real time, and an older one
76-//! them writes v8. An older reader refuses a newer100+//! mixes flat -- and saving any of them writes v9. An older reader refuses a
77-//! file by name.101+//! newer file by name.
78 //!102 //!
79 //! Text because an edit list is a few integers and a path, and a path is103 //! Text because an edit list is a few integers and a path, and a path is
80 //! *bytes* on this platform -- a JSON string would have to lossily decode one.104 //! *bytes* on this platform -- a JSON string would have to lossily decode one.
@@ -102,12 +126,14 @@ use std::path::{Path, PathBuf};
102 126
103 use crate::color::ColorParams;127 use crate::color::ColorParams;
104 use crate::eq::{Band, BandKind, EqParams};128 use crate::eq::{Band, BandKind, EqParams};
129+use crate::limiter::Limiter;
105 use crate::project::{Clip, Lane, LaneKind, Source, Speed};130 use crate::project::{Clip, Lane, LaneKind, Source, Speed};
106 use crate::scale::FitPolicy;131 use crate::scale::FitPolicy;
107 132
108 /// What [`save`] writes. Read support goes back to `edith 1`; see the module133 /// What [`save`] writes. Read support goes back to `edith 1`; see the module
109 /// docs for what those dialects looked like.134 /// docs for what those dialects looked like.
110-const MAGIC: &[u8] = b"edith 8";135+const MAGIC: &[u8] = b"edith 9";
136+const MAGIC_V8: &[u8] = b"edith 8";
111 const MAGIC_V7: &[u8] = b"edith 7";137 const MAGIC_V7: &[u8] = b"edith 7";
112 const MAGIC_V6: &[u8] = b"edith 6";138 const MAGIC_V6: &[u8] = b"edith 6";
113 const MAGIC_V5: &[u8] = b"edith 5";139 const MAGIC_V5: &[u8] = b"edith 5";
@@ -136,18 +162,37 @@ pub struct Document {
136 /// The project's own picture size. `None` for every dialect before v7 and162 /// The project's own picture size. `None` for every dialect before v7 and
137 /// for a v7 file that leaves it out, which both mean "source 0's picture".163 /// for a v7 file that leaves it out, which both mean "source 0's picture".
138 pub resolution: Option<(u32, u32)>,164 pub resolution: Option<(u32, u32)>,
165+ /// Every lane's own volume in dB, in the order `lanes` is in and as long as
166+ /// it; `0.0` for a lane nobody has turned, which is every lane of every
167+ /// dialect before v9.
168+ pub gains: Vec<f32>,
169+ /// The master limiter. Off for every dialect before v9, and for a v9 file
170+ /// that leaves the line out.
171+ pub limiter: Limiter,
172+ /// The timeline's frame rate. `None` for every dialect before v9 and for a
173+ /// v9 file that leaves it out, which both mean "whatever the scaffolding
174+ /// source runs at" -- the inference a project of nothing but stills and
175+ /// songs has no answer for (see
176+ /// [`crate::PlaybackSession::open_project`]).
177+ pub fps: Option<f64>,
139 pub playhead: u32,178 pub playhead: u32,
140 }179 }
141 180
142 /// Writes the project to `path`, atomically. `sources`, `eq` and `color` should181 /// Writes the project to `path`, atomically. `sources`, `eq` and `color` should
143-/// already be orphan-free ([`crate::Project::without_orphan_sources`]).182+/// already be orphan-free ([`crate::Project::without_orphan_sources`]);
183+/// `gains` is one dB per lane in the same order the lanes are in
184+/// ([`crate::Project::lane_gains`]).
185+#[allow(clippy::too_many_arguments)]
144 pub fn save(186 pub fn save(
145 path: &Path,187 path: &Path,
146 sources: &[Source],188 sources: &[Source],
147 lanes: &[(LaneKind, Vec<Clip>)],189 lanes: &[(LaneKind, Vec<Clip>)],
190+ gains: &[f32],
148 eq: &[EqParams],191 eq: &[EqParams],
149 color: &[ColorParams],192 color: &[ColorParams],
150 resolution: (u32, u32),193 resolution: (u32, u32),
194+ fps: Option<f64>,
195+ limiter: Limiter,
151 playhead: u32,196 playhead: u32,
152 ) -> crate::Result<()> {197 ) -> crate::Result<()> {
153 let dir = project_dir(path);198 let dir = project_dir(path);
@@ -160,7 +205,9 @@ pub fn save(
160 // the second one puts the name itself there.205 // the second one puts the name itself there.
161 let result = std::fs::File::create(&part)206 let result = std::fs::File::create(&part)
162 .and_then(|mut f| {207 .and_then(|mut f| {
163- f.write_all(&emit(&dir, sources, lanes, eq, color, resolution, playhead))?;208+ f.write_all(&emit(
209+ &dir, sources, lanes, gains, eq, color, resolution, fps, limiter, playhead,
210+ ))?;
164 f.sync_all()211 f.sync_all()
165 })212 })
166 .and_then(|()| std::fs::rename(&part, path))213 .and_then(|()| std::fs::rename(&part, path))
@@ -190,13 +237,17 @@ fn project_dir(path: &Path) -> PathBuf {
190 dir.canonicalize().unwrap_or_else(|_| dir.to_path_buf())237 dir.canonicalize().unwrap_or_else(|_| dir.to_path_buf())
191 }238 }
192 239
240+#[allow(clippy::too_many_arguments)]
193 fn emit(241 fn emit(
194 dir: &Path,242 dir: &Path,
195 sources: &[Source],243 sources: &[Source],
196 lanes: &[(LaneKind, Vec<Clip>)],244 lanes: &[(LaneKind, Vec<Clip>)],
245+ gains: &[f32],
197 eq: &[EqParams],246 eq: &[EqParams],
198 color: &[ColorParams],247 color: &[ColorParams],
199 resolution: (u32, u32),248 resolution: (u32, u32),
249+ fps: Option<f64>,
250+ limiter: Limiter,
200 playhead: u32,251 playhead: u32,
201 ) -> Vec<u8> {252 ) -> Vec<u8> {
202 let mut out = Vec::new();253 let mut out = Vec::new();
@@ -204,6 +255,26 @@ fn emit(
204 out.push(b'\n');255 out.push(b'\n');
205 out.extend_from_slice(format!("playhead {playhead}\n").as_bytes());256 out.extend_from_slice(format!("playhead {playhead}\n").as_bytes());
206 out.extend_from_slice(format!("resolution {} {}\n", resolution.0, resolution.1).as_bytes());257 out.extend_from_slice(format!("resolution {} {}\n", resolution.0, resolution.1).as_bytes());
258+ // `{:?}`, the eq table's rule: the rate a timeline was cut at has to read
259+ // back as the very number, or every clip on it lands on another frame.
260+ if let Some(fps) = fps.filter(|f| f.is_finite() && *f > 0.0) {
261+ out.extend_from_slice(format!("fps {fps:?}\n").as_bytes());
262+ }
263+ // Written only when it is not the default, so a project nobody has limited
264+ // is the same bytes it was in v8 bar the version line.
265+ if limiter != Limiter::default() {
266+ out.extend_from_slice(
267+ format!(
268+ "limiter {:?} {}\n",
269+ limiter.ceiling_db,
270+ match limiter.on {
271+ true => "on",
272+ false => "off",
273+ }
274+ )
275+ .as_bytes(),
276+ );
277+ }
207 for s in sources {278 for s in sources {
208 out.extend_from_slice(format!("source {} ", s.audio_stream).as_bytes());279 out.extend_from_slice(format!("source {} ", s.audio_stream).as_bytes());
209 escape(s.path.strip_prefix(dir).unwrap_or(&s.path), &mut out);280 escape(s.path.strip_prefix(dir).unwrap_or(&s.path), &mut out);
@@ -276,6 +347,25 @@ fn emit(
276 );347 );
277 }348 }
278 }349 }
350+ // After the lanes, not before them: a gain line names a lane that has to be
351+ // there already, and a lane is declared by its own lines. Only the lanes
352+ // somebody has turned get one.
353+ let (mut video, mut audio) = (0, 0);
354+ for ((kind, _), &db) in lanes.iter().zip(gains) {
355+ let (keyword, ord) = match kind {
356+ LaneKind::Video => {
357+ video += 1;
358+ ("video", video)
359+ }
360+ LaneKind::Audio => {
361+ audio += 1;
362+ ("audio", audio)
363+ }
364+ };
365+ if db != 0.0 {
366+ out.extend_from_slice(format!("gain {keyword} {ord} {db:?}\n").as_bytes());
367+ }
368+ }
279 out369 out
280 }370 }
281 371
@@ -289,8 +379,11 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> {
289 // The dialects that wrote a source line without its stream field. Reading379 // The dialects that wrote a source line without its stream field. Reading
290 // one is the whole of what "an old project still opens" means here.380 // one is the whole of what "an old project still opens" means here.
291 let streamless = v1 || first == MAGIC_V2;381 let streamless = v1 || first == MAGIC_V2;
292- // The one that carries a per-clip speed...382+ // The one that carries the mix -- lane volumes, the master limiter and the
293- let v8 = first == MAGIC;383+ // rate the timeline was cut at...
384+ let v9 = first == MAGIC;
385+ // ...the ones that carry a per-clip speed...
386+ let v8 = v9 || first == MAGIC_V8;
294 // ...the ones that carry a project resolution and per-clip fit policies...387 // ...the ones that carry a project resolution and per-clip fit policies...
295 let v7 = v8 || first == MAGIC_V7;388 let v7 = v8 || first == MAGIC_V7;
296 // ...the ones that carry colour grades...389 // ...the ones that carry colour grades...
@@ -322,6 +415,11 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> {
322 // Nothing before v7 has a resolution of its own: source 0's picture is415 // Nothing before v7 has a resolution of its own: source 0's picture is
323 // what those projects were, and `None` is how the loader is told so.416 // what those projects were, and `None` is how the loader is told so.
324 resolution: None,417 resolution: None,
418+ // ...and nothing before v9 carries a mix or a rate: every lane at unity,
419+ // no limiter, and the rate inferred from the scaffold as it always was.
420+ gains: Vec::new(),
421+ limiter: Limiter::default(),
422+ fps: None,
325 playhead: 0,423 playhead: 0,
326 };424 };
327 let mut playhead_seen = false;425 let mut playhead_seen = false;
@@ -360,6 +458,76 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> {
360 }458 }
361 doc.resolution = Some((width, height));459 doc.resolution = Some((width, height));
362 }460 }
461+ b"fps" if v9 => {
462+ if doc.fps.is_some() || !doc.sources.is_empty() {
463+ return Err(format!("line {n}: fps belongs once, before the sources").into());
464+ }
465+ let f = fields(rest, 1, "fps", n)?;
466+ let fps = std::str::from_utf8(f[0])
467+ .ok()
468+ .and_then(|s| s.parse::<f64>().ok())
469+ .filter(|f| f.is_finite() && *f > 0.0 && *f <= 1000.0)
470+ .ok_or_else(|| {
471+ format!(
472+ "line {n}: {:?} is not a frame rate",
473+ String::from_utf8_lossy(f[0])
474+ )
475+ })?;
476+ doc.fps = Some(fps);
477+ }
478+ b"limiter" if v9 => {
479+ if !doc.sources.is_empty() {
480+ return Err(
481+ format!("line {n}: limiter belongs once, before the sources").into(),
482+ );
483+ }
484+ let f = fields(rest, 2, "limiter", n)?;
485+ let on = match f[1] {
486+ b"on" => true,
487+ b"off" => false,
488+ other => {
489+ return Err(format!(
490+ "line {n}: limiter is on or off, not {:?}",
491+ String::from_utf8_lossy(other)
492+ )
493+ .into());
494+ }
495+ };
496+ // Through the same clamp a nudge goes through: a hand-written
497+ // ceiling above full scale is a ceiling that limits nothing.
498+ doc.limiter = Limiter {
499+ on,
500+ ..Limiter::default()
501+ }
502+ .with_ceiling(float(f[0], n)?);
503+ }
504+ // After the lanes it names, which is where `emit` writes it: a lane
505+ // is declared by its own lines, and a gain declares nothing.
506+ b"gain" if v9 => {
507+ let f = fields(rest, 3, "gain", n)?;
508+ let kind = match f[0] {
509+ b"video" => LaneKind::Video,
510+ b"audio" => LaneKind::Audio,
511+ other => {
512+ return Err(format!(
513+ "line {n}: gain names {:?}, not a lane kind",
514+ String::from_utf8_lossy(other)
515+ )
516+ .into());
517+ }
518+ };
519+ let ord = number(f[1], n)?;
520+ let at = doc
521+ .lanes
522+ .iter()
523+ .enumerate()
524+ .filter(|(_, (k, _))| *k == kind)
525+ .nth(ord.saturating_sub(1) as usize)
526+ .map(|(at, _)| at)
527+ .ok_or_else(|| format!("line {n}: gain names a lane that is not there"))?;
528+ doc.gains.resize(doc.lanes.len(), 0.0);
529+ doc.gains[at] = float(f[2], n)?;
530+ }
363 b"source" => {531 b"source" => {
364 if doc.lanes.iter().any(|(_, clips)| !clips.is_empty()) {532 if doc.lanes.iter().any(|(_, clips)| !clips.is_empty()) {
365 return Err(format!("line {n}: source after a clip").into());533 return Err(format!("line {n}: source after a clip").into());
@@ -518,6 +686,8 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> {
518 }686 }
519 }687 }
520 }688 }
689+ // One per lane whatever the file said, so a caller may zip the two.
690+ doc.gains.resize(doc.lanes.len(), 0.0);
521 // A file whose lanes are all empty *is* a project -- the emptied timeline,691 // A file whose lanes are all empty *is* a project -- the emptied timeline,
522 // saved. What it may not be is laneless; [`crate::Project::from_parts`]692 // saved. What it may not be is laneless; [`crate::Project::from_parts`]
523 // refuses that one, by the name it has there.693 // refuses that one, by the name it has there.
@@ -773,6 +943,35 @@ fn unescape(field: &[u8], line: usize) -> crate::Result<PathBuf> {
773 mod tests {943 mod tests {
774 use super::*;944 use super::*;
775 945
946+ /// [`super::emit`] for a project whose mix is flat: every lane at unity, no
947+ /// limiter, no rate written. Shadows the real one for the tests that were
948+ /// written before there was a mix to write -- the dialect they are about is
949+ /// the one this emits, and a v9 file with flat settings is a v8 file bar
950+ /// its version line, which is exactly what they assert.
951+ #[allow(clippy::too_many_arguments)]
952+ fn emit(
953+ dir: &Path,
954+ sources: &[Source],
955+ lanes: &[(LaneKind, Vec<Clip>)],
956+ eq: &[EqParams],
957+ color: &[ColorParams],
958+ resolution: (u32, u32),
959+ playhead: u32,
960+ ) -> Vec<u8> {
961+ super::emit(
962+ dir,
963+ sources,
964+ lanes,
965+ &[],
966+ eq,
967+ color,
968+ resolution,
969+ None,
970+ Limiter::default(),
971+ playhead,
972+ )
973+ }
974+
776 fn clip(start: u32, in_frame: u32, out_frame: u32, source: usize, link: Option<u32>) -> Clip {975 fn clip(start: u32, in_frame: u32, out_frame: u32, source: usize, link: Option<u32>) -> Clip {
777 Clip {976 Clip {
778 start,977 start,
@@ -833,7 +1032,7 @@ mod tests {
833 let bytes = flat(&dir, &sources, &lanes, 12);1032 let bytes = flat(&dir, &sources, &lanes, 12);
834 assert_eq!(1033 assert_eq!(
835 String::from_utf8_lossy(&bytes),1034 String::from_utf8_lossy(&bytes),
836- "edith 8\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\1035+ "edith 9\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\
837 source 2 /elsewhere/b.mp4\n\1036 source 2 /elsewhere/b.mp4\n\
838 video 1 0 0 30 0 0 - - fit 1000\nvideo 1 30 10 20 1 1 - - fit 1000\n\1037 video 1 0 0 30 0 0 - - fit 1000\nvideo 1 30 10 20 1 1 - - fit 1000\n\
839 audio 1 0 0 30 0 0 - - fit 1000\n",1038 audio 1 0 0 30 0 0 - - fit 1000\n",
@@ -870,7 +1069,7 @@ mod tests {
870 let bytes = flat(&dir, &sources, &lanes, 7);1069 let bytes = flat(&dir, &sources, &lanes, 7);
871 assert_eq!(1070 assert_eq!(
872 String::from_utf8_lossy(&bytes),1071 String::from_utf8_lossy(&bytes),
873- "edith 8\nplayhead 7\nresolution 1280 720\nsource 0 a.mp4\n\1072+ "edith 9\nplayhead 7\nresolution 1280 720\nsource 0 a.mp4\n\
874 video 1 0 0 30 0 4 - - fit 1000\naudio 1\n\1073 video 1 0 0 30 0 4 - - fit 1000\naudio 1\n\
875 video 2 40 0 10 0 - - - fit 1000\naudio 2 0 0 30 0 4 - - fit 1000\n",1074 video 2 40 0 10 0 - - - fit 1000\naudio 2 0 0 30 0 4 - - fit 1000\n",
876 "an empty lane is a line of its own; everything else is its clips"1075 "an empty lane is a line of its own; everything else is its clips"
@@ -978,7 +1177,7 @@ mod tests {
978 let bytes = emit(&dir, &sources, &lanes, &eq, &[], (1280, 720), 0);1177 let bytes = emit(&dir, &sources, &lanes, &eq, &[], (1280, 720), 0);
979 assert_eq!(1178 assert_eq!(
980 String::from_utf8_lossy(&bytes),1179 String::from_utf8_lossy(&bytes),
981- "edith 8\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\1180+ "edith 9\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
982 eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk\n\1181 eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk\n\
983 eq 16777215.0:-0.1:3.918315e-39:hs\n\1182 eq 16777215.0:-0.1:3.918315e-39:hs\n\
984 eq\n\1183 eq\n\
@@ -1082,7 +1281,7 @@ mod tests {
1082 let bytes = emit(&dir, &sources, &lanes, &[], &color, (1280, 720), 0);1281 let bytes = emit(&dir, &sources, &lanes, &[], &color, (1280, 720), 0);
1083 assert_eq!(1282 assert_eq!(
1084 String::from_utf8_lossy(&bytes),1283 String::from_utf8_lossy(&bytes),
1085- "edith 8\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\1284+ "edith 9\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
1086 color 0.1:1.2:0.9:-0.3\n\1285 color 0.1:1.2:0.9:-0.3\n\
1087 color -1e-7:16777215.0:3.918315e-39:-0.0\n\1286 color -1e-7:16777215.0:3.918315e-39:-0.0\n\
1088 color 0.0:1.0:1.0:0.0\n\1287 color 0.0:1.0:1.0:0.0\n\
@@ -1147,7 +1346,7 @@ mod tests {
1147 (1280, 720),1346 (1280, 720),
1148 old.playhead1347 old.playhead
1149 )),1348 )),
1150- "edith 8\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\1349+ "edith 9\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\
1151 eq 80.0:-3.0:0.707:ls\n\1350 eq 80.0:-3.0:0.707:ls\n\
1152 video 1 0 0 30 0 0 0 - fit 1000\naudio 1 0 0 30 0 0 - - fit 1000\n"1351 video 1 0 0 30 0 0 0 - fit 1000\naudio 1 0 0 30 0 0 - - fit 1000\n"
1153 );1352 );
@@ -1185,7 +1384,7 @@ mod tests {
1185 let bytes = emit(&dir, &sources, &lanes, &[], &[], (1280, 720), 0);1384 let bytes = emit(&dir, &sources, &lanes, &[], &[], (1280, 720), 0);
1186 assert_eq!(1385 assert_eq!(
1187 String::from_utf8_lossy(&bytes),1386 String::from_utf8_lossy(&bytes),
1188- "edith 8\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\1387+ "edith 9\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
1189 video 1 0 0 30 0 - - - fit 2000\nvideo 1 15 30 40 0 - - - fit 250\n\1388 video 1 0 0 30 0 - - - fit 2000\nvideo 1 15 30 40 0 - - - fit 250\n\
1190 audio 1 0 0 30 0 - - - fit 2000\n",1389 audio 1 0 0 30 0 - - - fit 2000\n",
1191 "the rate is the clip line's last field, in thousandths"1390 "the rate is the clip line's last field, in thousandths"
@@ -1214,7 +1413,7 @@ mod tests {
1214 (1280, 720),1413 (1280, 720),
1215 old.playhead1414 old.playhead
1216 )),1415 )),
1217- "edith 8\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\1416+ "edith 9\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\
1218 video 1 0 0 30 0 0 - - fit 1000\naudio 1 0 0 30 0 0 - - fit 1000\n"1417 video 1 0 0 30 0 0 - - fit 1000\naudio 1 0 0 30 0 0 - - fit 1000\n"
1219 );1418 );
1220 // A rate outside what the editor can set is a corrupt line, by name.1419 // A rate outside what the editor can set is a corrupt line, by name.
@@ -1225,6 +1424,105 @@ mod tests {
1225 );1424 );
1226 }1425 }
1227 1426
1427+ /// The whole of the v9 bump, the speed test's twin: the mix a project was
1428+ /// left at -- every track's own volume and the master limiter -- plus the
1429+ /// rate it was cut at, all written, all read back as the very numbers, and
1430+ /// a v8 file (which has none of them) loading flat and unlimited.
1431+ #[test]
1432+ fn the_mix_and_the_rate_round_trip_and_a_v8_file_is_flat() {
1433+ let dir = PathBuf::from("/proj");
1434+ let sources = vec![Source::new("/proj/a.mp4", 0)];
1435+ let lanes = vec![
1436+ (LaneKind::Video, vec![clip(0, 0, 30, 0, None)]),
1437+ (LaneKind::Audio, vec![clip(0, 0, 30, 0, None)]),
1438+ // A second audio track, turned down: the gain lines are per lane,
1439+ // so the two must not run into one another.
1440+ (LaneKind::Audio, vec![clip(0, 0, 30, 0, None)]),
1441+ ];
1442+ let limiter = Limiter {
1443+ ceiling_db: -1.5,
1444+ on: true,
1445+ };
1446+ let bytes = super::emit(
1447+ &dir,
1448+ &sources,
1449+ &lanes,
1450+ &[0.0, 3.0, -6.5],
1451+ &[],
1452+ &[],
1453+ (1280, 720),
1454+ Some(23.976023976023978),
1455+ limiter,
1456+ 0,
1457+ );
1458+ assert_eq!(
1459+ String::from_utf8_lossy(&bytes),
1460+ "edith 9\nplayhead 0\nresolution 1280 720\nfps 23.976023976023978\n\
1461+ limiter -1.5 on\nsource 0 a.mp4\n\
1462+ video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n\
1463+ audio 2 0 0 30 0 - - - fit 1000\n\
1464+ gain audio 1 3.0\ngain audio 2 -6.5\n",
1465+ "the mix is lines of its own, the gains after the lanes they name"
1466+ );
1467+ let back = parse(&bytes, &dir).expect("parse");
1468+ assert_eq!(back.lanes, lanes);
1469+ assert_eq!(back.gains, vec![0.0, 3.0, -6.5], "one per lane, in order");
1470+ assert_eq!(back.limiter, limiter);
1471+ assert_eq!(back.fps, Some(23.976023976023978), "bit-exact, not 23.976");
1472+
1473+ // ...and the dialect before it, which carried none of the three: a v8
1474+ // file mixes flat, limits nothing, and says nothing about its rate.
1475+ let v8 = b"edith 8\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\
1476+ video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n";
1477+ let old = parse(v8, &dir).expect("v8 parses");
1478+ assert_eq!(old.gains, vec![0.0, 0.0], "one per lane, all at unity");
1479+ assert_eq!(old.limiter, Limiter::default());
1480+ assert_eq!(old.fps, None);
1481+ // A v9 file may leave all three out too, and means the same thing.
1482+ assert_eq!(
1483+ String::from_utf8_lossy(&emit(
1484+ &dir,
1485+ &old.sources,
1486+ &old.lanes,
1487+ &old.eq,
1488+ &old.color,
1489+ (1280, 720),
1490+ old.playhead
1491+ )),
1492+ "edith 9\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\
1493+ video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n"
1494+ );
1495+
1496+ // Each of the three refuses by name, on its own line.
1497+ for (text, want) in [
1498+ (
1499+ "edith 9\nfps nope\nsource 0 a.mp4\n",
1500+ "line 2: \"nope\" is not a frame rate",
1501+ ),
1502+ (
1503+ "edith 9\nlimiter -1.0 maybe\nsource 0 a.mp4\n",
1504+ "line 2: limiter is on or off, not \"maybe\"",
1505+ ),
1506+ (
1507+ "edith 9\nsource 0 a.mp4\nvideo 1 0 0 30 0 - - - fit 1000\ngain audio 1 -3.0\n",
1508+ "line 4: gain names a lane that is not there",
1509+ ),
1510+ (
1511+ "edith 9\nsource 0 a.mp4\nvideo 1 0 0 30 0 - - - fit 1000\ngain lane 1 -3.0\n",
1512+ "line 4: gain names \"lane\", not a lane kind",
1513+ ),
1514+ ] {
1515+ assert_eq!(
1516+ parse(text.as_bytes(), &dir).unwrap_err().to_string(),
1517+ want,
1518+ "{text:?}"
1519+ );
1520+ }
1521+ // A hand-written ceiling nothing could limit at is clamped, not taken.
1522+ let loud = parse(b"edith 9\nlimiter 12.0 on\nsource 0 a.mp4\n", &dir).expect("parses");
1523+ assert_eq!(loud.limiter.ceiling_db, Limiter::MAX_DB);
1524+ }
1525+
1228 /// The refusals the colour grammar adds, each naming its line.1526 /// The refusals the colour grammar adds, each naming its line.
1229 #[test]1527 #[test]
1230 fn a_malformed_colour_names_its_line() {1528 fn a_malformed_colour_names_its_line() {
@@ -1355,7 +1653,7 @@ mod tests {
1355 assert!(old.eq.is_empty(), "nothing before v5 equalizes anything");1653 assert!(old.eq.is_empty(), "nothing before v5 equalizes anything");
1356 assert_eq!(1654 assert_eq!(
1357 String::from_utf8_lossy(&flat(&dir, &old.sources, &old.lanes, old.playhead)),1655 String::from_utf8_lossy(&flat(&dir, &old.sources, &old.lanes, old.playhead)),
1358- "edith 8\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\1656+ "edith 9\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\
1359 source 2 /elsewhere/b.mp4\n\1657 source 2 /elsewhere/b.mp4\n\
1360 video 1 0 0 30 0 0 - - fit 1000\nvideo 1 30 10 20 1 1 - - fit 1000\n\1658 video 1 0 0 30 0 0 - - fit 1000\nvideo 1 30 10 20 1 1 - - fit 1000\n\
1361 audio 1 0 0 30 0 0 - - fit 1000\n"1659 audio 1 0 0 30 0 0 - - fit 1000\n"
@@ -1408,7 +1706,7 @@ mod tests {
1408 let v5 = flat(&dir, &back.sources, &back.lanes, back.playhead);1706 let v5 = flat(&dir, &back.sources, &back.lanes, back.playhead);
1409 assert_eq!(1707 assert_eq!(
1410 String::from_utf8_lossy(&v5),1708 String::from_utf8_lossy(&v5),
1411- "edith 8\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\1709+ "edith 9\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\
1412 source 0 /elsewhere/b.mp4\n\1710 source 0 /elsewhere/b.mp4\n\
1413 video 1 0 0 30 0 0 - - fit 1000\nvideo 1 30 10 20 1 1 - - fit 1000\n\1711 video 1 0 0 30 0 0 - - fit 1000\nvideo 1 30 10 20 1 1 - - fit 1000\n\
1414 audio 1 0 0 30 0 0 - - fit 1000\n",1712 audio 1 0 0 30 0 0 - - fit 1000\n",
@@ -1440,7 +1738,7 @@ mod tests {
1440 // Saved again it is the current version, which round-trips to the1738 // Saved again it is the current version, which round-trips to the
1441 // same document.1739 // same document.
1442 let v5 = flat(&dir, &back.sources, &back.lanes, back.playhead);1740 let v5 = flat(&dir, &back.sources, &back.lanes, back.playhead);
1443- assert!(v5.starts_with(b"edith 8\n"));1741+ assert!(v5.starts_with(b"edith 9\n"));
1444 let again = parse(&v5, &dir).expect("v5 parses");1742 let again = parse(&v5, &dir).expect("v5 parses");
1445 assert_eq!(again.lanes, back.lanes);1743 assert_eq!(again.lanes, back.lanes);
1446 // A dialect may not be mixed: lane lines under v1, `clip` under v2.1744 // A dialect may not be mixed: lane lines under v1, `clip` under v2.
@@ -1535,14 +1833,17 @@ mod tests {
1535 &two(one.to_vec(), one.to_vec()),1833 &two(one.to_vec(), one.to_vec()),
1536 &[],1834 &[],
1537 &[],1835 &[],
1836+ &[],
1538 (1280, 720),1837 (1280, 720),
1838+ None,
1839+ Limiter::default(),
1539 0,1840 0,
1540 )1841 )
1541 .expect("save");1842 .expect("save");
1542 let bytes = std::fs::read(&path).expect("read back");1843 let bytes = std::fs::read(&path).expect("read back");
1543 assert_eq!(1844 assert_eq!(
1544 String::from_utf8_lossy(&bytes),1845 String::from_utf8_lossy(&bytes),
1545- "edith 8\nplayhead 0\nresolution 1280 720\nsource 1 a.mp4\n\1846+ "edith 9\nplayhead 0\nresolution 1280 720\nsource 1 a.mp4\n\
1546 video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n"1847 video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n"
1547 );1848 );
1548 // Loading rejoins the *given* directory, so the file is reached by the1849 // Loading rejoins the *given* directory, so the file is reached by the
@@ -1587,10 +1888,10 @@ mod tests {
1587 #[test]1888 #[test]
1588 fn a_wrong_first_line_is_refused_by_name() {1889 fn a_wrong_first_line_is_refused_by_name() {
1589 let dir = PathBuf::from("/proj");1890 let dir = PathBuf::from("/proj");
1590- let err = parse(b"edith 9\nsource 0 a.mp4\nvideo 0 0 5 0 -\n", &dir)1891+ let err = parse(b"edith 10\nsource 0 a.mp4\nvideo 0 0 5 0 -\n", &dir)
1591 .unwrap_err()1892 .unwrap_err()
1592 .to_string();1893 .to_string();
1593- assert_eq!(err, "line 1: unsupported version 9");1894+ assert_eq!(err, "line 1: unsupported version 10");
1594 for junk in [&b""[..], b"{}\n", b"source a.mp4\n"] {1895 for junk in [&b""[..], b"{}\n", b"source a.mp4\n"] {
1595 assert_eq!(1896 assert_eq!(
1596 parse(junk, &dir).unwrap_err().to_string(),1897 parse(junk, &dir).unwrap_err().to_string(),
crates/engine/src/export.rsmodified+34 -5
@@ -319,6 +319,15 @@ fn equalized(project: &Project) -> bool {
319 })319 })
320 }320 }
321 321
322+/// Whether the *mix* is doing something -- a lane turned off unity, or a
323+/// limiter in circuit. [`equalized`]'s pair, and a copy cannot carry either of
324+/// them: both live where the lanes are summed
325+/// ([`AudioSession::open_mixed_streams_master`]), and a copied packet was never
326+/// summed at all. An mp4 whose timeline is mixed is decoded and re-encoded.
327+fn mastered(project: &Project) -> bool {
328+ project.limiter().is_active() || project.audio_gains().iter().any(|&g| g != 1.0)
329+}
330+
322 /// The bitrate an export codes at: the caller's number through the same clamp331 /// The bitrate an export codes at: the caller's number through the same clamp
323 /// as the computed one, for the reason [`Enc::open`] states.332 /// as the computed one, for the reason [`Enc::open`] states.
324 fn bitrate_of(meta: &VideoMeta, settings: &ExportSettings) -> u64 {333 fn bitrate_of(meta: &VideoMeta, settings: &ExportSettings) -> u64 {
@@ -378,6 +387,7 @@ fn forces_encode(project: &Project) -> bool {
378 .iter()387 .iter()
379 .any(|&lane| project.lane(lane).iter().any(|c| !c.speed.is_normal()))388 .any(|&lane| project.lane(lane).iter().any(|c| !c.speed.is_normal()))
380 || equalized(project)389 || equalized(project)
390+ || mastered(project)
381 }391 }
382 392
383 /// What the sound is written by. Every audio encoder here is software -- there393 /// What the sound is written by. Every audio encoder here is software -- there
@@ -517,8 +527,11 @@ fn copy_audio(project: &Project, meta: &VideoMeta) -> crate::Result<Option<Expor
517 // Only these: a timeline nobody has touched still leaves through the copy527 // Only these: a timeline nobody has touched still leaves through the copy
518 // below, packet for packet, so no passthrough quietly becomes a generation528 // below, packet for packet, so no passthrough quietly becomes a generation
519 // of loss.529 // of loss.
530+ // ...and whether the mix itself does anything a packet never went through:
531+ // a lane volume is applied at the sum and a limiter over it, so copying
532+ // such a lane would write it at unity and unlimited, silently.
520 let speeded = project.lane(lane).iter().any(|c| !c.speed.is_normal());533 let speeded = project.lane(lane).iter().any(|c| !c.speed.is_normal());
521- if speeded || equalized(project) {534+ if speeded || equalized(project) || mastered(project) {
522 return encode_audio(project, meta);535 return encode_audio(project, meta);
523 }536 }
524 // What is left is a copy the *sources* may still not be able to give: AAC537 // What is left is a copy the *sources* may still not be able to give: AAC
@@ -561,8 +574,14 @@ fn encode_audio(project: &Project, meta: &VideoMeta) -> crate::Result<Option<Exp
561 let segs = project.audio_segments_from(0, meta.frame_rate);574 let segs = project.audio_segments_from(0, meta.frame_rate);
562 let eqs = project.audio_eqs_from(0, meta.frame_rate);575 let eqs = project.audio_eqs_from(0, meta.frame_rate);
563 let speeds = project.audio_speeds_from(0, meta.frame_rate);576 let speeds = project.audio_speeds_from(0, meta.frame_rate);
564- let Some((audio, chunks)) =577+ let Some((audio, chunks)) = AudioSession::open_mixed_streams_master(
565- AudioSession::open_mixed_streams_speed(&sources, &segs, &eqs, &speeds)?578+ &sources,
579+ &segs,
580+ &eqs,
581+ &speeds,
582+ &project.audio_gains(),
583+ project.limiter(),
584+ )?
566 else {585 else {
567 return Ok(None); // no audio to write, exactly as a copy of nothing is586 return Ok(None); // no audio to write, exactly as a copy of nothing is
568 };587 };
@@ -896,8 +915,18 @@ fn run_audio(
896 // 2x is half as long and holds the samples that were heard -- not a915 // 2x is half as long and holds the samples that were heard -- not a
897 // second pass here that could disagree with what the ear got.916 // second pass here that could disagree with what the ear got.
898 let speeds = project.audio_speeds_from(0, meta.frame_rate);917 let speeds = project.audio_speeds_from(0, meta.frame_rate);
899- let Some((audio, chunks)) =918+ // ...and the mix over both: each lane's volume into the sum, the master
900- AudioSession::open_mixed_streams_speed(&sources, &segs, &eqs, &speeds)?919+ // limiter out of it. The same opener playback's feeder reads from, so a
920+ // file is written at the levels it was heard at -- there is no second
921+ // place here that could mix it differently.
922+ let Some((audio, chunks)) = AudioSession::open_mixed_streams_master(
923+ &sources,
924+ &segs,
925+ &eqs,
926+ &speeds,
927+ &project.audio_gains(),
928+ project.limiter(),
929+ )?
901 else {930 else {
902 return Err("this timeline has no audio to export".into());931 return Err("this timeline has no audio to export".into());
903 };932 };
crates/engine/src/lib.rsmodified+1 -0
@@ -11,6 +11,7 @@ pub mod edith;
11 pub mod eq;11 pub mod eq;
12 pub mod export;12 pub mod export;
13 pub mod hw;13 pub mod hw;
14+pub mod limiter;
14 pub mod mux;15 pub mod mux;
15 pub mod playback;16 pub mod playback;
16 pub mod project;17 pub mod project;
crates/engine/src/limiter.rsadded+259 -0
@@ -0,0 +1,259 @@
1+//! The master limiter: one ceiling the whole mix is held under, applied where
2+//! the lanes are summed and nowhere else ([`crate::audio::mix`]).
3+//!
4+//! A mix is an add, and two lanes at full scale add past full scale: what used
5+//! to happen there was a hard `clamp`, which is a squared-off waveform and the
6+//! worst-sounding thing an editor can do to a hot timeline. This holds the sum
7+//! down *before* it reaches the clamp instead, and the clamp stays behind it as
8+//! the backstop it always was.
9+//!
10+//! Per sample, no FFT, no allocation while it runs:
11+//!
12+//! * **Lookahead.** The mix is written into a delay line [`LOOKAHEAD_MS`] long
13+//! and read out of it that much later, so the gain a peak needs is already in
14+//! force by the time the peak itself is emitted. No attack overshoot -- the
15+//! first sample over the ceiling is the first sample held under it, which is
16+//! what makes the peak of an exported file a *measurement* and not a hope.
17+//! * **Linked channels.** One gain for the frame, off the loudest channel in
18+//! it: a per-channel gain would move the stereo image every time one side
19+//! peaked.
20+//! * **Soft knee.** [`KNEE_DB`] wide and centred on the ceiling, so the gain
21+//! comes in gradually instead of switching on at one sample and off at the
22+//! next. The knee's own curve never lets the output past the ceiling (at the
23+//! centre it is already `KNEE_DB/8` under it), which is what keeps the
24+//! guarantee a hard knee would give.
25+//! * **Release**, not a per-sample snap back: `RELEASE_MS` of exponential
26+//! recovery, so one loud transient does not pump the whole bar around it.
27+//!
28+//! The latency is *taken out again*, not paid: the first `lookahead` frames of
29+//! output -- the empty delay line -- are dropped, so what comes out is sample
30+//! aligned with what went in and the sound stays locked to the picture. What
31+//! that costs is the last couple of milliseconds of the timeline's tail, which
32+//! is the trade every lookahead limiter makes.
33+
34+/// How far ahead the gain looks. 2 ms is ~96 frames at 48 kHz: long enough to
35+/// ride a transient in smoothly, short enough that the tail it eats is nothing.
36+const LOOKAHEAD_MS: f32 = 2.0;
37+/// How wide the knee is, centred on the ceiling.
38+const KNEE_DB: f32 = 6.0;
39+/// How fast the gain comes back once the loud part is over.
40+const RELEASE_MS: f32 = 120.0;
41+
42+/// What a project's master limiter is set to: a ceiling in dBFS and whether it
43+/// is in circuit at all. Off by default -- a timeline nobody has asked to limit
44+/// mixes exactly as it always did, down to the bit.
45+#[derive(Clone, Copy, Debug, PartialEq)]
46+pub struct Limiter {
47+ /// The level nothing may pass, in dBFS (0 dBFS is full scale).
48+ pub ceiling_db: f32,
49+ pub on: bool,
50+}
51+
52+impl Default for Limiter {
53+ fn default() -> Self {
54+ Self {
55+ ceiling_db: -1.0,
56+ on: false,
57+ }
58+ }
59+}
60+
61+impl Limiter {
62+ /// The ceilings a front-end may set, and what a file may name: a limiter
63+ /// above full scale would limit nothing, and one 24 dB down is already a
64+ /// fader.
65+ pub const MIN_DB: f32 = -24.0;
66+ pub const MAX_DB: f32 = 0.0;
67+
68+ /// The setting with `ceiling_db` put inside the range above, which is what
69+ /// a nudge and a parsed line both go through. Not finite means the default.
70+ pub fn with_ceiling(self, ceiling_db: f32) -> Self {
71+ Self {
72+ ceiling_db: match ceiling_db.is_finite() {
73+ true => ceiling_db.clamp(Self::MIN_DB, Self::MAX_DB),
74+ false => Self::default().ceiling_db,
75+ },
76+ ..self
77+ }
78+ }
79+
80+ /// Whether it is doing anything to the sound -- what an export asks before
81+ /// it decides a packet copy would be a lie.
82+ pub fn is_active(self) -> bool {
83+ self.on
84+ }
85+}
86+
87+/// dBFS as an amplitude. `db_to_linear(0.0)` is exactly 1.0, which is what
88+/// keeps a flat setting a bit-exact passthrough.
89+pub fn db_to_linear(db: f32) -> f32 {
90+ match db == 0.0 {
91+ true => 1.0,
92+ false => 10f32.powf(db / 20.0),
93+ }
94+}
95+
96+/// One running limiter: the delay line, the peak window and the gain.
97+pub struct LimiterState {
98+ channels: usize,
99+ /// The delayed mix, one frame per slot, `lookahead + 1` frames round.
100+ line: Vec<f32>,
101+ /// The loudest channel of each frame in `line`, same indexing.
102+ peaks: Vec<f32>,
103+ /// Where the next frame is written; the frame read out is the one after it.
104+ at: usize,
105+ /// Frames still to be swallowed before anything is emitted -- the empty
106+ /// delay line, which is how the latency is paid back (module docs).
107+ warm: usize,
108+ gain: f32,
109+ ceiling: f32,
110+ /// Where the knee starts, as an amplitude: under this the fast path runs
111+ /// and no logarithm is taken.
112+ knee_floor: f32,
113+ release: f32,
114+}
115+
116+impl LimiterState {
117+ pub fn new(params: &Limiter, sample_rate: u32, channels: usize) -> Self {
118+ let channels = channels.max(1);
119+ let frames = ((LOOKAHEAD_MS / 1000.0 * sample_rate as f32) as usize).max(1) + 1;
120+ let ceiling_db = params.with_ceiling(params.ceiling_db).ceiling_db;
121+ Self {
122+ channels,
123+ line: vec![0.0; frames * channels],
124+ peaks: vec![0.0; frames],
125+ at: 0,
126+ warm: frames - 1,
127+ gain: 1.0,
128+ ceiling: db_to_linear(ceiling_db),
129+ knee_floor: db_to_linear(ceiling_db - KNEE_DB / 2.0),
130+ // One time constant per sample: the gain covers 63% of the way back
131+ // in `RELEASE_MS`.
132+ release: 1.0 - (-1000.0 / (RELEASE_MS * sample_rate as f32)).exp(),
133+ }
134+ }
135+
136+ /// Rewrites `buf` -- interleaved frames -- as the limited mix. Shorter than
137+ /// what came in by the delay line's length, once, at the first call.
138+ pub fn process(&mut self, buf: &mut Vec<f32>) {
139+ let channels = self.channels;
140+ let frames = buf.len() / channels;
141+ let mut out: Vec<f32> = Vec::with_capacity(buf.len());
142+ for f in 0..frames {
143+ let frame = &buf[f * channels..(f + 1) * channels];
144+ let peak = frame.iter().fold(0.0f32, |m, s| m.max(s.abs()));
145+ self.line[self.at * channels..(self.at + 1) * channels].copy_from_slice(frame);
146+ self.peaks[self.at] = peak;
147+ self.at = (self.at + 1) % self.peaks.len();
148+
149+ // Every frame still in the line, the one about to leave included:
150+ // the gain below is therefore never larger than what the *emitted*
151+ // frame needs, which is the whole no-overshoot guarantee.
152+ let window = self.peaks.iter().fold(0.0f32, |m, &p| m.max(p));
153+ let want = match window <= self.knee_floor {
154+ true => 1.0,
155+ false => self.reduction(window),
156+ };
157+ // Up is the release, down is instant -- and instant is safe here
158+ // only because the frame it is for has not been emitted yet.
159+ self.gain += (want - self.gain).max(0.0) * self.release;
160+ self.gain = self.gain.min(want);
161+
162+ if self.warm > 0 {
163+ self.warm -= 1;
164+ continue;
165+ }
166+ for c in 0..channels {
167+ out.push(self.line[self.at * channels + c] * self.gain);
168+ }
169+ }
170+ *buf = out;
171+ }
172+
173+ /// The gain the loudest frame in the window needs: 1.0 under the knee, the
174+ /// knee's own curve across it, `ceiling/peak` above it.
175+ fn reduction(&self, peak: f32) -> f32 {
176+ let level = 20.0 * peak.log10();
177+ let ceiling = 20.0 * self.ceiling.log10();
178+ let over = level - ceiling;
179+ let out = match over >= KNEE_DB / 2.0 {
180+ true => ceiling,
181+ // The cookbook's quadratic knee. At `over == 0` this is already
182+ // `KNEE_DB/8` under the ceiling and it never crosses it, so nothing
183+ // the knee passes needs a clamp behind it.
184+ false => level - (over + KNEE_DB / 2.0).powi(2) / (2.0 * KNEE_DB),
185+ };
186+ 10f32.powf((out - level) / 20.0)
187+ }
188+}
189+
190+#[cfg(test)]
191+mod tests {
192+ use super::*;
193+
194+ /// The promise the whole file exists for: a sum well past full scale comes
195+ /// out under the ceiling, sample for sample, and the quiet part of the same
196+ /// stream is left where it was.
197+ #[test]
198+ fn a_hot_mix_comes_out_under_the_ceiling() {
199+ let rate = 48_000;
200+ let params = Limiter {
201+ ceiling_db: -3.0,
202+ on: true,
203+ };
204+ let mut state = LimiterState::new(&params, rate, 2);
205+ // Half a second of quiet, then half a second at 4x full scale: the
206+ // join is where an attack overshoot would show.
207+ let mut buf: Vec<f32> = (0..rate)
208+ .flat_map(|i| {
209+ let t = i as f32 / rate as f32;
210+ let amp = match i < rate / 2 {
211+ true => 0.05,
212+ false => 4.0,
213+ };
214+ let s = amp * (t * 440.0 * std::f32::consts::TAU).sin();
215+ [s, s]
216+ })
217+ .collect();
218+ let quiet_in = buf[..rate as usize / 2].to_vec();
219+ state.process(&mut buf);
220+ let ceiling = db_to_linear(-3.0);
221+ let peak = buf.iter().fold(0.0f32, |m, s| m.max(s.abs()));
222+ assert!(
223+ peak <= ceiling + 1e-6,
224+ "peak {peak} passed the {ceiling} ceiling"
225+ );
226+ // ...and it is not simply silence: the loud half is right at the wall.
227+ assert!(
228+ peak > ceiling * 0.99,
229+ "peak {peak} is nowhere near the wall"
230+ );
231+ // The quiet half is untouched, bar the frames the lookahead eats and
232+ // the ones where the gain has already started coming down for the loud
233+ // part that is about to arrive.
234+ let head = quiet_in.len() / 2;
235+ for (a, b) in buf[..head].iter().zip(&quiet_in[..head]) {
236+ assert!((a - b).abs() < 1e-6, "{a} != {b} under the knee");
237+ }
238+ // The delay line is paid back, not carried: the output is shorter by
239+ // exactly the lookahead and nothing else.
240+ assert_eq!(buf.len(), rate as usize * 2 - (state.peaks.len() - 1) * 2);
241+ }
242+
243+ /// Flat settings are a passthrough, which is what the export invariant
244+ /// rests on: 0 dB is exactly 1.0, never 0.9999999.
245+ #[test]
246+ fn zero_db_is_exactly_unity() {
247+ assert_eq!(db_to_linear(0.0), 1.0);
248+ assert!((db_to_linear(-6.0) - 0.5011872).abs() < 1e-6);
249+ assert!(!Limiter::default().is_active(), "off until asked for");
250+ assert_eq!(
251+ Limiter::default().with_ceiling(-99.0).ceiling_db,
252+ Limiter::MIN_DB
253+ );
254+ assert_eq!(
255+ Limiter::default().with_ceiling(f32::NAN).ceiling_db,
256+ Limiter::default().ceiling_db
257+ );
258+ }
259+}
crates/engine/src/playback.rsmodified+62 -14
@@ -496,11 +496,14 @@ impl PlaybackSession {
496 // then refuses every file on it for not matching. The rule this and496 // then refuses every file on it for not matching. The rule this and
497 // [`audio_source_of`] share: nothing may assume what source 0 *is*.497 // [`audio_source_of`] share: nothing may assume what source 0 *is*.
498 //498 //
499- // ponytail: a timeline of nothing but stills, or of stills and songs,499+ // A v9 file says what rate it was cut at, and that answer beats the
500- // still comes back at the rate its scaffold implies rather than the one500+ // scaffold's *where the scaffold has none to give*: a still and a song
501- // it was cut at -- the rate is written nowhere in the file. The upgrade501+ // are both given a made-up rate (`IMAGE_ONLY_RATE`,
502- // path is a dialect that writes it (`crate::edith`), which is also what502+ // `AUDIO_ONLY_CANVAS`), so a timeline of nothing but those used to come
503- // a project naming no file at all would need.503+ // back at 30 fps however it was cut. A scaffold with a picture keeps
504+ // defining the timeline as it always did -- it is the file every clip
505+ // on the lane was conformed to, and the two agree by construction.
506+ let saved_fps = doc.fps.filter(|f| f.is_finite() && *f > 0.0);
504 let scaffold = doc507 let scaffold = doc
505 .sources508 .sources
506 .iter()509 .iter()
@@ -530,7 +533,8 @@ impl PlaybackSession {
530 // like every other worker opened here.533 // like every other worker opened here.
531 let (mut meta, stream) = match crate::is_audio(&first.path) {534 let (mut meta, stream) = match crate::is_audio(&first.path) {
532 true => {535 true => {
533- let (width, height, frame_rate) = AUDIO_ONLY_CANVAS;536+ let (width, height, canvas_fps) = AUDIO_ONLY_CANVAS;
537+ let frame_rate = saved_fps.unwrap_or(canvas_fps);
534 let meta = VideoMeta {538 let meta = VideoMeta {
535 width,539 width,
536 height,540 height,
@@ -547,11 +551,12 @@ impl PlaybackSession {
547 false if crate::is_image(&first.path) => {551 false if crate::is_image(&first.path) => {
548 let still = crate::decode::Still::open(&first.path)552 let still = crate::decode::Still::open(&first.path)
549 .map_err(|e| format!("source {}: {e}", first.path.display()))?;553 .map_err(|e| format!("source {}: {e}", first.path.display()))?;
554+ let frame_rate = saved_fps.unwrap_or(IMAGE_ONLY_RATE);
550 let meta = VideoMeta {555 let meta = VideoMeta {
551 width: still.width,556 width: still.width,
552 height: still.height,557 height: still.height,
553- frame_rate: IMAGE_ONLY_RATE,558+ frame_rate,
554- frame_count: image_frames(IMAGE_ONLY_RATE),559+ frame_count: image_frames(frame_rate),
555 codec: Codec::H264,560 codec: Codec::H264,
556 };561 };
557 let stream = DecodeSession::open_still(562 let stream = DecodeSession::open_still(
@@ -668,7 +673,8 @@ impl PlaybackSession {
668 }673 }
669 674
670 let playhead = doc.playhead;675 let playhead = doc.playhead;
671- let project = Project::from_parts(doc.sources, doc.lanes, doc.eq, doc.color)?;676+ let project = Project::from_parts(doc.sources, doc.lanes, doc.eq, doc.color)?
677+ .with_mix(&doc.gains, doc.limiter);
672 let span = project.composite_span_at(0);678 let span = project.composite_span_at(0);
673 // Last, because it is the one thing here that cannot be taken back: the679 // Last, because it is the one thing here that cannot be taken back: the
674 // feeder thread outlives the `Audio` value (it holds its own clones) and680 // feeder thread outlives the `Audio` value (it holds its own clones) and
@@ -769,9 +775,19 @@ impl PlaybackSession {
769 path,775 path,
770 &sources,776 &sources,
771 &lanes,777 &lanes,
778+ // The lane volumes and the limiter with them: a mix that vanished
779+ // on a reload would be a mix nobody could keep, and both are the
780+ // project's, not this machine's (the monitoring volume is not
781+ // written and never will be).
782+ &self.project.lane_gains(),
772 &eq,783 &eq,
773 &color,784 &color,
774 (self.meta.width, self.meta.height),785 (self.meta.width, self.meta.height),
786+ // ...and the rate it was cut at, which nothing else in the file
787+ // says: a timeline of stills and songs used to come back at
788+ // whatever its scaffold implied (`open_project`).
789+ Some(self.meta.frame_rate),
790+ self.project.limiter(),
775 playhead,791 playhead,
776 )792 )
777 }793 }
@@ -1094,6 +1110,31 @@ impl PlaybackSession {
1094 self.edit(|p| p.set_eq(lane, idx, params))1110 self.edit(|p| p.set_eq(lane, idx, params))
1095 }1111 }
1096 1112
1113+ /// How loud that lane plays, in dB -- everything on it, every frequency of
1114+ /// it. See [`Project::lane_gain_db`] for what it is *not*.
1115+ pub fn lane_gain_db(&self, lane: Lane) -> f32 {
1116+ self.project.lane_gain_db(lane)
1117+ }
1118+
1119+ /// Sets it. One undo step and a reseek, the equalizer's rule for the
1120+ /// equalizer's reason: the mixer is rebuilt from the new volumes right
1121+ /// where the playhead is, so a track turned down during playback is heard
1122+ /// turned down from the next chunk on.
1123+ pub fn set_lane_gain_db(&mut self, lane: Lane, db: f32) -> bool {
1124+ self.edit(|p| p.set_lane_gain_db(lane, db))
1125+ }
1126+
1127+ /// The master limiter the whole mix is summed through.
1128+ pub fn limiter(&self) -> crate::limiter::Limiter {
1129+ self.project.limiter()
1130+ }
1131+
1132+ /// Sets it, live like a lane volume and for the same reason -- the ceiling
1133+ /// a person is dragging has to be the ceiling they are hearing.
1134+ pub fn set_limiter(&mut self, limiter: crate::limiter::Limiter) -> bool {
1135+ self.edit(|p| p.set_limiter(limiter))
1136+ }
1137+
1097 /// Lifts one lane's clip out, leaving a gap: black frames on the video lane,1138 /// Lifts one lane's clip out, leaving a gap: black frames on the video lane,
1098 /// silence on the audio one, and nothing else moves. Reseeks, because what1139 /// silence on the audio one, and nothing else moves. Reseeks, because what
1099 /// the playhead sits on has changed. `false` for a bad index -- the lift of1140 /// the playhead sits on has changed. `false` for a bad index -- the lift of
@@ -1797,11 +1838,18 @@ impl PlaybackSession {
1797 // Each source on the stream it was placed with: what plays is what1838 // Each source on the stream it was placed with: what plays is what
1798 // the library row said, and what an export copies (`export::run`).1839 // the library row said, and what an export copies (`export::run`).
1799 let sources = self.project.audio_sources();1840 let sources = self.project.audio_sources();
1800- audio_running =1841+ // ...and the mix settings over the lot: each lane's own volume on
1801- match AudioSession::open_mixed_streams_speed(&sources, &segs, &eqs, &speeds) {1842+ // its way into the sum and the master limiter over the sum, both
1802- Ok(Some((_, rx))) => audio.spawn_feeder(rx),1843+ // rebuilt here like the curves above, which is what makes a lane
1803- _ => false,1844+ // fader and a ceiling audible while the timeline runs.
1804- };1845+ let gains = self.project.audio_gains();
1846+ let limiter = self.project.limiter();
1847+ audio_running = match AudioSession::open_mixed_streams_master(
1848+ &sources, &segs, &eqs, &speeds, &gains, limiter,
1849+ ) {
1850+ Ok(Some((_, rx))) => audio.spawn_feeder(rx),
1851+ _ => false,
1852+ };
1805 if !audio_running {1853 if !audio_running {
1806 // Nothing will ever be fed again; let `tick` fall to wall time1854 // Nothing will ever be fed again; let `tick` fall to wall time
1807 // instead of waiting on a device that has no more work coming.1855 // instead of waiting on a device that has no more work coming.
crates/engine/src/project.rsmodified+125 -22
@@ -66,8 +66,18 @@ use std::path::{Path, PathBuf};
66 66
67 use crate::color::ColorParams;67 use crate::color::ColorParams;
68 use crate::eq::EqParams;68 use crate::eq::EqParams;
69+use crate::limiter::{Limiter, db_to_linear};
69 use crate::scale::FitPolicy;70 use crate::scale::FitPolicy;
70 71
72+/// How far down a lane's own volume goes ([`Project::set_lane_gain_db`]).
73+/// -60 dB is a thousandth of the amplitude -- a track that is out of the mix
74+/// for every purpose but the honest one, which is that it is still a level and
75+/// not a mute.
76+pub const MIN_GAIN_DB: f32 = -60.0;
77+/// ...and how far up. +12 dB is four times the amplitude, which is as much as
78+/// a mix bus can take before the limiter is doing all the work.
79+pub const MAX_GAIN_DB: f32 = 12.0;
80+
71 /// How fast a clip plays, in **thousandths of real time**: 1000 is the speed it81 /// How fast a clip plays, in **thousandths of real time**: 1000 is the speed it
72 /// was shot at, 2000 twice that, 500 half. An integer and not an `f32` for82 /// was shot at, 2000 twice that, 500 half. An integer and not an `f32` for
73 /// [`Clip`]'s sake -- a clip is `Copy` *and* `Eq`, a float is neither exactly83 /// [`Clip`]'s sake -- a clip is `Copy` *and* `Eq`, a float is neither exactly
@@ -477,21 +487,29 @@ struct LaneData {
477 kind: LaneKind,487 kind: LaneKind,
478 /// Sorted by `start` and disjoint ([`sorted_disjoint`]).488 /// Sorted by `start` and disjoint ([`sorted_disjoint`]).
479 clips: Vec<Clip>,489 clips: Vec<Clip>,
490+ /// How loud this lane plays, in dB, `0.0` for one nobody has touched --
491+ /// [`Project::lane_gain_db`]. Whole-lane and whole-band, which is what
492+ /// makes it a different thing from a clip's equalizer: it moves everything
493+ /// on the track by the same amount, cuts included. Meaningless on a video
494+ /// lane, where it is kept at 0 and asked by nothing.
495+ gain_db: f32,
480 }496 }
481 497
482 impl LaneData {498 impl LaneData {
499+ fn new(kind: LaneKind, clips: Vec<Clip>) -> Self {
500+ Self {
501+ kind,
502+ clips,
503+ gain_db: 0.0,
504+ }
505+ }
506+
483 /// The two lanes a project starts with: `V1` then `A1`, in display order.507 /// The two lanes a project starts with: `V1` then `A1`, in display order.
484 /// One place, because a freshly opened file is exactly this pair.508 /// One place, because a freshly opened file is exactly this pair.
485 fn two_lanes(video: Vec<Clip>, audio: Vec<Clip>) -> Vec<LaneData> {509 fn two_lanes(video: Vec<Clip>, audio: Vec<Clip>) -> Vec<LaneData> {
486 vec![510 vec![
487- LaneData {511+ LaneData::new(LaneKind::Video, video),
488- kind: LaneKind::Video,512+ LaneData::new(LaneKind::Audio, audio),
489- clips: video,
490- },
491- LaneData {
492- kind: LaneKind::Audio,
493- clips: audio,
494- },
495 ]513 ]
496 }514 }
497 }515 }
@@ -600,6 +618,12 @@ pub struct Project {
600 /// Never rolled back by an undo: an id retired by an undone split must not618 /// Never rolled back by an undo: an id retired by an undone split must not
601 /// come back and group two clips that were never together.619 /// come back and group two clips that were never together.
602 next_link: u32,620 next_link: u32,
621+ /// The master limiter every lane's sound is summed *through*
622+ /// ([`Project::limiter`]). Off by default, and not in the lane list, which
623+ /// is what the history snapshots hold: it is a setting on the mix, like the
624+ /// project's resolution is a setting on the picture, and neither is an undo
625+ /// step.
626+ limiter: Limiter,
603 }627 }
604 628
605 impl Project {629 impl Project {
@@ -628,6 +652,7 @@ impl Project {
628 color: Vec::new(),652 color: Vec::new(),
629 history: Vec::new(),653 history: Vec::new(),
630 next_link: 1,654 next_link: 1,
655+ limiter: Limiter::default(),
631 }656 }
632 }657 }
633 658
@@ -665,7 +690,7 @@ impl Project {
665 }690 }
666 let lanes: Vec<LaneData> = lanes691 let lanes: Vec<LaneData> = lanes
667 .into_iter()692 .into_iter()
668- .map(|(kind, clips)| LaneData { kind, clips })693+ .map(|(kind, clips)| LaneData::new(kind, clips))
669 .collect();694 .collect();
670 for (data, lane) in lanes.iter().zip(handles(&lanes)) {695 for (data, lane) in lanes.iter().zip(handles(&lanes)) {
671 let name = lane.label();696 let name = lane.label();
@@ -735,6 +760,7 @@ impl Project {
735 color,760 color,
736 history: Vec::new(),761 history: Vec::new(),
737 next_link,762 next_link,
763+ limiter: Limiter::default(),
738 })764 })
739 }765 }
740 766
@@ -770,10 +796,7 @@ impl Project {
770 /// ([`Project::from_parts`]); nothing plays until something is placed.796 /// ([`Project::from_parts`]); nothing plays until something is placed.
771 pub fn add_lane(&mut self, kind: LaneKind) -> Lane {797 pub fn add_lane(&mut self, kind: LaneKind) -> Lane {
772 self.snapshot();798 self.snapshot();
773- self.lanes.push(LaneData {799+ self.lanes.push(LaneData::new(kind, Vec::new()));
774- kind,
775- clips: Vec::new(),
776- });
777 Lane::new(kind, self.lane_count(kind) - 1)800 Lane::new(kind, self.lane_count(kind) - 1)
778 }801 }
779 802
@@ -1053,6 +1076,92 @@ impl Project {
1053 )1076 )
1054 }1077 }
1055 1078
1079+ /// How loud `lane` plays, in dB: `0.0` for one nobody has touched, and for
1080+ /// a lane that is not there. Whole-lane and whole-band -- every clip on the
1081+ /// track moves by it, which is what makes it a different control from a
1082+ /// clip's equalizer (one frequency range of one take) and from the master
1083+ /// volume (what this machine monitors at, which no file carries).
1084+ pub fn lane_gain_db(&self, lane: Lane) -> f32 {
1085+ self.index(lane).map_or(0.0, |i| self.lanes[i].gain_db)
1086+ }
1087+
1088+ /// Sets that lane's volume, clamped to [`MIN_GAIN_DB`]..=[`MAX_GAIN_DB`].
1089+ /// One undo step like every other edit -- it is in the lane list, so an
1090+ /// undo restores it with the rest. `false`, and no history, for a lane that
1091+ /// is not there, for a value that is not finite, and for one already set.
1092+ pub fn set_lane_gain_db(&mut self, lane: Lane, db: f32) -> bool {
1093+ let Some(i) = self.index(lane) else {
1094+ return false;
1095+ };
1096+ if !db.is_finite() {
1097+ return false;
1098+ }
1099+ let db = db.clamp(MIN_GAIN_DB, MAX_GAIN_DB);
1100+ if self.lanes[i].gain_db == db {
1101+ return false;
1102+ }
1103+ self.snapshot();
1104+ self.lanes[i].gain_db = db;
1105+ true
1106+ }
1107+
1108+ /// Every lane's volume in dB, in display order -- what a save writes,
1109+ /// beside the lanes [`Project::without_orphan_sources`] hands back.
1110+ pub fn lane_gains(&self) -> Vec<f32> {
1111+ self.lanes.iter().map(|l| l.gain_db).collect()
1112+ }
1113+
1114+ /// The mix settings a *load* puts back: lane volumes in display order (a
1115+ /// short list leaves the rest at unity) and the master limiter, both
1116+ /// clamped as their setters clamp them.
1117+ ///
1118+ /// The load's own door, beside [`from_parts`](Project::from_parts): the
1119+ /// setters push an undo step, and a project that arrives one undo away from
1120+ /// a state it was never in is a project whose first ctrl+z is a surprise.
1121+ pub fn with_mix(mut self, gains: &[f32], limiter: Limiter) -> Self {
1122+ for (data, &db) in self.lanes.iter_mut().zip(gains) {
1123+ if db.is_finite() {
1124+ data.gain_db = db.clamp(MIN_GAIN_DB, MAX_GAIN_DB);
1125+ }
1126+ }
1127+ self.limiter = limiter.with_ceiling(limiter.ceiling_db);
1128+ self
1129+ }
1130+
1131+ /// What each of [`audio_segments_from`](Project::audio_segments_from)'s
1132+ /// lanes is multiplied by on its way into the mix: the same lanes in the
1133+ /// same order, as *amplitudes*, so the mixer never sees a decibel. `1.0`
1134+ /// for a lane nobody has turned, which is a multiply f32 leaves alone --
1135+ /// the bit-exact path.
1136+ pub fn audio_gains(&self) -> Vec<f32> {
1137+ self.audio_lanes()
1138+ .into_iter()
1139+ .map(|lane| db_to_linear(self.lane_gain_db(lane)))
1140+ .collect()
1141+ }
1142+
1143+ /// The master limiter the mix is summed through. A project setting, not a
1144+ /// clip's and not a lane's: there is one mix.
1145+ pub fn limiter(&self) -> Limiter {
1146+ self.limiter
1147+ }
1148+
1149+ /// Sets it, with the ceiling clamped to what [`Limiter`] allows. `false`
1150+ /// for a setting already in force.
1151+ ///
1152+ /// ponytail: not an undo step, for the reason the project resolution is not
1153+ /// one ([`crate::PlaybackSession::set_resolution`]) -- it is not in the
1154+ /// lane list the history snapshots. Upgrade path is a history entry that
1155+ /// holds the mix settings beside the lanes.
1156+ pub fn set_limiter(&mut self, limiter: Limiter) -> bool {
1157+ let limiter = limiter.with_ceiling(limiter.ceiling_db);
1158+ if self.limiter == limiter {
1159+ return false;
1160+ }
1161+ self.limiter = limiter;
1162+ true
1163+ }
1164+
1056 /// What the clip at `idx` of `lane` plays through, or `None` for one that1165 /// What the clip at `idx` of `lane` plays through, or `None` for one that
1057 /// plays flat (and for an index that is not there) -- what a feeder and an1166 /// plays flat (and for an index that is not there) -- what a feeder and an
1058 /// export ask before they build an [`crate::eq::EqState`].1167 /// export ask before they build an [`crate::eq::EqState`].
@@ -5342,14 +5451,8 @@ mod tests {
5342 speed: Speed::NORMAL,5451 speed: Speed::NORMAL,
5343 };5452 };
5344 let lanes = vec![5453 let lanes = vec![
5345- LaneData {5454+ LaneData::new(LaneKind::Video, vec![linked(3, 4)]),
5346- kind: LaneKind::Video,5455+ LaneData::new(LaneKind::Video, vec![linked(5, 4)]),
5347- clips: vec![linked(3, 4)],
5348- },
5349- LaneData {
5350- kind: LaneKind::Video,
5351- clips: vec![linked(5, 4)],
5352- },
5353 ];5456 ];
5354 assert_eq!(5457 assert_eq!(
5355 links_are_consistent(&lanes).unwrap_err().to_string(),5458 links_are_consistent(&lanes).unwrap_err().to_string(),
@@ -5364,7 +5467,7 @@ mod tests {
5364 /// checked at the untrusted door and no edit can produce these.5467 /// checked at the untrusted door and no edit can produce these.
5365 #[test]5468 #[test]
5366 fn a_group_may_span_any_lane() {5469 fn a_group_may_span_any_lane() {
5367- let lane = |kind, clips: Vec<Clip>| LaneData { kind, clips };5470+ let lane = |kind, clips: Vec<Clip>| LaneData::new(kind, clips);
5368 let one = |start: u32, end: u32, link| Clip {5471 let one = |start: u32, end: u32, link| Clip {
5369 start,5472 start,
5370 in_frame: start,5473 in_frame: start,
crates/engine/tests/audio_export.rsmodified+121 -1
@@ -15,7 +15,7 @@ use std::path::{Path, PathBuf};
15 use std::time::{Duration, Instant};15 use std::time::{Duration, Instant};
16 16
17 use engine::export::{ExportSettings, Format};17 use engine::export::{ExportSettings, Format};
18-use engine::project::{LaneKind, Source, Speed};18+use engine::project::{Lane, LaneKind, Source, Speed};
19 use engine::scale::FitPolicy;19 use engine::scale::FitPolicy;
20 use engine::{AudioSession, Clip, ExportHandle, Project};20 use engine::{AudioSession, Clip, ExportHandle, Project};
21 21
@@ -365,6 +365,126 @@ fn a_still_and_a_song_export_as_an_mp4_with_sound() {
365 /// Cancel leaves nothing behind -- not the output, not the `.part`. The365 /// Cancel leaves nothing behind -- not the output, not the `.part`. The
366 /// timeline is long enough (a minute of audio) that the escape lands mid-decode366 /// timeline is long enough (a minute of audio) that the escape lands mid-decode
367 /// rather than after the file is already closed.367 /// rather than after the file is already closed.
368+/// What the two mix settings do to a *written file*, which is the only place
369+/// the claim can be checked: a track's fader is that track's alone, and the
370+/// master limiter holds the sum of them under its ceiling instead of letting it
371+/// square off at full scale.
372+///
373+/// Four audio tracks of the same second, so the sum is four times one file and
374+/// well past what a sample can hold. Measured as the peak of the WAV read back
375+/// through the engine's own reader -- a level, not a shape, because that is
376+/// exactly what a limiter promises.
377+#[test]
378+fn a_fader_is_one_tracks_own_and_the_limiter_holds_the_sum() {
379+ let clip = Clip {
380+ start: 0,
381+ in_frame: 0,
382+ out_frame: 30,
383+ source: 0,
384+ link: None,
385+ eq: None,
386+ color: None,
387+ fit: FitPolicy::default(),
388+ speed: Speed::NORMAL,
389+ };
390+ let four = || {
391+ Project::from_parts(
392+ vec![Source::new(asset("test_av.mp4"), 0)],
393+ vec![
394+ (LaneKind::Video, vec![clip]),
395+ (LaneKind::Audio, vec![clip]),
396+ (LaneKind::Audio, vec![clip]),
397+ (LaneKind::Audio, vec![clip]),
398+ (LaneKind::Audio, vec![clip]),
399+ ],
400+ Vec::new(),
401+ Vec::new(),
402+ )
403+ .expect("one second on four audio tracks")
404+ };
405+ let write = |project: Project, name: &str| {
406+ let out = out_path(name, "wav");
407+ let handle = engine::export::start(
408+ project,
409+ meta(),
410+ &out,
411+ &ExportSettings {
412+ format: Format::Wav,
413+ ..Default::default()
414+ },
415+ );
416+ wait(&handle, Duration::from_secs(60)).unwrap_or_else(|e| panic!("{name}: {e}"));
417+ let (audio, samples) = decode(&out);
418+ let peak = samples.iter().fold(0.0f32, |m, s| m.max(s.abs()));
419+ let level = rms(&samples, usize::from(audio.channels), 0.05, 0.95);
420+ let _ = std::fs::remove_file(&out);
421+ (peak, level)
422+ };
423+
424+ // Four copies of one file, each fader all the way up: the sum is well past
425+ // what a sample can hold, and with no limiter it is clamped at full scale
426+ // by the mixer's own backstop -- which is the clipping this exists for.
427+ let hot = || {
428+ let mut project = four();
429+ for ord in 0..4 {
430+ assert!(project.set_lane_gain_db(
431+ Lane::new(LaneKind::Audio, ord),
432+ engine::project::MAX_GAIN_DB
433+ ));
434+ }
435+ project
436+ };
437+ let (flat_peak, flat_level) = write(hot(), "mix_flat");
438+ println!("flat: peak {flat_peak:.4} rms {flat_level:.4}");
439+
440+ // One track's fader, and one track's only: A2, A3 and A4 all the way down
441+ // leaves a quarter of the sum, so the level drops by ~12 dB against the
442+ // four of them at the same setting. A whole-band
443+ // change -- there is no frequency in this claim, which is what makes it a
444+ // different control from the equalizer.
445+ let (unity_peak, unity_level) = write(four(), "mix_unity");
446+ let mut down = four();
447+ for ord in 1..4 {
448+ assert!(down.set_lane_gain_db(
449+ Lane::new(LaneKind::Audio, ord),
450+ engine::project::MIN_GAIN_DB
451+ ));
452+ }
453+ let (_, quiet_level) = write(down, "mix_fader");
454+ let drop_db = 20.0 * (quiet_level / unity_level).log10();
455+ println!("one track alone: rms {quiet_level:.4} ({drop_db:.1} dB)");
456+ assert!(
457+ (drop_db + 12.0).abs() < 1.5,
458+ "three of four tracks down left {drop_db:.1} dB, not ~-12"
459+ );
460+
461+ // The limiter over the same hot sum: the peak lands under the ceiling, and
462+ // the sound is still there (a limiter that silenced the mix would pass a
463+ // peak test and fail every ear).
464+ let ceiling_db = -3.0;
465+ let mut limited = hot();
466+ assert!(limited.set_limiter(engine::limiter::Limiter {
467+ ceiling_db,
468+ on: true,
469+ }));
470+ let (peak, level) = write(limited, "mix_limited");
471+ let ceiling = 10f32.powf(ceiling_db / 20.0);
472+ println!("limited: peak {peak:.4} vs ceiling {ceiling:.4} rms {level:.4}");
473+ assert!(
474+ flat_peak > ceiling,
475+ "the flat mix was not hot to begin with"
476+ );
477+ assert!(
478+ peak <= ceiling + 1e-3,
479+ "peak {peak:.4} passed the {ceiling:.4} ceiling"
480+ );
481+ assert!(level > unity_level, "the limiter took the mix out");
482+ assert!(
483+ unity_peak < 1.0,
484+ "four at unity fit; the +12 dB four did not"
485+ );
486+}
487+
368 #[test]488 #[test]
369 fn a_cancelled_audio_export_leaves_no_file() {489 fn a_cancelled_audio_export_leaves_no_file() {
370 let source = asset("test_av.mp4");490 let source = asset("test_av.mp4");
crates/engine/tests/backends.rsmodified+64 -0
@@ -193,6 +193,70 @@ fn audio_only_job_names_its_encoder(format: Format) {
193 assert_eq!(opened, planned, "{}", format.ext());193 assert_eq!(opened, planned, "{}", format.ext());
194 }194 }
195 195
196+/// A mixed timeline cannot be copied, and the card must say so *before* the
197+/// export: a fader and a limiter both live where the lanes are summed, and a
198+/// copied AAC packet was never summed at all -- so an mp4 of such a timeline is
199+/// decoded and re-encoded, and the line names the encoder that will do it.
200+///
201+/// The truthfulness rule of this whole file, applied to the one edit that used
202+/// to be invisible to it.
203+#[test]
204+fn a_mixed_timeline_says_it_re_encodes_and_then_does() {
205+ let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
206+ assert_eq!(
207+ session.planned_audio(Format::Mp4),
208+ "AAC copy",
209+ "a timeline nobody has mixed is still a copy"
210+ );
211+ // A fader off unity...
212+ assert!(session.set_lane_gain_db(engine::project::Lane::A1, -3.0));
213+ let planned = session.planned_audio(Format::Mp4);
214+ assert!(planned.contains("encode"), "a faded lane: {planned}");
215+ // ...and back at unity it is a copy again: the answer follows the edit, it
216+ // is not a latch.
217+ assert!(session.set_lane_gain_db(engine::project::Lane::A1, 0.0));
218+ assert_eq!(session.planned_audio(Format::Mp4), "AAC copy");
219+ // ...and the limiter alone does it too.
220+ assert!(session.set_limiter(engine::limiter::Limiter {
221+ ceiling_db: -1.0,
222+ on: true,
223+ }));
224+ assert_eq!(session.planned_audio(Format::Mp4), planned);
225+
226+ // ...and the job opens exactly that, which is the pin the whole file is
227+ // about: the encoders line published by the running export.
228+ let out = out_path("mixed", "mp4");
229+ let handle = session.export_to_with(
230+ &out,
231+ &ExportSettings {
232+ format: Format::Mp4,
233+ ..ExportSettings::default()
234+ },
235+ );
236+ let started = Instant::now();
237+ let opened = loop {
238+ if let Some(line) = handle.encoders() {
239+ break line;
240+ }
241+ assert!(
242+ !handle.is_finished(),
243+ "the export settled before it opened an encoder: {:?}",
244+ handle.result().map(|r| r.err())
245+ );
246+ assert!(
247+ started.elapsed() < Duration::from_secs(60),
248+ "no encoder was published"
249+ );
250+ std::thread::sleep(Duration::from_millis(10));
251+ };
252+ handle.cancel();
253+ wind_down(&handle);
254+ assert!(
255+ opened.ends_with(&planned),
256+ "{opened} does not end in {planned}"
257+ );
258+}
259+
196 /// Waits for a cancelled job to settle, so its `.part` is gone before the test260 /// Waits for a cancelled job to settle, so its `.part` is gone before the test
197 /// ends -- and so no worker outlives the process holding a VA-API session.261 /// ends -- and so no worker outlives the process holding a VA-API session.
198 fn wind_down(handle: &ExportHandle) {262 fn wind_down(handle: &ExportHandle) {
crates/engine/tests/saveload.rsmodified+77 -6
@@ -209,7 +209,7 @@ fn a_version_1_project_loads_fully_grouped_and_saves_as_version_7() {
209 let v2 = dir.join("new.edith");209 let v2 = dir.join("new.edith");
210 loaded.save_project(&v2).expect("save");210 loaded.save_project(&v2).expect("save");
211 let text = std::fs::read_to_string(&v2).expect("read back");211 let text = std::fs::read_to_string(&v2).expect("read back");
212- assert!(text.starts_with("edith 8\n"), "{text}");212+ assert!(text.starts_with("edith 9\n"), "{text}");
213 assert!(213 assert!(
214 text.contains("\nresolution 1280 720\n"),214 text.contains("\nresolution 1280 720\n"),
215 "a project with no resolution of its own is saved at source 0's: {text}"215 "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() {
297 loaded.save_project(&again).expect("save");297 loaded.save_project(&again).expect("save");
298 assert_eq!(298 assert_eq!(
299 std::fs::read_to_string(&again).expect("read back"),299 std::fs::read_to_string(&again).expect("read back"),
300- "edith 8\nplayhead 0\nresolution 1280 720\nsource 0 test_av.mp4\n\300+ "edith 9\nplayhead 0\nresolution 1280 720\nfps 30.0\nsource 0 test_av.mp4\n\
301 video 1 0 0 30 0 3 - - fit 1000\naudio 1\n\301 video 1 0 0 30 0 3 - - fit 1000\naudio 1\n\
302 video 2 40 0 20 0 - - - fit 1000\naudio 2 0 0 30 0 3 - - fit 1000\n",302 video 2 40 0 20 0 - - - fit 1000\naudio 2 0 0 30 0 3 - - fit 1000\n",
303 "a four-lane project is written as it was read, three versions on"303 "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() {
327 loaded.save_project(&again).expect("save");327 loaded.save_project(&again).expect("save");
328 assert_eq!(328 assert_eq!(
329 std::fs::read_to_string(&again).expect("read back"),329 std::fs::read_to_string(&again).expect("read back"),
330- "edith 8\nplayhead 0\nresolution 1280 720\nsource 0 test_av.mp4\n\330+ "edith 9\nplayhead 0\nresolution 1280 720\nfps 30.0\nsource 0 test_av.mp4\n\
331 eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk\n\331 eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk\n\
332 eq 12000.0:6.25:0.5:hs\n\332 eq 12000.0:6.25:0.5:hs\n\
333 video 1 0 0 30 0 - 0 - fit 1000\nvideo 1 30 30 60 0 - 1 - fit 1000\n\333 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() {
362 loaded.save_project(&again).expect("save");362 loaded.save_project(&again).expect("save");
363 assert_eq!(363 assert_eq!(
364 std::fs::read_to_string(&again).expect("read back"),364 std::fs::read_to_string(&again).expect("read back"),
365- "edith 8\nplayhead 0\nresolution 1280 720\nsource 0 test_av.mp4\n\365+ "edith 9\nplayhead 0\nresolution 1280 720\nfps 30.0\nsource 0 test_av.mp4\n\
366 eq 80.0:-3.0:0.707:ls\n\366 eq 80.0:-3.0:0.707:ls\n\
367 color 0.1:1.2:0.9:-0.3\n\367 color 0.1:1.2:0.9:-0.3\n\
368 color -0.25:1.0:0.0:0.5\n\368 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() {
412 loaded.save_project(&again).expect("save");412 loaded.save_project(&again).expect("save");
413 assert_eq!(413 assert_eq!(
414 std::fs::read_to_string(&again).expect("read back"),414 std::fs::read_to_string(&again).expect("read back"),
415- "edith 8\nplayhead 0\nresolution 960 720\nsource 0 test_av.mp4\n\415+ "edith 9\nplayhead 0\nresolution 960 720\nfps 30.0\nsource 0 test_av.mp4\n\
416 video 1 0 0 30 0 - - - fill 1000\nvideo 1 30 30 60 0 - - - center 1000\n\416 video 1 0 0 30 0 - - - fill 1000\nvideo 1 30 30 60 0 - - - center 1000\n\
417 audio 1 0 0 60 0 - - - fit 1000\n",417 audio 1 0 0 60 0 - - - fit 1000\n",
418 "a v7 project is written back as the v8 it now is: the same clips, each \418 "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() {
670 670
671 for (text, want) in [671 for (text, want) in [
672 (672 (
673- "edith 9\nsource 0 test_av.mp4\nvideo 1 0 0 30 0 - - - fit\n",673+ "edith 10\nsource 0 test_av.mp4\nvideo 1 0 0 30 0 - - - fit\n",
674 "line 1",674 "line 1",
675 ),675 ),
676 // An eq index the table does not hold, and a band shape there is none.676 // 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() {
755 )755 )
756 );756 );
757 }757 }
758+
759+/// The mix a project was left at comes back with it: a track's fader, the
760+/// master limiter and the rate the timeline was cut at. A fader that vanished
761+/// on a reload would be a setting nobody could keep.
762+#[test]
763+fn the_mix_survives_a_save_and_an_open() {
764+ use engine::project::{Lane, LaneKind};
765+ let dir = scratch("mix");
766+ let source = copy_in(&dir, "test_av.mp4");
767+ let mut saved = PlaybackSession::open(&source).expect("open the fixture");
768+ let a2 = saved.add_lane(LaneKind::Audio);
769+ assert!(saved.set_lane_gain_db(Lane::A1, -6.0));
770+ assert!(saved.set_lane_gain_db(a2, 3.0));
771+ let limiter = engine::limiter::Limiter {
772+ ceiling_db: -2.0,
773+ on: true,
774+ };
775+ assert!(saved.set_limiter(limiter));
776+ let path = dir.join("mix.edith");
777+ saved.save_project(&path).expect("save");
778+
779+ let mut loaded = PlaybackSession::open_project(&path).expect("open the project");
780+ assert_eq!(loaded.lane_gain_db(Lane::A1), -6.0, "A1's fader");
781+ assert_eq!(loaded.lane_gain_db(a2), 3.0, "A2's own, not A1's");
782+ assert_eq!(loaded.limiter(), limiter);
783+ assert!(!loaded.undo(), "a loaded mix is not an undo step");
784+ // ...and saving it again is the same bytes: the format holds all of it.
785+ let again = dir.join("again.edith");
786+ loaded
787+ .save_project(&again)
788+ .expect("save the loaded project");
789+ assert_eq!(
790+ std::fs::read(&path).unwrap(),
791+ std::fs::read(&again).unwrap(),
792+ "save -> load -> save is not a fixed point"
793+ );
794+}
795+
796+/// The other half of the v9 bump, and the debt it pays: a timeline holding
797+/// nothing but a song has no file to take a frame rate from, so it used to come
798+/// back at the canvas rate whatever it was cut at. The written `fps` is now
799+/// preferred over that inference -- and a project whose scaffold *does* have a
800+/// picture still takes the rate from the file, which is what every clip on it
801+/// was conformed to.
802+#[test]
803+fn a_song_only_project_comes_back_at_the_rate_it_names() {
804+ let dir = scratch("song_fps");
805+ copy_in(&dir, "test_tone.mp3");
806+ let path = dir.join("song.edith");
807+ std::fs::write(
808+ &path,
809+ "edith 9\nplayhead 0\nresolution 1920 1080\nfps 24.0\nsource 0 test_tone.mp3\n\
810+ video 1\naudio 1 0 0 24 0 - - - fit 1000\n",
811+ )
812+ .expect("write a v9 song project");
813+ let loaded = PlaybackSession::open_project(&path).expect("a song-only project opens");
814+ assert_eq!(loaded.meta().frame_rate, 24.0, "the rate the file names");
815+ assert_eq!(loaded.timeline_duration(), 1.0, "one second at 24 fps");
816+
817+ // The same file without the line -- which is every dialect before v9 --
818+ // still comes back at the canvas rate, so an old project is unchanged.
819+ let old = dir.join("song8.edith");
820+ std::fs::write(
821+ &old,
822+ "edith 8\nplayhead 0\nresolution 1920 1080\nsource 0 test_tone.mp3\n\
823+ video 1\naudio 1 0 0 24 0 - - - fit 1000\n",
824+ )
825+ .expect("write a v8 song project");
826+ let loaded = PlaybackSession::open_project(&old).expect("a v8 song project opens");
827+ assert_eq!(loaded.meta().frame_rate, 30.0, "the canvas rate, as before");
828+}
crates/engine/tests/silence.rsmodified+14 -2
@@ -360,10 +360,22 @@ fn scanning_a_clip_and_cutting_what_it_finds() {
360 std::fs::create_dir_all(&dir).expect("a place to save");360 std::fs::create_dir_all(&dir).expect("a place to save");
361 let file = dir.join("cut.edith");361 let file = dir.join("cut.edith");
362 let (sources, lanes, eq, color) = p.without_orphan_sources();362 let (sources, lanes, eq, color) = p.without_orphan_sources();
363- engine::edith::save(&file, &sources, &lanes, &eq, &color, (1920, 1080), 0).expect("save");363+ engine::edith::save(
364+ &file,
365+ &sources,
366+ &lanes,
367+ &p.lane_gains(),
368+ &eq,
369+ &color,
370+ (1920, 1080),
371+ None,
372+ p.limiter(),
373+ 0,
374+ )
375+ .expect("save");
364 let text = std::fs::read_to_string(&file).expect("read it back");376 let text = std::fs::read_to_string(&file).expect("read it back");
365 assert!(377 assert!(
366- text.starts_with("edith 8"),378+ text.starts_with("edith 9"),
367 "{:?}",379 "{:?}",
368 &text[..16.min(text.len())]380 &text[..16.min(text.len())]
369 );381 );