Skip to content

FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust

M7.5: Audio Gain dialog (set / adjust / normalize max peak / normalize all peaks) and default audio transitions

Brandon Thomasc42fa205cd01
diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs
index 300f0a21c..6bc65609d 100644
--- a/crates/engine/src/commands.rs
+++ b/crates/engine/src/commands.rs
@@ -876,20 +876,16 @@ fn build() -> Vec<CommandSpec> {
})?;
Ok(Value::Null)
}),
- cmd!("clip.audioGain", "Audio Gain…", ["Clip"], Some("G"), r#"{"db":f64,"relative":bool}"#, has_selection, |s, p| {
- let db = f64_p(p, "db").unwrap_or(0.0);
- let rel = bool_p(p, "relative").unwrap_or(true);
- let sel = with_links(s, &s.state.selection.clone());
- s.edit_sequence("Audio Gain", |q, _, _| {
- for t in q.audio_tracks.iter_mut() {
- for i in t.items.iter_mut().filter(|i| sel.contains(&i.id)) {
- i.gain_db = if rel { i.gain_db + db } else { db };
- }
- }
- Ok(())
- })?;
- Ok(Value::Null)
- }),
+ cmd!(
+ "clip.audioGain",
+ "Audio Gain…",
+ ["Clip"],
+ Some("G"),
+ r#"{"mode":"set|adjust|normalizeMax|normalizeAll"?,"db":f64,"relative":bool?}"#,
+ has_selection,
+ |s, p| crate::mixer::audio_gain(s, p)
+ ),
+ query!("clip.audioPeak", "Audio Clip Peak Amplitude", r#"{"clips":[id]?}"#, |s, p| crate::mixer::audio_peak(s, p)),
cmd!("clip.frameHold", "Add Frame Hold", ["Clip", "Video Options"], None, "{}", has_selection, |s, _| {
let t = s.playhead();
let sel = s.state.selection.clone();
diff --git a/crates/engine/src/mixer.rs b/crates/engine/src/mixer.rs
index 1e4a25b53..5f3781efb 100644
--- a/crates/engine/src/mixer.rs
+++ b/crates/engine/src/mixer.rs
@@ -869,6 +869,119 @@ fn clip_set(s: &mut Session, p: &Value) -> Result<Value> {
Ok(Value::Null)
}
+// ------------------------------------------------------------------------------------- audio gain
+
+/// Peak (dBFS, before clip gain) of each selected audio clip's source range.
+fn clip_peaks(s: &Session, clips: &[filmcraft_project::ClipId]) -> Vec<(filmcraft_project::ClipId, f64)> {
+ let Some(seq) = s.active_sequence() else { return Vec::new() };
+ let sr = seq.settings.sample_rate.max(1);
+ let provider = s.media.provider(s.project.clone(), s.services.clone());
+ let mut out = Vec::new();
+ for t in &seq.audio_tracks {
+ for it in t.items.iter().filter(|i| clips.contains(&i.id)) {
+ let Some(src) = filmcraft_render::SourceProvider::source(&provider, it.item) else { continue };
+ if !src.info().has_audio() {
+ continue;
+ }
+ let s0 = it.source_in.to_units_floor(sr as i64);
+ let len = ((it.duration.to_units_floor(sr as i64) as f64) * it.speed.abs().max(1e-6)).ceil() as i64;
+ let mut peak = 0f32;
+ let mut pos = s0;
+ while pos < s0 + len {
+ let n = (s0 + len - pos).min(sr as i64) as usize;
+ if let Ok(b) = src.audio(pos, n, sr) {
+ peak = b.peaks().into_iter().fold(peak, f32::max);
+ }
+ pos += n as i64;
+ }
+ out.push((it.id, 20.0 * (peak.max(1e-9) as f64).log10()));
+ }
+ }
+ out
+}
+
+fn gain_targets(s: &Session, p: &Value) -> Vec<filmcraft_project::ClipId> {
+ let sel: Vec<filmcraft_project::ClipId> = match p.get("clips").and_then(Value::as_array) {
+ Some(a) => a.iter().filter_map(|v| v.as_u64().map(filmcraft_project::ClipId)).collect(),
+ None => s.state.selection.clone(),
+ };
+ crate::commands::with_links(s, &sel)
+}
+
+/// `clip.audioPeak`: the peak amplitude of the selection (with its current clip gain), as the Audio
+/// Gain dialog shows it.
+pub fn audio_peak(s: &mut Session, p: &Value) -> Result<Value> {
+ let clips = gain_targets(s, p);
+ let seq = active_seq(s)?;
+ let gain = |c: filmcraft_project::ClipId| seq.find_item(c).map(|(_, i)| i.gain_db).unwrap_or(0.0);
+ let peaks = clip_peaks(s, &clips);
+ let max = peaks.iter().map(|(c, pk)| pk + gain(*c)).fold(f64::NEG_INFINITY, f64::max);
+ Ok(json!({
+ "peakDb": if max.is_finite() { json!(max) } else { Value::Null },
+ "clips": peaks.iter().map(|(c, pk)| json!({"clip": c.0, "sourcePeakDb": pk, "gainDb": gain(*c)})).collect::<Vec<_>>(),
+ }))
+}
+
+/// `clip.audioGain`: Set Gain to / Adjust Gain by / Normalize Max Peak to / Normalize All Peaks to.
+pub fn audio_gain(s: &mut Session, p: &Value) -> Result<Value> {
+ let db = f64_p(p, "db").unwrap_or(0.0);
+ let mode = match str_p(p, "mode") {
+ Some(m) => m.to_string(),
+ None => if bool_p(p, "relative").unwrap_or(true) { "adjust" } else { "set" }.to_string(),
+ };
+ let clips = gain_targets(s, p);
+ let new_gain: Vec<(filmcraft_project::ClipId, f64)> = match mode.as_str() {
+ "set" => clips.iter().map(|c| (*c, db)).collect(),
+ "adjust" => {
+ let seq = active_seq(s)?;
+ clips.iter().filter_map(|c| seq.find_item(*c).map(|(_, i)| (*c, i.gain_db + db))).collect()
+ }
+ "normalizeMax" | "normalizeAll" => {
+ let peaks = clip_peaks(s, &clips);
+ if peaks.is_empty() {
+ return Err(bad("clip.audioGain", "no audio clips with audio in the selection"));
+ }
+ let seq = active_seq(s)?;
+ let gain = |c: filmcraft_project::ClipId| seq.find_item(c).map(|(_, i)| i.gain_db).unwrap_or(0.0);
+ if mode == "normalizeAll" {
+ peaks.iter().map(|(c, pk)| (*c, db - pk)).collect()
+ } else {
+ let loudest = peaks.iter().map(|(c, pk)| pk + gain(*c)).fold(f64::NEG_INFINITY, f64::max);
+ let delta = db - loudest;
+ peaks.iter().map(|(c, _)| (*c, gain(*c) + delta)).collect()
+ }
+ }
+ m => return Err(bad("clip.audioGain", format!("unknown mode `{m}` (set, adjust, normalizeMax, normalizeAll)"))),
+ };
+ let n = new_gain.len();
+ let applied = new_gain.clone();
+ s.edit_sequence("Audio Gain", move |q, _, _| {
+ for t in q.audio_tracks.iter_mut() {
+ for i in t.items.iter_mut() {
+ if let Some((_, g)) = new_gain.iter().find(|(c, _)| *c == i.id) {
+ i.gain_db = g.clamp(-96.0, 96.0);
+ }
+ }
+ }
+ Ok(())
+ })?;
+ Ok(json!({"mode": mode, "clips": n, "gainDb": applied.iter().map(|(c, g)| json!({"clip": c.0, "gainDb": g})).collect::<Vec<_>>()}))
+}
+
+/// Effects panel ▸ Set Selected as Default Transition (video or audio, from the effect's kind).
+fn set_default_transition(s: &mut Session, p: &Value) -> Result<Value> {
+ let id = str_p(p, "effect").ok_or_else(|| bad("effects.setDefaultTransition", "need `effect`"))?;
+ let def = find_effect(id)
+ .or_else(|| filmcraft_project::effect_defs().iter().find(|d| d.name.eq_ignore_ascii_case(id)))
+ .ok_or_else(|| bad("effects.setDefaultTransition", format!("no effect `{id}`")))?;
+ match def.kind {
+ filmcraft_project::EffectKind::AudioTransition => s.state.default_audio_transition = def.id.to_string(),
+ filmcraft_project::EffectKind::VideoTransition => s.state.default_video_transition = def.id.to_string(),
+ _ => return Err(bad("effects.setDefaultTransition", format!("`{}` is not a transition", def.name))),
+ }
+ Ok(json!({"video": s.state.default_video_transition, "audio": s.state.default_audio_transition}))
+}
+
fn not_recording(s: &Session) -> std::result::Result<(), String> {
has_seq(s)?;
if s.mixrec.active() { Err("an automation pass is already recording".into()) } else { Ok(()) }
@@ -988,6 +1101,16 @@ pub fn commands() -> Vec<CommandSpec> {
clip_set,
true,
),
+ spec(
+ "effects.setDefaultTransition",
+ "Set Selected as Default Transition",
+ &[],
+ None,
+ r#"{"effect":"constant_power|constant_gain|exponential_fade|<video transition>"}"#,
+ always,
+ set_default_transition,
+ true,
+ ),
spec("mixer.addSubmix", "Add Audio Submix Track", &["Sequence"], None, r#"{"name":str?,"channels":"Mono|Stereo|5.1"?}"#, has_seq, add_submix, true),
spec("mixer.deleteSubmix", "Delete Submix Track", &[], None, r#"{"strip":"S1"|id}"#, has_seq, delete_submix, true),
spec(
diff --git a/crates/engine/src/mixer_tests.rs b/crates/engine/src/mixer_tests.rs
index 24c44d80c..73a89a3ef 100644
--- a/crates/engine/src/mixer_tests.rs
+++ b/crates/engine/src/mixer_tests.rs
@@ -280,3 +280,47 @@ fn recorded_pass_plays_back_through_the_mix() {
assert_eq!(s.active_sequence().unwrap().master_volume_at(Tick(sec(1.0))), -6.0);
assert!(s.active_sequence().unwrap().strip(MASTER_STRIP).is_some());
}
+
+#[test]
+fn audio_gain_modes_and_peak() {
+ let mut s = demo();
+ let clips: Vec<u64> = a1(&s).items.iter().take(3).map(|i| i.id.0).collect();
+ s.execute("timeline.select", json!({"clips": clips})).unwrap();
+ let pk = s.execute("clip.audioPeak", json!({})).unwrap();
+ let peak = pk["peakDb"].as_f64().unwrap();
+ assert!(peak.is_finite() && peak > -60.0, "{pk}");
+ // adjust (and the old {db, relative} form)
+ s.execute("clip.audioGain", json!({"mode": "adjust", "db": -2.0})).unwrap();
+ assert_eq!(a1(&s).items[0].gain_db, -2.0);
+ s.execute("clip.audioGain", json!({"db": 1.0, "relative": true})).unwrap();
+ assert_eq!(a1(&s).items[0].gain_db, -1.0);
+ s.execute("clip.audioGain", json!({"mode": "set", "db": 3.0})).unwrap();
+ assert!(a1(&s).items.iter().take(3).all(|i| i.gain_db == 3.0));
+ // normalize max peak: the loudest clip lands on the target, the others keep their offsets
+ s.execute("clip.audioGain", json!({"mode": "normalizeMax", "db": -1.0})).unwrap();
+ let pk = s.execute("clip.audioPeak", json!({})).unwrap();
+ assert!((pk["peakDb"].as_f64().unwrap() + 1.0).abs() < 1e-6, "{pk}");
+ let g: Vec<f64> = a1(&s).items.iter().take(3).map(|i| i.gain_db).collect();
+ assert!(g.windows(2).all(|w| (w[0] - w[1]).abs() < 1e-9), "same adjustment for all: {g:?}");
+ // normalize all peaks: every clip on the target
+ s.execute("clip.audioGain", json!({"mode": "normalizeAll", "db": -6.0})).unwrap();
+ let pk = s.execute("clip.audioPeak", json!({})).unwrap();
+ for c in pk["clips"].as_array().unwrap() {
+ let total = c["sourcePeakDb"].as_f64().unwrap() + c["gainDb"].as_f64().unwrap();
+ assert!((total + 6.0).abs() < 1e-6, "{c}");
+ }
+ assert!(s.execute("clip.audioGain", json!({"mode": "loud"})).is_err());
+}
+
+#[test]
+fn default_audio_transition_is_used_by_apply() {
+ let mut s = demo();
+ s.execute("effects.setDefaultTransition", json!({"effect": "Exponential Fade"})).unwrap();
+ assert_eq!(s.state.default_audio_transition, "exponential_fade");
+ assert!(s.execute("effects.setDefaultTransition", json!({"effect": "amplify"})).is_err());
+ let clip = a1(&s).items[1].id.0;
+ s.execute("sequence.applyAudioTransition", json!({"clip": clip})).unwrap();
+ let tr = &a1(&s).transitions;
+ assert_eq!(tr.len(), 1);
+ assert_eq!(tr[0].effect.effect, "exponential_fade");
+}
diff --git a/crates/render/src/mixer_tests.rs b/crates/render/src/mixer_tests.rs
index d4270dae7..154b98298 100644
--- a/crates/render/src/mixer_tests.rs
+++ b/crates/render/src/mixer_tests.rs
@@ -432,3 +432,22 @@ fn perf_24_tracks_3_effects_realtime_factor() {
let min = if cfg!(debug_assertions) { 1.0 } else { 4.0 };
assert!(rt > min, "realtime factor {rt:.2}");
}
+
+#[test]
+fn audio_transition_curves() {
+ use crate::transitions::audio_gains;
+ for i in 0..=20 {
+ let p = i as f32 / 20.0;
+ let (a, b) = audio_gains("constant_power", p);
+ assert!(close(a * a + b * b, 1.0, 1e-5), "constant power keeps power at {p}");
+ let (a, b) = audio_gains("constant_gain", p);
+ assert!(close(a + b, 1.0, 1e-6), "constant gain keeps amplitude at {p}");
+ let (a, b) = audio_gains("exponential_fade", p);
+ assert!((0.0..=1.0).contains(&a) && (0.0..=1.0).contains(&b));
+ }
+ for k in ["constant_power", "constant_gain", "exponential_fade"] {
+ assert_eq!(audio_gains(k, 0.0), (1.0, 0.0), "{k} starts on A");
+ let (a, b) = audio_gains(k, 1.0);
+ assert!(a.abs() < 1e-6 && close(b, 1.0, 1e-6), "{k} ends on B");
+ }
+}
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 8350b5d2e..b4d853fd1 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -63,6 +63,8 @@ pub enum Dialog {
Recovery,
/// "Are you sure you want to discard your changes?" (File ▸ Revert).
RevertConfirm,
+ /// Clip ▸ Audio Gain… (G).
+ AudioGain,
}
#[derive(Default)]
diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs
index ef10d0013..1fe9084c0 100644
--- a/crates/ui-egui/src/menus.rs
+++ b/crates/ui-egui/src/menus.rs
@@ -163,6 +163,15 @@ pub fn invoke(app: &mut FilmcraftApp, ctx: &egui::Context, id: &str, params: Val
app.dialog = Some(crate::Dialog::Preferences);
return Ok(Value::Null);
}
+ // Audio Gain from the menu or G opens the dialog; with params it applies directly.
+ "clip.audioGain" if params.as_object().is_none_or(|m| m.is_empty()) => {
+ filmcraft_engine::find_command("clip.audioGain").map_or(Ok(()), |c| (c.enabled)(&app.session))?;
+ if app.ui.audio_gain.mode.is_empty() {
+ app.ui.audio_gain.mode = "adjust".into();
+ }
+ app.dialog = Some(crate::Dialog::AudioGain);
+ return Ok(json!({"dialog": "audioGain"}));
+ }
// From menus/shortcuts (no params) these ask first; agents pass params to act directly.
"file.revert" if params.as_object().is_none_or(|m| m.is_empty()) && app.session.is_dirty() => {
if app.session.path.is_none() {
diff --git a/crates/ui-egui/src/panels/dialogs.rs b/crates/ui-egui/src/panels/dialogs.rs
index 73436d25e..0f6020359 100644
--- a/crates/ui-egui/src/panels/dialogs.rs
+++ b/crates/ui-egui/src/panels/dialogs.rs
@@ -38,9 +38,96 @@ pub fn show(app: &mut FilmcraftApp, ctx: &egui::Context) {
});
});
}
+ Dialog::AudioGain => {
+ if !audio_gain(app, ctx) {
+ app.dialog = None;
+ }
+ return;
+ }
Dialog::NewSequence | Dialog::Preferences | Dialog::Recovery | Dialog::RevertConfirm => {}
}
if !open {
app.dialog = None;
}
}
+
+/// Clip ▸ Audio Gain…: Set Gain to / Adjust Gain by / Normalize Max Peak to / Normalize All Peaks to,
+/// with the selection's peak amplitude. Returns whether the dialog stays open.
+///
+/// Automation ids: `audioGain.<set|adjust|normalizeMax|normalizeAll>` (radio buttons),
+/// `audioGain.<mode>.value` (dB fields), `audioGain.peak`, `audioGain.ok`, `audioGain.cancel`.
+fn audio_gain(app: &mut FilmcraftApp, ctx: &egui::Context) -> bool {
+ let peak_id = egui::Id::new("audio-gain-peak");
+ let rev = app.session.revision;
+ let cached: Option<(u64, Option<f64>)> = ctx.data(|d| d.get_temp(peak_id));
+ let peak = match cached {
+ Some((r, p)) if r == rev => p,
+ _ => {
+ let p = app.session.execute("clip.audioPeak", serde_json::json!({})).ok().and_then(|v| v["peakDb"].as_f64());
+ ctx.data_mut(|d| d.insert_temp(peak_id, (rev, p)));
+ p
+ }
+ };
+ let mut draft = app.ui.audio_gain.clone();
+ let mut keep = true;
+ let mut apply = false;
+ let mut elems: Vec<(String, egui::Rect, String)> = Vec::new();
+ egui::Window::new("Audio Gain").collapsible(false).resizable(false).anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0]).show(ctx, |ui| {
+ ui.add_space(6.0);
+ egui::Grid::new("audio-gain").num_columns(2).spacing([12.0, 10.0]).show(ui, |ui| {
+ let rows: [(&str, &str, &mut f64); 4] = [
+ ("set", "Set Gain to:", &mut draft.set_db),
+ ("adjust", "Adjust Gain by:", &mut draft.adjust_db),
+ ("normalizeMax", "Normalize Max Peak to:", &mut draft.max_peak_db),
+ ("normalizeAll", "Normalize All Peaks to:", &mut draft.all_peaks_db),
+ ];
+ for (id, label, v) in rows {
+ let r = ui.radio(draft.mode == id, label);
+ elems.push((format!("audioGain.{id}"), r.rect, label.to_string()));
+ if r.clicked() {
+ draft.mode = id.to_string();
+ }
+ let f = ui.add_enabled(draft.mode == id, egui::DragValue::new(v).speed(0.1).range(-96.0..=96.0).suffix(" dB"));
+ elems.push((format!("audioGain.{id}.value"), f.rect, format!("{v:.1} dB")));
+ ui.end_row();
+ }
+ });
+ ui.add_space(8.0);
+ let pk_text = format!("Peak Amplitude: {}", peak.map(|p| format!("{p:.1} dB")).unwrap_or_else(|| "—".into()));
+ let pk = ui.label(&pk_text);
+ elems.push(("audioGain.peak".into(), pk.rect, pk_text));
+ ui.add_space(8.0);
+ ui.horizontal(|ui| {
+ let c = ui.button("Cancel");
+ elems.push(("audioGain.cancel".into(), c.rect, "Cancel".into()));
+ if c.clicked() {
+ keep = false;
+ }
+ let o = ui.add(egui::Button::new(egui::RichText::new("OK").color(egui::Color32::WHITE)).fill(app.tokens.accent));
+ elems.push(("audioGain.ok".into(), o.rect, "OK".into()));
+ if o.clicked() {
+ apply = true;
+ }
+ });
+ });
+ for (id, r, l) in elems {
+ app.auto.add(&id, r, &l);
+ }
+ if ctx.input(|i| i.key_pressed(egui::Key::Escape)) {
+ keep = false;
+ }
+ if apply {
+ let db = match draft.mode.as_str() {
+ "set" => draft.set_db,
+ "normalizeMax" => draft.max_peak_db,
+ "normalizeAll" => draft.all_peaks_db,
+ _ => draft.adjust_db,
+ };
+ if let Err(e) = app.session.execute("clip.audioGain", serde_json::json!({"mode": draft.mode, "db": db})) {
+ app.ui.status = e.to_string();
+ }
+ keep = false;
+ }
+ app.ui.audio_gain = draft;
+ keep
+}
diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs
index 7b0586e68..1172cdb88 100644
--- a/crates/ui-egui/src/state.rs
+++ b/crates/ui-egui/src/state.rs
@@ -283,6 +283,21 @@ pub struct UiState {
/// Audio Track Mixer: effects and sends section expanded.
#[serde(default)]
pub mixer_fx_open: bool,
+ /// Audio Gain dialog draft (mode, dB values).
+ #[serde(default)]
+ pub audio_gain: AudioGainDraft,
+}
+
+/// The Audio Gain dialog (Clip ▸ Audio Gain…, G).
+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
+#[serde(default)]
+pub struct AudioGainDraft {
+ /// "set" | "adjust" | "normalizeMax" | "normalizeAll"
+ pub mode: String,
+ pub set_db: f64,
+ pub adjust_db: f64,
+ pub max_peak_db: f64,
+ pub all_peaks_db: f64,
}
fn captions_tab() -> String {
@@ -322,6 +337,7 @@ impl Default for UiState {
caption_search: String::new(),
play_after_render: true,
mixer_fx_open: false,
+ audio_gain: AudioGainDraft::default(),
}
}
}
diff --git a/crates/ui-egui/tests/mixer_ui.rs b/crates/ui-egui/tests/mixer_ui.rs
index ed29d02f2..dac7dbdd6 100644
--- a/crates/ui-egui/tests/mixer_ui.rs
+++ b/crates/ui-egui/tests/mixer_ui.rs
@@ -254,3 +254,24 @@ fn clip_mixer_strips_follow_the_playhead() {
assert!(level < -8.0, "clip volume lowered from the demo's -8 dB: {level}");
d.snapshot("mixer-clip-mixer", Some("clipMixer."));
}
+
+#[test]
+fn audio_gain_dialog_normalizes_the_selection() {
+ let mut d = Driver::demo();
+ let seq = d.exec("sequence.inspect", json!({}));
+ let clip = seq["audio"][0]["items"][0]["clip"].as_u64().unwrap();
+ d.exec("timeline.select", json!({"clips": [clip]}));
+ let r = d.ok("ui.menu.invoke", json!({"id": "clip.audioGain"}));
+ assert_eq!(r["dialog"], "audioGain", "{r}");
+ d.frames(3);
+ let ids = d.ids("audioGain.");
+ for id in ["audioGain.set", "audioGain.adjust", "audioGain.normalizeMax", "audioGain.normalizeAll", "audioGain.ok", "audioGain.peak"] {
+ assert!(ids.iter().any(|i| i == id), "{id} missing: {ids:?}");
+ }
+ d.click("audioGain.normalizeMax");
+ d.snapshot("mixer-audio-gain-dialog", Some("audioGain."));
+ d.click("audioGain.ok");
+ let pk = d.exec("clip.audioPeak", json!({"clips": [clip]}));
+ assert!(pk["peakDb"].as_f64().unwrap().abs() < 1e-6, "normalized to 0 dB: {pk}");
+ assert!(d.ids("audioGain.").is_empty(), "dialog closed");
+}