FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust
M7.4: Essential Sound model and commands — audio types, per-type settings as clip effects, presets, loudness auto-match, ducking keyframes
Brandon Thomas6a0a3add7f83
diff --git a/Cargo.lock b/Cargo.lockindex 72dbdba55..b17228e81 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -1429,6 +1429,7 @@ dependencies = [name = "filmcraft-engine"version = "0.1.0"dependencies = [+ "filmcraft-audio-dsp","filmcraft-captions","filmcraft-codecs","filmcraft-color",diff --git a/crates/edit/src/tests.rs b/crates/edit/src/tests.rsindex b9d41d4d6..9ca16a77a 100644--- a/crates/edit/src/tests.rs+++ b/crates/edit/src/tests.rs@@ -54,6 +54,7 @@ impl Fx {gain_db: 0.0,frame_hold: None,scale_to_frame: false,+ essential: None,}}fn put(&mut self, track: TrackId, start: i64, dur: i64, src_in: i64) -> ClipId {diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.tomlindex 287c1a325..49c5ea37a 100644--- a/crates/engine/Cargo.toml+++ b/crates/engine/Cargo.toml@@ -20,6 +20,7 @@ filmcraft-project = { workspace = true }filmcraft-edit = { workspace = true }filmcraft-render = { workspace = true }filmcraft-text = { workspace = true }+filmcraft-audio-dsp = { workspace = true }filmcraft-export = { workspace = true }filmcraft-format = { workspace = true }filmcraft-interchange = { workspace = true }diff --git a/crates/engine/src/autosave.rs b/crates/engine/src/autosave.rsindex e66b7c2d6..64c154b80 100644--- a/crates/engine/src/autosave.rs+++ b/crates/engine/src/autosave.rs@@ -104,6 +104,21 @@ pub struct Preferences {pub audio: AudioPrefs,pub playback: PlaybackPrefs,pub trim: TrimPrefs,+ pub essential_sound: EssentialSoundPrefs,+}++/// Essential Sound: user presets saved from the panel (built-in presets live in+/// `filmcraft_project::essential`).+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase", default)]+pub struct EssentialSoundPrefs {+ pub user_presets: Vec<UserSoundPreset>,+}++#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]+pub struct UserSoundPreset {+ pub name: String,+ pub settings: filmcraft_project::EssentialSound,}/// Preferences ▸ Audio (the mixer-automation part) and the Track Mixer panel-menu toggle.@@ -122,6 +137,11 @@ pub struct AudioPrefs {pub minimum_time_ms: u32,/// Track Mixer ▸ "Switch to Touch after Write".pub switch_to_touch_after_write: bool,+ /// Essential Sound Loudness Auto-Match targets (integrated LUFS) per audio type.+ pub dialogue_target_lufs: f64,+ pub music_target_lufs: f64,+ pub sfx_target_lufs: f64,+ pub ambience_target_lufs: f64,}impl Default for AudioPrefs {@@ -133,15 +153,36 @@ impl Default for AudioPrefs {minimum_time_interval_thinning: false,minimum_time_ms: 20,switch_to_touch_after_write: true,+ dialogue_target_lufs: -23.0,+ music_target_lufs: -25.0,+ sfx_target_lufs: -21.0,+ ambience_target_lufs: -30.0,}}}impl AudioPrefs {+ /// Auto-Match target for an audio type.+ pub fn loudness_target(&self, t: filmcraft_project::AudioType) -> f64 {+ match t {+ filmcraft_project::AudioType::Dialogue => self.dialogue_target_lufs,+ filmcraft_project::AudioType::Music => self.music_target_lufs,+ filmcraft_project::AudioType::Sfx => self.sfx_target_lufs,+ filmcraft_project::AudioType::Ambience => self.ambience_target_lufs,+ }+ }fn clamp(&mut self) {self.automatch_time = if self.automatch_time.is_finite() { self.automatch_time.clamp(0.0, 30.0) } else { 1.0 };self.large_volume_adjustment = if self.large_volume_adjustment.is_finite() { self.large_volume_adjustment.clamp(0.0, 96.0) } else { 6.0 };self.minimum_time_ms = self.minimum_time_ms.clamp(1, 10_000);+ for (v, d) in [+ (&mut self.dialogue_target_lufs, -23.0),+ (&mut self.music_target_lufs, -25.0),+ (&mut self.sfx_target_lufs, -21.0),+ (&mut self.ambience_target_lufs, -30.0),+ ] {+ *v = if v.is_finite() { v.clamp(-60.0, 0.0) } else { d };+ }}}diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rsindex 7f3ae7e09..978ed43fa 100644--- a/crates/engine/src/commands.rs+++ b/crates/engine/src/commands.rs@@ -1849,6 +1849,7 @@ fn build() -> Vec<CommandSpec> {];v.extend(crate::captions::commands());v.extend(crate::mixer::commands());+ v.extend(crate::essential_sound::commands());v.extend(crate::graphics::commands());v.extend(crate::shortcuts::commands());// Labels as individual commands (Edit ▸ Label ▸ <name>)diff --git a/crates/engine/src/essential_sound.rs b/crates/engine/src/essential_sound.rsnew file mode 100644index 000000000..cd05fca83--- /dev/null+++ b/crates/engine/src/essential_sound.rs@@ -0,0 +1,469 @@+//! Essential Sound commands (`essentialSound.*`).+//!+//! Clips get an audio type (Dialogue / Music / SFX / Ambience) and per-type settings+//! ([`filmcraft_project::essential`]). Every change goes through one undoable edit that updates the+//! settings and reconciles the clip's essential effects, clip gain, Volume and Panner+//! ([`filmcraft_project::essential::apply`]), so what the panel does is ordinary clip data that the+//! mixer, playback and export render without special cases.+//!+//! | command | does |+//! |---|---|+//! | `essentialSound.inspect` | types, settings and essential effects of the selected audio clips; presets; targets |+//! | `essentialSound.setType` / `clearType` | assign / clear the audio type (clearing removes its effects and gain) |+//! | `essentialSound.set` | one setting by dotted key (`repair.noise.amount`), or several (`values`) |+//! | `essentialSound.applyPreset` / `savePreset` / `deletePreset` | built-in and user presets |+//! | `essentialSound.autoMatch` | measure integrated loudness (BS.1770) and set the match gain to the target |+//! | `essentialSound.generateDucking` | Volume keyframes that duck Music / Ambience under the trigger types |++use serde_json::{Value, json};++use filmcraft_audio_dsp::LoudnessMeter;+use filmcraft_project::essential::{self as es, AudioType, EssentialSound, Preset, Section};+use filmcraft_project::{ClipId, ParamValue, Project, TrackItem};+use filmcraft_render::SourceProvider;+use filmcraft_time::Tick;++use crate::autosave::UserSoundPreset;+use crate::commands::{CommandSpec, always, bad, bool_p, f64_p, has_seq, str_p, with_links};+use crate::{EngineError, Result, Session};++type Run = fn(&mut Session, &Value) -> Result<Value>;+type Enabled = fn(&Session) -> std::result::Result<(), String>;++/// The audio clips a command acts on: `clips` (or `clip`), else the selection, with linked partners.+pub fn targets(s: &Session, p: &Value) -> Vec<ClipId> {+ let sel: Vec<ClipId> = match p.get("clips").and_then(Value::as_array) {+ Some(a) => a.iter().filter_map(|v| v.as_u64().map(ClipId)).collect(),+ None => match p.get("clip").and_then(Value::as_u64) {+ Some(c) => vec![ClipId(c)],+ None => s.state.selection.clone(),+ },+ };+ let Some(seq) = s.active_sequence() else { return Vec::new() };+ let all = with_links(s, &sel);+ seq.audio_tracks.iter().flat_map(|t| t.items.iter()).filter(|i| all.contains(&i.id)).map(|i| i.id).collect()+}++fn mt_of(it: &TrackItem, t: Tick) -> Tick {+ it.source_time_at(t.clamp(it.start, (it.end() - Tick(1)).max(it.start)))+}++/// Change the settings of `clips` with `f` and reconcile their effects, as one undo step (or merged+/// into the previous step with the same `merge` key while a control is dragged).+fn update(+ s: &mut Session,+ cmd: &str,+ label: &str,+ merge: Option<String>,+ clips: &[ClipId],+ f: impl Fn(&TrackItem, &mut Option<EssentialSound>) -> std::result::Result<(), String>,+) -> Result<usize> {+ if clips.is_empty() {+ return Err(bad(cmd, "select one or more audio clips"));+ }+ let seq_id = s.state.active_sequence.ok_or(EngineError::NoSequence)?;+ let ph = s.playhead();+ let body = |p: &mut Project, _: &mut crate::EditorState| -> Result<usize> {+ let seq = p.sequence_mut(seq_id).ok_or(EngineError::NoSequence)?;+ let mut n = 0;+ for it in seq.audio_tracks.iter_mut().flat_map(|t| t.items.iter_mut()).filter(|i| clips.contains(&i.id)) {+ let old = it.essential.clone();+ let mut next = old.clone();+ f(it, &mut next).map_err(|e| bad(cmd, e))?;+ if next != old {+ it.essential = next;+ let mt = mt_of(it, ph);+ es::apply(it, old.as_ref(), mt);+ n += 1;+ }+ }+ Ok(n)+ };+ match merge {+ Some(k) => s.edit_merged(label, &k, body),+ None => s.edit(label, body),+ }+}++/// Built-in presets followed by the user's.+pub fn presets(s: &Session) -> Vec<Preset> {+ let mut v = es::builtin_presets();+ v.extend(s.prefs.essential_sound.user_presets.iter().map(|u| Preset {+ name: u.name.clone(),+ kind: u.settings.kind,+ settings: u.settings.clone(),+ builtin: false,+ }));+ v+}++fn type_p(p: &Value, cmd: &str) -> Result<Option<AudioType>> {+ match str_p(p, "type") {+ None => Ok(None),+ Some(t) => AudioType::parse(t).map(Some).ok_or_else(|| bad(cmd, format!("unknown audio type `{t}` (dialogue, music, sfx, ambience)"))),+ }+}++fn clip_json(s: &Session, it: &TrackItem, track: &str) -> Value {+ let t = s.playhead();+ let level = it.effect("volume").map(|e| e.f64_at("level", mt_of(it, t))).unwrap_or(0.0);+ json!({+ "clip": it.id.0,+ "name": it.name,+ "track": track,+ "type": it.essential.as_ref().map(|e| e.kind.label()),+ "settings": it.essential.as_ref().map(EssentialSound::to_value),+ "gainDb": it.gain_db,+ "volumeDb": level,+ "volumeAnimated": it.effect("volume").and_then(|e| e.param("level")).is_some_and(|p| p.is_animated()),+ "effects": it.effects.iter().enumerate().filter(|(_, e)| e.essential).map(|(i, e)| json!({"index": i, "effect": e.effect, "enabled": e.enabled})).collect::<Vec<_>>(),+ })+}++fn inspect(s: &mut Session, p: &Value) -> Result<Value> {+ let clips = targets(s, p);+ let mut out = Vec::new();+ let mut kinds = Vec::new();+ if let Some(seq) = s.active_sequence() {+ for (k, t) in seq.audio_tracks.iter().enumerate() {+ for it in t.items.iter().filter(|i| clips.contains(&i.id)) {+ out.push(clip_json(s, it, &format!("A{}", k + 1)));+ kinds.push(it.essential.as_ref().map(|e| e.kind));+ }+ }+ }+ kinds.dedup();+ let kind = match kinds.as_slice() {+ [Some(k)] => json!(k.label()),+ [None] | [] => Value::Null,+ _ => json!("mixed"),+ };+ let ps = presets(s);+ let by_type = |t: AudioType| ps.iter().filter(|p| p.kind == t).map(|p| json!({"name": p.name, "builtin": p.builtin})).collect::<Vec<_>>();+ Ok(json!({+ "clips": out,+ "type": kind,+ "presets": AudioType::ALL.iter().map(|t| (t.label().to_string(), json!(by_type(*t)))).collect::<serde_json::Map<_, _>>(),+ "sections": AudioType::ALL.iter().map(|t| (t.label().to_string(), json!(t.sections().iter().map(|s| s.label()).collect::<Vec<_>>()))).collect::<serde_json::Map<_, _>>(),+ "targets": AudioType::ALL.iter().map(|t| (t.label().to_string(), json!(s.prefs.audio.loudness_target(*t)))).collect::<serde_json::Map<_, _>>(),+ "eqPresets": es::EQ_PRESETS.iter().map(|p| p.name).collect::<Vec<_>>(),+ "reverbPresets": es::REVERB_PRESETS.iter().map(|p| p.name).collect::<Vec<_>>(),+ }))+}++fn set_type(s: &mut Session, p: &Value) -> Result<Value> {+ let t = type_p(p, "essentialSound.setType")?.ok_or_else(|| bad("essentialSound.setType", "need `type`"))?;+ let clips = targets(s, p);+ let n = update(s, "essentialSound.setType", &format!("Set Audio Type to {}", t.label()), None, &clips, |_, e| {+ if e.as_ref().is_none_or(|x| x.kind != t) {+ *e = Some(EssentialSound::new(t));+ }+ Ok(())+ })?;+ Ok(json!({"clips": n, "type": t.label()}))+}++fn clear_type(s: &mut Session, p: &Value) -> Result<Value> {+ let clips = targets(s, p);+ let n = update(s, "essentialSound.clearType", "Clear Audio Type", None, &clips, |_, e| {+ *e = None;+ Ok(())+ })?;+ Ok(json!({"clips": n}))+}++fn set(s: &mut Session, p: &Value) -> Result<Value> {+ let mut kv: Vec<(String, Value)> = Vec::new();+ if let Some(k) = str_p(p, "key") {+ kv.push((k.to_string(), p.get("value").cloned().ok_or_else(|| bad("essentialSound.set", "need `value`"))?));+ }+ if let Some(m) = p.get("values").and_then(Value::as_object) {+ kv.extend(m.iter().map(|(k, v)| (k.clone(), v.clone())));+ }+ if kv.is_empty() {+ return Err(bad("essentialSound.set", "need `key` + `value` or `values`"));+ }+ let clips = targets(s, p);+ if bool_p(p, "begin").unwrap_or(false) {+ s.history.merge_key = None;+ }+ let keys: Vec<&str> = kv.iter().map(|(k, _)| k.as_str()).collect();+ let merge = format!("essentialSound:{clips:?}:{}", keys.join(","));+ let n = update(s, "essentialSound.set", "Essential Sound", Some(merge), &clips, |it, e| {+ let st = e.as_mut().ok_or_else(|| format!("clip `{}` has no audio type; set one first", it.name))?;+ for (k, v) in &kv {+ st.set(k, v)?;+ }+ Ok(())+ })?;+ Ok(json!({"clips": n}))+}++fn apply_preset(s: &mut Session, p: &Value) -> Result<Value> {+ let cmd = "essentialSound.applyPreset";+ let name = str_p(p, "preset").ok_or_else(|| bad(cmd, "need `preset`"))?.to_string();+ let forced = type_p(p, cmd)?;+ let ps = presets(s);+ let clips = targets(s, p);+ let n = update(s, cmd, &format!("Apply Sound Preset {name}"), None, &clips, |it, e| {+ let kind = forced.or(e.as_ref().map(|x| x.kind)).ok_or_else(|| format!("clip `{}` has no audio type; pass `type`", it.name))?;+ let pr =+ ps.iter().rev().find(|x| x.kind == kind && x.name.eq_ignore_ascii_case(&name)).ok_or_else(|| format!("no {} preset `{name}`", kind.label()))?;+ *e = Some(es::with_preset(e.as_ref(), pr));+ Ok(())+ })?;+ Ok(json!({"clips": n, "preset": name}))+}++fn save_preset(s: &mut Session, p: &Value) -> Result<Value> {+ let cmd = "essentialSound.savePreset";+ let name = str_p(p, "name").map(str::trim).filter(|n| !n.is_empty()).ok_or_else(|| bad(cmd, "need `name`"))?.to_string();+ let clips = targets(s, p);+ let seq = s.active_sequence().ok_or(EngineError::NoSequence)?;+ let mut st =+ clips.iter().find_map(|c| seq.find_item(*c).and_then(|(_, i)| i.essential.clone())).ok_or_else(|| bad(cmd, "select a clip with an audio type"))?;+ if es::builtin_presets().iter().any(|b| b.kind == st.kind && b.name.eq_ignore_ascii_case(&name)) {+ return Err(bad(cmd, format!("`{name}` is a built-in preset name")));+ }+ st.preset = name.clone();+ st.loudness = es::Loudness { enabled: st.loudness.enabled, ..Default::default() };+ st.volume = Default::default();+ st.mute = false;+ let kind = st.kind;+ let mut prefs = s.prefs.clone();+ prefs.essential_sound.user_presets.retain(|u| !(u.settings.kind == kind && u.name.eq_ignore_ascii_case(&name)));+ prefs.essential_sound.user_presets.push(UserSoundPreset { name: name.clone(), settings: st });+ s.set_prefs(prefs).map_err(|e| EngineError::Other(format!("saving preferences: {e}")))?;+ // the clips now show the saved preset+ let _ = update(s, cmd, "Save Sound Preset", None, &clips, |_, e| {+ if let Some(x) = e.as_mut().filter(|x| x.kind == kind) {+ x.preset = name.clone();+ }+ Ok(())+ });+ Ok(json!({"name": name, "type": kind.label()}))+}++fn delete_preset(s: &mut Session, p: &Value) -> Result<Value> {+ let cmd = "essentialSound.deletePreset";+ let name = str_p(p, "name").or_else(|| str_p(p, "preset")).ok_or_else(|| bad(cmd, "need `name`"))?.to_string();+ let kind = type_p(p, cmd)?;+ let mut prefs = s.prefs.clone();+ let before = prefs.essential_sound.user_presets.len();+ prefs.essential_sound.user_presets.retain(|u| !(u.name.eq_ignore_ascii_case(&name) && kind.is_none_or(|k| k == u.settings.kind)));+ if prefs.essential_sound.user_presets.len() == before {+ return Err(bad(cmd, format!("no user preset `{name}` (built-in presets cannot be deleted)")));+ }+ s.set_prefs(prefs).map_err(|e| EngineError::Other(format!("saving preferences: {e}")))?;+ Ok(json!({"deleted": name}))+}++// ------------------------------------------------------------------------------------- loudness++/// Integrated loudness (LUFS) of a clip's own signal (clip gain + clip effects) over its whole+/// timeline range, or `None` when it is silent / has no audio.+pub fn clip_loudness(item: &TrackItem, sr: u32, sources: &dyn SourceProvider) -> Option<f64> {+ let a0 = item.start.to_units_floor(sr as i64);+ let a1 = item.end().to_units_floor(sr as i64);+ let mut meter = LoudnessMeter::new(sr as f64, 2);+ let mut pos = a0;+ while pos < a1 {+ let n = (a1 - pos).min(sr as i64) as usize;+ let [l, r] = filmcraft_render::audio::clip_signal(item, pos, n, sr, sources)?;+ meter.process(&[&l, &r]);+ pos += n as i64;+ }+ Some(meter.integrated()).filter(|v| v.is_finite())+}++fn auto_match(s: &mut Session, p: &Value) -> Result<Value> {+ let cmd = "essentialSound.autoMatch";+ let clips = targets(s, p);+ let target_p = f64_p(p, "target");+ let seq = s.active_sequence().ok_or(EngineError::NoSequence)?;+ let sr = seq.settings.sample_rate.max(1);+ let provider = s.media.provider(s.project.clone(), s.services.clone());+ // measure first (read-only), then write every match in one undo step+ let mut matches: Vec<(ClipId, f64, f64, f64)> = Vec::new(); // clip, measured (without match gain), target, new match gain+ let mut report = Vec::new();+ for it in seq.audio_tracks.iter().flat_map(|t| t.items.iter()).filter(|i| clips.contains(&i.id)) {+ let Some(st) = it.essential.as_ref() else {+ report.push(json!({"clip": it.id.0, "skipped": "no audio type"}));+ continue;+ };+ let target = target_p.unwrap_or_else(|| s.prefs.audio.loudness_target(st.kind)).clamp(-60.0, 0.0);+ let Some(l) = clip_loudness(it, sr, &provider) else {+ report.push(json!({"clip": it.id.0, "skipped": "silent"}));+ continue;+ };+ // the clip gain (including any earlier match gain) applies linearly after the effects+ let current = st.loudness_gain_db();+ let measured = l - current;+ let gain = filmcraft_audio_dsp::normalize_gain_db(measured, target);+ matches.push((it.id, measured, target, gain));+ report.push(json!({"clip": it.id.0, "measuredLufs": measured, "targetLufs": target, "gainDb": gain}));+ }+ if matches.is_empty() {+ return Err(bad(cmd, "no clips with an audio type and audible audio in the selection"));+ }+ let ids: Vec<ClipId> = matches.iter().map(|m| m.0).collect();+ update(s, cmd, "Auto-Match Loudness", None, &ids, |it, e| {+ if let (Some(st), Some(m)) = (e.as_mut(), matches.iter().find(|m| m.0 == it.id)) {+ st.loudness.enabled = true;+ st.loudness.measured_lufs = Some(m.1);+ st.loudness.target_lufs = Some(m.2);+ st.loudness.gain_db = m.3;+ }+ Ok(())+ })?;+ Ok(json!({"clips": report}))+}++// ------------------------------------------------------------------------------------- ducking++/// Analysis hop and smoothing window of the ducking detector.+const DUCK_HOP_S: f64 = 0.01;+const DUCK_WINDOW_HOPS: usize = 5;+/// Ignore trigger blips shorter than this; bridge pauses between words shorter than this.+const DUCK_MIN_ON_S: f32 = 0.1;+const DUCK_BRIDGE_S: f32 = 0.25;++/// Level envelope (dBFS, 10 ms hops, 50 ms centred window) of the summed trigger clips over+/// timeline samples `[a0, a1)`.+fn trigger_envelope(triggers: &[&TrackItem], a0: i64, a1: i64, sr: u32, sources: &dyn SourceProvider) -> Vec<f32> {+ let hop = ((sr as f64 * DUCK_HOP_S).round() as usize).max(1);+ let hops = ((a1 - a0).max(0) as usize).div_ceil(hop);+ let mut power = vec![0.0f64; hops];+ let chunk = hop * 100;+ let mut pos = a0;+ while pos < a1 {+ let n = ((a1 - pos) as usize).min(chunk);+ let mut sum = [vec![0.0f32; n], vec![0.0f32; n]];+ for t in triggers {+ if let Some(b) = filmcraft_render::audio::clip_signal(t, pos, n, sr, sources) {+ for c in 0..2 {+ for (d, x) in sum[c].iter_mut().zip(&b[c]) {+ *d += x;+ }+ }+ }+ }+ let base = ((pos - a0) as usize) / hop;+ for (k, i) in (0..n).step_by(hop).enumerate() {+ let e = (i + hop).min(n);+ let pw: f64 = (i..e).map(|j| 0.5 * ((sum[0][j] as f64).powi(2) + (sum[1][j] as f64).powi(2))).sum::<f64>() / (e - i) as f64;+ if let Some(p) = power.get_mut(base + k) {+ *p = pw;+ }+ }+ pos += n as i64;+ }+ let h = DUCK_WINDOW_HOPS / 2;+ (0..hops)+ .map(|k| {+ let (lo, hi) = (k.saturating_sub(h), (k + h + 1).min(hops));+ let m = power[lo..hi].iter().sum::<f64>() / (hi - lo) as f64;+ (10.0 * m.max(1e-12).log10()).max(-120.0) as f32+ })+ .collect()+}++fn generate_ducking(s: &mut Session, p: &Value) -> Result<Value> {+ let cmd = "essentialSound.generateDucking";+ let clips = targets(s, p);+ let seq = s.active_sequence().ok_or(EngineError::NoSequence)?;+ let sr = seq.settings.sample_rate.max(1);+ let provider = s.media.provider(s.project.clone(), s.services.clone());+ let all: Vec<&TrackItem> = seq.audio_tracks.iter().flat_map(|t| t.items.iter()).collect();+ let mut plans: Vec<(ClipId, Vec<(Tick, f64)>, f64)> = Vec::new();+ let mut report = Vec::new();+ for it in all.iter().copied().filter(|i| clips.contains(&i.id)) {+ let Some(st) = it.essential.as_ref().filter(|e| e.kind.has(Section::Ducking)) else { continue };+ let d = &st.ducking;+ let triggers: Vec<&TrackItem> = all+ .iter()+ .copied()+ .filter(|o| o.id != it.id && o.enabled && o.range().overlaps(&it.range()))+ .filter(|o| match o.essential.as_ref() {+ Some(e) => !e.mute && d.against.contains(&e.kind),+ None => d.against_untyped,+ })+ .collect();+ let (a0, a1) = (it.start.to_units_floor(sr as i64), it.end().to_units_floor(sr as i64));+ let env = trigger_envelope(&triggers, a0, a1, sr, &provider);+ let thr = filmcraft_audio_dsp::ducking::sensitivity_threshold_db(d.sensitivity as f32);+ let regions = filmcraft_audio_dsp::ducking::activity(&env, DUCK_HOP_S as f32, thr, DUCK_MIN_ON_S, DUCK_BRIDGE_S);+ let start_s = a0 as f64 / sr as f64;+ let end_s = a1 as f64 / sr as f64;+ let abs: Vec<(f64, f64)> = regions.iter().map(|(x, y)| (start_s + x, start_s + y)).collect();+ let lvl = it.effect("volume").and_then(|e| e.param("level"));+ let base = match lvl {+ Some(p) if p.is_animated() => p.keyframes.iter().filter_map(|k| k.value.as_f64()).fold(f64::NEG_INFINITY, f64::max),+ Some(p) => p.value.as_f64().unwrap_or(0.0),+ None => 0.0,+ };+ let kfs = filmcraft_audio_dsp::ducking::duck_keyframes(&abs, start_s, end_s, base, d.reduce_db, d.fade_s);+ let ticks: Vec<(Tick, f64)> = kfs.iter().map(|(t, v)| (Tick::from_seconds_f64(*t).clamp(it.start, it.end()), *v)).collect();+ report.push(json!({+ "clip": it.id.0,+ "triggers": triggers.iter().map(|t| t.id.0).collect::<Vec<_>>(),+ "regions": abs.iter().map(|(a, b)| json!([a, b])).collect::<Vec<_>>(),+ "keyframes": ticks.iter().map(|(t, v)| json!({"time": t.0, "seconds": t.seconds(), "levelDb": v})).collect::<Vec<_>>(),+ }));+ plans.push((it.id, ticks, base));+ }+ if plans.is_empty() {+ return Err(bad(cmd, "select Music or Ambience clips (ducking applies to those types)"));+ }+ let seq_id = s.state.active_sequence.ok_or(EngineError::NoSequence)?;+ s.edit("Generate Ducking Keyframes", |pr, _| {+ let seq = pr.sequence_mut(seq_id).ok_or(EngineError::NoSequence)?;+ for (c, ticks, base) in &plans {+ let Some((_, it)) = seq.find_item_mut(*c) else { continue };+ if let Some(e) = it.essential.as_mut() {+ e.ducking.enabled = true;+ }+ let at: Vec<(Tick, f64)> = ticks.iter().map(|(t, v)| (mt_of(it, *t), *v)).collect();+ let Some(par) = it.effect_mut("volume").and_then(|e| e.param_mut("level")) else { continue };+ par.keyframes.clear();+ par.value = ParamValue::Float(*base);+ for (mt, v) in at {+ par.put_keyframe(mt, ParamValue::Float(v));+ }+ }+ Ok(())+ })?;+ Ok(json!({"clips": report}))+}++fn spec(id: &'static str, label: &'static str, params: &'static str, enabled: Enabled, run: Run, journal: bool) -> CommandSpec {+ CommandSpec { id, label, menu: &[], shortcut: None, params, enabled, run, journal }+}++pub fn commands() -> Vec<CommandSpec> {+ vec![+ spec("essentialSound.inspect", "Inspect Essential Sound", r#"{"clips":[id]?}"#, always, inspect, false),+ spec("essentialSound.setType", "Set Audio Type", r#"{"clips":[id]?,"type":"dialogue|music|sfx|ambience"}"#, has_seq, set_type, true),+ spec("essentialSound.clearType", "Clear Audio Type", r#"{"clips":[id]?}"#, has_seq, clear_type, true),+ spec(+ "essentialSound.set",+ "Essential Sound Setting",+ r#"{"clips":[id]?,"key":"repair.noise.on|repair.noise.amount|repair.humHz|clarity.eqPreset|creative.reverbPreset|ducking.reduceDb|volume.levelDb|mute|…","value":any,"values":{key:value}?,"begin":bool?}"#,+ has_seq,+ set,+ true,+ ),+ spec(+ "essentialSound.applyPreset",+ "Apply Sound Preset",+ r#"{"clips":[id]?,"preset":str,"type":"dialogue|music|sfx|ambience"?}"#,+ has_seq,+ apply_preset,+ true,+ ),+ spec("essentialSound.savePreset", "Save Sound Preset", r#"{"clips":[id]?,"name":str}"#, has_seq, save_preset, true),+ spec("essentialSound.deletePreset", "Delete Sound Preset", r#"{"name":str,"type":"dialogue|music|sfx|ambience"?}"#, always, delete_preset, true),+ spec("essentialSound.autoMatch", "Auto-Match Loudness", r#"{"clips":[id]?,"target":lufs?}"#, has_seq, auto_match, true),+ spec("essentialSound.generateDucking", "Generate Ducking Keyframes", r#"{"clips":[id]?}"#, has_seq, generate_ducking, true),+ ]+}diff --git a/crates/engine/src/essential_sound_tests.rs b/crates/engine/src/essential_sound_tests.rsnew file mode 100644index 000000000..2474972ad--- /dev/null+++ b/crates/engine/src/essential_sound_tests.rs@@ -0,0 +1,467 @@+//! Essential Sound: types, settings → clip effects, presets, loudness auto-match, ducking, repair+//! metrics through the render path, render-vs-export identity.++use std::sync::Arc;++use filmcraft_audio_dsp::LoudnessMeter;+use filmcraft_project::{AudioType, ClipId, TrackItem};+use filmcraft_time::Tick;+use serde_json::{Value, json};++use super::*;++const SR: u32 = 48_000;++/// Deterministic xorshift noise in [-1, 1).+struct Rng(u64);+impl Rng {+ fn next(&mut self) -> f32 {+ self.0 ^= self.0 << 13;+ self.0 ^= self.0 >> 7;+ self.0 ^= self.0 << 17;+ ((self.0 >> 40) as f32 / (1u64 << 24) as f32) * 2.0 - 1.0+ }+}++/// A speech-like signal: a voiced source (gliding f0 ≈ 110–160 Hz, harmonics falling 6 dB/oct up+/// to 4 kHz) under a syllable envelope (~4.5 syllables/s), only where `active(t)`.+fn speech(secs: f64, amp: f32, active: impl Fn(f64) -> bool) -> Vec<f32> {+ let n = (secs * SR as f64) as usize;+ let mut phase = 0.0f64;+ (0..n)+ .map(|i| {+ let t = i as f64 / SR as f64;+ if !active(t) {+ return 0.0;+ }+ let f0 = 135.0 + 25.0 * (2.0 * std::f64::consts::PI * 0.7 * t).sin();+ phase += f0 / SR as f64;+ let mut v = 0.0;+ let mut k = 1;+ while k as f64 * f0 < 4000.0 {+ v += (2.0 * std::f64::consts::PI * phase * k as f64).sin() / k as f64;+ k += 1;+ }+ let syl = 0.6 - 0.4 * (2.0 * std::f64::consts::PI * 4.5 * t).cos();+ (v * syl * 0.5) as f32 * amp+ })+ .collect()+}++fn tone(secs: f64, f: f64, amp: f32) -> Vec<f32> {+ (0..(secs * SR as f64) as usize).map(|i| (amp as f64 * (2.0 * std::f64::consts::PI * f * i as f64 / SR as f64).sin()) as f32).collect()+}++fn add(a: &[f32], b: &[f32]) -> Vec<f32> {+ a.iter().zip(b).map(|(x, y)| x + y).collect()+}++/// A session with one sequence and each signal on its own audio track (A1, A2…) at `start` seconds.+fn session_with(tracks: &[(Vec<f32>, f64)]) -> (Session, Vec<ClipId>) {+ let mut s = Session::default();+ s.execute("file.newSequence", json!({"name": "es", "audio": tracks.len().max(2), "video": 1})).unwrap();+ let mut clips = Vec::new();+ for (k, (x, start)) in tracks.iter().enumerate() {+ let inter: Vec<f32> = x.iter().flat_map(|v| [*v, *v]).collect();+ let bytes: Arc<[u8]> = crate::previews::write_wav_f32(&inter, SR).into();+ let item = crate::commands::import_bytes(&mut s, &format!("/sig{k}.wav"), bytes, None).unwrap();+ let r = s.execute("timeline.place", json!({"item": item.0, "audioTrack": format!("A{}", k + 1), "seconds": start})).unwrap();+ clips.push(ClipId(r["clips"][0].as_u64().unwrap()));+ }+ s.execute("edit.deselectAll", json!({})).unwrap();+ (s, clips)+}++fn item(s: &Session, c: ClipId) -> TrackItem {+ s.active_sequence().unwrap().find_item(c).unwrap().1.clone()+}++fn es_ids(s: &Session, c: ClipId) -> Vec<String> {+ item(s, c).effects.iter().filter(|e| e.essential).map(|e| e.effect.clone()).collect()+}++/// The full sequence mix for `[a, a + n)` samples, in requests of `chunk` samples.+fn mix(s: &Session, a: i64, n: usize, chunk: usize) -> [Vec<f32>; 2] {+ let provider = s.media.provider(s.project.clone(), s.services.clone());+ let seq = s.active_sequence().unwrap();+ let mut out = [Vec::new(), Vec::new()];+ let mut pos = a;+ while pos < a + n as i64 {+ let m = chunk.min((a + n as i64 - pos) as usize);+ let b = filmcraft_render::audio::mix_sequence(&s.project, seq, pos, m, &provider);+ out[0].extend_from_slice(&b.channels[0]);+ out[1].extend_from_slice(&b.channels[1]);+ pos += m as i64;+ }+ out+}++fn lufs(x: &[Vec<f32>; 2]) -> f64 {+ let mut m = LoudnessMeter::new(SR as f64, 2);+ m.process(&[&x[0], &x[1]]);+ m.integrated()+}++/// The clip's own processed signal (clip gain + effects) over its whole range.+fn clip_out(s: &Session, c: ClipId) -> [Vec<f32>; 2] {+ let it = item(s, c);+ let provider = s.media.provider(s.project.clone(), s.services.clone());+ let a0 = it.start.to_units_floor(SR as i64);+ let n = (it.end().to_units_floor(SR as i64) - a0) as usize;+ let mut out = [Vec::new(), Vec::new()];+ let mut pos = a0;+ while pos < a0 + n as i64 {+ let m = 4800.min((a0 + n as i64 - pos) as usize);+ let b = filmcraft_render::audio::clip_signal(&it, pos, m, SR, &provider).unwrap();+ out[0].extend_from_slice(&b[0]);+ out[1].extend_from_slice(&b[1]);+ pos += m as i64;+ }+ out+}++fn db(x: f64) -> f64 {+ 20.0 * x.max(1e-12).log10()+}++fn rms(x: &[f32]) -> f64 {+ (x.iter().map(|v| (*v as f64).powi(2)).sum::<f64>() / x.len().max(1) as f64).sqrt()+}++/// Amplitude of the `f` component (single-bin DFT).+fn tone_amp(x: &[f32], f: f64) -> f64 {+ let (mut re, mut im) = (0.0f64, 0.0f64);+ for (i, v) in x.iter().enumerate() {+ let w = 2.0 * std::f64::consts::PI * f * i as f64 / SR as f64;+ re += *v as f64 * w.cos();+ im += *v as f64 * w.sin();+ }+ 2.0 * (re * re + im * im).sqrt() / x.len() as f64+}++fn secs(a: f64, b: f64) -> std::ops::Range<usize> {+ (a * SR as f64) as usize..(b * SR as f64) as usize+}++#[test]+fn commands_are_registered() {+ for id in [+ "essentialSound.inspect",+ "essentialSound.setType",+ "essentialSound.clearType",+ "essentialSound.set",+ "essentialSound.applyPreset",+ "essentialSound.savePreset",+ "essentialSound.deletePreset",+ "essentialSound.autoMatch",+ "essentialSound.generateDucking",+ ] {+ let c = commands::find(id).unwrap_or_else(|| panic!("{id} missing"));+ assert!(!c.label.is_empty() && !c.params.is_empty());+ }+ assert!(!Session::default().is_enabled("essentialSound.setType"), "needs a sequence");+}++#[test]+fn type_settings_effects_undo_redo_and_clear() {+ let (mut s, c) = session_with(&[(speech(2.0, 0.3, |_| true), 0.0)]);+ let c = c[0];+ assert!(s.execute("essentialSound.set", json!({"clips": [c.0], "key": "repair.noise.on", "value": true})).is_err(), "untyped");+ s.execute("timeline.select", json!({"clips": [c.0]})).unwrap();+ s.execute("essentialSound.setType", json!({"type": "dialogue"})).unwrap();+ assert_eq!(item(&s, c).essential.as_ref().unwrap().kind, AudioType::Dialogue);+ s.execute(+ "essentialSound.set",+ json!({"values": {"repair.noise.on": true, "repair.noise.amount": 7.0, "clarity.eq.on": true, "clarity.eqPreset": "Telephone"}}),+ )+ .unwrap();+ assert_eq!(es_ids(&s, c), ["denoise", "parametric_eq"]);+ let it = item(&s, c);+ assert_eq!(it.effect("denoise").unwrap().f64_at("amount", Tick::ZERO), 70.0);+ assert_eq!(it.effect("parametric_eq").unwrap().f64_at("low_gain", Tick::ZERO), -9.0, "Telephone at amount 5 of 10");+ // a drag (same key, no begin) is one undo step+ for v in [6.0, 5.0, 4.0] {+ s.execute("essentialSound.set", json!({"key": "repair.noise.amount", "value": v})).unwrap();+ }+ assert_eq!(item(&s, c).effect("denoise").unwrap().f64_at("amount", Tick::ZERO), 40.0);+ s.execute("edit.undo", json!({})).unwrap();+ assert_eq!(item(&s, c).effect("denoise").unwrap().f64_at("amount", Tick::ZERO), 70.0);+ s.execute("edit.redo", json!({})).unwrap();+ // inspect+ let v = s.execute("essentialSound.inspect", json!({})).unwrap();+ assert_eq!(v["type"], "Dialogue");+ assert_eq!(v["clips"][0]["settings"]["repair"]["noise"]["amount"], 4.0);+ assert_eq!(v["clips"][0]["effects"].as_array().unwrap().len(), 2);+ assert!(v["presets"]["Dialogue"].as_array().unwrap().len() > 3);+ assert_eq!(v["targets"]["Dialogue"], -23.0);+ // type change resets, clear removes everything+ s.execute("essentialSound.setType", json!({"type": "music"})).unwrap();+ assert!(es_ids(&s, c).is_empty());+ s.execute("essentialSound.clearType", json!({})).unwrap();+ assert!(item(&s, c).essential.is_none());+ s.execute("edit.undo", json!({})).unwrap();+ s.execute("edit.undo", json!({})).unwrap();+ assert_eq!(es_ids(&s, c), ["denoise", "parametric_eq"]);+ // bad input+ assert!(s.execute("essentialSound.set", json!({"key": "repair.nope", "value": 1})).is_err());+ assert!(s.execute("essentialSound.setType", json!({"type": "podcast"})).is_err());+}++#[test]+fn presets_apply_save_and_delete() {+ let (mut s, c) = session_with(&[(speech(2.0, 0.3, |_| true), 0.0)]);+ let c = c[0];+ s.execute("essentialSound.applyPreset", json!({"clips": [c.0], "type": "dialogue", "preset": "Podcast Voice"})).unwrap();+ assert_eq!(es_ids(&s, c), ["highpass", "deesser", "dynamics", "parametric_eq", "speech_enhance"]);+ assert_eq!(item(&s, c).essential.unwrap().preset, "Podcast Voice");+ s.execute("essentialSound.set", json!({"clips": [c.0], "key": "creative.reverb.on", "value": true})).unwrap();+ assert!(item(&s, c).essential.unwrap().preset.is_empty());+ s.execute("essentialSound.savePreset", json!({"clips": [c.0], "name": "My Voice"})).unwrap();+ assert_eq!(item(&s, c).essential.unwrap().preset, "My Voice");+ assert!(s.execute("essentialSound.savePreset", json!({"clips": [c.0], "name": "(Default)"})).is_err());+ s.execute("essentialSound.applyPreset", json!({"clips": [c.0], "preset": "(Default)"})).unwrap();+ assert!(es_ids(&s, c).is_empty());+ s.execute("essentialSound.applyPreset", json!({"clips": [c.0], "preset": "My Voice"})).unwrap();+ assert!(es_ids(&s, c).contains(&"studio_reverb".to_string()));+ let v = s.execute("essentialSound.inspect", json!({"clips": [c.0]})).unwrap();+ assert!(v["presets"]["Dialogue"].as_array().unwrap().iter().any(|p| p["name"] == "My Voice" && p["builtin"] == false));+ s.execute("essentialSound.deletePreset", json!({"name": "My Voice"})).unwrap();+ assert!(s.execute("essentialSound.deletePreset", json!({"name": "Podcast Voice"})).is_err());+ assert!(s.execute("essentialSound.applyPreset", json!({"clips": [c.0], "preset": "My Voice"})).is_err());+}++#[test]+fn auto_match_hits_the_target_loudness() {+ // quiet and loud speech, one with a repair/clarity chain, plus a preference target+ let quiet = speech(12.0, 0.05, |t| (t % 3.0) < 2.2);+ let loud = speech(12.0, 0.9, |t| (t % 2.0) < 1.5);+ for (sig, chain, target) in [(quiet.clone(), false, None), (loud, false, None), (quiet, true, Some(-16.0))] {+ let (mut s, c) = session_with(&[(sig, 0.0)]);+ let c = c[0];+ s.execute("essentialSound.setType", json!({"clips": [c.0], "type": "dialogue"})).unwrap();+ if chain {+ s.execute(+ "essentialSound.set",+ json!({"clips": [c.0], "values": {"repair.rumble.on": true, "repair.noise.on": true, "clarity.dynamics.on": true, "clarity.eq.on": true}}),+ )+ .unwrap();+ }+ if let Some(t) = target {+ s.execute("prefs.set", json!({"key": "audio.dialogueTargetLufs", "value": t})).unwrap();+ }+ let want = target.unwrap_or(-23.0);+ let r = s.execute("essentialSound.autoMatch", json!({"clips": [c.0]})).unwrap();+ let got = lufs(&mix(&s, 0, 12 * SR as usize, 48_000));+ println!("auto-match: measured {:.2} LUFS → mix {got:.3} LUFS (target {want}), chain {chain}", r["clips"][0]["measuredLufs"].as_f64().unwrap());+ assert!((got - want).abs() <= 0.5, "mix {got} LUFS, target {want}");+ let st = item(&s, c).essential.unwrap();+ assert_eq!(st.loudness.target_lufs, Some(want));+ assert!((item(&s, c).gain_db - st.loudness.gain_db).abs() < 1e-9, "match gain is clip gain");+ // matching again is stable; switching Loudness off removes the gain+ s.execute("essentialSound.autoMatch", json!({"clips": [c.0]})).unwrap();+ assert!((lufs(&mix(&s, 0, 12 * SR as usize, 48_000)) - want).abs() <= 0.5);+ s.execute("essentialSound.set", json!({"clips": [c.0], "key": "loudness.enabled", "value": false})).unwrap();+ assert!(item(&s, c).gain_db.abs() < 1e-9);+ }+}++#[test]+fn ducking_generates_volume_keyframes_under_dialogue() {+ // dialogue in [2, 4] and [6, 7.5] s; music for 10 s+ let dlg = speech(10.0, 0.4, |t| (2.0..4.0).contains(&t) || (6.0..7.5).contains(&t));+ let music = add(&tone(10.0, 220.0, 0.2), &tone(10.0, 330.0, 0.1));+ let (mut s, c) = session_with(&[(dlg, 0.0), (music, 0.0)]);+ s.execute("essentialSound.setType", json!({"clips": [c[0].0], "type": "dialogue"})).unwrap();+ s.execute("essentialSound.setType", json!({"clips": [c[1].0], "type": "music"})).unwrap();+ s.execute("essentialSound.set", json!({"clips": [c[1].0], "values": {"ducking.enabled": true, "ducking.reduceDb": -15.0, "ducking.fadeS": 0.8}})).unwrap();+ let r = s.execute("essentialSound.generateDucking", json!({"clips": [c[1].0]})).unwrap();+ let kf = r["clips"][0]["keyframes"].as_array().unwrap();+ let got: Vec<(f64, f64)> = kf.iter().map(|k| (k["seconds"].as_f64().unwrap(), k["levelDb"].as_f64().unwrap())).collect();+ println!("ducking keyframes: {got:?}");+ let want = [(1.2, 0.0), (2.0, -15.0), (4.0, -15.0), (4.8, 0.0), (5.2, 0.0), (6.0, -15.0), (7.5, -15.0), (8.3, 0.0)];+ assert_eq!(got.len(), want.len(), "{got:?}");+ for ((t, v), (wt, wv)) in got.iter().zip(want) {+ assert!((t - wt).abs() <= 0.06, "keyframe at {t} s, expected {wt} s");+ assert!((v - wv).abs() < 1e-9);+ }+ // the keyframes are on the music clip's Volume level, and the mix follows them+ let it = item(&s, c[1]);+ let lvl = it.effect("volume").unwrap().param("level").unwrap();+ assert_eq!(lvl.keyframes.len(), 8);+ assert_eq!(lvl.f64_at(it.source_time_at(Tick::from_seconds_f64(3.0))), -15.0);+ assert_eq!(lvl.f64_at(it.source_time_at(Tick::from_seconds_f64(5.0))), 0.0);+ // listen to the music alone+ s.execute("timeline.select", json!({"clips": [c[0].0]})).unwrap();+ s.execute("clip.enable", json!({"clips": [c[0].0]})).unwrap();+ let m = mix(&s, 0, 10 * SR as usize, 48_000);+ let during = tone_amp(&m[0][secs(2.5, 3.5)], 220.0);+ let between = tone_amp(&m[0][secs(0.2, 1.0)], 220.0);+ println!("music 220 Hz: {:.2} dB ducked vs open", db(during / between));+ assert!((db(during / between) + 15.0).abs() < 0.3);+ // regenerate after changing the depth: replaces the keyframes, no stacking+ s.execute("clip.enable", json!({"clips": [c[0].0]})).unwrap();+ s.execute("essentialSound.set", json!({"clips": [c[1].0], "key": "ducking.reduceDb", "value": -6.0})).unwrap();+ s.execute("essentialSound.generateDucking", json!({"clips": [c[1].0]})).unwrap();+ let lvl = item(&s, c[1]).effects.iter().find(|e| e.effect == "volume").unwrap().params["level"].clone();+ assert_eq!(lvl.keyframes.len(), 8);+ assert!(lvl.keyframes.iter().all(|k| matches!(k.value.as_f64(), Some(v) if v == 0.0 || v == -6.0)));+ // undo restores the previous keyframes+ s.execute("edit.undo", json!({})).unwrap();+ let lvl = item(&s, c[1]).effects.iter().find(|e| e.effect == "volume").unwrap().params["level"].clone();+ assert!(lvl.keyframes.iter().any(|k| k.value.as_f64() == Some(-15.0)));+ // nothing to duck against → no keyframes+ assert!(s.execute("essentialSound.generateDucking", json!({"clips": [c[0].0]})).is_err(), "dialogue does not duck");+}++/// Run `sig` through one Dialogue repair setting and return (input, output) over 1…len−0.5 s.+fn repair(sig: Vec<f32>, values: Value) -> (Vec<f32>, Vec<f32>) {+ let (mut s, c) = session_with(&[(sig.clone(), 0.0)]);+ let c = c[0];+ s.execute("essentialSound.setType", json!({"clips": [c.0], "type": "dialogue"})).unwrap();+ s.execute("essentialSound.set", json!({"clips": [c.0], "values": values})).unwrap();+ let out = clip_out(&s, c);+ (sig, out[0].clone())+}++#[test]+fn repair_stages_improve_their_metrics() {+ let n_s = 6.0;+ let voice = speech(n_s, 0.3, |t| (t % 1.0) < 0.6);+ // DeHum: 60 Hz hum + harmonics+ let hum = add(&add(&tone(n_s, 60.0, 0.05), &tone(n_s, 180.0, 0.03)), &voice);+ let (x, y) = repair(hum, json!({"repair.dehum.on": true, "repair.dehum.amount": 5.0, "repair.humHz": 60}));+ let r = secs(2.0, 5.5);+ let (h0, h1) = (tone_amp(&x[r.clone()], 60.0), tone_amp(&y[r.clone()], 60.0));+ println!("DeHum: 60 Hz {:.1} dB", db(h1 / h0));+ assert!(db(h1 / h0) < -20.0);+ // Reduce Rumble: 25 Hz rumble+ let rum = add(&tone(n_s, 25.0, 0.1), &voice);+ let (x, y) = repair(rum, json!({"repair.rumble.on": true, "repair.rumble.amount": 5.0}));+ let (r0, r1) = (tone_amp(&x[r.clone()], 25.0), tone_amp(&y[r.clone()], 25.0));+ println!("Reduce Rumble: 25 Hz {:.1} dB", db(r1 / r0));+ assert!(db(r1 / r0) < -15.0);+ // Reduce Noise: white noise floor, measured in the pauses (latency-aligned by the render path)+ let mut g = Rng(0x1234_5678);+ let noise: Vec<f32> = (0..voice.len()).map(|_| g.next() * 0.01).collect();+ let (x, y) = repair(add(&voice, &noise), json!({"repair.noise.on": true, "repair.noise.amount": 6.0}));+ let pause = secs(4.7, 4.95);+ let nr = db(rms(&y[pause.clone()]) / rms(&x[pause.clone()]));+ let speech_change = db(rms(&y[secs(4.1, 4.5)]) / rms(&x[secs(4.1, 4.5)]));+ println!("Reduce Noise: floor {nr:.1} dB, speech {speech_change:.2} dB");+ assert!(nr < -6.0);+ assert!(speech_change.abs() < 2.0);+}++#[test]+fn deess_and_dereverb_improve_their_metrics() {+ let n_s = 6.0;+ let voice = speech(n_s, 0.3, |t| (t % 1.0) < 0.6);+ // sibilants: 5–10 kHz noise bursts (2nd-difference of white noise ≈ high-passed) at the+ // start of every syllable group+ let mut g = Rng(99);+ let mut prev = (0.0f32, 0.0f32);+ let sib: Vec<f32> = (0..voice.len())+ .map(|i| {+ let w = g.next();+ let hp = w - 2.0 * prev.0 + prev.1;+ prev = (w, prev.0);+ let t = i as f64 / SR as f64;+ if (t % 1.0) < 0.12 { hp * 0.12 } else { 0.0 }+ })+ .collect();+ let (x, y) = repair(add(&voice, &sib), json!({"repair.deess.on": true, "repair.deess.amount": 8.0}));+ let hi = |v: &[f32]| {+ // energy above ~5 kHz: first difference twice (a crude high-pass), RMS+ let d: Vec<f32> = v.windows(3).map(|w| w[2] - 2.0 * w[1] + w[0]).collect();+ rms(&d)+ };+ let burst = secs(4.0, 4.1);+ let red = db(hi(&y[burst.clone()]) / hi(&x[burst.clone()]));+ let body = db(tone_amp(&y[secs(4.2, 4.55)], 135.0).max(1e-9) / tone_amp(&x[secs(4.2, 4.55)], 135.0).max(1e-9));+ println!("DeEss: sibilance {red:.1} dB, voice body {body:.2} dB");+ assert!(red < -4.0, "sibilance only {red} dB");+ // Reduce Reverb: dry bursts convolved with an exponentially decaying noise tail (RT60 0.8 s)+ let dry = speech(n_s, 0.3, |t| (t % 0.5) < 0.1);+ let mut g = Rng(7);+ let ir_len = (0.8 * SR as f64) as usize;+ let ir: Vec<f32> = (0..ir_len).map(|i| if i == 0 { 1.0 } else { g.next() * 0.08 * (-6.9 * i as f64 / ir_len as f64).exp() as f32 }).collect();+ // sparse convolution (decimated IR taps are enough for a diffuse tail)+ let mut wet = dry.clone();+ for (k, h) in ir.iter().enumerate().skip(1).step_by(7) {+ for i in k..dry.len() {+ wet[i] += dry[i - k] * h * 7.0f32.sqrt();+ }+ }+ let (x, y) = repair(wet, json!({"repair.reverb.on": true, "repair.reverb.amount": 10.0}));+ let ratio = |v: &[f32]| {+ // tail energy (gaps 0.2–0.45 s after each burst) relative to burst energy, over 3…5.5 s+ let (mut b, mut t) = (0.0, 0.0);+ for k in 6..11 {+ let s0 = k as f64 * 0.5;+ b += rms(&v[secs(s0 + 0.01, s0 + 0.09)]).powi(2);+ t += rms(&v[secs(s0 + 0.2, s0 + 0.45)]).powi(2);+ }+ 10.0 * (t / b).log10()+ };+ let (rx, ry) = (ratio(&x), ratio(&y));+ println!("Reduce Reverb: tail/burst {rx:.1} dB → {ry:.1} dB");+ assert!(ry < rx - 3.0);+}++#[test]+fn rendered_mix_is_identical_however_requests_are_cut_and_matches_export() {+ let mut g = Rng(42);+ let voice: Vec<f32> = speech(4.0, 0.3, |t| (t % 1.0) < 0.6).iter().map(|v| v + g.next() * 0.005).collect();+ let (mut s, c) = session_with(&[(voice, 0.5)]);+ s.execute("essentialSound.applyPreset", json!({"clips": [c[0].0], "type": "dialogue", "preset": "Podcast Voice"})).unwrap();+ s.execute(+ "essentialSound.set",+ json!({"clips": [c[0].0], "values": {"repair.noise.on": true, "repair.reverb.on": true, "repair.dehum.on": true, "creative.reverb.on": true}}),+ )+ .unwrap();+ s.execute("essentialSound.autoMatch", json!({"clips": [c[0].0]})).unwrap();+ let n = 5 * SR as usize;+ let whole = mix(&s, 0, n, n);+ for chunk in [512usize, 1000, 4096 + 7] {+ let cut = mix(&s, 0, n, chunk);+ let d = whole[0].iter().chain(&whole[1]).zip(cut[0].iter().chain(&cut[1])).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max);+ assert!(d <= 1e-6, "chunk {chunk}: max diff {d}");+ }+ assert!(rms(&whole[0]) > 0.01);+ // export (WAV, 16-bit) equals the mix+ let dir = std::env::temp_dir().join(format!("fc-es-{}", std::process::id()));+ std::fs::create_dir_all(&dir).unwrap();+ let path = dir.join("es.wav");+ s.execute("file.exportMedia", json!({"path": path.to_string_lossy(), "format": "wav", "wait": true})).unwrap();+ let bytes: Arc<[u8]> = std::fs::read(&path).unwrap().into();+ let src = filmcraft_media::open_bytes("es.wav", bytes, &[]).unwrap();+ let back = src.audio(0, n, SR).unwrap();+ let d = (0..n).map(|i| (back.channels[0][i] - whole[0][i]).abs().max((back.channels[1][i] - whole[1][i]).abs())).fold(0.0f32, f32::max);+ println!("export vs render: max diff {d:e}");+ assert!(d <= 2.0 / 32768.0, "export differs from render by {d}");+ let _ = std::fs::remove_dir_all(&dir);+}++/// `cargo test --release -p filmcraft-engine essential_sound_tests::perf -- --ignored --nocapture`+#[test]+#[ignore]+fn perf_full_dialogue_chain_realtime_factor() {+ let secs_len = 60.0;+ let mut g = Rng(5);+ let voice: Vec<f32> = speech(secs_len, 0.3, |t| (t % 1.0) < 0.6).iter().map(|v| v + g.next() * 0.005).collect();+ let (mut s, c) = session_with(&[(voice, 0.0)]);+ s.execute("essentialSound.setType", json!({"clips": [c[0].0], "type": "dialogue"})).unwrap();+ s.execute(+ "essentialSound.set",+ json!({"clips": [c[0].0], "values": {+ "repair.noise.on": true, "repair.rumble.on": true, "repair.dehum.on": true, "repair.deess.on": true, "repair.reverb.on": true,+ "clarity.dynamics.on": true, "clarity.eq.on": true, "clarity.enhance.on": true, "creative.reverb.on": true}}),+ )+ .unwrap();+ assert_eq!(es_ids(&s, c[0]).len(), 9);+ let t0 = std::time::Instant::now();+ let out = clip_out(&s, c[0]);+ let el = t0.elapsed().as_secs_f64();+ assert!(rms(&out[0]) > 0.0);+ println!("full Dialogue chain (9 effects), 60 s stereo 48 kHz: {el:.2} s → {:.1}× realtime", secs_len / el);+}diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rsindex e9a9f2788..54ae949cb 100644--- a/crates/engine/src/lib.rs+++ b/crates/engine/src/lib.rs@@ -12,6 +12,7 @@ pub mod autosave;pub mod captions;pub mod commands;pub mod demo;+pub mod essential_sound;pub mod graphics;pub mod interchange;pub mod media_pool;@@ -555,6 +556,8 @@ pub fn media_duration(p: &Project, _pool: &MediaPool, id: ItemId) -> Option<Tick#[cfg(test)]mod autosave_tests;#[cfg(test)]+mod essential_sound_tests;+#[cfg(test)]mod file_tests;#[cfg(test)]mod mixer_tests;diff --git a/crates/interchange/src/common.rs b/crates/interchange/src/common.rsindex d2adb920c..9a1fb5716 100644--- a/crates/interchange/src/common.rs+++ b/crates/interchange/src/common.rs@@ -414,6 +414,7 @@ impl Builder {gain_db: 0.0,frame_hold: None,scale_to_frame: false,+ essential: None,}}@@ -597,6 +598,7 @@ pub(crate) fn transition_effect(name: &str, audio: bool, report: &mut Report) ->params: Default::default(),masks: vec![],post_fader: false,+ essential: false,})}diff --git a/crates/project/src/effect.rs b/crates/project/src/effect.rsindex 9d0378bd6..5e93f788f 100644--- a/crates/project/src/effect.rs+++ b/crates/project/src/effect.rs@@ -86,6 +86,7 @@ impl EffectDef {params: self.params.iter().map(|p| (p.id.to_string(), Param::new(p.default.clone()))).collect(),masks: Vec::new(),post_fader: false,+ essential: false,}}}@@ -117,6 +118,9 @@ pub struct EffectInstance {/// Track/Mix inserts only: process after the fader instead of before it.#[serde(default, skip_serializing_if = "std::ops::Not::not")]pub post_fader: bool,+ /// Managed by the Essential Sound panel (see [`crate::essential`]).+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]+ pub essential: bool,}impl EffectInstance {@@ -252,6 +256,7 @@ const A_FILTER: &[&str] = &["Audio Effects", "Filter and EQ"];const A_NOISE: &[&str] = &["Audio Effects", "Noise Reduction/Restoration"];const A_REVERB: &[&str] = &["Audio Effects", "Reverb"];const A_SPECIAL: &[&str] = &["Audio Effects", "Special"];+const A_STEREO: &[&str] = &["Audio Effects", "Stereo Imagery"];const A_TIME: &[&str] = &["Audio Effects", "Time and Pitch"];const A_TRANS: &[&str] = &["Audio Transitions", "Crossfade"];@@ -882,7 +887,24 @@ fn build_effects() -> Vec<EffectDef> {audio("denoise", "DeNoise", A_NOISE, vec![f("amount", "Amount", 40.0, 0.0, 100.0, "%")]),audio("dehummer", "DeHummer", A_NOISE, vec![ch("freq", "Frequency", &["50 Hz", "60 Hz"], 1), f("gain", "Gain", -40.0, -80.0, 0.0, "dB")]),audio("declicker", "Automatic Click Remover", A_NOISE, vec![]),- audio("dereverb", "DeReverb", A_NOISE, vec![]),+ audio(+ "dereverb",+ "DeReverb",+ A_NOISE,+ vec![f("amount", "Amount", 50.0, 0.0, 100.0, "%"), fs("rt60", "Decay Time (RT60)", 0.8, (0.1, 5.0), (0.1, 3.0), "s", 2)],+ ),+ audio(+ "deesser",+ "DeEsser",+ A_AMP,+ vec![+ fs("frequency", "Frequency", 6000.0, (2000.0, 12000.0), (2000.0, 12000.0), "Hz", 0),+ fs("threshold", "Threshold", -12.0, (-40.0, 0.0), (-40.0, 0.0), "dB", 1),+ fs("reduction", "Maximum Reduction", 8.0, (0.0, 24.0), (0.0, 24.0), "dB", 1),+ ],+ ),+ audio("speech_enhance", "Enhance Speech", A_NOISE, vec![f("mix", "Mix", 100.0, 0.0, 100.0, "%"), ch("tone", "Voice", &["Low Tone", "High Tone"], 0)]),+ audio("stereo_width", "Stereo Width", A_STEREO, vec![fs("width", "Width", 100.0, (0.0, 200.0), (0.0, 200.0), "%", 0)]),audio("studio_reverb","Studio Reverb",diff --git a/crates/project/src/essential.rs b/crates/project/src/essential.rsnew file mode 100644index 000000000..d3a3d821f--- /dev/null+++ b/crates/project/src/essential.rs@@ -0,0 +1,885 @@+//! Essential Sound: clip audio types (Dialogue / Music / SFX / Ambience), their section settings+//! and presets, and how those settings become ordinary clip effects.+//!+//! The panel never processes audio itself. Like Premiere, it drives effects on the clip "under the+//! hood": Reduce Rumble is a Highpass, Reduce Noise a DeNoise, DeHum a DeHummer, DeEss a DeEsser,+//! Reduce Reverb a DeReverb, Dynamics a Dynamics Processing, EQ a Parametric Equalizer, Enhance+//! Speech the Enhance Speech chain, Stereo Width the Stereo Width effect and Reverb a Studio+//! Reverb. These instances carry [`EffectInstance::essential`], appear in Effect Controls (where+//! their parameters can be keyframed) and render through the normal clip-effect path, so the+//! mixer, playback and export need nothing special. Loudness auto-match writes clip gain, Clip+//! Volume the intrinsic Volume level, Pan the Panner, and Ducking writes Volume keyframes.+//!+//! [`apply`] reconciles a clip's essential effects with its settings after every change: missing+//! effects are inserted in canonical order, effects of slots that were switched off are removed,+//! and only parameters whose derived value changed are written (at the playhead, so keyframes the+//! user added in Effect Controls survive unrelated slider moves).++use serde::{Deserialize, Serialize};+use serde_json::Value;++use crate::effect::{EffectInstance, find_effect};+use crate::keyframe::ParamValue;+use crate::{Param, TrackItem};+use filmcraft_time::Tick;++/// Clip audio type.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]+pub enum AudioType {+ Dialogue,+ Music,+ #[serde(rename = "SFX")]+ Sfx,+ Ambience,+}++impl AudioType {+ pub const ALL: [AudioType; 4] = [AudioType::Dialogue, AudioType::Music, AudioType::Sfx, AudioType::Ambience];+ pub fn label(self) -> &'static str {+ match self {+ AudioType::Dialogue => "Dialogue",+ AudioType::Music => "Music",+ AudioType::Sfx => "SFX",+ AudioType::Ambience => "Ambience",+ }+ }+ /// Command-parameter id (`dialogue`, `music`, `sfx`, `ambience`).+ pub fn id(self) -> &'static str {+ match self {+ AudioType::Dialogue => "dialogue",+ AudioType::Music => "music",+ AudioType::Sfx => "sfx",+ AudioType::Ambience => "ambience",+ }+ }+ pub fn parse(s: &str) -> Option<AudioType> {+ AudioType::ALL.into_iter().find(|t| t.id().eq_ignore_ascii_case(s) || t.label().eq_ignore_ascii_case(s))+ }+ /// The sections the panel shows for this type (Premiere's layout).+ pub fn sections(self) -> &'static [Section] {+ match self {+ AudioType::Dialogue => &[Section::Loudness, Section::Repair, Section::Clarity, Section::Creative],+ AudioType::Music => &[Section::Loudness, Section::Duration, Section::Ducking],+ AudioType::Sfx => &[Section::Loudness, Section::Creative, Section::Pan],+ AudioType::Ambience => &[Section::Loudness, Section::Creative, Section::Ducking],+ }+ }+ pub fn has(self, s: Section) -> bool {+ self.sections().contains(&s)+ }+}++/// A collapsible panel section.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]+pub enum Section {+ Loudness,+ Repair,+ Clarity,+ Creative,+ Ducking,+ Duration,+ Pan,+}++impl Section {+ pub fn label(self) -> &'static str {+ match self {+ Section::Loudness => "Loudness",+ Section::Repair => "Repair",+ Section::Clarity => "Clarity",+ Section::Creative => "Creative",+ Section::Ducking => "Ducking",+ Section::Duration => "Duration",+ Section::Pan => "Pan",+ }+ }+ /// Settings key of the section's on/off switch (`None` for Duration, which has none).+ pub fn key(self) -> Option<&'static str> {+ Some(match self {+ Section::Loudness => "loudness.enabled",+ Section::Repair => "repair.enabled",+ Section::Clarity => "clarity.enabled",+ Section::Creative => "creative.enabled",+ Section::Ducking => "ducking.enabled",+ Section::Pan => "pan.enabled",+ Section::Duration => return None,+ })+ }+}++/// A checkbox + 0…10 slider pair.+#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]+pub struct Slot {+ pub on: bool,+ pub amount: f64,+}++impl Slot {+ const fn off(amount: f64) -> Self {+ Slot { on: false, amount }+ }+ const fn at(amount: f64) -> Self {+ Slot { on: true, amount }+ }+}++#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]+#[serde(default)]+pub struct Loudness {+ pub enabled: bool,+ /// Integrated loudness measured by the last Auto-Match (LUFS, before the match gain).+ pub measured_lufs: Option<f64>,+ /// Target used by the last Auto-Match.+ pub target_lufs: Option<f64>,+ /// Gain the match applied (dB); part of the clip gain while the section is on.+ pub gain_db: f64,+}++impl Default for Loudness {+ fn default() -> Self {+ Loudness { enabled: true, measured_lufs: None, target_lufs: None, gain_db: 0.0 }+ }+}++#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]+#[serde(default)]+pub struct Repair {+ pub enabled: bool,+ pub noise: Slot,+ pub rumble: Slot,+ pub dehum: Slot,+ /// Mains frequency for DeHum: 50 or 60 Hz.+ pub hum_hz: u32,+ pub deess: Slot,+ pub reverb: Slot,+}++impl Default for Repair {+ fn default() -> Self {+ Repair {+ enabled: true,+ noise: Slot::off(5.0),+ rumble: Slot::off(5.0),+ dehum: Slot::off(5.0),+ hum_hz: 60,+ deess: Slot::off(5.0),+ reverb: Slot::off(5.0),+ }+ }+}++#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]+#[serde(default)]+pub struct Clarity {+ pub enabled: bool,+ pub dynamics: Slot,+ pub eq: Slot,+ pub eq_preset: String,+ /// Enhance Speech; `amount` is the mix (0…10).+ pub enhance: Slot,+ /// 0 = low tone (lower voices), 1 = high tone.+ pub enhance_tone: u32,+}++impl Default for Clarity {+ fn default() -> Self {+ Clarity { enabled: true, dynamics: Slot::off(5.0), eq: Slot::off(5.0), eq_preset: EQ_PRESETS[0].name.into(), enhance: Slot::off(10.0), enhance_tone: 0 }+ }+}++#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]+#[serde(default)]+pub struct Creative {+ pub enabled: bool,+ pub reverb: Slot,+ pub reverb_preset: String,+ /// Stereo Width (Ambience): 0…10 → 100…200 %.+ pub width: Slot,+}++impl Default for Creative {+ fn default() -> Self {+ Creative { enabled: true, reverb: Slot::off(5.0), reverb_preset: REVERB_PRESETS[0].name.into(), width: Slot::off(5.0) }+ }+}++#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]+#[serde(default)]+pub struct Ducking {+ pub enabled: bool,+ /// Duck against clips of these types.+ pub against: Vec<AudioType>,+ /// Also duck against clips without an audio type.+ pub against_untyped: bool,+ /// 0…10: how quiet a trigger may be and still count.+ pub sensitivity: f64,+ /// Reduction in dB (negative).+ pub reduce_db: f64,+ /// Fade length (s).+ pub fade_s: f64,+}++impl Default for Ducking {+ fn default() -> Self {+ Ducking { enabled: false, against: vec![AudioType::Dialogue], against_untyped: false, sensitivity: 6.0, reduce_db: -15.0, fade_s: 0.8 }+ }+}++#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]+#[serde(default)]+pub struct Pan {+ pub enabled: bool,+ /// −100 (left) … +100 (right).+ pub value: f64,+}++/// Clip Volume (footer): an offset in dB on the clip's Volume level while `on`.+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]+#[serde(default)]+pub struct ClipVolume {+ pub on: bool,+ pub level_db: f64,+}++/// A clip's Essential Sound settings.+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]+pub struct EssentialSound {+ pub kind: AudioType,+ /// Last applied preset ("(Default)" or a preset name); cleared when a setting is changed by hand.+ #[serde(default)]+ pub preset: String,+ #[serde(default)]+ pub loudness: Loudness,+ #[serde(default)]+ pub repair: Repair,+ #[serde(default)]+ pub clarity: Clarity,+ #[serde(default)]+ pub creative: Creative,+ #[serde(default)]+ pub ducking: Ducking,+ #[serde(default)]+ pub pan: Pan,+ #[serde(default)]+ pub volume: ClipVolume,+ #[serde(default)]+ pub mute: bool,+}++pub const DEFAULT_PRESET: &str = "(Default)";++impl EssentialSound {+ /// The type's default settings.+ pub fn new(kind: AudioType) -> Self {+ let mut ducking = Ducking::default();+ if kind == AudioType::Ambience {+ ducking.reduce_db = -10.0;+ }+ EssentialSound {+ kind,+ preset: DEFAULT_PRESET.into(),+ loudness: Loudness::default(),+ repair: Repair::default(),+ clarity: Clarity::default(),+ creative: Creative::default(),+ ducking,+ pan: Pan::default(),+ volume: ClipVolume::default(),+ mute: false,+ }+ }++ /// The settings as JSON (keys as in [`EssentialSound::set`]).+ pub fn to_value(&self) -> Value {+ serde_json::to_value(self).unwrap_or(Value::Null)+ }++ /// A setting by dotted key (`repair.noise.amount`, `clarity.eqPreset`…; snake_case is+ /// accepted too).+ pub fn get(&self, key: &str) -> Option<Value> {+ let v = self.to_value();+ let mut cur = &v;+ for part in key.split('.') {+ cur = cur.get(snake(part).as_str())?;+ }+ Some(cur.clone())+ }++ /// Set one setting by dotted key. Values are validated and clamped; the type cannot be changed+ /// here (use a type assignment, which resets the settings).+ pub fn set(&mut self, key: &str, value: &Value) -> Result<(), String> {+ let parts: Vec<String> = key.split('.').map(snake).collect();+ if parts.first().map(String::as_str) == Some("kind") {+ return Err("the audio type is changed with essentialSound.setType".into());+ }+ let mut v = self.to_value();+ {+ let mut cur = &mut v;+ for part in &parts {+ cur = cur.get_mut(part.as_str()).ok_or_else(|| format!("unknown Essential Sound setting `{key}`"))?;+ }+ let ok = match (&*cur, value) {+ (Value::Bool(_), Value::Bool(_)) | (Value::String(_), Value::String(_)) | (Value::Array(_), Value::Array(_)) => true,+ (Value::Number(_), Value::Number(_)) | (Value::Null, Value::Number(_)) => true,+ (Value::Null, Value::Null) => true,+ (Value::Number(_), Value::Null) => false,+ _ => false,+ };+ if !ok {+ return Err(format!("`{key}`: expected {}", type_name(cur)));+ }+ *cur = value.clone();+ }+ let mut next: EssentialSound = serde_json::from_value(v).map_err(|e| format!("`{key}`: {e}"))?;+ next.clamp();+ if parts.first().map(String::as_str) == Some("clarity")+ && parts.get(1).map(String::as_str) == Some("eq_preset")+ && eq_preset(&next.clarity.eq_preset).is_none()+ {+ return Err(format!("unknown EQ preset `{}`", next.clarity.eq_preset));+ }+ if parts.first().map(String::as_str) == Some("creative")+ && parts.get(1).map(String::as_str) == Some("reverb_preset")+ && reverb_preset(&next.creative.reverb_preset).is_none()+ {+ return Err(format!("unknown reverb preset `{}`", next.creative.reverb_preset));+ }+ next.kind = self.kind;+ if !matches!(parts.first().map(String::as_str), Some("preset" | "volume" | "mute")) {+ next.preset.clear();+ }+ *self = next;+ Ok(())+ }++ fn clamp(&mut self) {+ let c = |v: &mut f64, lo: f64, hi: f64, def: f64| *v = if v.is_finite() { v.clamp(lo, hi) } else { def };+ for s in [+ &mut self.repair.noise,+ &mut self.repair.rumble,+ &mut self.repair.dehum,+ &mut self.repair.deess,+ &mut self.repair.reverb,+ &mut self.clarity.dynamics,+ &mut self.clarity.eq,+ &mut self.clarity.enhance,+ &mut self.creative.reverb,+ &mut self.creative.width,+ ] {+ c(&mut s.amount, 0.0, 10.0, 5.0);+ }+ self.repair.hum_hz = if self.repair.hum_hz < 55 { 50 } else { 60 };+ self.clarity.enhance_tone = self.clarity.enhance_tone.min(1);+ c(&mut self.ducking.sensitivity, 0.0, 10.0, 6.0);+ c(&mut self.ducking.reduce_db, -40.0, 0.0, -15.0);+ c(&mut self.ducking.fade_s, 0.0, 5.0, 0.8);+ self.ducking.against.dedup();+ c(&mut self.pan.value, -100.0, 100.0, 0.0);+ c(&mut self.volume.level_db, -96.0, 15.0, 0.0);+ c(&mut self.loudness.gain_db, -96.0, 96.0, 0.0);+ }++ /// Clip gain this state contributes (the Auto-Match gain while Loudness is on).+ pub fn loudness_gain_db(&self) -> f64 {+ if self.loudness.enabled { self.loudness.gain_db } else { 0.0 }+ }+ /// Offset this state adds to the Volume level.+ pub fn volume_offset_db(&self) -> f64 {+ if self.volume.on { self.volume.level_db } else { 0.0 }+ }+ /// Panner balance this state sets (`None` when Pan is not in use).+ pub fn pan_value(&self) -> Option<f64> {+ self.kind.has(Section::Pan).then_some(if self.pan.enabled { self.pan.value } else { 0.0 })+ }++ /// The clip effects these settings call for, in processing order, with their parameter values.+ pub fn effects(&self) -> Vec<EffectInstance> {+ let mut out = Vec::new();+ let k = self.kind;+ let mut push = |id: &str, section_on: bool, params: &[(&str, ParamValue)]| {+ if let Some(d) = find_effect(id) {+ let mut e = d.instance();+ e.essential = true;+ e.enabled = section_on;+ for (pid, v) in params {+ if let Some(p) = e.params.get_mut(*pid) {+ p.value = v.clone();+ }+ }+ out.push(e);+ }+ };+ let f = ParamValue::Float;+ if k.has(Section::Repair) {+ let r = &self.repair;+ if r.rumble.on {+ push("highpass", r.enabled, &[("cutoff", f(rumble_cutoff(r.rumble.amount)))]);+ }+ if r.noise.on {+ push("denoise", r.enabled, &[("amount", f(r.noise.amount * 10.0))]);+ }+ if r.dehum.on {+ push("dehummer", r.enabled, &[("freq", ParamValue::Choice(u32::from(r.hum_hz == 60))), ("gain", f(-r.dehum.amount * 8.0))]);+ }+ if r.deess.on {+ let a = r.deess.amount;+ push("deesser", r.enabled, &[("threshold", f(-6.0 - a * 1.2)), ("reduction", f(a * 2.4))]);+ }+ if r.reverb.on {+ push("dereverb", r.enabled, &[("amount", f(r.reverb.amount * 10.0))]);+ }+ }+ if k.has(Section::Clarity) {+ let c = &self.clarity;+ if c.dynamics.on {+ let a = c.dynamics.amount;+ push("dynamics", c.enabled, &[("threshold", f(-12.0 - a * 2.4)), ("ratio", f(1.5 + a * 0.45)), ("attack", f(5.0)), ("release", f(120.0))]);+ }+ if c.eq.on {+ let p = eq_preset(&c.eq_preset).unwrap_or(&EQ_PRESETS[0]);+ let s = c.eq.amount / 10.0;+ push(+ "parametric_eq",+ c.enabled,+ &[+ ("low_freq", f(p.low.0)),+ ("low_gain", f(p.low.1 * s)),+ ("mid_freq", f(p.mid.0)),+ ("mid_gain", f(p.mid.1 * s)),+ ("mid_q", f(p.mid_q)),+ ("high_freq", f(p.high.0)),+ ("high_gain", f(p.high.1 * s)),+ ],+ );+ }+ if c.enhance.on {+ push("speech_enhance", c.enabled, &[("mix", f(c.enhance.amount * 10.0)), ("tone", ParamValue::Choice(c.enhance_tone))]);+ }+ }+ if k.has(Section::Creative) {+ let c = &self.creative;+ if c.width.on && k == AudioType::Ambience {+ push("stereo_width", c.enabled, &[("width", f(100.0 + c.width.amount * 10.0))]);+ }+ if c.reverb.on {+ let p = reverb_preset(&c.reverb_preset).unwrap_or(&REVERB_PRESETS[0]);+ push(+ "studio_reverb",+ c.enabled,+ &[("room", f(p.room)), ("decay", f(p.decay)), ("damping", f(p.damping)), ("dry", f(100.0)), ("wet", f(c.reverb.amount * 8.0))],+ );+ }+ }+ out+ }+}++fn snake(s: &str) -> String {+ let mut o = String::with_capacity(s.len() + 4);+ for c in s.chars() {+ if c.is_ascii_uppercase() {+ o.push('_');+ o.push(c.to_ascii_lowercase());+ } else {+ o.push(c);+ }+ }+ o+}++fn type_name(v: &Value) -> &'static str {+ match v {+ Value::Bool(_) => "a boolean",+ Value::Number(_) | Value::Null => "a number",+ Value::String(_) => "a string",+ Value::Array(_) => "a list",+ Value::Object(_) => "a setting inside this group",+ }+}++/// Reduce Rumble amount (0…10) → highpass cutoff (30…150 Hz).+pub fn rumble_cutoff(amount: f64) -> f64 {+ 30.0 + amount * 12.0+}++/// Canonical processing order of the effects Essential Sound manages.+pub const EFFECT_ORDER: &[&str] =+ &["highpass", "denoise", "dehummer", "deesser", "dereverb", "dynamics", "parametric_eq", "speech_enhance", "stereo_width", "studio_reverb"];++fn rank(id: &str) -> usize {+ EFFECT_ORDER.iter().position(|e| *e == id).unwrap_or(EFFECT_ORDER.len())+}++/// Reconcile `item`'s essential effects, clip gain, Volume and Panner with `item.essential`,+/// given the settings before the change (`old`; `None` = nothing was applied yet). Parameters+/// whose derived value did not change are left alone; changed ones are written at media time `mt`+/// (as a keyframe when the parameter is animated).+pub fn apply(item: &mut TrackItem, old: Option<&EssentialSound>, mt: Tick) {+ let new = item.essential.clone();+ let want = new.as_ref().map(EssentialSound::effects).unwrap_or_default();+ let had = old.map(EssentialSound::effects).unwrap_or_default();+ // remove essential effects no longer wanted+ item.effects.retain(|e| !e.essential || want.iter().any(|w| w.effect == e.effect));+ for w in &want {+ match item.effects.iter().position(|e| e.essential && e.effect == w.effect) {+ Some(i) => {+ let prev = had.iter().find(|h| h.effect == w.effect);+ let e = &mut item.effects[i];+ e.enabled = w.enabled;+ for (pid, p) in &w.params {+ let changed = prev.and_then(|h| h.params.get(pid)).is_none_or(|hp| hp.value != p.value);+ if changed && let Some(dst) = e.params.get_mut(pid) {+ dst.set_at(mt, p.value.clone());+ }+ }+ }+ None => {+ // after the last essential effect of a lower rank, else before the first other+ // standard effect+ let r = rank(&w.effect);+ let first_std = item.effects.iter().position(|e| !e.def().is_some_and(|d| d.intrinsic)).unwrap_or(item.effects.len());+ let pos = item.effects.iter().rposition(|e| e.essential && rank(&e.effect) < r).map(|i| i + 1).unwrap_or(first_std);+ item.effects.insert(pos, w.clone());+ }+ }+ }+ // clip gain (Auto-Match), Volume offset, Pan+ let g_old = old.map(EssentialSound::loudness_gain_db).unwrap_or(0.0);+ let g_new = new.as_ref().map(EssentialSound::loudness_gain_db).unwrap_or(0.0);+ if (g_new - g_old).abs() > 1e-12 {+ item.gain_db = (item.gain_db + g_new - g_old).clamp(-96.0, 96.0);+ }+ let v_old = old.map(EssentialSound::volume_offset_db).unwrap_or(0.0);+ let v_new = new.as_ref().map(EssentialSound::volume_offset_db).unwrap_or(0.0);+ if (v_new - v_old).abs() > 1e-12+ && let Some(p) = item.effect_mut("volume").and_then(|e| e.param_mut("level"))+ {+ offset_param(p, v_new - v_old);+ }+ let p_old = old.and_then(EssentialSound::pan_value);+ let p_new = new.as_ref().and_then(EssentialSound::pan_value);+ if p_new != p_old+ && let Some(p) = item.effect_mut("panner").and_then(|e| e.param_mut("balance"))+ {+ p.set_at(mt, ParamValue::Float(p_new.unwrap_or(0.0)));+ }+}++/// Add `db` to a level parameter: the static value, or every keyframe (keeps ducking shapes).+pub fn offset_param(p: &mut Param, db: f64) {+ let add = |v: &mut ParamValue| {+ if let ParamValue::Float(x) = v {+ *x = (*x + db).clamp(-287.5, 15.0);+ }+ };+ add(&mut p.value);+ for k in &mut p.keyframes {+ add(&mut k.value);+ }+}++// ------------------------------------------------------------------------------------- presets++/// An EQ preset for Clarity ▸ EQ: (frequency Hz, gain dB at full amount) per band. Values are our+/// own.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct EqPreset {+ pub name: &'static str,+ pub low: (f64, f64),+ pub mid: (f64, f64),+ pub mid_q: f64,+ pub high: (f64, f64),+}++pub const EQ_PRESETS: &[EqPreset] = &[+ EqPreset { name: "Balanced Voice", low: (120.0, -3.0), mid: (3000.0, 3.0), mid_q: 1.0, high: (10000.0, 2.0) },+ EqPreset { name: "Presence Lift", low: (100.0, 0.0), mid: (4000.0, 5.0), mid_q: 0.8, high: (12000.0, 1.0) },+ EqPreset { name: "Warm Voice", low: (200.0, 3.0), mid: (3500.0, 1.5), mid_q: 1.0, high: (9000.0, -2.0) },+ EqPreset { name: "Clear Muddiness", low: (100.0, -2.0), mid: (300.0, -6.0), mid_q: 1.4, high: (10000.0, 1.0) },+ EqPreset { name: "Soften Harshness", low: (100.0, 0.0), mid: (3200.0, -5.0), mid_q: 1.2, high: (9000.0, -2.0) },+ EqPreset { name: "Bright Air", low: (100.0, 0.0), mid: (3000.0, 1.0), mid_q: 1.0, high: (8000.0, 6.0) },+ EqPreset { name: "Radio Voice", low: (150.0, -10.0), mid: (2500.0, 6.0), mid_q: 1.0, high: (6000.0, -8.0) },+ EqPreset { name: "Telephone", low: (400.0, -18.0), mid: (1500.0, 6.0), mid_q: 0.7, high: (3500.0, -18.0) },+];++pub fn eq_preset(name: &str) -> Option<&'static EqPreset> {+ EQ_PRESETS.iter().find(|p| p.name.eq_ignore_ascii_case(name))+}++/// A reverb preset for Creative ▸ Reverb (Studio Reverb room / decay / damping, %). Our own values.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct ReverbPreset {+ pub name: &'static str,+ pub room: f64,+ pub decay: f64,+ pub damping: f64,+}++pub const REVERB_PRESETS: &[ReverbPreset] = &[+ ReverbPreset { name: "Small Room", room: 25.0, decay: 25.0, damping: 60.0 },+ ReverbPreset { name: "Warm Room", room: 40.0, decay: 35.0, damping: 80.0 },+ ReverbPreset { name: "Medium Room", room: 50.0, decay: 45.0, damping: 50.0 },+ ReverbPreset { name: "Bright Studio", room: 45.0, decay: 40.0, damping: 15.0 },+ ReverbPreset { name: "Large Hall", room: 85.0, decay: 70.0, damping: 40.0 },+ ReverbPreset { name: "Stone Church", room: 100.0, decay: 92.0, damping: 30.0 },+ ReverbPreset { name: "Open Air", room: 90.0, decay: 15.0, damping: 70.0 },+];++pub fn reverb_preset(name: &str) -> Option<&'static ReverbPreset> {+ REVERB_PRESETS.iter().find(|p| p.name.eq_ignore_ascii_case(name))+}++/// A named Essential Sound preset for one audio type: settings applied on top of the type's+/// defaults.+#[derive(Clone, Debug, PartialEq)]+pub struct Preset {+ pub name: String,+ pub kind: AudioType,+ pub settings: EssentialSound,+ /// Built in (cannot be deleted).+ pub builtin: bool,+}++/// The built-in presets (our own names and values), "(Default)" first for each type.+pub fn builtin_presets() -> Vec<Preset> {+ use AudioType::*;+ let mk = |kind: AudioType, name: &str, f: &dyn Fn(&mut EssentialSound)| {+ let mut s = EssentialSound::new(kind);+ f(&mut s);+ s.preset = name.to_string();+ Preset { name: name.to_string(), kind, settings: s, builtin: true }+ };+ vec![+ mk(Dialogue, DEFAULT_PRESET, &|_| {}),+ mk(Dialogue, "Balanced Voice", &|s| {+ s.repair.rumble = Slot::at(4.0);+ s.clarity.dynamics = Slot::at(4.0);+ s.clarity.eq = Slot::at(5.0);+ s.clarity.eq_preset = "Balanced Voice".into();+ }),+ mk(Dialogue, "Clean Up Noisy Dialogue", &|s| {+ s.repair.noise = Slot::at(6.0);+ s.repair.rumble = Slot::at(5.0);+ s.repair.dehum = Slot::at(5.0);+ s.clarity.dynamics = Slot::at(3.0);+ }),+ mk(Dialogue, "Podcast Voice", &|s| {+ s.repair.rumble = Slot::at(5.0);+ s.repair.deess = Slot::at(4.0);+ s.clarity.dynamics = Slot::at(6.0);+ s.clarity.eq = Slot::at(6.0);+ s.clarity.eq_preset = "Presence Lift".into();+ s.clarity.enhance = Slot::at(7.0);+ }),+ mk(Dialogue, "Dry Up a Roomy Voice", &|s| {+ s.repair.reverb = Slot::at(6.0);+ s.repair.rumble = Slot::at(4.0);+ s.clarity.eq = Slot::at(4.0);+ s.clarity.eq_preset = "Clear Muddiness".into();+ }),+ mk(Dialogue, "Phone Call", &|s| {+ s.clarity.eq = Slot::at(10.0);+ s.clarity.eq_preset = "Telephone".into();+ s.clarity.dynamics = Slot::at(5.0);+ }),+ mk(Dialogue, "Radio Announcer", &|s| {+ s.clarity.eq = Slot::at(8.0);+ s.clarity.eq_preset = "Radio Voice".into();+ s.clarity.dynamics = Slot::at(8.0);+ s.repair.deess = Slot::at(5.0);+ }),+ mk(Dialogue, "Voice in a Hall", &|s| {+ s.creative.reverb = Slot::at(5.0);+ s.creative.reverb_preset = "Large Hall".into();+ }),+ mk(Music, DEFAULT_PRESET, &|_| {}),+ mk(Music, "Duck Under Dialogue", &|s| {+ s.ducking.enabled = true;+ }),+ mk(Music, "Duck Deep Under Dialogue", &|s| {+ s.ducking.enabled = true;+ s.ducking.reduce_db = -24.0;+ s.ducking.fade_s = 1.2;+ }),+ mk(Music, "Duck Under Voice and Effects", &|s| {+ s.ducking.enabled = true;+ s.ducking.against = vec![Dialogue, Sfx];+ s.ducking.reduce_db = -12.0;+ }),+ mk(Sfx, DEFAULT_PRESET, &|_| {}),+ mk(Sfx, "From the Left", &|s| {+ s.pan.enabled = true;+ s.pan.value = -60.0;+ }),+ mk(Sfx, "From the Right", &|s| {+ s.pan.enabled = true;+ s.pan.value = 60.0;+ }),+ mk(Sfx, "In a Room", &|s| {+ s.creative.reverb = Slot::at(4.0);+ s.creative.reverb_preset = "Small Room".into();+ }),+ mk(Sfx, "Far Away", &|s| {+ s.creative.reverb = Slot::at(8.0);+ s.creative.reverb_preset = "Open Air".into();+ }),+ mk(Ambience, DEFAULT_PRESET, &|_| {}),+ mk(Ambience, "Wide Outdoor", &|s| {+ s.creative.width = Slot::at(7.0);+ }),+ mk(Ambience, "Interior Room Tone", &|s| {+ s.creative.reverb = Slot::at(3.0);+ s.creative.reverb_preset = "Warm Room".into();+ }),+ mk(Ambience, "Duck Under Dialogue", &|s| {+ s.ducking.enabled = true;+ }),+ ]+}++/// Apply a preset's settings to a clip's state, keeping what a preset does not own (the+/// measured loudness and its match gain, Clip Volume, Mute).+pub fn with_preset(current: Option<&EssentialSound>, preset: &Preset) -> EssentialSound {+ let mut s = preset.settings.clone();+ s.preset = preset.name.clone();+ if let Some(c) = current.filter(|c| c.kind == preset.kind) {+ s.loudness.measured_lufs = c.loudness.measured_lufs;+ s.loudness.target_lufs = c.loudness.target_lufs;+ s.loudness.gain_db = c.loudness.gain_db;+ s.volume = c.volume.clone();+ s.mute = c.mute;+ }+ s+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::effect::intrinsic_audio;+ use serde_json::json;++ fn clip() -> TrackItem {+ TrackItem {+ id: crate::ClipId(1),+ item: crate::ItemId(2),+ name: "d".into(),+ label: crate::Label::Iris,+ start: Tick::ZERO,+ duration: Tick(1000),+ source_in: Tick::ZERO,+ speed: 1.0,+ reverse: false,+ enabled: true,+ link: None,+ group: None,+ effects: intrinsic_audio(),+ markers: vec![],+ gain_db: 0.0,+ frame_hold: None,+ scale_to_frame: false,+ essential: None,+ }+ }++ fn ids(it: &TrackItem) -> Vec<String> {+ it.effects.iter().map(|e| e.effect.clone()).collect()+ }++ #[test]+ fn set_get_and_validation() {+ let mut s = EssentialSound::new(AudioType::Dialogue);+ s.set("repair.noise.on", &json!(true)).unwrap();+ s.set("repair.noise.amount", &json!(42.0)).unwrap();+ assert_eq!(s.repair.noise, Slot { on: true, amount: 10.0 });+ s.set("clarity.eqPreset", &json!("Telephone")).unwrap();+ assert_eq!(s.get("clarity.eqPreset"), Some(json!("Telephone")));+ assert!(s.set("clarity.eqPreset", &json!("Nope")).is_err());+ assert!(s.set("repair.noise.on", &json!(3)).is_err());+ assert!(s.set("nope", &json!(3)).is_err());+ assert!(s.set("kind", &json!("Music")).is_err());+ assert!(s.preset.is_empty(), "a manual change leaves the preset");+ s.set("ducking.against", &json!(["Dialogue", "SFX"])).unwrap();+ assert_eq!(s.ducking.against, vec![AudioType::Dialogue, AudioType::Sfx]);+ }++ #[test]+ fn apply_inserts_updates_and_removes_effects_in_order() {+ let mut it = clip();+ it.effects.push(find_effect("delay").unwrap().instance());+ let mut s = EssentialSound::new(AudioType::Dialogue);+ s.repair.deess = Slot::at(5.0);+ s.creative.reverb = Slot::at(5.0);+ s.repair.rumble = Slot::at(5.0);+ it.essential = Some(s.clone());+ apply(&mut it, None, Tick::ZERO);+ assert_eq!(ids(&it), ["volume", "channel_volume", "panner", "highpass", "deesser", "studio_reverb", "delay"]);+ // keyframe a parameter by hand, then change an unrelated slider: keyframes survive+ let k = it.effects.iter_mut().find(|e| e.effect == "deesser").unwrap();+ k.params.get_mut("reduction").unwrap().put_keyframe(Tick(10), ParamValue::Float(3.0));+ let old = s.clone();+ s.repair.rumble.amount = 10.0;+ s.repair.noise = Slot::at(2.0);+ it.essential = Some(s.clone());+ apply(&mut it, Some(&old), Tick::ZERO);+ assert_eq!(ids(&it), ["volume", "channel_volume", "panner", "highpass", "denoise", "deesser", "studio_reverb", "delay"]);+ assert_eq!(it.effect("highpass").unwrap().f64_at("cutoff", Tick::ZERO), 150.0);+ assert!(it.effect("deesser").unwrap().param("reduction").unwrap().is_animated());+ // section off bypasses, slot off removes+ let old = s.clone();+ s.repair.enabled = false;+ s.creative.reverb.on = false;+ it.essential = Some(s.clone());+ apply(&mut it, Some(&old), Tick::ZERO);+ assert!(!it.effect("highpass").unwrap().enabled);+ assert!(it.effect("studio_reverb").is_none());+ // clearing removes every essential effect but keeps the user's+ let old = s.clone();+ it.essential = None;+ apply(&mut it, Some(&old), Tick::ZERO);+ assert_eq!(ids(&it), ["volume", "channel_volume", "panner", "delay"]);+ }++ #[test]+ fn gain_volume_and_pan_are_deltas() {+ let mut it = clip();+ it.gain_db = 2.0;+ let mut s = EssentialSound::new(AudioType::Sfx);+ s.loudness.gain_db = -5.0;+ s.volume = ClipVolume { on: true, level_db: -3.0 };+ s.pan = Pan { enabled: true, value: 40.0 };+ it.essential = Some(s.clone());+ apply(&mut it, None, Tick::ZERO);+ assert_eq!(it.gain_db, -3.0);+ assert_eq!(it.effect("volume").unwrap().f64_at("level", Tick::ZERO), -3.0);+ assert_eq!(it.effect("panner").unwrap().f64_at("balance", Tick::ZERO), 40.0);+ let old = s.clone();+ it.essential = None;+ apply(&mut it, Some(&old), Tick::ZERO);+ assert_eq!(it.gain_db, 2.0);+ assert_eq!(it.effect("volume").unwrap().f64_at("level", Tick::ZERO), 0.0);+ assert_eq!(it.effect("panner").unwrap().f64_at("balance", Tick::ZERO), 0.0);+ }++ #[test]+ fn presets_are_valid_and_unique() {+ let ps = builtin_presets();+ for t in AudioType::ALL {+ let mine: Vec<_> = ps.iter().filter(|p| p.kind == t).collect();+ assert_eq!(mine[0].name, DEFAULT_PRESET);+ let mut names: Vec<_> = mine.iter().map(|p| p.name.as_str()).collect();+ names.dedup();+ assert_eq!(names.len(), mine.len());+ }+ for p in &ps {+ assert!(eq_preset(&p.settings.clarity.eq_preset).is_some());+ assert!(reverb_preset(&p.settings.creative.reverb_preset).is_some());+ for e in p.settings.effects() {+ assert!(e.def().is_some(), "{}: unknown effect {}", p.name, e.effect);+ }+ }+ // serde round trip+ let s = &ps[3].settings;+ let back: EssentialSound = serde_json::from_value(s.to_value()).unwrap();+ assert_eq!(&back, s);+ }+}diff --git a/crates/project/src/lib.rs b/crates/project/src/lib.rsindex b502794fd..de149c64e 100644--- a/crates/project/src/lib.rs+++ b/crates/project/src/lib.rs@@ -9,6 +9,7 @@pub mod caption;pub mod effect;+pub mod essential;pub mod graphic;pub mod keyframe;pub mod mixer;@@ -22,6 +23,7 @@ use serde::{Deserialize, Serialize};pub use caption::{Caption, CaptionAlign, CaptionAnchor, CaptionFormat, CaptionStyle, CaptionTrack, plain_text};pub use effect::{EffectDef, EffectInstance, EffectKind, ParamDef, ParamKind, effect_defs, find_effect};+pub use essential::{AudioType, EssentialSound};pub use keyframe::{Interpolation, Keyframe, Param, ParamValue};pub use mixer::{AutomationMode, InputMap, MixerStrip, TrackSend};@@ -431,6 +433,9 @@ pub struct TrackItem {/// Scale to frame size (Set to Frame Size / Scale to Frame Size).#[serde(default)]pub scale_to_frame: bool,+ /// Essential Sound audio type and settings (audio clips).+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub essential: Option<EssentialSound>,}impl TrackItem {@@ -899,6 +904,7 @@ impl Project {gain_db: 0.0,frame_hold: None,scale_to_frame: false,+ essential: None,})}diff --git a/crates/render/src/audio.rs b/crates/render/src/audio.rsindex 1f051593b..81ab684ec 100644--- a/crates/render/src/audio.rs+++ b/crates/render/src/audio.rs@@ -93,9 +93,11 @@ fn mix_item(project: &Project, item: &TrackItem, start: i64, frames: usize, sr:if a1 <= a0 {return;}+ if item.essential.as_ref().is_some_and(|e| e.mute) {+ return;+ }let n = (a1 - a0) as usize;- let read = |x0: i64, len: usize| raw_stereo(item, src.as_ref(), x0, len, sr);- let buf = if crate::audio_fx::has_effects(item) { crate::audio_fx::process(item, a0, n, sr, &read) } else { read(a0, n) };+ let buf = effected(item, src.as_ref(), a0, n, sr);// gains: clip gain × Volume (keyframed, per 64-sample block) × channel volume × pannerlet clip_gain = db_to_gain(item.gain_db);let vol = item.effect("volume").filter(|e| e.enabled && !e.param("bypass").and_then(|p| p.value.as_bool()).unwrap_or(false));@@ -122,6 +124,39 @@ fn mix_item(project: &Project, item: &TrackItem, start: i64, frames: usize, sr:}}+/// The clip's audio after speed/reverse and clip effects (before clip gain, Volume and Panner) for+/// timeline samples `[a0, a0 + n)`.+fn effected(item: &TrackItem, src: &dyn filmcraft_media::MediaSource, a0: i64, n: usize, sr: u32) -> [Vec<f32>; 2] {+ let read = |x0: i64, len: usize| raw_stereo(item, src, x0, len, sr);+ if crate::audio_fx::has_effects(item) { crate::audio_fx::process(item, a0, n, sr, &read) } else { read(a0, n) }+}++/// One clip's own signal for timeline samples `[start, start + frames)` (sequence rate): clip gain+/// and clip effects, without Volume / Channel Volume / Panner, transitions or Mute (silence outside+/// the clip). Loudness Auto-Match and ducking analyse this. `None` when the clip has no audio+/// source (nested sequences are not analysed).+pub fn clip_signal(item: &TrackItem, start: i64, frames: usize, sr: u32, sources: &dyn SourceProvider) -> Option<[Vec<f32>; 2]> {+ let src = sources.source(item.item)?;+ if !src.info().has_audio() {+ return None;+ }+ let mut out = [vec![0.0f32; frames], vec![0.0f32; frames]];+ let a0 = start.max(item.start.to_units_floor(sr as i64));+ let a1 = (start + frames as i64).min(item.end().to_units_floor(sr as i64));+ if a1 > a0 {+ let n = (a1 - a0) as usize;+ let off = (a0 - start) as usize;+ let g = db_to_gain(item.gain_db);+ let buf = effected(item, src.as_ref(), a0, n, sr);+ for (dst, b) in out.iter_mut().zip(&buf) {+ for (d, x) in dst[off..off + n].iter_mut().zip(b) {+ *d = x * g;+ }+ }+ }+ Some(out)+}+/// The clip's audio (after speed/reverse) for timeline samples `[x0, x0 + len)` as stereo, with/// silence outside the clip. Mono sources are duplicated to both channels.fn raw_stereo(item: &TrackItem, src: &dyn filmcraft_media::MediaSource, x0: i64, len: usize, sr: u32) -> [Vec<f32>; 2] {diff --git a/crates/render/src/audio_fx.rs b/crates/render/src/audio_fx.rsindex 28f335b4a..79174fbf8 100644--- a/crates/render/src/audio_fx.rs+++ b/crates/render/src/audio_fx.rs@@ -83,12 +83,43 @@ pub(crate) fn mapping(id: &str) -> Option<Mapping> {"highpass" => Mapping { dsp: "parametric_eq", preroll: |_, _| 0.05, apply: |d, e, t| band(d, 4.0, f(e, "cutoff", t), 0.707) },"lowpass" => Mapping { dsp: "parametric_eq", preroll: |_, _| 0.05, apply: |d, e, t| band(d, 3.0, f(e, "cutoff", t), 0.707) },"bandpass" => Mapping { dsp: "parametric_eq", preroll: |_, _| 0.05, apply: |d, e, t| band(d, 6.0, f(e, "center", t), f(e, "q", t)) },- "denoise" => Mapping { dsp: "denoise", preroll: |_, _| 1.0, apply: |d, e, t| ignore(d.set_param("amount", f(e, "amount", t))) },+ // Amount 0…100 % → 0…40 dB of reduction.+ "denoise" => Mapping { dsp: "denoise", preroll: |_, _| 1.0, apply: |d, e, t| ignore(d.set_param("reduction", f(e, "amount", t) * 0.4)) },+ // Gain is the notch depth: the wet/dry amount that leaves 10^(gain/20) of the hum."dehummer" => Mapping {dsp: "dehum",preroll: |_, _| 0.2,- apply: |d, e, t| ignore(d.set_param("frequency", e.param("freq").and_then(|p| p.value_at(t).as_f64()).unwrap_or(1.0) as f32)),+ apply: |d, e, t| {+ d.set_param("frequency", e.param("freq").and_then(|p| p.value_at(t).as_f64()).unwrap_or(1.0) as f32);+ d.set_param("amount", (1.0 - 10f32.powf(f(e, "gain", t).min(0.0) / 20.0)) * 100.0);+ },+ },+ "deesser" => Mapping {+ dsp: "deesser",+ preroll: |_, _| 0.1,+ apply: |d, e, t| {+ d.set_param("frequency", f(e, "frequency", t));+ d.set_param("threshold", f(e, "threshold", t));+ d.set_param("reduction", f(e, "reduction", t));+ },+ },+ "dereverb" => Mapping {+ dsp: "dereverb",+ preroll: |e, t| (f(e, "rt60", t) as f64 + 0.3).clamp(0.5, 3.0),+ apply: |d, e, t| {+ d.set_param("amount", f(e, "amount", t));+ d.set_param("rt60", f(e, "rt60", t));+ },+ },+ "speech_enhance" => Mapping {+ dsp: "speech_enhance",+ preroll: |_, _| 0.3,+ apply: |d, e, t| {+ d.set_param("mix", f(e, "mix", t));+ d.set_param("tone", e.param("tone").and_then(|p| p.value_at(t).as_f64()).unwrap_or(0.0) as f32);+ },},+ "stereo_width" => Mapping { dsp: "stereo_width", preroll: |_, _| 0.0, apply: |d, e, t| ignore(d.set_param("width", f(e, "width", t))) },"studio_reverb" => Mapping {dsp: "reverb",preroll: |e, t| 0.3 * 30f64.powf(f(e, "decay", t) as f64 / 100.0).min(8.0),