FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust
M7.2: audio mixer graph, track automation and mixer commands
Brandon Thomas6b00314e9669
diff --git a/crates/engine/src/autosave.rs b/crates/engine/src/autosave.rsindex 436841ab7..0cc02293a 100644--- a/crates/engine/src/autosave.rs+++ b/crates/engine/src/autosave.rs@@ -69,6 +69,46 @@ impl AutoSavePrefs {#[serde(rename_all = "camelCase", default)]pub struct Preferences {pub auto_save: AutoSavePrefs,+ pub audio: AudioPrefs,+}++/// Preferences ▸ Audio (the mixer-automation part) and the Track Mixer panel-menu toggle.+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase", default)]+pub struct AudioPrefs {+ /// "Automatch Time" (s): how long Touch takes to return to the existing automation.+ pub automatch_time: f64,+ /// "Large Volume Adjustment" (dB) for the Increase/Decrease Clip Volume Many commands.+ pub large_volume_adjustment: f64,+ /// Automation Keyframe Optimization: "Linear keyframe thinning".+ pub linear_keyframe_thinning: bool,+ /// "Minimum time interval thinning".+ pub minimum_time_interval_thinning: bool,+ /// "Minimum time" (ms).+ pub minimum_time_ms: u32,+ /// Track Mixer ▸ "Switch to Touch after Write".+ pub switch_to_touch_after_write: bool,+}++impl Default for AudioPrefs {+ fn default() -> Self {+ Self {+ automatch_time: 1.0,+ large_volume_adjustment: 6.0,+ linear_keyframe_thinning: true,+ minimum_time_interval_thinning: false,+ minimum_time_ms: 20,+ switch_to_touch_after_write: true,+ }+ }+}++impl AudioPrefs {+ 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);+ }}impl Preferences {@@ -118,6 +158,7 @@ impl Preferences {*slot = value;let mut p: Preferences = serde_json::from_value(v).map_err(|e| format!("`{key}`: {e}"))?;p.auto_save.clamp();+ p.audio.clamp();*self = p;Ok(())}@@ -125,6 +166,7 @@ impl Preferences {pub fn load(path: &Path) -> Self {let mut p: Preferences = fs::read(path).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default();p.auto_save.clamp();+ p.audio.clamp();p}diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rsindex 687721f3b..300f0a21c 100644--- a/crates/engine/src/commands.rs+++ b/crates/engine/src/commands.rs@@ -1814,6 +1814,7 @@ fn build() -> Vec<CommandSpec> {)),];v.extend(crate::captions::commands());+ v.extend(crate::mixer::commands());// Labels as individual commands (Edit ▸ Label ▸ <name>)for l in Label::ALL {let _ = l;diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rsindex dfaba163b..f5346461c 100644--- a/crates/engine/src/lib.rs+++ b/crates/engine/src/lib.rs@@ -14,6 +14,7 @@ pub mod commands;pub mod demo;pub mod interchange;pub mod media_pool;+pub mod mixer;pub mod previews;pub mod trim;@@ -162,6 +163,8 @@ pub struct Session {pub loaded_schema: u32,/// Render preview files + render-bar segments (shared with the frontend's frame workers).pub previews: Arc<previews::PreviewStore>,+ /// Audio Track Mixer automation pass in progress.+ pub mixrec: mixer::Recorder,}/// A background job with shared progress.@@ -221,6 +224,7 @@ impl Session {persistence: None,loaded_schema: filmcraft_format::SCHEMA_VERSION,previews: Arc::new(previews::PreviewStore::temp()),+ mixrec: Default::default(),}}@@ -314,6 +318,8 @@ impl Session {(spec.enabled)(self).map_err(|why| EngineError::Disabled(id.to_string(), why))?;let r = (spec.run)(self, ¶ms);self.sync_persistence();+ // playback reads the newest snapshot (mixer moves, mutes… are heard while playing)+ self.previews.live.publish_project(self.project.clone());if r.is_ok() && spec.journal {self.journal.push((id.to_string(), params));if self.journal.len() > 10_000 {@@ -488,6 +494,8 @@ mod autosave_tests;#[cfg(test)]mod file_tests;#[cfg(test)]+mod mixer_tests;+#[cfg(test)]mod previews_tests;#[cfg(test)]mod tests;diff --git a/crates/engine/src/mixer.rs b/crates/engine/src/mixer.rsnew file mode 100644index 000000000..78bd9fd74--- /dev/null+++ b/crates/engine/src/mixer.rs@@ -0,0 +1,1026 @@+//! Audio Track Mixer commands and the automation recorder.+//!+//! Strips are addressed by `strip` (or `track`): `"A1"` … (audio tracks), `"S1"` … (submixes),+//! `"Mix"` (the master), a track id, or a strip name. Lanes are `volume`, `pan`, `mute`,+//! `send.<i>.level` and `fx.<slot>.<param>` (see [`filmcraft_project::mixer`]).+//!+//! **Recording.** `mixer.recordStart` begins an automation pass at the playhead (the UI calls it+//! when playback starts). While it runs, `mixer.touch` / `mixer.release` are the fader gestures:+//! the audio follows the control immediately (through [`filmcraft_render::mixer::LiveMix`]) and the+//! gesture is recorded as a stream of (time, value) points. `mixer.recordStop` (playback stops)+//! thins every stream into keyframes and writes them as one undoable step, following the strip's+//! automation mode:+//!+//! | mode | records | after release |+//! |---|---|---|+//! | Off / Read | nothing (Read plays the automation) | the control returns to the automation |+//! | Latch | from the first touch | keeps writing the last value until playback stops |+//! | Touch | while touched | ramps back to the existing automation over the automatch time |+//! | Write | every control from the start of playback | keeps writing the last value until playback stops |+//!+//! With "Switch to Touch after Write" (on by default) a Write strip changes to Touch after the+//! pass. Without a recording pass, `mixer.touch` holds the control live and `mixer.release` commits+//! it once (a static value, or a keyframe at the playhead when the lane is automated).++use serde_json::{Value, json};++use filmcraft_project::mixer::{+ self as pm, FADER_MAX_DB, FADER_MIN_DB, LANE_MUTE, LANE_PAN, LANE_VOLUME, MASTER_STRIP, lane_info, parse_fx_lane, parse_send_lane, thin_points, write_lane,+};+use filmcraft_project::{AudioChannels, AutomationMode, InputMap, ItemId, Param, ParamValue, Sequence, Track, TrackId, TrackKind, TrackSend, find_effect};+use filmcraft_time::{TICKS_PER_SECOND, Tick};++use crate::commands::{CommandSpec, always, bad, bool_p, f64_p, has_seq, str_p, time_p, u64_p};+use crate::{EngineError, Result, Session};++type Run = fn(&mut Session, &Value) -> Result<Value>;+type Enabled = fn(&Session) -> std::result::Result<(), String>;++// ------------------------------------------------------------------------------------- recorder++/// A held value ends this long before the next move (one sample at 48 kHz).+const HOLD_EPS: Tick = Tick(TICKS_PER_SECOND / 48_000);++/// One recorded control gesture.+#[derive(Clone, Debug)]+pub struct Gesture {+ pub strip: TrackId,+ pub lane: String,+ pub mode: AutomationMode,+ /// Recorded (time, value) points.+ pub points: Vec<(Tick, f64)>,+ pub touching: bool,+ /// Touch: released at.+ pub released: Option<Tick>,+ last: (Tick, f64),+}++impl Gesture {+ fn new(strip: TrackId, lane: &str, mode: AutomationMode, t: Tick, v: f64) -> Self {+ Gesture { strip, lane: lane.to_string(), mode, points: vec![(t, v)], touching: true, released: None, last: (t, v) }+ }+ /// A new value at `t`. Repeats of the same value extend the hold instead of adding points, so a+ /// fader held still records a flat line, not a ramp to the next move.+ fn push(&mut self, t: Tick, v: f64) {+ if t < self.last.0 {+ return;+ }+ if v == self.last.1 {+ self.last.0 = t;+ return;+ }+ if self.points.last().is_some_and(|p| self.last.0 > p.0) {+ self.points.push(self.last);+ }+ self.points.push((t, v));+ self.last = (t, v);+ }+ fn flush(&mut self) {+ if self.points.last().is_some_and(|p| self.last.0 > p.0) {+ self.points.push(self.last);+ }+ }+ pub fn value(&self) -> f64 {+ self.last.1+ }+}++/// State of the current automation pass.+#[derive(Clone, Debug, Default)]+pub struct Recorder {+ /// Sequence being recorded (None = no pass running).+ pub seq: Option<ItemId>,+ pub start: Tick,+ pub gestures: Vec<Gesture>,+}++impl Recorder {+ pub fn active(&self) -> bool {+ self.seq.is_some()+ }+ fn find(&mut self, strip: TrackId, lane: &str) -> Option<&mut Gesture> {+ self.gestures.iter_mut().find(|g| g.strip == strip && g.lane == lane)+ }+}++/// Lanes a Write pass records on every strip.+fn write_lanes(strip: TrackId) -> &'static [&'static str] {+ if strip == MASTER_STRIP { &[LANE_VOLUME] } else { &[LANE_VOLUME, LANE_PAN, LANE_MUTE] }+}++/// The lane value as automation plays it (no live overrides).+fn underlying(tr: &Track, lane: &str, t: Tick) -> f64 {+ let v = tr.lane_value(lane, t);+ if lane_info(lane).is_some_and(|i| i.hold) {+ // hold lanes: last keyframe at or before t+ if let Some(p) = tr.lane(lane).filter(|p| p.is_animated() && tr.mixer.mode.reads()) {+ let i = p.keyframes.partition_point(|k| k.time <= t);+ return p.keyframes[i.saturating_sub(1)].value.as_f64().unwrap_or(v);+ }+ }+ v+}++fn clamp_lane(lane: &str, v: f64) -> f64 {+ match lane_info(lane) {+ Some(i) if i.hold => {+ if v >= 0.5 {+ 1.0+ } else {+ 0.0+ }+ }+ Some(i) => v.clamp(i.min, i.max),+ None => v,+ }+}++fn seq_of(s: &Session, id: ItemId) -> Result<&Sequence> {+ s.project.sequence(id).ok_or(EngineError::NoSequence)+}++/// Start an automation pass at `t` (playback start).+pub fn record_start(s: &mut Session, t: Tick) -> Result<Value> {+ let seq_id = s.state.active_sequence.ok_or(EngineError::NoSequence)?;+ let seq = seq_of(s, seq_id)?;+ let mut gestures = Vec::new();+ for id in seq.strip_ids() {+ let Some(tr) = seq.strip(id) else { continue };+ if tr.mixer.mode != AutomationMode::Write {+ continue;+ }+ for lane in write_lanes(id) {+ let v = underlying(&tr, lane, t);+ let mut g = Gesture::new(id, lane, AutomationMode::Write, t, v);+ g.touching = false;+ gestures.push(g);+ }+ }+ s.previews.live.clear_all();+ for g in &gestures {+ s.previews.live.hold(g.strip, &g.lane, g.value());+ }+ let n = gestures.len();+ s.mixrec = Recorder { seq: Some(seq_id), start: t, gestures };+ Ok(json!({"recording": true, "writing": n}))+}++/// A control moved to `v` at `t`.+pub fn touch(s: &mut Session, strip: TrackId, lane: &str, v: f64, t: Tick) -> Result<Value> {+ let v = clamp_lane(lane, v);+ let seq_id = s.mixrec.seq.or(s.state.active_sequence).ok_or(EngineError::NoSequence)?;+ let mode = seq_of(s, seq_id)?.strip(strip).ok_or_else(|| bad("mixer.touch", "no such strip"))?.mixer.mode;+ s.previews.live.hold(strip, lane, v);+ if !s.mixrec.active() || !mode.writes() {+ return Ok(json!({"recording": false, "value": v}));+ }+ match s.mixrec.find(strip, lane) {+ Some(g) => {+ if !g.touching {+ if g.mode == AutomationMode::Touch {+ // a new touch after a release: the old ramp is overwritten from here+ g.released = None;+ } else if t > g.last.0 {+ // Write / Latch held the last value until this touch+ g.last.0 = (t - HOLD_EPS).max(g.last.0);+ }+ }+ g.touching = true;+ g.push(t, v);+ }+ None => s.mixrec.gestures.push(Gesture::new(strip, lane, mode, t, v)),+ }+ Ok(json!({"recording": true, "value": v}))+}++/// A control let go at `t`.+pub fn release(s: &mut Session, strip: TrackId, lane: &str, t: Tick) -> Result<Value> {+ let automatch = Tick::from_seconds_f64(s.prefs.audio.automatch_time);+ if s.mixrec.active() {+ if let Some(g) = s.mixrec.find(strip, lane) {+ g.touching = false;+ g.push(t, g.value());+ if g.mode == AutomationMode::Touch {+ g.released = Some(t);+ s.previews.live.release(strip, lane, t, automatch);+ }+ // Latch / Write keep holding the last value until playback stops.+ return Ok(json!({"recording": true}));+ }+ s.previews.live.clear(strip, lane);+ return Ok(json!({"recording": false}));+ }+ // no pass: commit the held value once+ let held = s.previews.live.get(strip, lane);+ s.previews.live.clear(strip, lane);+ match held {+ Some(o) => {+ set_value(s, strip, lane, o.value, t)?;+ Ok(json!({"recording": false, "value": o.value}))+ }+ None => Ok(json!({"recording": false})),+ }+}++/// End the pass at `t`: write every gesture as keyframes (one undo step).+pub fn record_stop(s: &mut Session, t_stop: Tick) -> Result<Value> {+ let rec = std::mem::take(&mut s.mixrec);+ let Some(seq_id) = rec.seq.filter(|_| !rec.gestures.is_empty()) else {+ s.previews.live.clear_all();+ return Ok(json!({"recording": false, "lanes": 0}));+ };+ let automatch = Tick::from_seconds_f64(s.prefs.audio.automatch_time);+ let prefs = s.prefs.audio.clone();+ let rate = seq_of(s, seq_id)?.settings.sample_rate.max(1) as i64;+ let eps = Tick::from_units(1, rate).max(Tick(1));+ let min_interval = if prefs.minimum_time_interval_thinning { Tick(prefs.minimum_time_ms as i64 * TICKS_PER_SECOND / 1000) } else { Tick::ZERO };+ let mut written = Vec::new();+ let mut keyframes = 0usize;+ let result = s.edit("Write Automation", |p, _| {+ let seq = p.sequence_mut(seq_id).ok_or(EngineError::NoSequence)?;+ for mut g in rec.gestures {+ if g.points.is_empty() {+ continue;+ }+ let Some(tr) = seq.strip(g.strip).map(|c| c.into_owned()) else { continue };+ let hold = lane_info(&g.lane).is_some_and(|i| i.hold);+ let held = g.value();+ let end = match g.mode {+ AutomationMode::Touch => g.released.unwrap_or(t_stop).min(t_stop.max(g.points[0].0)),+ _ => t_stop,+ };+ g.push(end.max(g.last.0), held);+ g.flush();+ let mut pts = g.points.clone();+ if g.mode == AutomationMode::Touch && automatch.0 > 0 && !hold {+ let back = end + automatch;+ pts.push((back, underlying(&tr, &g.lane, back)));+ }+ let t0 = pts[0].0;+ let t1 = pts.last().map(|p| p.0).unwrap_or(t0);+ let tol = if hold {+ 0.0+ } else if prefs.linear_keyframe_thinning {+ if g.lane == LANE_PAN { 0.25 } else { 0.05 }+ } else {+ 0.0+ };+ let thinned = thin_points(&pts, tol, min_interval, hold);+ let before = (t0.0 > 0).then(|| underlying(&tr, &g.lane, t0 - eps));+ let after = tr.lane(&g.lane).filter(|p| p.keyframes.iter().any(|k| k.time > t1)).map(|_| underlying(&tr, &g.lane, t1 + eps));+ keyframes += thinned.len();+ let lane = g.lane.clone();+ seq.with_strip_mut(g.strip, |tr| {+ if let Some(param) = tr.lane_mut(&lane) {+ write_lane(param, t0, t1, &thinned, before, after, eps, hold);+ }+ });+ written.push(json!({"strip": g.strip.0, "lane": lane, "from": t0.0, "to": t1.0, "keyframes": thinned.len(), "points": pts.len()}));+ }+ if prefs.switch_to_touch_after_write {+ for id in seq.strip_ids() {+ seq.with_strip_mut(id, |tr| {+ if tr.mixer.mode == AutomationMode::Write {+ tr.mixer.mode = AutomationMode::Touch;+ }+ });+ }+ }+ Ok(())+ });+ s.previews.live.clear_all();+ s.previews.live.publish_project(s.project.clone());+ result?;+ Ok(json!({"recording": false, "lanes": written.len(), "keyframes": keyframes, "written": written}))+}++// ------------------------------------------------------------------------------------- helpers++fn active_seq(s: &Session) -> Result<&Sequence> {+ s.active_sequence().ok_or(EngineError::NoSequence)+}++/// Parse a strip reference: id, "A1", "S1", "Mix", or a strip name.+pub fn strip_ref(seq: &Sequence, v: &Value) -> Option<TrackId> {+ if let Some(id) = v.as_u64() {+ let id = TrackId(id);+ return seq.strip(id).map(|_| id);+ }+ let name = v.as_str()?.trim();+ if name.eq_ignore_ascii_case("mix") || name.eq_ignore_ascii_case("master") {+ return Some(MASTER_STRIP);+ }+ let idx = |pre: &str| {+ name.strip_prefix(pre).or_else(|| name.strip_prefix(&pre.to_lowercase())).and_then(|n| n.parse::<usize>().ok()).and_then(|n| n.checked_sub(1))+ };+ if let Some(i) = idx("A") {+ return seq.audio_tracks.get(i).map(|t| t.id);+ }+ if let Some(i) = idx("S") {+ return seq.submix_tracks.get(i).map(|t| t.id);+ }+ seq.audio_tracks.iter().chain(&seq.submix_tracks).find(|t| t.name.eq_ignore_ascii_case(name)).map(|t| t.id)+}++/// Display reference of a strip ("A1", "S2", "Mix").+pub fn strip_label(seq: &Sequence, id: TrackId) -> String {+ if id == MASTER_STRIP {+ return "Mix".into();+ }+ if let Some(i) = seq.audio_tracks.iter().position(|t| t.id == id) {+ return format!("A{}", i + 1);+ }+ if let Some(i) = seq.submix_tracks.iter().position(|t| t.id == id) {+ return format!("S{}", i + 1);+ }+ id.0.to_string()+}++fn strip_p(s: &Session, p: &Value, cmd: &str) -> Result<TrackId> {+ let seq = active_seq(s)?;+ let v = p.get("strip").or_else(|| p.get("track")).ok_or_else(|| bad(cmd, "need `strip` (\"A1\", \"S1\", \"Mix\" or an id)"))?;+ strip_ref(seq, v).ok_or_else(|| bad(cmd, format!("no strip {v}")))+}++fn lane_p(s: &Session, p: &Value, strip: TrackId, cmd: &str) -> Result<String> {+ let lane = str_p(p, "lane").unwrap_or(LANE_VOLUME).to_string();+ let seq = active_seq(s)?;+ let tr = seq.strip(strip).ok_or_else(|| bad(cmd, "no such strip"))?;+ let ok = match parse_fx_lane(&lane) {+ Some((slot, param)) => tr.effects.get(slot).and_then(|e| e.param(param)).is_some_and(|p| p.value.as_f64().is_some()),+ None => lane_info(&lane).is_some() && (parse_send_lane(&lane).is_none_or(|i| i < tr.mixer.sends.len())),+ };+ if !ok {+ return Err(bad(cmd, format!("no lane `{lane}` on this strip (volume, pan, mute, send.<i>.level, fx.<slot>.<param>)")));+ }+ if strip == MASTER_STRIP && (lane == LANE_PAN || lane == LANE_MUTE || parse_send_lane(&lane).is_some()) {+ return Err(bad(cmd, "the Mix track has volume and effect lanes only"));+ }+ Ok(lane)+}++fn value_p(p: &Value, lane: &str, cmd: &str) -> Result<f64> {+ let v = p.get("value").ok_or_else(|| bad(cmd, "need `value`"))?;+ let x = v.as_f64().or_else(|| v.as_bool().map(|b| if b { 1.0 } else { 0.0 })).ok_or_else(|| bad(cmd, "`value` must be a number"))?;+ Ok(clamp_lane(lane, x))+}++/// Set a control outside a recording pass: the static value, or a keyframe at `t` when the lane+/// is automated and the strip reads automation.+pub fn set_value(s: &mut Session, strip: TrackId, lane: &str, v: f64, t: Tick) -> Result<()> {+ let lane = lane.to_string();+ let hold = lane_info(&lane).is_some_and(|i| i.hold);+ s.edit_sequence("Track Mixer Adjust", move |q, _, _| {+ q.with_strip_mut(strip, |tr| {+ let animated = tr.lane(&lane).is_some_and(Param::is_animated) && tr.mixer.mode.reads();+ if animated {+ if let Some(p) = tr.lane_mut(&lane) {+ set_keyframe(p, t, v, hold);+ }+ } else {+ tr.set_lane_static(&lane, v);+ }+ })+ .ok_or_else(|| EngineError::Other("no such strip".into()))+ })+}++fn set_keyframe(p: &mut Param, t: Tick, v: f64, hold: bool) {+ p.put_keyframe(t, ParamValue::Float(v));+ if hold {+ for k in p.keyframes.iter_mut() {+ k.interp = filmcraft_project::Interpolation::Hold;+ }+ }+}++fn mode_p(p: &Value) -> Option<AutomationMode> {+ str_p(p, "mode").and_then(AutomationMode::from_name)+}++fn channels_name(c: AudioChannels) -> &'static str {+ match c {+ AudioChannels::Mono => "Mono",+ AudioChannels::Stereo => "Stereo",+ AudioChannels::Surround51 => "5.1",+ AudioChannels::Adaptive => "Adaptive",+ }+}++fn channels_from(s: &str) -> Option<AudioChannels> {+ match s.to_ascii_lowercase().as_str() {+ "mono" => Some(AudioChannels::Mono),+ "stereo" => Some(AudioChannels::Stereo),+ "5.1" | "surround51" => Some(AudioChannels::Surround51),+ "adaptive" => Some(AudioChannels::Adaptive),+ _ => None,+ }+}++/// JSON view of one strip at time `t`.+pub fn strip_json(s: &Session, seq: &Sequence, id: TrackId, t: Tick) -> Value {+ let Some(tr) = seq.strip(id) else { return Value::Null };+ let live = &s.previews.live;+ let shown = |lane: &str| live.get(id, lane).map(|o| o.value).unwrap_or_else(|| underlying(&tr, lane, t));+ let lanes: serde_json::Map<String, Value> = tr+ .automated_lanes()+ .into_iter()+ .map(|k| {+ let kf: Vec<Value> = tr.lane_keyframes(&k).iter().map(|kf| json!([kf.time.0, kf.value.as_f64()])).collect();+ (k, Value::Array(kf))+ })+ .collect();+ let kind = if id == MASTER_STRIP {+ "mix"+ } else if seq.submix_tracks.iter().any(|t| t.id == id) {+ "submix"+ } else {+ "audio"+ };+ json!({+ "id": id.0,+ "ref": strip_label(seq, id),+ "name": tr.name,+ "kind": kind,+ "channels": channels_name(tr.channels),+ "mode": tr.mixer.mode.label(),+ "volumeDb": tr.volume_db,+ "pan": tr.pan,+ "muted": tr.muted,+ "solo": tr.solo,+ "recordArm": tr.mixer.record_arm,+ "soloSafe": tr.mixer.solo_safe,+ "inputMap": tr.mixer.input_map.label(),+ "output": tr.mixer.output.map(|o| strip_label(seq, o)).unwrap_or_else(|| if id == MASTER_STRIP { String::new() } else { "Mix".into() }),+ "inserts": tr.effects.iter().enumerate().map(|(i, e)| json!({"slot": i, "effect": e.effect, "name": e.def().map(|d| d.name).unwrap_or(""), "enabled": e.enabled, "postFader": e.post_fader})).collect::<Vec<_>>(),+ "sends": tr.mixer.sends.iter().enumerate().map(|(i, sd)| json!({"send": i, "target": strip_label(seq, sd.target), "levelDb": sd.level_db, "pan": sd.pan, "preFader": sd.pre_fader, "muted": sd.muted})).collect::<Vec<_>>(),+ "at": {"time": t.0, "volumeDb": shown(LANE_VOLUME), "pan": shown(LANE_PAN), "mute": shown(LANE_MUTE) >= 0.5},+ "lanes": lanes,+ })+}++fn inspect(s: &mut Session, p: &Value) -> Result<Value> {+ let t = time_p(s, p, "").unwrap_or(s.playhead());+ let seq = active_seq(s)?;+ let strips: Vec<Value> = seq.strip_ids().into_iter().map(|id| strip_json(s, seq, id, t)).collect();+ Ok(json!({+ "strips": strips,+ "recording": s.mixrec.active(),+ "gestures": s.mixrec.gestures.iter().map(|g| json!({"strip": strip_label(seq, g.strip), "lane": g.lane, "mode": g.mode.label(), "touching": g.touching, "points": g.points.len(), "value": g.value()})).collect::<Vec<_>>(),+ "latencySamples": filmcraft_render::mixer::graph_latency(seq),+ "automatchTime": s.prefs.audio.automatch_time,+ }))+}++fn set_strip(s: &mut Session, p: &Value) -> Result<Value> {+ let id = strip_p(s, p, "mixer.setStrip")?;+ let seq = active_seq(s)?;+ let output = match p.get("output") {+ None => None,+ Some(Value::Null) => Some(None),+ Some(v) => {+ let o = strip_ref(seq, v).ok_or_else(|| bad("mixer.setStrip", format!("no output {v}")))?;+ if o == MASTER_STRIP {+ Some(None)+ } else if o == id || !seq.submix_tracks.iter().any(|t| t.id == o) {+ return Err(bad("mixer.setStrip", "output must be the Mix or a submix"));+ } else if seq+ .submix_tracks+ .iter()+ .position(|t| t.id == id)+ .is_some_and(|me| seq.submix_tracks.iter().position(|t| t.id == o).is_some_and(|it| it <= me))+ {+ return Err(bad("mixer.setStrip", "a submix can only feed a submix after it (no feedback)"));+ } else {+ Some(Some(o))+ }+ }+ };+ let p = p.clone();+ s.edit_sequence("Track Mixer Settings", move |q, _, _| {+ q.with_strip_mut(id, |t| {+ if let Some(v) = str_p(&p, "name") {+ t.name = v.to_string();+ }+ if let Some(v) = f64_p(&p, "volumeDb") {+ t.volume_db = v.clamp(FADER_MIN_DB, FADER_MAX_DB);+ }+ if let Some(v) = f64_p(&p, "pan") {+ t.pan = v.clamp(-100.0, 100.0);+ }+ if let Some(v) = bool_p(&p, "muted") {+ t.muted = v;+ }+ if let Some(v) = bool_p(&p, "solo") {+ t.solo = v;+ }+ if let Some(v) = bool_p(&p, "recordArm") {+ t.mixer.record_arm = v;+ }+ if let Some(v) = bool_p(&p, "soloSafe") {+ t.mixer.solo_safe = v;+ }+ if let Some(m) = mode_p(&p) {+ t.mixer.mode = m;+ }+ if let Some(m) = str_p(&p, "inputMap").and_then(InputMap::from_name) {+ t.mixer.input_map = m;+ }+ if let Some(c) = str_p(&p, "channels").and_then(channels_from) {+ t.channels = c;+ }+ if let Some(o) = output {+ t.mixer.output = o;+ }+ })+ .ok_or_else(|| EngineError::Other("no such strip".into()))+ })?;+ let seq = active_seq(s)?;+ Ok(strip_json(s, seq, id, s.playhead()))+}++fn add_submix(s: &mut Session, p: &Value) -> Result<Value> {+ let name = str_p(p, "name").map(str::to_string);+ let channels = str_p(p, "channels").and_then(channels_from).unwrap_or(AudioChannels::Stereo);+ let seq_id = s.state.active_sequence.ok_or(EngineError::NoSequence)?;+ let id = s.edit("Add Submix Track", |pr, _| {+ let id = TrackId(pr.alloc_id());+ let seq = pr.sequence_mut(seq_id).ok_or(EngineError::NoSequence)?;+ let n = seq.submix_tracks.len() + 1;+ let mut t = Track::new(id, TrackKind::Audio, name.unwrap_or_else(|| format!("Submix {n}")));+ t.channels = channels;+ seq.submix_tracks.push(t);+ Ok(id)+ })?;+ let seq = active_seq(s)?;+ Ok(json!({"id": id.0, "ref": strip_label(seq, id)}))+}++fn delete_submix(s: &mut Session, p: &Value) -> Result<Value> {+ let id = strip_p(s, p, "mixer.deleteSubmix")?;+ if !active_seq(s)?.submix_tracks.iter().any(|t| t.id == id) {+ return Err(bad("mixer.deleteSubmix", "not a submix"));+ }+ s.edit_sequence("Delete Submix Track", move |q, _, _| {+ q.submix_tracks.retain(|t| t.id != id);+ // re-route everything that fed it to the Mix and drop sends to it+ for sid in q.strip_ids() {+ q.with_strip_mut(sid, |t| {+ if t.mixer.output == Some(id) {+ t.mixer.output = None;+ }+ while let Some(i) = t.mixer.sends.iter().position(|sd| sd.target == id) {+ t.remove_send(i);+ }+ });+ }+ Ok(())+ })?;+ Ok(Value::Null)+}++fn slot_p(p: &Value, cmd: &str) -> Result<usize> {+ u64_p(p, "slot").map(|v| v as usize).ok_or_else(|| bad(cmd, "need `slot` (0-based)"))+}++fn add_insert(s: &mut Session, p: &Value) -> Result<Value> {+ let id = strip_p(s, p, "mixer.addInsert")?;+ let eid = str_p(p, "effect").ok_or_else(|| bad("mixer.addInsert", "need `effect` (an audio effect id)"))?;+ let def = find_effect(eid)+ .filter(|d| d.kind == filmcraft_project::EffectKind::Audio && !d.intrinsic)+ .ok_or_else(|| bad("mixer.addInsert", format!("`{eid}` is not an audio effect")))?;+ let mut inst = def.instance();+ inst.post_fader = bool_p(p, "postFader").unwrap_or(false);+ let slot = u64_p(p, "slot").map(|v| v as usize);+ let n = active_seq(s)?.strip(id).map(|t| t.effects.len()).unwrap_or(0);+ if n >= pm::MAX_INSERTS {+ return Err(bad("mixer.addInsert", format!("all {} effect slots are in use", pm::MAX_INSERTS)));+ }+ let at = slot.unwrap_or(n).min(n);+ s.edit_sequence(&format!("Add Track Effect {}", def.name), move |q, _, _| {+ q.with_strip_mut(id, |t| t.effects.insert(at, inst)).ok_or_else(|| EngineError::Other("no such strip".into()))+ })?;+ Ok(json!({"slot": at}))+}++fn remove_insert(s: &mut Session, p: &Value) -> Result<Value> {+ let id = strip_p(s, p, "mixer.removeInsert")?;+ let slot = slot_p(p, "mixer.removeInsert")?;+ let ok = s.edit_sequence("Remove Track Effect", move |q, _, _| Ok(q.with_strip_mut(id, |t| t.remove_insert(slot)).unwrap_or(false)))?;+ if !ok {+ return Err(bad("mixer.removeInsert", "no effect in that slot"));+ }+ Ok(Value::Null)+}++fn set_insert(s: &mut Session, p: &Value) -> Result<Value> {+ let id = strip_p(s, p, "mixer.setInsert")?;+ let slot = slot_p(p, "mixer.setInsert")?;+ let p = p.clone();+ s.edit_sequence("Track Effect Settings", move |q, _, _| {+ q.with_strip_mut(id, |t| -> Result<()> {+ let e = t.effects.get_mut(slot).ok_or_else(|| bad("mixer.setInsert", "no effect in that slot"))?;+ if let Some(v) = bool_p(&p, "enabled") {+ e.enabled = v;+ }+ if let Some(v) = bool_p(&p, "postFader") {+ e.post_fader = v;+ }+ if let Some(obj) = p.get("params").and_then(Value::as_object) {+ for (k, v) in obj {+ let par = e.param_mut(k).ok_or_else(|| bad("mixer.setInsert", format!("no parameter `{k}`")))?;+ par.value = match (&par.value, v) {+ (ParamValue::Bool(_), Value::Bool(b)) => ParamValue::Bool(*b),+ (ParamValue::Choice(_), v) => ParamValue::Choice(v.as_u64().unwrap_or(0) as u32),+ (_, v) => ParamValue::Float(v.as_f64().ok_or_else(|| bad("mixer.setInsert", format!("`{k}` needs a number")))?),+ };+ }+ }+ Ok(())+ })+ .ok_or_else(|| EngineError::Other("no such strip".into()))?+ })?;+ Ok(Value::Null)+}++fn send_target(s: &Session, p: &Value, id: TrackId, cmd: &str) -> Result<TrackId> {+ let seq = active_seq(s)?;+ let v = p.get("target").ok_or_else(|| bad(cmd, "need `target` (a submix)"))?;+ let t = strip_ref(seq, v).filter(|t| seq.submix_tracks.iter().any(|x| x.id == *t)).ok_or_else(|| bad(cmd, "`target` must be a submix"))?;+ let pos = |x: TrackId| seq.submix_tracks.iter().position(|y| y.id == x);+ if t == id || pos(id).is_some_and(|me| pos(t).is_some_and(|it| it <= me)) {+ return Err(bad(cmd, "a submix can only send to a submix after it (no feedback)"));+ }+ Ok(t)+}++fn add_send(s: &mut Session, p: &Value) -> Result<Value> {+ let id = strip_p(s, p, "mixer.addSend")?;+ if id == MASTER_STRIP {+ return Err(bad("mixer.addSend", "the Mix track has no sends"));+ }+ let target = send_target(s, p, id, "mixer.addSend")?;+ let mut snd = TrackSend::new(target);+ snd.level_db = f64_p(p, "levelDb").unwrap_or(0.0).clamp(FADER_MIN_DB, FADER_MAX_DB);+ snd.pre_fader = bool_p(p, "preFader").unwrap_or(false);+ snd.pan = f64_p(p, "pan").unwrap_or(0.0).clamp(-100.0, 100.0);+ if active_seq(s)?.strip(id).is_some_and(|t| t.mixer.sends.len() >= pm::MAX_SENDS) {+ return Err(bad("mixer.addSend", format!("all {} send slots are in use", pm::MAX_SENDS)));+ }+ let i = s.edit_sequence("Add Send", move |q, _, _| {+ q.with_strip_mut(id, |t| {+ t.mixer.sends.push(snd);+ t.mixer.sends.len() - 1+ })+ .ok_or_else(|| EngineError::Other("no such strip".into()))+ })?;+ Ok(json!({"send": i}))+}++fn set_send(s: &mut Session, p: &Value) -> Result<Value> {+ let id = strip_p(s, p, "mixer.setSend")?;+ let i = u64_p(p, "send").ok_or_else(|| bad("mixer.setSend", "need `send` (0-based)"))? as usize;+ let target = if p.get("target").is_some() { Some(send_target(s, p, id, "mixer.setSend")?) } else { None };+ let p = p.clone();+ s.edit_sequence("Send Settings", move |q, _, _| {+ q.with_strip_mut(id, |t| -> Result<()> {+ let sd = t.mixer.sends.get_mut(i).ok_or_else(|| bad("mixer.setSend", "no such send"))?;+ if let Some(v) = f64_p(&p, "levelDb") {+ sd.level_db = v.clamp(FADER_MIN_DB, FADER_MAX_DB);+ }+ if let Some(v) = f64_p(&p, "pan") {+ sd.pan = v.clamp(-100.0, 100.0);+ }+ if let Some(v) = bool_p(&p, "preFader") {+ sd.pre_fader = v;+ }+ if let Some(v) = bool_p(&p, "muted") {+ sd.muted = v;+ }+ if let Some(t) = target {+ sd.target = t;+ }+ Ok(())+ })+ .ok_or_else(|| EngineError::Other("no such strip".into()))?+ })?;+ Ok(Value::Null)+}++fn remove_send(s: &mut Session, p: &Value) -> Result<Value> {+ let id = strip_p(s, p, "mixer.removeSend")?;+ let i = u64_p(p, "send").ok_or_else(|| bad("mixer.removeSend", "need `send` (0-based)"))? as usize;+ let ok = s.edit_sequence("Remove Send", move |q, _, _| Ok(q.with_strip_mut(id, |t| t.remove_send(i)).unwrap_or(false)))?;+ if !ok {+ return Err(bad("mixer.removeSend", "no such send"));+ }+ Ok(Value::Null)+}++fn set_kf(s: &mut Session, p: &Value) -> Result<Value> {+ let id = strip_p(s, p, "mixer.setKeyframe")?;+ let lane = lane_p(s, p, id, "mixer.setKeyframe")?;+ let t = time_p(s, p, "").unwrap_or(s.playhead());+ let v = value_p(p, &lane, "mixer.setKeyframe")?;+ let hold = lane_info(&lane).is_some_and(|i| i.hold);+ s.edit_sequence("Add Track Keyframe", move |q, _, _| {+ q.with_strip_mut(id, |tr| {+ if let Some(par) = tr.lane_mut(&lane) {+ if par.keyframes.is_empty() {+ // the first keyframe keeps the current value everywhere else+ let cur = par.value.as_f64().unwrap_or(v);+ par.value = ParamValue::Float(cur);+ }+ set_keyframe(par, t, v, hold);+ }+ })+ .ok_or_else(|| EngineError::Other("no such strip".into()))+ })?;+ Ok(json!({"time": t.0, "value": v}))+}++fn delete_kf(s: &mut Session, p: &Value) -> Result<Value> {+ let id = strip_p(s, p, "mixer.deleteKeyframe")?;+ let lane = lane_p(s, p, id, "mixer.deleteKeyframe")?;+ let t = time_p(s, p, "").ok_or_else(|| bad("mixer.deleteKeyframe", "need `time`"))?;+ let ok = s.edit_sequence("Delete Track Keyframe", move |q, _, _| {+ Ok(q.with_strip_mut(id, |tr| tr.lane_mut(&lane).is_some_and(|par| par.remove_keyframe_at(t))).unwrap_or(false))+ })?;+ if !ok {+ return Err(bad("mixer.deleteKeyframe", "no keyframe at that time"));+ }+ Ok(Value::Null)+}++fn move_kf(s: &mut Session, p: &Value) -> Result<Value> {+ let id = strip_p(s, p, "mixer.moveKeyframe")?;+ let lane = lane_p(s, p, id, "mixer.moveKeyframe")?;+ let t = time_p(s, p, "").ok_or_else(|| bad("mixer.moveKeyframe", "need `time` (the keyframe)"))?;+ let nt = time_p(s, p, "new");+ let nv = p.get("value").map(|_| value_p(p, &lane, "mixer.moveKeyframe")).transpose()?;+ let ok = s.edit_sequence("Move Track Keyframe", move |q, _, _| {+ Ok(q.with_strip_mut(id, |tr| {+ let Some(par) = tr.lane_mut(&lane) else { return false };+ let Ok(i) = par.keyframes.binary_search_by_key(&t, |k| k.time) else { return false };+ let mut k = par.keyframes.remove(i);+ if let Some(nt) = nt {+ // keep keyframe order: clamp between the neighbours+ let lo = i.checked_sub(1).map(|j| par.keyframes[j].time + Tick(1)).unwrap_or(Tick::ZERO);+ let hi = par.keyframes.get(i).map(|n| n.time - Tick(1)).unwrap_or(Tick(i64::MAX));+ k.time = nt.clamp(lo, hi);+ }+ if let Some(v) = nv {+ k.value = ParamValue::Float(v);+ }+ let j = par.keyframes.partition_point(|x| x.time < k.time);+ par.keyframes.insert(j, k);+ true+ })+ .unwrap_or(false))+ })?;+ if !ok {+ return Err(bad("mixer.moveKeyframe", "no keyframe at that time"));+ }+ Ok(Value::Null)+}++fn clear_lane(s: &mut Session, p: &Value) -> Result<Value> {+ let id = strip_p(s, p, "mixer.clearLane")?;+ let lane = lane_p(s, p, id, "mixer.clearLane")?;+ let t = s.playhead();+ s.edit_sequence("Clear Track Keyframes", move |q, _, _| {+ q.with_strip_mut(id, |tr| {+ let v = tr.lane_value(&lane, t);+ if let Some(par) = tr.lane_mut(&lane) {+ par.keyframes.clear();+ }+ tr.set_lane_static(&lane, v);+ if parse_fx_lane(&lane).is_none() {+ tr.mixer.lanes.remove(&lane);+ }+ })+ .ok_or_else(|| EngineError::Other("no such strip".into()))+ })?;+ Ok(Value::Null)+}++fn write_automation(s: &mut Session, p: &Value) -> Result<Value> {+ let id = strip_p(s, p, "mixer.writeAutomation")?;+ let lane = lane_p(s, p, id, "mixer.writeAutomation")?;+ let pts: Vec<(Tick, f64)> = p+ .get("points")+ .and_then(Value::as_array)+ .ok_or_else(|| bad("mixer.writeAutomation", "need `points`: [[ticks, value], …]"))?+ .iter()+ .filter_map(|v| Some((Tick(v.get(0)?.as_i64()?), clamp_lane(&lane, v.get(1)?.as_f64()?))))+ .collect();+ if pts.is_empty() {+ return Err(bad("mixer.writeAutomation", "no points"));+ }+ let hold = lane_info(&lane).is_some_and(|i| i.hold);+ let tol = f64_p(p, "tolerance").unwrap_or(if hold { 0.0 } else { 0.05 });+ let thinned = thin_points(&pts, tol, Tick::ZERO, hold);+ let (t0, t1) = (thinned[0].0, thinned[thinned.len() - 1].0);+ let rate = active_seq(s)?.settings.sample_rate.max(1) as i64;+ let eps = Tick::from_units(1, rate).max(Tick(1));+ let n = thinned.len();+ s.edit_sequence("Write Automation", move |q, _, _| {+ q.with_strip_mut(id, |tr| {+ let before = (t0.0 > 0).then(|| underlying(tr, &lane, t0 - eps));+ let after = tr.lane(&lane).filter(|p| p.keyframes.iter().any(|k| k.time > t1)).map(|_| underlying(tr, &lane, t1 + eps));+ if let Some(par) = tr.lane_mut(&lane) {+ write_lane(par, t0, t1, &thinned, before, after, eps, hold);+ }+ })+ .ok_or_else(|| EngineError::Other("no such strip".into()))+ })?;+ Ok(json!({"keyframes": n, "points": pts.len()}))+}++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(()) }+}++fn spec(+ id: &'static str,+ label: &'static str,+ menu: &'static [&'static str],+ shortcut: Option<&'static str>,+ params: &'static str,+ enabled: Enabled,+ run: Run,+ journal: bool,+) -> CommandSpec {+ CommandSpec { id, label, menu, shortcut, params, enabled, run, journal }+}++pub fn commands() -> Vec<CommandSpec> {+ vec![+ spec("mixer.inspect", "Inspect Audio Track Mixer", &[], None, r#"{"time":ticks?}"#, always, inspect, false),+ spec(+ "mixer.setStrip",+ "Track Mixer Settings",+ &[],+ None,+ r#"{"strip":"A1"|"S1"|"Mix"|id,"name":str?,"volumeDb":f64?,"pan":f64?,"muted":bool?,"solo":bool?,"recordArm":bool?,"soloSafe":bool?,"mode":"Off|Read|Latch|Touch|Write"?,"output":"Mix"|"S1"?,"inputMap":"Stereo|Left|Right|Swap|Mono"?,"channels":"Mono|Stereo|5.1"?}"#,+ has_seq,+ set_strip,+ true,+ ),+ spec(+ "mixer.setValue",+ "Set Mixer Control",+ &[],+ None,+ r#"{"strip":"A1"|"S1"|"Mix"|id,"lane":"volume|pan|mute|send.<i>.level|fx.<slot>.<param>","value":f64,"time":ticks?}"#,+ has_seq,+ |s, p| {+ let id = strip_p(s, p, "mixer.setValue")?;+ let lane = lane_p(s, p, id, "mixer.setValue")?;+ let v = value_p(p, &lane, "mixer.setValue")?;+ let t = time_p(s, p, "").unwrap_or(s.playhead());+ if s.mixrec.active() {+ touch(s, id, &lane, v, t)?;+ return release(s, id, &lane, t);+ }+ set_value(s, id, &lane, v, t)?;+ Ok(json!({"value": v}))+ },+ true,+ ),+ spec(+ "mixer.touch",+ "Touch Mixer Control",+ &[],+ None,+ r#"{"strip":"A1"|"S1"|"Mix"|id,"lane":"volume|pan|mute|send.<i>.level|fx.<slot>.<param>","value":f64,"time":ticks?}"#,+ has_seq,+ |s, p| {+ let id = strip_p(s, p, "mixer.touch")?;+ let lane = lane_p(s, p, id, "mixer.touch")?;+ let v = value_p(p, &lane, "mixer.touch")?;+ let t = time_p(s, p, "").unwrap_or(s.playhead());+ touch(s, id, &lane, v, t)+ },+ false,+ ),+ spec(+ "mixer.release",+ "Release Mixer Control",+ &[],+ None,+ r#"{"strip":"A1"|"S1"|"Mix"|id,"lane":str?,"time":ticks?}"#,+ has_seq,+ |s, p| {+ let id = strip_p(s, p, "mixer.release")?;+ let lane = lane_p(s, p, id, "mixer.release")?;+ let t = time_p(s, p, "").unwrap_or(s.playhead());+ release(s, id, &lane, t)+ },+ true,+ ),+ spec(+ "mixer.recordStart",+ "Start Automation Pass",+ &[],+ None,+ r#"{"time":ticks?}"#,+ not_recording,+ |s, p| {+ let t = time_p(s, p, "").unwrap_or(s.playhead());+ record_start(s, t)+ },+ false,+ ),+ spec(+ "mixer.recordStop",+ "Write Automation",+ &[],+ None,+ r#"{"time":ticks?}"#,+ has_seq,+ |s, p| {+ let t = time_p(s, p, "").unwrap_or(s.playhead());+ record_stop(s, t)+ },+ 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(+ "mixer.addInsert",+ "Add Track Effect",+ &[],+ None,+ r#"{"strip":"A1"|"S1"|"Mix"|id,"effect":str,"slot":n?,"postFader":bool?}"#,+ has_seq,+ add_insert,+ true,+ ),+ spec("mixer.removeInsert", "Remove Track Effect", &[], None, r#"{"strip":"A1"|"S1"|"Mix"|id,"slot":n}"#, has_seq, remove_insert, true),+ spec(+ "mixer.setInsert",+ "Track Effect Settings",+ &[],+ None,+ r#"{"strip":"A1"|"S1"|"Mix"|id,"slot":n,"enabled":bool?,"postFader":bool?,"params":{id:value}?}"#,+ has_seq,+ set_insert,+ true,+ ),+ spec(+ "mixer.addSend",+ "Add Send",+ &[],+ None,+ r#"{"strip":"A1"|"S1"|id,"target":"S1"|id,"levelDb":f64?,"preFader":bool?,"pan":f64?}"#,+ has_seq,+ add_send,+ true,+ ),+ spec(+ "mixer.setSend",+ "Send Settings",+ &[],+ None,+ r#"{"strip":"A1"|"S1"|id,"send":n,"levelDb":f64?,"pan":f64?,"preFader":bool?,"muted":bool?,"target":"S1"?}"#,+ has_seq,+ set_send,+ true,+ ),+ spec("mixer.removeSend", "Remove Send", &[], None, r#"{"strip":"A1"|"S1"|id,"send":n}"#, has_seq, remove_send, true),+ spec(+ "mixer.setKeyframe",+ "Add Track Keyframe",+ &[],+ None,+ r#"{"strip":"A1"|"S1"|"Mix"|id,"lane":str?,"time":ticks?,"value":f64}"#,+ has_seq,+ set_kf,+ true,+ ),+ spec("mixer.deleteKeyframe", "Delete Track Keyframe", &[], None, r#"{"strip":"A1"|"S1"|"Mix"|id,"lane":str?,"time":ticks}"#, has_seq, delete_kf, true),+ spec(+ "mixer.moveKeyframe",+ "Move Track Keyframe",+ &[],+ None,+ r#"{"strip":"A1"|"S1"|"Mix"|id,"lane":str?,"time":ticks,"newTime":ticks?,"value":f64?}"#,+ has_seq,+ move_kf,+ true,+ ),+ spec("mixer.clearLane", "Clear Track Keyframes", &[], None, r#"{"strip":"A1"|"S1"|"Mix"|id,"lane":str?}"#, has_seq, clear_lane, true),+ spec(+ "mixer.writeAutomation",+ "Write Automation Points",+ &[],+ None,+ r#"{"strip":"A1"|"S1"|"Mix"|id,"lane":str?,"points":[[ticks,value]],"tolerance":f64?}"#,+ has_seq,+ write_automation,+ true,+ ),+ ]+}diff --git a/crates/engine/src/mixer_tests.rs b/crates/engine/src/mixer_tests.rsnew file mode 100644index 000000000..24c44d80c--- /dev/null+++ b/crates/engine/src/mixer_tests.rs@@ -0,0 +1,282 @@+//! Audio Track Mixer commands and automation recording.++use super::*;+use filmcraft_project::mixer::{LANE_VOLUME, MASTER_STRIP};+use filmcraft_project::{AutomationMode, ParamValue};+use filmcraft_time::TICKS_PER_SECOND;+use serde_json::json;++fn demo() -> Session {+ let mut s = Session::default();+ s.execute("file.openDemoProject", json!({})).unwrap();+ s+}++fn sec(x: f64) -> i64 {+ (x * TICKS_PER_SECOND as f64) as i64+}++fn a1(s: &Session) -> &filmcraft_project::Track {+ &s.active_sequence().unwrap().audio_tracks[0]+}++fn vol_at(s: &Session, x: f64) -> f64 {+ a1(s).lane_value(LANE_VOLUME, Tick(sec(x)))+}++fn set_mode(s: &mut Session, strip: &str, mode: &str) {+ s.execute("mixer.setStrip", json!({"strip": strip, "mode": mode})).unwrap();+}++#[test]+fn every_mixer_command_is_registered_with_a_label() {+ for id in [+ "mixer.inspect",+ "mixer.setStrip",+ "mixer.setValue",+ "mixer.touch",+ "mixer.release",+ "mixer.recordStart",+ "mixer.recordStop",+ "mixer.addSubmix",+ "mixer.deleteSubmix",+ "mixer.addInsert",+ "mixer.removeInsert",+ "mixer.setInsert",+ "mixer.addSend",+ "mixer.setSend",+ "mixer.removeSend",+ "mixer.setKeyframe",+ "mixer.deleteKeyframe",+ "mixer.moveKeyframe",+ "mixer.clearLane",+ "mixer.writeAutomation",+ ] {+ let c = commands::find(id).unwrap_or_else(|| panic!("{id} missing"));+ assert!(!c.label.is_empty() && !c.params.is_empty());+ }+ let s = Session::default();+ assert!(s.clone_disabled("mixer.setStrip"), "needs a sequence");+}++impl Session {+ fn clone_disabled(&self, id: &str) -> bool {+ !self.is_enabled(id)+ }+}++#[test]+fn strip_settings_undo_redo_and_inspect() {+ let mut s = demo();+ s.execute("mixer.setStrip", json!({"strip": "A1", "volumeDb": -6.0, "pan": -30.0, "mode": "Touch", "recordArm": true, "solo": true})).unwrap();+ let t = a1(&s);+ assert_eq!((t.volume_db, t.pan, t.mixer.mode, t.mixer.record_arm, t.solo), (-6.0, -30.0, AutomationMode::Touch, true, true));+ s.execute("mixer.setStrip", json!({"strip": "Mix", "volumeDb": -3.0})).unwrap();+ assert_eq!(s.active_sequence().unwrap().master_volume_db, -3.0);+ s.execute("edit.undo", json!({})).unwrap();+ s.execute("edit.undo", json!({})).unwrap();+ assert_eq!(a1(&s).volume_db, 0.0);+ s.execute("edit.redo", json!({})).unwrap();+ assert_eq!(a1(&s).volume_db, -6.0);+ let v = s.execute("mixer.inspect", json!({})).unwrap();+ let strips = v["strips"].as_array().unwrap();+ assert_eq!(strips.last().unwrap()["ref"], "Mix");+ assert_eq!(strips[0]["ref"], "A1");+ assert_eq!(strips[0]["mode"], "Touch");+ // errors+ assert!(s.execute("mixer.setStrip", json!({"strip": "A99"})).is_err());+ assert!(s.execute("mixer.setValue", json!({"strip": "Mix", "lane": "pan", "value": 3})).is_err(), "Mix has no pan");+}++#[test]+fn submixes_sends_and_inserts() {+ let mut s = demo();+ let r = s.execute("mixer.addSubmix", json!({"name": "Reverb"})).unwrap();+ assert_eq!(r["ref"], "S1");+ s.execute("mixer.addSubmix", json!({})).unwrap();+ s.execute("mixer.addSend", json!({"strip": "A1", "target": "S1", "levelDb": -6.0, "preFader": true})).unwrap();+ s.execute("mixer.addInsert", json!({"strip": "S1", "effect": "studio_reverb"})).unwrap();+ s.execute("mixer.addInsert", json!({"strip": "A1", "effect": "dynamics", "postFader": true})).unwrap();+ s.execute("mixer.setInsert", json!({"strip": "A1", "slot": 0, "params": {"threshold": -30.0}})).unwrap();+ s.execute("mixer.setStrip", json!({"strip": "S1", "output": "S2"})).unwrap();+ assert!(s.execute("mixer.setStrip", json!({"strip": "S2", "output": "S1"})).is_err(), "no feedback");+ assert!(s.execute("mixer.addSend", json!({"strip": "S2", "target": "S1"})).is_err(), "no feedback");+ assert!(s.execute("mixer.addInsert", json!({"strip": "A1", "effect": "gaussian_blur"})).is_err());+ let q = s.active_sequence().unwrap();+ assert_eq!(q.audio_tracks[0].mixer.sends[0].level_db, -6.0);+ assert!(q.audio_tracks[0].effects[0].post_fader);+ assert_eq!(q.audio_tracks[0].effects[0].param("threshold").unwrap().value, ParamValue::Float(-30.0));+ // the mix renders through the graph (the demo has audio on A1)+ let provider = s.media.provider(s.project.clone(), s.services.clone());+ let b = filmcraft_render::audio::mix_sequence(&s.project, q, 0, 4_800, &provider);+ assert_eq!(b.frames(), 4_800);+ // deleting a submix re-routes and drops sends+ let s1 = q.submix_tracks[0].id.0;+ s.execute("mixer.deleteSubmix", json!({"strip": s1})).unwrap();+ let q = s.active_sequence().unwrap();+ assert!(q.audio_tracks[0].mixer.sends.is_empty());+ assert_eq!(q.submix_tracks.len(), 1);+ s.execute("mixer.removeInsert", json!({"strip": "A1", "slot": 0})).unwrap();+ assert!(a1(&s).effects.is_empty());+}++#[test]+fn keyframes_by_command_and_pen_edits() {+ let mut s = demo();+ s.execute("mixer.setKeyframe", json!({"strip": "A1", "time": sec(1.0), "value": -10.0})).unwrap();+ s.execute("mixer.setKeyframe", json!({"strip": "A1", "time": sec(2.0), "value": 0.0})).unwrap();+ assert_eq!(vol_at(&s, 0.0), -10.0);+ assert!((vol_at(&s, 1.5) + 5.0).abs() < 1e-9);+ s.execute("mixer.moveKeyframe", json!({"strip": "A1", "time": sec(2.0), "newTime": sec(3.0), "value": -20.0})).unwrap();+ assert!((vol_at(&s, 2.0) + 15.0).abs() < 1e-9);+ s.execute("mixer.deleteKeyframe", json!({"strip": "A1", "time": sec(1.0)})).unwrap();+ assert_eq!(vol_at(&s, 0.0), -20.0);+ // a fader move on an automated lane (Read, stopped) adds a keyframe at the playhead+ s.execute("playhead.set", json!({"seconds": 5.0})).unwrap();+ s.execute("mixer.setValue", json!({"strip": "A1", "value": -3.0})).unwrap();+ assert_eq!(vol_at(&s, 5.0), -3.0);+ assert_eq!(a1(&s).lane_keyframes(LANE_VOLUME).len(), 2);+ // mute keyframes hold+ s.execute("mixer.setKeyframe", json!({"strip": "A1", "lane": "mute", "time": sec(1.0), "value": true})).unwrap();+ s.execute("mixer.setKeyframe", json!({"strip": "A1", "lane": "mute", "time": sec(2.0), "value": false})).unwrap();+ assert_eq!(a1(&s).lane_value("mute", Tick(sec(1.9))), 1.0);+ s.execute("mixer.clearLane", json!({"strip": "A1", "lane": "volume"})).unwrap();+ assert!(a1(&s).lane_keyframes(LANE_VOLUME).is_empty());+ // effect parameter lanes+ s.execute("mixer.addInsert", json!({"strip": "A1", "effect": "amplify"})).unwrap();+ s.execute("mixer.setKeyframe", json!({"strip": "A1", "lane": "fx.0.gain", "time": sec(1.0), "value": 6.0})).unwrap();+ assert!(a1(&s).automated_lanes().contains(&"fx.0.gain".to_string()));+}++/// Simulate a fader gesture: `(seconds, dB)` samples as the UI would send them each frame.+fn gesture(s: &mut Session, strip: &str, pts: &[(f64, f64)]) {+ for &(t, v) in pts {+ s.execute("mixer.touch", json!({"strip": strip, "lane": "volume", "value": v, "time": sec(t)})).unwrap();+ }+}++#[test]+fn touch_records_while_held_and_returns_over_automatch() {+ let mut s = demo();+ set_mode(&mut s, "A1", "Touch");+ s.execute("mixer.recordStart", json!({"time": 0})).unwrap();+ assert!(s.execute("mixer.recordStart", json!({})).is_err(), "already recording");+ // hold -10 dB from 1 s to 2 s (frames every 1/30 s)+ let pts: Vec<(f64, f64)> = (0..=30).map(|i| (1.0 + i as f64 / 30.0, -10.0)).collect();+ gesture(&mut s, "A1", &pts);+ // the audio follows the fader while recording+ assert_eq!(s.previews.live.get(a1(&s).id, LANE_VOLUME).map(|o| o.value), Some(-10.0));+ s.execute("mixer.release", json!({"strip": "A1", "time": sec(2.0)})).unwrap();+ let r = s.execute("mixer.recordStop", json!({"time": sec(5.0)})).unwrap();+ assert_eq!(r["lanes"], 1);+ assert!(!s.previews.live.is_active());+ assert_eq!(vol_at(&s, 0.5), 0.0, "before the touch: unchanged");+ assert_eq!(vol_at(&s, 1.5), -10.0);+ assert!((vol_at(&s, 2.5) + 5.0).abs() < 0.01, "halfway back after 0.5 s of the 1 s automatch: {}", vol_at(&s, 2.5));+ assert_eq!(vol_at(&s, 3.5), 0.0, "back to the old automation");+ // thinned: a held value is a few keyframes, not 31+ assert!(a1(&s).lane_keyframes(LANE_VOLUME).len() <= 5, "{:?}", a1(&s).lane_keyframes(LANE_VOLUME));+ // one undo step removes the pass+ s.execute("edit.undo", json!({})).unwrap();+ assert!(a1(&s).lane_keyframes(LANE_VOLUME).is_empty());+}++#[test]+fn touch_over_existing_automation_and_custom_automatch() {+ let mut s = demo();+ s.execute("prefs.set", json!({"key": "audio.automatchTime", "value": 2.0})).unwrap();+ s.execute("mixer.writeAutomation", json!({"strip": "A1", "points": [[0, -20.0], [sec(8.0), -20.0]]})).unwrap();+ set_mode(&mut s, "A1", "Touch");+ s.execute("mixer.recordStart", json!({"time": sec(0.5)})).unwrap();+ gesture(&mut s, "A1", &[(1.0, 0.0), (1.5, 0.0)]);+ s.execute("mixer.release", json!({"strip": "A1", "time": sec(1.5)})).unwrap();+ s.execute("mixer.recordStop", json!({"time": sec(6.0)})).unwrap();+ assert_eq!(vol_at(&s, 0.9), -20.0);+ assert_eq!(vol_at(&s, 1.25), 0.0);+ assert!((vol_at(&s, 2.5) + 10.0).abs() < 0.05, "{}", vol_at(&s, 2.5));+ assert_eq!(vol_at(&s, 4.0), -20.0);+ assert_eq!(vol_at(&s, 7.0), -20.0);+}++#[test]+fn latch_holds_until_stop() {+ let mut s = demo();+ s.execute("mixer.writeAutomation", json!({"strip": "A1", "points": [[0, 0.0], [sec(8.0), 0.0]]})).unwrap();+ set_mode(&mut s, "A1", "Latch");+ s.execute("mixer.recordStart", json!({"time": 0})).unwrap();+ gesture(&mut s, "A1", &[(1.0, -4.0), (1.5, -8.0), (2.0, -12.0)]);+ s.execute("mixer.release", json!({"strip": "A1", "time": sec(2.0)})).unwrap();+ s.execute("mixer.recordStop", json!({"time": sec(4.0)})).unwrap();+ assert_eq!(vol_at(&s, 0.5), 0.0);+ assert!((vol_at(&s, 1.25) + 6.0).abs() < 1e-6);+ assert_eq!(vol_at(&s, 3.0), -12.0, "latched");+ assert_eq!(vol_at(&s, 3.99), -12.0);+ assert!(vol_at(&s, 4.5) > -12.0, "existing automation after the stop resumes");+}++#[test]+fn write_overwrites_from_start_and_switches_to_touch() {+ let mut s = demo();+ s.execute("mixer.writeAutomation", json!({"strip": "A1", "points": [[0, -30.0], [sec(8.0), 0.0]]})).unwrap();+ s.execute("mixer.setStrip", json!({"strip": "A1", "mode": "Write"})).unwrap();+ s.execute("mixer.recordStart", json!({"time": sec(2.0)})).unwrap();+ let start_val = -30.0 + 30.0 * 2.0 / 8.0;+ // untouched until 3 s: the fader's value at the start is written+ gesture(&mut s, "A1", &[(3.0, -6.0), (3.5, -6.0)]);+ s.execute("mixer.release", json!({"strip": "A1", "time": sec(3.5)})).unwrap();+ s.execute("mixer.recordStop", json!({"time": sec(5.0)})).unwrap();+ assert!((vol_at(&s, 1.0) - (-30.0 + 30.0 / 8.0)).abs() < 0.05, "before the pass: unchanged");+ assert!((vol_at(&s, 2.5) - start_val).abs() < 0.05, "{}", vol_at(&s, 2.5));+ assert_eq!(vol_at(&s, 4.0), -6.0);+ assert_eq!(vol_at(&s, 4.9), -6.0, "Write holds the last value to the stop");+ assert_eq!(a1(&s).mixer.mode, AutomationMode::Touch, "Switch to Touch after Write");+ // pan and mute are written too+ assert!(a1(&s).lane_keyframes("pan").len() >= 2 && a1(&s).lane_keyframes("mute").len() >= 2);+ // the preference can keep Write+ s.execute("prefs.set", json!({"key": "audio.switchToTouchAfterWrite", "value": false})).unwrap();+ s.execute("mixer.setStrip", json!({"strip": "A1", "mode": "Write"})).unwrap();+ s.execute("mixer.recordStart", json!({"time": sec(6.0)})).unwrap();+ s.execute("mixer.recordStop", json!({"time": sec(7.0)})).unwrap();+ assert_eq!(a1(&s).mixer.mode, AutomationMode::Write);+}++#[test]+fn read_mode_does_not_record_and_commits_once_without_a_pass() {+ let mut s = demo();+ s.execute("mixer.recordStart", json!({"time": 0})).unwrap();+ gesture(&mut s, "A1", &[(1.0, -6.0), (2.0, -9.0)]);+ s.execute("mixer.release", json!({"strip": "A1", "time": sec(2.0)})).unwrap();+ let r = s.execute("mixer.recordStop", json!({"time": sec(3.0)})).unwrap();+ assert_eq!(r["lanes"], 0);+ assert!(a1(&s).lane_keyframes(LANE_VOLUME).is_empty());+ // stopped: a drag is heard live, then committed as one undo step+ let undo0 = s.history.undo.len();+ gesture(&mut s, "A1", &[(0.0, -2.0), (0.0, -4.0), (0.0, -5.0)]);+ assert_eq!(a1(&s).volume_db, 0.0);+ s.execute("mixer.release", json!({"strip": "A1"})).unwrap();+ assert_eq!(a1(&s).volume_db, -5.0);+ assert_eq!(s.history.undo.len(), undo0 + 1);+}++#[test]+fn recorded_pass_plays_back_through_the_mix() {+ let mut s = demo();+ // only A1 (the demo has music on another track)+ s.execute("mixer.setStrip", json!({"strip": "A1", "solo": true})).unwrap();+ set_mode(&mut s, "A1", "Latch");+ s.execute("mixer.recordStart", json!({"time": 0})).unwrap();+ gesture(&mut s, "A1", &[(0.5, -96.0)]);+ s.execute("mixer.release", json!({"strip": "A1", "time": sec(0.5)})).unwrap();+ s.execute("mixer.recordStop", json!({"time": sec(2.0)})).unwrap();+ let q = s.active_sequence().unwrap();+ let seq_id = s.state.active_sequence.unwrap();+ let provider = s.media.provider(s.project.clone(), s.services.clone());+ let b = s.previews.mix(&s.project, seq_id, 48_000, 4_800, &provider);+ assert!(b.channels[0].iter().all(|x| x.abs() < 1e-6), "faded out by the recorded automation");+ let before = filmcraft_render::audio::mix_sequence(&s.project, q, 0, 4_800, &provider);+ assert!(before.channels[0].iter().any(|x| x.abs() > 1e-4), "audible before the move");+ // master strip automation+ s.execute("mixer.setKeyframe", json!({"strip": "Mix", "time": 0, "value": -6.0})).unwrap();+ 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());+}diff --git a/crates/engine/src/previews.rs b/crates/engine/src/previews.rsindex c031ea1b2..c49db99c0 100644--- a/crates/engine/src/previews.rs+++ b/crates/engine/src/previews.rs@@ -79,6 +79,8 @@ pub struct PreviewStore {audio_memo: Mutex<Vec<AudioMemo>>,/// Bumped whenever the set of preview files changes.pub generation: AtomicU64,+ /// Live mixer state shared with playback: held controls, meters, newest project snapshot.+ pub live: Arc<filmcraft_render::mixer::LiveMix>,}fn video_name(hash: &str) -> String {@@ -244,9 +246,11 @@ impl PreviewStore {/// live mix ([`filmcraft_render::audio::mix_sequence`]) everywhere else.pub fn mix(&self, project: &Arc<Project>, seq: ItemId, start: i64, frames: usize, sources: &dyn filmcraft_render::SourceProvider) -> AudioBuffer {let Some(q) = project.sequence(seq) else { return AudioBuffer::silence(48_000, 2, frames) };+ let live = Some(&*self.live);let has_audio = self.files.read().unwrap_or_else(|e| e.into_inner()).iter().any(|n| n.ends_with(".wav"));- if !has_audio {- return filmcraft_render::audio::mix_sequence(project, q, start, frames, sources);+ // held mixer controls are heard live (rendered previews don't know them)+ if !has_audio || self.live.is_active() {+ return filmcraft_render::mixer::mix_graph(project, q, start, frames, sources, live);}let segs = self.audio_segments(project, seq);let mut out = AudioBuffer::silence(q.settings.sample_rate, 2, frames);@@ -271,7 +275,7 @@ impl PreviewStore {}}_ => {- let b = filmcraft_render::audio::mix_sequence(project, q, pos, n, sources);+ let b = filmcraft_render::mixer::mix_graph(project, q, pos, n, sources, live);for c in 0..2 {out.channels[c][off..off + n].copy_from_slice(&b.channels[c.min(b.channels.len() - 1)][..n]);}diff --git a/crates/interchange/src/common.rs b/crates/interchange/src/common.rsindex a8b63526d..d2adb920c 100644--- a/crates/interchange/src/common.rs+++ b/crates/interchange/src/common.rs@@ -469,6 +469,8 @@ pub(crate) fn empty_sequence(settings: SequenceSettings) -> Sequence {start_timecode: 0,master_volume_db: 0.0,master_effects: Vec::new(),+ master_mixer: Default::default(),+ submix_tracks: Vec::new(),caption_tracks: Vec::new(),}}@@ -594,6 +596,7 @@ pub(crate) fn transition_effect(name: &str, audio: bool, report: &mut Report) ->enabled: true,params: Default::default(),masks: vec![],+ post_fader: false,})}diff --git a/crates/project/src/effect.rs b/crates/project/src/effect.rsindex 80f69e005..201ee52e8 100644--- a/crates/project/src/effect.rs+++ b/crates/project/src/effect.rs@@ -85,6 +85,7 @@ impl EffectDef {enabled: true,params: self.params.iter().map(|p| (p.id.to_string(), Param::new(p.default.clone()))).collect(),masks: Vec::new(),+ post_fader: false,}}}@@ -113,6 +114,9 @@ pub struct EffectInstance {pub params: BTreeMap<String, Param>,#[serde(default, skip_serializing_if = "Vec::is_empty")]pub masks: Vec<Mask>,+ /// 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,}impl EffectInstance {diff --git a/crates/project/src/keyframe.rs b/crates/project/src/keyframe.rsindex 3e1029f00..693e79262 100644--- a/crates/project/src/keyframe.rs+++ b/crates/project/src/keyframe.rs@@ -186,6 +186,11 @@ impl Param {self.set_at_force(t, v);}+ /// Add or replace a keyframe at `t` (the parameter becomes animated).+ pub fn put_keyframe(&mut self, t: Tick, value: ParamValue) {+ self.set_at_force(t, value);+ }+fn set_at_force(&mut self, t: Tick, value: ParamValue) {match self.keyframes.binary_search_by_key(&t, |k| k.time) {Ok(i) => self.keyframes[i].value = value,@@ -238,6 +243,35 @@ impl Param {pub fn f64_at(&self, t: Tick) -> f64 {self.value_at(t).as_f64().unwrap_or(0.0)}++ /// Allocation-free [`Param::f64_at`] for scalar parameters (Float / Choice / Bool), for+ /// per-sample evaluation in the audio mixer. Non-scalar values evaluate to 0.+ pub fn scalar_at(&self, t: Tick) -> f64 {+ let k = &self.keyframes;+ let s = |v: &ParamValue| v.as_f64().unwrap_or(0.0);+ if k.is_empty() {+ return s(&self.value);+ }+ if t <= k[0].time {+ return s(&k[0].value);+ }+ let last = &k[k.len() - 1];+ if t >= last.time {+ return s(&last.value);+ }+ let i = match k.binary_search_by_key(&t, |kf| kf.time) {+ Ok(i) => return s(&k[i].value),+ Err(i) => i - 1,+ };+ let (a, b) = (&k[i], &k[i + 1]);+ let (va, vb) = (s(&a.value), s(&b.value));+ if a.interp == Interpolation::Hold || !matches!(a.value, ParamValue::Float(_)) {+ return va;+ }+ let u = (t - a.time).0 as f64 / (b.time - a.time).0 as f64;+ va + (vb - va) * ease(a, b, u)+ }+pub fn vec2_at(&self, t: Tick) -> Vec2 {self.value_at(t).as_vec2().unwrap_or_default()}diff --git a/crates/project/src/lib.rs b/crates/project/src/lib.rsindex 20d7ac5e8..1c13277fc 100644--- a/crates/project/src/lib.rs+++ b/crates/project/src/lib.rs@@ -10,6 +10,7 @@pub mod caption;pub mod effect;pub mod keyframe;+pub mod mixer;use std::collections::BTreeMap;@@ -21,6 +22,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 keyframe::{Interpolation, Keyframe, Param, ParamValue};+pub use mixer::{AutomationMode, InputMap, MixerStrip, TrackSend};macro_rules! id_type {($name:ident) => {@@ -528,9 +530,12 @@ pub struct Track {/// Audio track volume (dB) and pan (-100..100) for the Track Mixer.pub volume_db: f64,pub pan: f64,- /// Track-level audio effects (mixer inserts).+ /// Track-level audio effects (mixer inserts, slots 1–5; `EffectInstance::post_fader` picks the side).#[serde(default)]pub effects: Vec<EffectInstance>,+ /// Audio Track Mixer state: automation mode and lanes, sends, output, record arm.+ #[serde(default)]+ pub mixer: MixerStrip,}impl Track {@@ -550,6 +555,7 @@ impl Track {volume_db: 0.0,pan: 0.0,effects: Vec::new(),+ mixer: MixerStrip::default(),}}pub fn end(&self) -> Tick {@@ -640,8 +646,16 @@ pub struct Sequence {/// Master audio volume (dB).#[serde(default)]pub master_volume_db: f64,+ /// Mix track inserts (`EffectInstance::post_fader` picks the side).#[serde(default)]pub master_effects: Vec<EffectInstance>,+ /// Mix track automation (`volume` lane) and mode.+ #[serde(default)]+ pub master_mixer: MixerStrip,+ /// Audio submix tracks (no clips); tracks and sends route into them, they route to the Mix+ /// or to a submix after them.+ #[serde(default)]+ pub submix_tracks: Vec<Track>,/// Caption tracks (drawn above the video tracks; first = top). Older files have none (serde default).#[serde(default)]pub caption_tracks: Vec<CaptionTrack>,@@ -826,6 +840,8 @@ impl Project {start_timecode: 0,master_volume_db: 0.0,master_effects: Vec::new(),+ master_mixer: MixerStrip::default(),+ submix_tracks: Vec::new(),caption_tracks: Vec::new(),};for i in 0..v {diff --git a/crates/project/src/mixer.rs b/crates/project/src/mixer.rsnew file mode 100644index 000000000..14388a4b0--- /dev/null+++ b/crates/project/src/mixer.rs@@ -0,0 +1,548 @@+//! Audio Track Mixer model: automation modes and lanes, sends, submix routing, channel mapping.+//!+//! Every audio track, every submix track ([`crate::Sequence::submix_tracks`]) and the Mix (master)+//! track has a [`MixerStrip`]. Static values stay where they always were (`Track::volume_db`,+//! `Track::pan`, `Track::muted`, `TrackSend::level_db`, effect parameter values); automation is+//! keyframes in **sequence time** on top of them:+//!+//! | lane key | value | stored in |+//! |---|---|---|+//! | `volume` | fader level, dB | `MixerStrip::lanes` |+//! | `pan` | pan / balance, −100 … 100 | `MixerStrip::lanes` |+//! | `mute` | 0 / 1 (hold) | `MixerStrip::lanes` |+//! | `send.<i>.level` | send `i` level, dB | `MixerStrip::lanes` |+//! | `fx.<slot>.<param>` | insert effect parameter | the effect's own `Param` keyframes |+//!+//! [`AutomationMode`] decides whether playback reads the lanes (anything but Off) and how the+//! mixer writes them while recording (Latch / Touch / Write; see the engine's recorder).++use std::collections::BTreeMap;++use filmcraft_time::Tick;+use serde::{Deserialize, Serialize};++use crate::keyframe::{Interpolation, Keyframe, Param, ParamValue};+use crate::{Track, TrackId};++pub const LANE_VOLUME: &str = "volume";+pub const LANE_PAN: &str = "pan";+pub const LANE_MUTE: &str = "mute";++/// At most this many insert effects per strip (Premiere's effect slots 1–5).+pub const MAX_INSERTS: usize = 5;+/// At most this many sends per strip (Premiere's send slots 1–5).+pub const MAX_SENDS: usize = 5;+/// Fader range (dB): the Track Mixer's scale runs from −∞ to +15 dB (Clip Mixer and Mix too).+pub const FADER_MAX_DB: f64 = 15.0;+/// Values at or below this are −∞ (silence).+pub const FADER_MIN_DB: f64 = -96.0;++pub fn send_lane(i: usize) -> String {+ format!("send.{i}.level")+}++pub fn fx_lane(slot: usize, param: &str) -> String {+ format!("fx.{slot}.{param}")+}++/// Track automation mode (the dropdown above the M/S/R buttons).+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]+pub enum AutomationMode {+ /// Ignore stored automation; play the static values.+ Off,+ /// Play automation; touching a control during playback does not record.+ #[default]+ Read,+ /// Record from the first touch; after release keep writing the last value until playback stops.+ Latch,+ /// Record while touched; after release return to the previous automation over the automatch time.+ Touch,+ /// Record every automatable control from the start of playback until it stops.+ Write,+}++impl AutomationMode {+ pub const ALL: [AutomationMode; 5] = [AutomationMode::Off, AutomationMode::Read, AutomationMode::Latch, AutomationMode::Touch, AutomationMode::Write];+ pub fn label(self) -> &'static str {+ match self {+ AutomationMode::Off => "Off",+ AutomationMode::Read => "Read",+ AutomationMode::Latch => "Latch",+ AutomationMode::Touch => "Touch",+ AutomationMode::Write => "Write",+ }+ }+ pub fn from_name(s: &str) -> Option<Self> {+ Self::ALL.into_iter().find(|m| m.label().eq_ignore_ascii_case(s))+ }+ /// Plays stored automation.+ pub fn reads(self) -> bool {+ self != AutomationMode::Off+ }+ /// Records automation during playback.+ pub fn writes(self) -> bool {+ matches!(self, AutomationMode::Latch | AutomationMode::Touch | AutomationMode::Write)+ }+}++/// How the clips' (stereo) audio feeds the track input: basic channel mapping.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]+pub enum InputMap {+ /// L → L, R → R.+ #[default]+ Stereo,+ /// Left channel to both sides.+ Left,+ /// Right channel to both sides.+ Right,+ /// L ↔ R.+ Swap,+ /// (L + R) / 2 to both sides.+ Mono,+}++impl InputMap {+ pub const ALL: [InputMap; 5] = [InputMap::Stereo, InputMap::Left, InputMap::Right, InputMap::Swap, InputMap::Mono];+ pub fn label(self) -> &'static str {+ match self {+ InputMap::Stereo => "Stereo",+ InputMap::Left => "Left",+ InputMap::Right => "Right",+ InputMap::Swap => "Swap",+ InputMap::Mono => "Mono",+ }+ }+ pub fn from_name(s: &str) -> Option<Self> {+ Self::ALL.into_iter().find(|m| m.label().eq_ignore_ascii_case(s))+ }+}++/// A send from a strip to a submix.+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]+pub struct TrackSend {+ /// Destination submix track.+ pub target: TrackId,+ /// Send level (dB); automatable as lane `send.<i>.level`.+ pub level_db: f64,+ /// Send pan / balance (−100 … 100).+ #[serde(default)]+ pub pan: f64,+ /// Tap before the fader (after the pre-fader inserts) instead of after the post-fader inserts.+ #[serde(default)]+ pub pre_fader: bool,+ #[serde(default)]+ pub muted: bool,+}++impl TrackSend {+ pub fn new(target: TrackId) -> Self {+ TrackSend { target, level_db: 0.0, pan: 0.0, pre_fader: false, muted: false }+ }+}++/// Mixer-only state of a channel strip (audio track, submix or Mix).+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]+#[serde(default)]+pub struct MixerStrip {+ pub mode: AutomationMode,+ /// Automation lanes (`volume`, `pan`, `mute`, `send.<i>.level`), keyframes in sequence time.+ #[serde(skip_serializing_if = "BTreeMap::is_empty")]+ pub lanes: BTreeMap<String, Param>,+ #[serde(skip_serializing_if = "Vec::is_empty")]+ pub sends: Vec<TrackSend>,+ /// Output assignment: a submix track, or `None` for the Mix track.+ pub output: Option<TrackId>,+ /// Record-arm (R): the track records voice-over input.+ pub record_arm: bool,+ /// Solo safe: never solo-muted, and keeps its sources audible while other strips are soloed.+ pub solo_safe: bool,+ /// How clip audio feeds the track.+ pub input_map: InputMap,+}++/// Description of an automation lane for display and value ranges.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct LaneInfo {+ pub min: f64,+ pub max: f64,+ /// Values hold between keyframes (switches such as mute).+ pub hold: bool,+ pub unit: &'static str,+}++/// Range and behaviour of a non-effect lane (`volume`, `pan`, `mute`, `send.<i>.level`).+pub fn lane_info(key: &str) -> Option<LaneInfo> {+ match key {+ LANE_VOLUME => Some(LaneInfo { min: FADER_MIN_DB, max: FADER_MAX_DB, hold: false, unit: "dB" }),+ LANE_PAN => Some(LaneInfo { min: -100.0, max: 100.0, hold: false, unit: "" }),+ LANE_MUTE => Some(LaneInfo { min: 0.0, max: 1.0, hold: true, unit: "" }),+ k if parse_send_lane(k).is_some() => Some(LaneInfo { min: FADER_MIN_DB, max: FADER_MAX_DB, hold: false, unit: "dB" }),+ _ => None,+ }+}++pub fn parse_send_lane(key: &str) -> Option<usize> {+ key.strip_prefix("send.")?.strip_suffix(".level")?.parse().ok()+}++pub fn parse_fx_lane(key: &str) -> Option<(usize, &str)> {+ let rest = key.strip_prefix("fx.")?;+ let (slot, param) = rest.split_once('.')?;+ Some((slot.parse().ok()?, param))+}++impl Track {+ /// Static (un-automated) value of a lane.+ pub fn lane_static(&self, key: &str) -> Option<f64> {+ match key {+ LANE_VOLUME => Some(self.volume_db),+ LANE_PAN => Some(self.pan),+ LANE_MUTE => Some(if self.muted { 1.0 } else { 0.0 }),+ k => {+ if let Some(i) = parse_send_lane(k) {+ return self.mixer.sends.get(i).map(|s| s.level_db);+ }+ let (slot, p) = parse_fx_lane(k)?;+ self.effects.get(slot)?.param(p)?.value.as_f64()+ }+ }+ }++ /// The keyframed parameter behind a lane, if any.+ pub fn lane(&self, key: &str) -> Option<&Param> {+ match parse_fx_lane(key) {+ Some((slot, p)) => self.effects.get(slot)?.param(p),+ None => self.mixer.lanes.get(key),+ }+ }++ /// The parameter behind a lane, created (static, from the current value) if missing.+ pub fn lane_mut(&mut self, key: &str) -> Option<&mut Param> {+ if let Some((slot, p)) = parse_fx_lane(key) {+ return self.effects.get_mut(slot)?.param_mut(p);+ }+ let stat = self.lane_static(key)?;+ lane_info(key)?;+ Some(self.mixer.lanes.entry(key.to_string()).or_insert_with(|| Param::new(ParamValue::Float(stat))))+ }++ /// Lane keyframes (empty when the lane is not automated).+ pub fn lane_keyframes(&self, key: &str) -> &[Keyframe] {+ self.lane(key).map(|p| p.keyframes.as_slice()).unwrap_or(&[])+ }++ /// Value of a lane at sequence time `t` as playback hears it (automation unless the mode is Off).+ pub fn lane_value(&self, key: &str, t: Tick) -> f64 {+ let stat = self.lane_static(key).unwrap_or(0.0);+ if !self.mixer.mode.reads() {+ return stat;+ }+ match self.lane(key) {+ Some(p) if p.is_animated() => p.scalar_at(t),+ _ => stat,+ }+ }++ /// All automated lane keys of this strip.+ pub fn automated_lanes(&self) -> Vec<String> {+ let mut v: Vec<String> = self.mixer.lanes.iter().filter(|(_, p)| p.is_animated()).map(|(k, _)| k.clone()).collect();+ for (slot, e) in self.effects.iter().enumerate() {+ for (pid, p) in &e.params {+ if p.is_animated() {+ v.push(fx_lane(slot, pid));+ }+ }+ }+ v+ }++ /// Set a lane's static value (fader moves in Off/Read mode, or no automation yet).+ pub fn set_lane_static(&mut self, key: &str, v: f64) -> bool {+ match key {+ LANE_VOLUME => self.volume_db = v.clamp(FADER_MIN_DB, FADER_MAX_DB),+ LANE_PAN => self.pan = v.clamp(-100.0, 100.0),+ LANE_MUTE => self.muted = v >= 0.5,+ k => {+ if let Some(i) = parse_send_lane(k) {+ match self.mixer.sends.get_mut(i) {+ Some(s) => s.level_db = v.clamp(FADER_MIN_DB, FADER_MAX_DB),+ None => return false,+ }+ } else if let Some((slot, p)) = parse_fx_lane(k) {+ match self.effects.get_mut(slot).and_then(|e| e.param_mut(p)) {+ Some(par) => par.value = ParamValue::Float(v),+ None => return false,+ }+ } else {+ return false;+ }+ }+ }+ true+ }++ /// Remove insert `slot` (its automation goes with it: effect lanes live inside the effect).+ pub fn remove_insert(&mut self, slot: usize) -> bool {+ if slot < self.effects.len() {+ self.effects.remove(slot);+ true+ } else {+ false+ }+ }++ /// Remove send `i` and shift the automation lanes of the sends above it down.+ pub fn remove_send(&mut self, i: usize) -> bool {+ if i >= self.mixer.sends.len() {+ return false;+ }+ self.mixer.sends.remove(i);+ let mut lanes = std::mem::take(&mut self.mixer.lanes);+ let moved: Vec<(String, Param)> = lanes.iter().filter_map(|(k, p)| parse_send_lane(k).filter(|&j| j >= i).map(|_| (k.clone(), p.clone()))).collect();+ for (k, _) in &moved {+ lanes.remove(k);+ }+ for (k, p) in moved {+ let j = parse_send_lane(&k).unwrap_or(0);+ if j > i {+ lanes.insert(send_lane(j - 1), p);+ }+ }+ self.mixer.lanes = lanes;+ true+ }+}++/// Strip id of the Mix (master) track.+pub const MASTER_STRIP: TrackId = TrackId(u64::MAX);++impl crate::Sequence {+ /// The Mix track as a [`Track`] (volume, inserts and mixer state; no clips).+ pub fn master_strip(&self) -> Track {+ let mut m = Track::new(MASTER_STRIP, crate::TrackKind::Audio, "Mix".into());+ m.volume_db = self.master_volume_db;+ m.effects = self.master_effects.clone();+ m.mixer = self.master_mixer.clone();+ m.channels = self.settings.audio_master;+ m+ }++ /// Any mixer strip (audio track, submix or [`MASTER_STRIP`]).+ pub fn strip(&self, id: TrackId) -> Option<std::borrow::Cow<'_, Track>> {+ if id == MASTER_STRIP {+ return Some(std::borrow::Cow::Owned(self.master_strip()));+ }+ self.mix_track(id).map(std::borrow::Cow::Borrowed)+ }++ /// Edit any mixer strip; edits to the Mix are written back to the sequence's master fields.+ pub fn with_strip_mut<R>(&mut self, id: TrackId, f: impl FnOnce(&mut Track) -> R) -> Option<R> {+ if id == MASTER_STRIP {+ let mut m = self.master_strip();+ let r = f(&mut m);+ self.master_volume_db = m.volume_db;+ self.master_effects = m.effects;+ self.master_mixer = m.mixer;+ return Some(r);+ }+ self.mix_track_mut(id).map(f)+ }++ /// Ids of all strips in mixer order: audio tracks, submixes, Mix.+ pub fn strip_ids(&self) -> Vec<TrackId> {+ self.audio_tracks.iter().chain(&self.submix_tracks).map(|t| t.id).chain(std::iter::once(MASTER_STRIP)).collect()+ }++ /// An audio or submix track (the strips that have a fader besides the Mix).+ pub fn mix_track(&self, id: TrackId) -> Option<&Track> {+ self.audio_tracks.iter().chain(&self.submix_tracks).find(|t| t.id == id)+ }+ pub fn mix_track_mut(&mut self, id: TrackId) -> Option<&mut Track> {+ self.audio_tracks.iter_mut().chain(self.submix_tracks.iter_mut()).find(|t| t.id == id)+ }+ /// Mix track volume (dB) at sequence time `t` (automation unless the Mix is in Off mode).+ pub fn master_volume_at(&self, t: Tick) -> f64 {+ match self.master_mixer.lanes.get(LANE_VOLUME) {+ Some(p) if p.is_animated() && self.master_mixer.mode.reads() => p.scalar_at(t),+ _ => self.master_volume_db,+ }+ }+}++/// Thin a recorded gesture (time, value) into keyframes: Ramer–Douglas–Peucker on the value axis+/// (every dropped point lies within `tolerance` of the line between the kept neighbours), then drop+/// points closer than `min_interval` to the previous kept one (except the last). `hold` lanes keep+/// only the points where the value changes.+pub fn thin_points(points: &[(Tick, f64)], tolerance: f64, min_interval: Tick, hold: bool) -> Vec<(Tick, f64)> {+ let mut pts: Vec<(Tick, f64)> = Vec::with_capacity(points.len());+ for &(t, v) in points {+ match pts.last_mut() {+ Some(last) if last.0 == t => last.1 = v,+ Some(last) if last.0 > t => {}+ _ => pts.push((t, v)),+ }+ }+ if pts.len() <= 2 {+ return pts;+ }+ if hold {+ let mut out = vec![pts[0]];+ for w in pts.windows(2) {+ if (w[1].1 - w[0].1).abs() > tolerance.max(1e-9) {+ out.push(w[1]);+ }+ }+ return out;+ }+ let mut keep = vec![false; pts.len()];+ keep[0] = true;+ keep[pts.len() - 1] = true;+ let mut stack = vec![(0usize, pts.len() - 1)];+ while let Some((a, b)) = stack.pop() {+ if b <= a + 1 {+ continue;+ }+ let (ta, va) = (pts[a].0.0 as f64, pts[a].1);+ let (tb, vb) = (pts[b].0.0 as f64, pts[b].1);+ let mut worst = (0.0f64, 0usize);+ for (i, p) in pts.iter().enumerate().take(b).skip(a + 1) {+ let u = (p.0.0 as f64 - ta) / (tb - ta);+ let d = (p.1 - (va + (vb - va) * u)).abs();+ if d > worst.0 {+ worst = (d, i);+ }+ }+ if worst.0 > tolerance {+ keep[worst.1] = true;+ stack.push((a, worst.1));+ stack.push((worst.1, b));+ }+ }+ let mut out: Vec<(Tick, f64)> = Vec::new();+ let n = pts.len();+ for (i, p) in pts.into_iter().enumerate() {+ if !keep[i] {+ continue;+ }+ if i + 1 < n && min_interval.0 > 0 && out.last().is_some_and(|l: &(Tick, f64)| p.0 - l.0 < min_interval) {+ continue;+ }+ out.push(p);+ }+ out+}++/// Replace the keyframes of `param` within `[t0, t1]` by `points` (already thinned).+///+/// `before`/`after` are the lane values just outside the written range: when given, a keyframe is+/// placed one `eps` outside the range so the automation outside `[t0, t1]` is unchanged.+pub fn write_lane(param: &mut Param, t0: Tick, t1: Tick, points: &[(Tick, f64)], before: Option<f64>, after: Option<f64>, eps: Tick, hold: bool) {+ let interp = if hold { Interpolation::Hold } else { Interpolation::Linear };+ param.keyframes.retain(|k| k.time < t0 || k.time > t1);+ let mut add = |t: Tick, v: f64| {+ let mut k = Keyframe::new(t, ParamValue::Float(v));+ k.interp = interp;+ match param.keyframes.binary_search_by_key(&t, |k| k.time) {+ Ok(i) => param.keyframes[i] = k,+ Err(i) => param.keyframes.insert(i, k),+ }+ };+ if let Some(b) = before {+ let tb = t0 - eps;+ if tb.0 >= 0 {+ add(tb, b);+ }+ }+ for &(t, v) in points.iter().filter(|p| p.0 >= t0 && p.0 <= t1) {+ add(t, v);+ }+ if let Some(a) = after {+ add(t1 + eps, a);+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::TrackKind;++ fn tr() -> Track {+ Track::new(TrackId(1), TrackKind::Audio, "Audio 1".into())+ }++ #[test]+ fn mode_names_roundtrip() {+ for m in AutomationMode::ALL {+ assert_eq!(AutomationMode::from_name(m.label()), Some(m));+ }+ assert_eq!(AutomationMode::default(), AutomationMode::Read);+ assert!(!AutomationMode::Off.reads() && AutomationMode::Touch.writes() && !AutomationMode::Read.writes());+ }++ #[test]+ fn lanes_read_static_and_keyframes() {+ let mut t = tr();+ t.volume_db = -6.0;+ assert_eq!(t.lane_value(LANE_VOLUME, Tick(0)), -6.0);+ let p = t.lane_mut(LANE_VOLUME).unwrap();+ p.keyframes.push(Keyframe::new(Tick(0), ParamValue::Float(0.0)));+ p.keyframes.push(Keyframe::new(Tick(100), ParamValue::Float(-20.0)));+ assert_eq!(t.lane_value(LANE_VOLUME, Tick(50)), -10.0);+ t.mixer.mode = AutomationMode::Off;+ assert_eq!(t.lane_value(LANE_VOLUME, Tick(50)), -6.0);+ assert_eq!(t.automated_lanes(), vec!["volume".to_string()]);+ }++ #[test]+ fn thinning_keeps_shape_within_tolerance() {+ // a ramp sampled densely collapses to its end points; a corner survives+ let pts: Vec<(Tick, f64)> = (0..=100).map(|i| (Tick(i * 10), if i <= 50 { i as f64 * 0.2 } else { 10.0 - (i - 50) as f64 * 0.2 })).collect();+ let th = thin_points(&pts, 0.01, Tick(0), false);+ assert_eq!(th, vec![(Tick(0), 0.0), (Tick(500), 10.0), (Tick(1000), 0.0)]);+ // every original point within tolerance of the thinned curve+ let mut p = Param::new(ParamValue::Float(0.0));+ write_lane(&mut p, Tick(0), Tick(1000), &th, None, None, Tick(1), false);+ for (t, v) in pts {+ assert!((p.scalar_at(t) - v).abs() <= 0.01 + 1e-9);+ }+ // hold lanes keep change points only+ let m = [(Tick(0), 0.0), (Tick(10), 0.0), (Tick(20), 1.0), (Tick(30), 1.0), (Tick(40), 0.0)];+ assert_eq!(thin_points(&m, 0.0, Tick(0), true), vec![(Tick(0), 0.0), (Tick(20), 1.0), (Tick(40), 0.0)]);+ }++ #[test]+ fn write_lane_preserves_outside() {+ let mut p = Param::new(ParamValue::Float(0.0));+ write_lane(&mut p, Tick(0), Tick(1000), &[(Tick(0), -3.0), (Tick(1000), -3.0)], None, None, Tick(1), false);+ write_lane(&mut p, Tick(400), Tick(600), &[(Tick(400), -20.0), (Tick(600), -20.0)], Some(-3.0), Some(-3.0), Tick(1), false);+ assert_eq!(p.scalar_at(Tick(200)), -3.0);+ assert_eq!(p.scalar_at(Tick(500)), -20.0);+ assert_eq!(p.scalar_at(Tick(800)), -3.0);+ assert_eq!(p.keyframes.len(), 6);+ }++ #[test]+ fn send_removal_shifts_lanes() {+ let mut t = tr();+ for k in 0..3 {+ t.mixer.sends.push(TrackSend::new(TrackId(10 + k)));+ t.mixer.sends[k as usize].level_db = -(k as f64);+ t.lane_mut(&send_lane(k as usize)).unwrap().keyframes.push(Keyframe::new(Tick(0), ParamValue::Float(-(k as f64))));+ }+ assert!(t.remove_send(1));+ assert_eq!(t.mixer.sends.len(), 2);+ assert_eq!(t.lane_keyframes(&send_lane(1))[0].value, ParamValue::Float(-2.0));+ assert!(t.lane(&send_lane(2)).is_none());+ }++ #[test]+ fn serde_defaults() {+ let s: MixerStrip = serde_json::from_str("{}").unwrap();+ assert_eq!(s, MixerStrip::default());+ let mut t = tr();+ t.mixer.mode = AutomationMode::Touch;+ let j = serde_json::to_string(&t).unwrap();+ let back: Track = serde_json::from_str(&j).unwrap();+ assert_eq!(back, t);+ }+}diff --git a/crates/render/src/audio.rs b/crates/render/src/audio.rsindex 01cb5643c..1f051593b 100644--- a/crates/render/src/audio.rs+++ b/crates/render/src/audio.rs@@ -1,11 +1,9 @@-//! Sequence audio mixdown (clip gain → Volume/Channel Volume/Panner → track volume/pan →-//! master), with audio transitions, mute/solo, speed changes (varispeed resampling).-//!-//! The dedicated `audio` crate (M7) adds the effect DSP, submixes and meters; this module is the-//! reference mixer used by playback and export.+//! Clip-level audio: clip gain → clip effects → Volume / Channel Volume / Panner, audio transitions+//! and speed changes (varispeed resampling), summed per track. The track/submix/Mix graph that+//! consumes it is [`crate::mixer`].use filmcraft_frame::AudioBuffer;-use filmcraft_project::{Project, Sequence, TrackItem};+use filmcraft_project::{Project, Sequence, Track, TrackItem};use filmcraft_time::{Tick, TimeRange};use crate::{SourceProvider, transitions};@@ -14,74 +12,63 @@ pub fn db_to_gain(db: f64) -> f32 {if db <= -96.0 { 0.0 } else { 10f64.powf(db / 20.0) as f32 }}-/// Mix `frames` stereo samples of sequence audio starting at sample `start` (sequence rate).+/// Mix `frames` stereo samples of sequence audio starting at sample `start` (sequence rate), through+/// the full mixer graph ([`crate::mixer`]). Export and playback both use this.pub fn mix_sequence(project: &Project, seq: &Sequence, start: i64, frames: usize, sources: &dyn SourceProvider) -> AudioBuffer {- let sr = seq.settings.sample_rate;- let mut out = AudioBuffer::silence(sr, 2, frames);+ crate::mixer::mix_graph(project, seq, start, frames, sources, None)+}++/// The summed clip audio of one track (clip gain, clip effects, Volume / Channel Volume / Panner,+/// audio transitions) for sequence samples `[start, start + frames)`: the track's mixer input.+pub fn track_input(project: &Project, track: &Track, start: i64, frames: usize, sr: u32, sources: &dyn SourceProvider) -> AudioBuffer {let range = TimeRange::from_bounds(Tick::from_units(start, sr as i64), Tick::from_units(start + frames as i64, sr as i64));- let any_solo = seq.audio_tracks.iter().any(|t| t.solo);- for track in &seq.audio_tracks {- if track.muted || (any_solo && !track.solo) {+ let mut tbuf = AudioBuffer::silence(sr, 2, frames);+ for item in track.items.iter().filter(|i| i.enabled && i.range().overlaps(&range)) {+ mix_item(project, item, start, frames, sr, sources, &mut tbuf, 1.0);+ }+ // audio transitions: attenuate the covered region of each side+ for tr in &track.transitions {+ if !tr.range().overlaps(&range) {continue;}- let mut tbuf = AudioBuffer::silence(sr, 2, frames);- for item in track.items.iter().filter(|i| i.enabled && i.range().overlaps(&range)) {- mix_item(project, item, start, frames, sr, sources, &mut tbuf, 1.0);+ // Re-mix: recompute the covered samples with crossfade gains.+ let from = tr.from.and_then(|id| track.item(id));+ let to = tr.to.and_then(|id| track.item(id));+ let s0 = tr.start.to_units_floor(sr as i64).max(start);+ let s1 = tr.end().to_units_floor(sr as i64).min(start + frames as i64);+ if s1 <= s0 {+ continue;}- // audio transitions: attenuate the covered region of each side- for tr in &track.transitions {- if !tr.range().overlaps(&range) {- continue;- }- // Re-mix: recompute the covered samples with crossfade gains.- let from = tr.from.and_then(|id| track.item(id));- let to = tr.to.and_then(|id| track.item(id));- let s0 = tr.start.to_units_floor(sr as i64).max(start);- let s1 = tr.end().to_units_floor(sr as i64).min(start + frames as i64);- if s1 <= s0 {- continue;- }- let n = (s1 - s0) as usize;- let off = (s0 - start) as usize;- for ch in tbuf.channels.iter_mut() {- ch[off..off + n].fill(0.0);- }- let mut a = AudioBuffer::silence(sr, 2, n);- let mut b = AudioBuffer::silence(sr, 2, n);- if let Some(f) = from {- mix_item(project, f, s0, n, sr, sources, &mut a, 1.0);- }- if let Some(tt) = to {- mix_item(project, tt, s0, n, sr, sources, &mut b, 1.0);- }- let dur = (tr.end() - tr.start).to_units_floor(sr as i64).max(1) as f32;- let base = (s0 - tr.start.to_units_floor(sr as i64)) as f32;- for i in 0..n {- let p = (base + i as f32) / dur;- let (ga, gb) = transitions::audio_gains(&tr.effect.effect, p);- for c in 0..2 {- tbuf.channels[c][off + i] += a.channels[c][i] * ga + b.channels[c][i] * gb;- }- }+ let n = (s1 - s0) as usize;+ let off = (s0 - start) as usize;+ for ch in tbuf.channels.iter_mut() {+ ch[off..off + n].fill(0.0);}- let g = db_to_gain(track.volume_db);- let pan = (track.pan / 100.0).clamp(-1.0, 1.0) as f32;- let (gl, gr) = pan_gains(pan);- out.mix_from(&tbuf, &[g * gl, g * gr]);- }- let mg = db_to_gain(seq.master_volume_db);- if (mg - 1.0).abs() > 1e-6 {- for ch in &mut out.channels {- for s in ch.iter_mut() {- *s *= mg;+ let mut a = AudioBuffer::silence(sr, 2, n);+ let mut b = AudioBuffer::silence(sr, 2, n);+ if let Some(f) = from {+ mix_item(project, f, s0, n, sr, sources, &mut a, 1.0);+ }+ if let Some(tt) = to {+ mix_item(project, tt, s0, n, sr, sources, &mut b, 1.0);+ }+ let dur = (tr.end() - tr.start).to_units_floor(sr as i64).max(1) as f32;+ let base = (s0 - tr.start.to_units_floor(sr as i64)) as f32;+ for i in 0..n {+ let p = (base + i as f32) / dur;+ let (ga, gb) = transitions::audio_gains(&tr.effect.effect, p);+ for c in 0..2 {+ tbuf.channels[c][off + i] += a.channels[c][i] * ga + b.channels[c][i] * gb;}}}- out+ tbuf}-/// -3 dB constant-power pan law, normalised so centre = unity.-fn pan_gains(pan: f32) -> (f32, f32) {+/// Balance for stereo signals (clip Panner, stereo track pan): centre = unity on both sides, turning+/// one way attenuates the other side along the −3 dB constant-power curve (normalised so the+/// centre is 0 dB); hard left/right silences the opposite side.+pub fn pan_gains(pan: f32) -> (f32, f32) {let a = (pan + 1.0) * std::f32::consts::FRAC_PI_4;let k = std::f32::consts::SQRT_2;((a.cos() * k).min(1.0), (a.sin() * k).min(1.0))@@ -115,19 +102,23 @@ fn mix_item(project: &Project, item: &TrackItem, start: i64, frames: usize, sr:let chv = item.effect("channel_volume").filter(|e| e.enabled && !e.param("bypass").and_then(|p| p.value.as_bool()).unwrap_or(false));let pan = item.effect("panner").filter(|e| e.enabled);let off = (a0 - start) as usize;- for blk in (0..n).step_by(64) {- let t_tl = Tick::from_units(a0 + blk as i64, sr as i64);+ // Gains change on an absolute 64-sample grid, so the output does not depend on how callers cut+ // the timeline into requests.+ let mut blk = 0usize;+ while blk < n {+ let t_tl = Tick::from_units((a0 + blk as i64).div_euclid(64) * 64, sr as i64);let mt = item.source_time_at(t_tl);let v = vol.map(|e| db_to_gain(e.f64_at("level", mt))).unwrap_or(1.0);let (cl, cr) = chv.map(|e| (db_to_gain(e.f64_at("left", mt)), db_to_gain(e.f64_at("right", mt)))).unwrap_or((1.0, 1.0));let (pl, pr) = pan.map(|e| pan_gains((e.f64_at("balance", mt) / 100.0) as f32)).unwrap_or((1.0, 1.0));let g = clip_gain * v * extra;- let end = (blk + 64).min(n);+ let end = (((a0 + blk as i64).div_euclid(64) + 1) * 64 - a0).min(n as i64) as usize;for i in blk..end {let (l, r) = (buf[0][i], buf[1][i]);out.channels[0][off + i] += l * g * cl * pl;out.channels[1][off + i] += r * g * cr * pr;}+ blk = end;}}diff --git a/crates/render/src/audio_fx.rs b/crates/render/src/audio_fx.rsindex a6a10e8cd..89a3074d3 100644--- a/crates/render/src/audio_fx.rs+++ b/crates/render/src/audio_fx.rs@@ -15,12 +15,12 @@ use filmcraft_project::{EffectInstance, TrackItem};use filmcraft_time::Tick;/// How a project effect maps onto a DSP effect.-struct Mapping {- dsp: &'static str,+pub(crate) struct Mapping {+ pub(crate) dsp: &'static str,/// Pre-roll (seconds) for a fresh chain; closures get the effect instance at the start time.- preroll: fn(&EffectInstance, Tick) -> f64,+ pub(crate) preroll: fn(&EffectInstance, Tick) -> f64,/// Set DSP parameters from the (keyframed) project parameters at media time `mt`.- apply: fn(&mut dyn AudioEffect, &EffectInstance, Tick),+ pub(crate) apply: fn(&mut dyn AudioEffect, &EffectInstance, Tick),}fn ignore(_: bool) {}@@ -29,7 +29,7 @@ fn f(e: &EffectInstance, id: &str, mt: Tick) -> f32 {e.f64_at(id, mt) as f32}-fn mapping(id: &str) -> Option<Mapping> {+pub(crate) fn mapping(id: &str) -> Option<Mapping> {Some(match id {"amplify" => Mapping { dsp: "amplify", preroll: |_, _| 0.0, apply: |d, e, t| ignore(d.set_param("gain", f(e, "gain", t))) },"dynamics" => Mapping {@@ -160,8 +160,10 @@ fn run(chain: &mut Chain, item: &TrackItem, in0: i64, input: &mut [Vec<f32>; 2],let n = input[0].len();let mut i = 0;while i < n {- let end = (i + BLOCK).min(n);- let mt = item.source_time_at(Tick::from_units(in0 + i as i64, sr as i64));+ // absolute block grid: parameters update at the same samples however requests are cut+ let pos = in0 + i as i64;+ let end = (((pos.div_euclid(BLOCK as i64) + 1) * BLOCK as i64 - in0) as usize).min(n);+ let mt = item.source_time_at(Tick::from_units(pos.div_euclid(BLOCK as i64) * BLOCK as i64, sr as i64));for ((e, m), d) in act.iter().zip(chain.fx.iter_mut()) {(m.apply)(d.as_mut(), e, mt);}diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rsindex a723b6bc5..329c46c93 100644--- a/crates/render/src/lib.rs+++ b/crates/render/src/lib.rs@@ -12,6 +12,7 @@ pub mod audio_fx;pub mod blend;pub mod effects;pub mod image;+pub mod mixer;pub mod plan;pub mod preview;pub mod transitions;@@ -304,6 +305,10 @@ pub fn arc_source(s: impl filmcraft_media::MediaSource + 'static) -> SharedSourc#[cfg(test)]mod tests;+#[cfg(test)]+#[path = "mixer_tests.rs"]+mod mixer_tests;+#[cfg(test)]#[path = "preview_tests.rs"]mod preview_tests;diff --git a/crates/render/src/mixer.rs b/crates/render/src/mixer.rsnew file mode 100644index 000000000..e83e0be20--- /dev/null+++ b/crates/render/src/mixer.rs@@ -0,0 +1,803 @@+//! The audio mixer graph (Audio Track Mixer): tracks → submixes → Mix.+//!+//! Signal path of every strip, in Premiere's documented order:+//!+//! ```text+//! track input (clips: gain → clip effects → clip Volume / Channel Volume / Panner, transitions)+//! → input map / mono fold → pre-fader inserts → pre-fader sends → mute → fader (volume)+//! → meter → post-fader inserts → post-fader sends → pan / balance → output (submix or Mix)+//! submix: bus sum → the same strip path → output (Mix or a later submix)+//! Mix: bus sum → pre-fader inserts → fader → meter → post-fader inserts → out+//! ```+//!+//! * **Sample accurate.** Automated lanes (volume, pan, mute, send levels) are evaluated per sample+//! from their keyframes; effect parameters update on an absolute 64-sample grid. The output does+//! not depend on how callers cut the timeline into requests.+//! * **Latency compensated.** Inserts that report latency (look-ahead limiter, STFT effects) delay+//! their strip; every route into a bus gets a compensation delay so all inputs of a bus line up,+//! and the whole graph is read ahead by its total latency, so the output is aligned with the+//! timeline. Automation is evaluated at *content* time (input time minus the latency so far).+//! * **Stateful and pull-based.** Graph state (insert DSP, compensation delays) is cached per graph+//! structure and keyed by the next sample it will produce. Sequential consumers (playback, export,+//! meters) continue it; any other request starts fresh with a pre-roll long enough for effect+//! tails and the graph latency.+//! * **Solo.** When any strip is soloed, a strip stays audible if it is soloed or solo-safe, feeds+//! (directly or through submixes) a soloed or solo-safe strip, or is fed by one. Everything else+//! is solo-muted (silent, sends included). Track mute sits after the pre-fader sends, so+//! pre-fader sends of a muted track keep sending, as in Premiere.+//! * **Pan law.** Mono tracks pan with the −3 dB constant-power law (centre = −3 dB per side);+//! stereo (and, for now, 5.1) tracks and sends use balance (centre = unity, the far side follows+//! the same constant-power curve normalised to the centre).+//!+//! [`LiveMix`] carries what the UI does while playing: control overrides while a fader is held+//! (with Touch's ramp back to the automation), per-strip meters, and the newest project snapshot.++use std::borrow::Cow;+use std::collections::{HashMap, HashSet};+use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::{Arc, Mutex, OnceLock};++use filmcraft_audio_dsp::AudioEffect;+use filmcraft_frame::AudioBuffer;+use filmcraft_project::mixer::{LANE_MUTE, LANE_PAN, LANE_VOLUME, fx_lane, send_lane};+use filmcraft_project::{AudioChannels, EffectInstance, InputMap, Param, ParamValue, Project, Sequence, Track, TrackId};+use filmcraft_time::Tick;+use rayon::prelude::*;++use crate::SourceProvider;+use crate::audio::{pan_gains, track_input};+use crate::audio_fx::{Mapping, mapping};++/// Strip id of the Mix (master) track in [`LiveMix`] and commands.+pub const MASTER: TrackId = filmcraft_project::mixer::MASTER_STRIP;+/// Effect parameters update on this absolute sample grid.+pub const PARAM_BLOCK: i64 = 64;+/// Longest pre-roll for a fresh graph (seconds).+const MAX_PREROLL_S: f64 = 3.0;++// ------------------------------------------------------------------------------------- live state++/// A control held (or just released) on the mixer while playing.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct Override {+ pub value: f64,+ /// Released at `.0`; the value ramps back to the automation over `.1` (Touch).+ pub release: Option<(Tick, Tick)>,+}++/// What the live mixer UI feeds into playback (and reads back from it).+#[derive(Default)]+pub struct LiveMix {+ overrides: Mutex<HashMap<(TrackId, String), Override>>,+ active: AtomicBool,+ meters: Mutex<HashMap<TrackId, [f32; 2]>>,+ project: Mutex<Option<Arc<Project>>>,+}++fn lock<T>(m: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {+ m.lock().unwrap_or_else(|e| e.into_inner())+}++impl LiveMix {+ pub fn new() -> Self {+ Self::default()+ }+ /// Hold a control at `value` (a fader or knob being touched/moved).+ pub fn hold(&self, strip: TrackId, lane: &str, value: f64) {+ lock(&self.overrides).insert((strip, lane.to_string()), Override { value, release: None });+ self.active.store(true, Ordering::Release);+ }+ /// Release a held control at `at`: playback ramps from the held value back to the automation+ /// over `ramp` (zero = jump back immediately).+ pub fn release(&self, strip: TrackId, lane: &str, at: Tick, ramp: Tick) {+ let mut g = lock(&self.overrides);+ if ramp.0 <= 0 {+ g.remove(&(strip, lane.to_string()));+ } else if let Some(o) = g.get_mut(&(strip, lane.to_string())) {+ o.release = Some((at, ramp));+ }+ self.active.store(!g.is_empty(), Ordering::Release);+ }+ pub fn clear(&self, strip: TrackId, lane: &str) {+ let mut g = lock(&self.overrides);+ g.remove(&(strip, lane.to_string()));+ self.active.store(!g.is_empty(), Ordering::Release);+ }+ pub fn clear_all(&self) {+ lock(&self.overrides).clear();+ self.active.store(false, Ordering::Release);+ }+ /// Whether any control is overridden (rendered audio previews are bypassed then).+ pub fn is_active(&self) -> bool {+ self.active.load(Ordering::Acquire)+ }+ pub fn get(&self, strip: TrackId, lane: &str) -> Option<Override> {+ lock(&self.overrides).get(&(strip, lane.to_string())).copied()+ }+ pub fn overrides(&self) -> HashMap<(TrackId, String), Override> {+ lock(&self.overrides).clone()+ }+ /// Peak levels (linear, L/R, post-fader) per strip since the last call; [`MASTER`] is the Mix.+ pub fn take_meters(&self) -> HashMap<TrackId, [f32; 2]> {+ std::mem::take(&mut *lock(&self.meters))+ }+ fn post_meters(&self, m: &[(TrackId, [f32; 2])]) {+ let mut g = lock(&self.meters);+ for (id, p) in m {+ let e = g.entry(*id).or_insert([0.0; 2]);+ e[0] = e[0].max(p[0]);+ e[1] = e[1].max(p[1]);+ }+ }+ /// Publish the newest project snapshot (playback picks up edits made while it runs).+ pub fn publish_project(&self, p: Arc<Project>) {+ *lock(&self.project) = Some(p);+ }+ pub fn project(&self) -> Option<Arc<Project>> {+ lock(&self.project).clone()+ }+}++// ------------------------------------------------------------------------------------- pan laws++/// −3 dB constant-power pan of a mono signal: (left, right) gains; centre = 0.7071 each.+pub fn pan_law_mono(pan: f32) -> (f32, f32) {+ let a = (pan.clamp(-1.0, 1.0) + 1.0) * std::f32::consts::FRAC_PI_4;+ (a.cos(), a.sin())+}++/// Stereo balance (centre = unity). Same curve as the clip Panner.+pub fn balance(pan: f32) -> (f32, f32) {+ pan_gains(pan.clamp(-1.0, 1.0))+}++#[inline]+fn db_gain(db: f64) -> f32 {+ if db <= filmcraft_project::mixer::FADER_MIN_DB { 0.0 } else { 10f64.powf(db / 20.0) as f32 }+}++// ------------------------------------------------------------------------------------- lanes++/// One automatable control of a strip, ready for per-sample evaluation.+struct Lane<'a> {+ param: Option<&'a Param>,+ stat: f64,+ ov: Option<Override>,+ /// Switch lanes (mute) hold between keyframes whatever their interpolation.+ hold: bool,+}++impl<'a> Lane<'a> {+ fn new(track: &'a Track, strip: TrackId, key: &str, ovs: &HashMap<(TrackId, String), Override>) -> Self {+ let reads = track.mixer.mode.reads();+ let param = track.lane(key).filter(|p| reads && p.is_animated());+ let hold = filmcraft_project::mixer::lane_info(key).is_some_and(|i| i.hold);+ Lane { param, stat: track.lane_static(key).unwrap_or(0.0), ov: ovs.get(&(strip, key.to_string())).copied(), hold }+ }+ fn auto(&self, t: Tick) -> f64 {+ match self.param {+ None => self.stat,+ Some(p) if self.hold => {+ let i = p.keyframes.partition_point(|k| k.time <= t);+ p.keyframes[i.saturating_sub(1)].value.as_f64().unwrap_or(0.0)+ }+ Some(p) => p.scalar_at(t),+ }+ }+ /// The value when it is the same at every sample.+ fn constant(&self) -> Option<f64> {+ match self.ov {+ Some(Override { value, release: None }) => Some(value),+ Some(_) => None,+ None => self.param.is_none().then_some(self.stat),+ }+ }+ fn at(&self, t: Tick) -> f64 {+ match self.ov {+ None => self.auto(t),+ Some(Override { value, release: None }) => value,+ Some(Override { value, release: Some((r, d)) }) => {+ if t < r {+ value+ } else if t >= r + d {+ self.auto(t)+ } else {+ let u = (t - r).0 as f64 / d.0.max(1) as f64;+ value + (self.auto(t) - value) * u+ }+ }+ }+ }+ /// Per-sample values for content samples `c0 ..`, mapped through `f`, into `out`.+ /// Returns the constant instead when the lane does not change.+ fn fill(&self, c0: i64, sr: u32, out: &mut [f32], f: impl Fn(f64) -> f32) -> Option<f32> {+ if let Some(v) = self.constant() {+ return Some(f(v));+ }+ for (i, o) in out.iter_mut().enumerate() {+ *o = f(self.at(Tick::from_units(c0 + i as i64, sr as i64)));+ }+ None+ }+}++// ------------------------------------------------------------------------------------- plan++#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+enum Kind {+ Track,+ Submix,+ Master,+}++#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+enum Tap {+ /// After the pre-fader inserts.+ Pre,+ /// After the post-fader inserts (before pan).+ Post,+ /// The strip output (after pan).+ Out,+}++struct Insert<'a> {+ slot: usize,+ effect: Cow<'a, EffectInstance>,+ map: Mapping,+}++struct Strip<'a> {+ track: Cow<'a, Track>,+ kind: Kind,+ pre: Vec<Insert<'a>>,+ post: Vec<Insert<'a>>,+ /// Silent (solo-muted, or muted with nothing tapping before the mute).+ silent: bool,+}++#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+struct RouteSpec {+ src: usize,+ tap: Tap,+ /// Send index (sends), `None` for the main output.+ send: Option<usize>,+ target: usize,+}++struct Plan<'a> {+ strips: Vec<Strip<'a>>,+ routes: Vec<RouteSpec>,+}++fn inserts<'a>(track: &'a Track, post: bool) -> Vec<Insert<'a>> {+ let reads = track.mixer.mode.reads();+ track+ .effects+ .iter()+ .enumerate()+ .take(filmcraft_project::mixer::MAX_INSERTS)+ .filter(|(_, e)| e.enabled && e.post_fader == post && !e.param("bypass").and_then(|p| p.value.as_bool()).unwrap_or(false))+ .filter_map(|(slot, e)| mapping(&e.effect).map(|m| (slot, e, m)))+ .map(|(slot, e, map)| {+ let effect = if reads { Cow::Borrowed(e) } else { Cow::Owned(strip_keyframes(e)) };+ Insert { slot, effect, map }+ })+ .collect()+}++fn strip_keyframes(e: &EffectInstance) -> EffectInstance {+ let mut c = e.clone();+ for p in c.params.values_mut() {+ p.keyframes.clear();+ }+ c+}++impl<'a> Plan<'a> {+ fn build(seq: &'a Sequence, ovs: &HashMap<(TrackId, String), Override>) -> Plan<'a> {+ let mut strips: Vec<Strip<'a>> = Vec::new();+ for t in &seq.audio_tracks {+ strips.push(Strip { track: Cow::Borrowed(t), kind: Kind::Track, pre: inserts(t, false), post: inserts(t, true), silent: false });+ }+ for t in &seq.submix_tracks {+ strips.push(Strip { track: Cow::Borrowed(t), kind: Kind::Submix, pre: inserts(t, false), post: inserts(t, true), silent: false });+ }+ let m = seq.master_strip();+ strips.push(Strip { track: Cow::Owned(m), kind: Kind::Master, pre: Vec::new(), post: Vec::new(), silent: false });+ let mi = strips.len() - 1;+ // master inserts borrow from the sequence (same effects as the owned copy)+ {+ let reads = seq.master_mixer.mode.reads();+ let mk = |post: bool| -> Vec<Insert<'a>> {+ seq.master_effects+ .iter()+ .enumerate()+ .take(filmcraft_project::mixer::MAX_INSERTS)+ .filter(|(_, e)| e.enabled && e.post_fader == post)+ .filter_map(|(slot, e)| {+ mapping(&e.effect).map(|map| Insert { slot, effect: if reads { Cow::Borrowed(e) } else { Cow::Owned(strip_keyframes(e)) }, map })+ })+ .collect()+ };+ strips[mi].pre = mk(false);+ strips[mi].post = mk(true);+ }+ // live overrides of effect parameters+ for s in strips.iter_mut() {+ let id = s.track.id;+ for ins in s.pre.iter_mut().chain(s.post.iter_mut()) {+ let slot = ins.slot;+ let pids: Vec<String> = ins.effect.params.keys().cloned().collect();+ for pid in pids {+ if let Some(o) = ovs.get(&(id, fx_lane(slot, &pid))) {+ let e = ins.effect.to_mut();+ if let Some(p) = e.param_mut(&pid) {+ p.value = ParamValue::Float(o.value);+ p.keyframes.clear();+ }+ }+ }+ }+ }+ // routes+ let ntr = seq.audio_tracks.len();+ let index_of = |id: TrackId| seq.submix_tracks.iter().position(|t| t.id == id).map(|i| ntr + i);+ let mut routes = Vec::new();+ for (si, s) in strips.iter().enumerate() {+ if s.kind == Kind::Master {+ continue;+ }+ // submixes may only feed submixes after them (no feedback)+ let valid = |ti: usize| s.kind == Kind::Track || ti > si;+ for (k, snd) in s.track.mixer.sends.iter().enumerate().take(filmcraft_project::mixer::MAX_SENDS) {+ if let Some(ti) = index_of(snd.target).filter(|&ti| valid(ti)) {+ routes.push(RouteSpec { src: si, tap: if snd.pre_fader { Tap::Pre } else { Tap::Post }, send: Some(k), target: ti });+ }+ }+ let target = s.track.mixer.output.and_then(index_of).filter(|&ti| valid(ti)).unwrap_or(mi);+ routes.push(RouteSpec { src: si, tap: Tap::Out, send: None, target });+ }+ let mut plan = Plan { strips, routes };+ plan.solo(ovs);+ plan+ }++ /// Solo-mute and static-mute pruning.+ fn solo(&mut self, ovs: &HashMap<(TrackId, String), Override>) {+ let n = self.strips.len();+ let soloed: Vec<usize> = (0..n).filter(|&i| self.strips[i].kind != Kind::Master && self.strips[i].track.solo).collect();+ if !soloed.is_empty() {+ let mut keep: HashSet<usize> = soloed.iter().copied().collect();+ keep.extend((0..n).filter(|&i| self.strips[i].kind != Kind::Master && self.strips[i].track.mixer.solo_safe));+ let seeds: Vec<usize> = keep.iter().copied().collect();+ // downstream and upstream closures+ for &s in &seeds {+ let mut stack = vec![s];+ while let Some(x) = stack.pop() {+ for r in self.routes.iter().filter(|r| r.src == x) {+ if keep.insert(r.target) {+ stack.push(r.target);+ }+ }+ }+ let mut stack = vec![s];+ while let Some(x) = stack.pop() {+ for r in self.routes.iter().filter(|r| r.target == x) {+ if keep.insert(r.src) {+ stack.push(r.src);+ }+ }+ }+ }+ for (i, s) in self.strips.iter_mut().enumerate() {+ if s.kind != Kind::Master && !keep.contains(&i) {+ s.silent = true;+ }+ }+ }+ // statically muted with nothing before the mute that is heard: skip entirely+ for (i, s) in self.strips.iter_mut().enumerate() {+ let id = s.track.id;+ let mute_static = Lane::new(&s.track, id, LANE_MUTE, ovs).constant().is_some_and(|m| m >= 0.5);+ let pre_sends = self.routes.iter().any(|r| r.src == i && r.tap == Tap::Pre);+ if s.kind != Kind::Master && mute_static && !pre_sends {+ s.silent = true;+ }+ }+ }++ fn structure_hash(&self, sr: u32) -> u64 {+ use std::hash::{Hash, Hasher};+ let mut h = std::collections::hash_map::DefaultHasher::new();+ sr.hash(&mut h);+ for s in &self.strips {+ s.track.id.hash(&mut h);+ s.kind.hash(&mut h);+ for (side, v) in [(0u8, &s.pre), (1u8, &s.post)] {+ for i in v.iter() {+ (side, i.slot, &i.effect.effect, i.map.dsp).hash(&mut h);+ }+ }+ }+ self.routes.hash(&mut h);+ h.finish()+ }++ /// Longest pre-roll the inserts need for a fresh graph (samples).+ fn preroll(&self, t: Tick, sr: u32) -> usize {+ let s = self.strips.iter().flat_map(|s| s.pre.iter().chain(&s.post)).map(|i| (i.map.preroll)(&i.effect, t)).fold(0.0, f64::max);+ (s.min(MAX_PREROLL_S) * sr as f64).ceil() as usize+ }+}++// ------------------------------------------------------------------------------------- state++struct DelayLine {+ buf: Vec<[f32; 2]>,+ pos: usize,+}++impl DelayLine {+ fn new(len: usize) -> Self {+ DelayLine { buf: vec![[0.0; 2]; len], pos: 0 }+ }+ /// Delay `x` in place.+ fn run(&mut self, x: &mut [Vec<f32>; 2]) {+ if self.buf.is_empty() {+ return;+ }+ let n = self.buf.len();+ for i in 0..x[0].len() {+ let out = self.buf[self.pos];+ self.buf[self.pos] = [x[0][i], x[1][i]];+ x[0][i] = out[0];+ x[1][i] = out[1];+ self.pos = (self.pos + 1) % n;+ }+ }+ fn clear(&mut self) {+ self.buf.fill([0.0; 2]);+ }+}++struct StripState {+ pre: Vec<Box<dyn AudioEffect>>,+ post: Vec<Box<dyn AudioEffect>>,+ lat_pre: usize,+ lat_post: usize,+ /// Latency of the strip's input (bus alignment).+ in_lat: usize,+ /// Compensation delay per outgoing route (same order as the plan's routes from this strip).+ delays: Vec<DelayLine>,+}++struct GraphState {+ next_out: i64,+ strips: Vec<StripState>,+ latency: usize,+}++fn build_state(plan: &Plan, sr: u32) -> GraphState {+ let mk = |v: &[Insert]| -> Vec<Box<dyn AudioEffect>> { v.iter().filter_map(|i| filmcraft_audio_dsp::create_effect(i.map.dsp, sr as f32, 2)).collect() };+ let mut strips: Vec<StripState> = plan+ .strips+ .iter()+ .map(|s| {+ let pre = mk(&s.pre);+ let post = mk(&s.post);+ let lat_pre = pre.iter().map(|d| d.latency()).sum();+ let lat_post = post.iter().map(|d| d.latency()).sum();+ StripState { pre, post, lat_pre, lat_post, in_lat: 0, delays: Vec::new() }+ })+ .collect();+ let tap_lat = |s: &StripState, tap: Tap| s.in_lat + if tap == Tap::Pre { s.lat_pre } else { s.lat_pre + s.lat_post };+ // strips are in topological order (routes only go forward)+ for i in 0..strips.len() {+ let in_lat = plan.routes.iter().filter(|r| r.target == i).map(|r| tap_lat(&strips[r.src], r.tap)).max().unwrap_or(0);+ strips[i].in_lat = in_lat;+ }+ for r in &plan.routes {+ let d = strips[r.target].in_lat - tap_lat(&strips[r.src], r.tap);+ strips[r.src].delays.push(DelayLine::new(d));+ }+ let m = strips.len() - 1;+ let latency = strips[m].in_lat + strips[m].lat_pre + strips[m].lat_post;+ GraphState { next_out: 0, strips, latency }+}++fn cache() -> &'static Mutex<HashMap<u64, Vec<GraphState>>> {+ static C: OnceLock<Mutex<HashMap<u64, Vec<GraphState>>>> = OnceLock::new();+ C.get_or_init(Default::default)+}++/// Total latency (samples) of the sequence's mixer graph: how far ahead of the timeline the graph+/// is read so its output lines up.+pub fn graph_latency(seq: &Sequence) -> usize {+ let plan = Plan::build(seq, &HashMap::new());+ build_state(&plan, seq.settings.sample_rate).latency+}++// ------------------------------------------------------------------------------------- processing++type Stereo = [Vec<f32>; 2];++fn silent(n: usize) -> Stereo {+ [vec![0.0; n], vec![0.0; n]]+}++/// Run `chain` over `buf` (input-time samples from `x0`) with parameters at content time+/// `x - lat` updated on the absolute [`PARAM_BLOCK`] grid.+fn run_inserts(chain: &mut [Box<dyn AudioEffect>], ins: &[Insert], buf: &mut Stereo, x0: i64, lat: usize, sr: u32) {+ if chain.is_empty() {+ return;+ }+ let n = buf[0].len();+ let mut i = 0usize;+ while i < n {+ let pos = x0 + i as i64;+ let end = (((pos.div_euclid(PARAM_BLOCK) + 1) * PARAM_BLOCK - x0) as usize).min(n);+ // parameters of the whole grid block (also when a request starts mid-block)+ let t = Tick::from_units(pos.div_euclid(PARAM_BLOCK) * PARAM_BLOCK - lat as i64, sr as i64);+ for (d, e) in chain.iter_mut().zip(ins) {+ (e.map.apply)(d.as_mut(), &e.effect, t);+ }+ let [l, r] = buf;+ let mut ch: [&mut [f32]; 2] = [&mut l[i..end], &mut r[i..end]];+ for d in chain.iter_mut() {+ d.process(&mut ch);+ }+ i = end;+ }+}++/// Multiply by a per-sample (or constant) gain pair.+fn apply_gain(buf: &mut Stereo, g: Option<f32>, per: &[f32]) {+ match g {+ Some(1.0) => {}+ Some(g) => {+ for c in buf.iter_mut() {+ for s in c.iter_mut() {+ *s *= g;+ }+ }+ }+ None => {+ for c in buf.iter_mut() {+ for (s, g) in c.iter_mut().zip(per) {+ *s *= g;+ }+ }+ }+ }+}++/// Apply a pan/balance lane (values −100 … 100) with `law`.+fn apply_pan(buf: &mut Stereo, lane: &Lane, c0: i64, sr: u32, law: fn(f32) -> (f32, f32), scratch: &mut [f32]) {+ match lane.fill(c0, sr, scratch, |v| v as f32) {+ Some(p) => {+ let (gl, gr) = law(p / 100.0);+ if gl != 1.0 || gr != 1.0 {+ buf[0].iter_mut().for_each(|s| *s *= gl);+ buf[1].iter_mut().for_each(|s| *s *= gr);+ }+ }+ None => {+ for (i, p) in scratch.iter().enumerate() {+ let (gl, gr) = law(p / 100.0);+ buf[0][i] *= gl;+ buf[1][i] *= gr;+ }+ }+ }+}++struct StripOut {+ /// (route index in the plan, delayed signal)+ routes: Vec<(usize, Stereo)>,+ meter: [f32; 2],+ /// Final signal (Mix only).+ out: Option<Stereo>,+}++#[allow(clippy::too_many_arguments)]+fn run_strip(+ plan: &Plan,+ si: usize,+ st: &mut StripState,+ mut buf: Stereo,+ x0: i64,+ skip: usize,+ sr: u32,+ ovs: &HashMap<(TrackId, String), Override>,+) -> StripOut {+ let s = &plan.strips[si];+ let tr: &Track = &s.track;+ let id = tr.id;+ let n = buf[0].len();+ let my_routes: Vec<(usize, &RouteSpec)> = plan.routes.iter().enumerate().filter(|(_, r)| r.src == si).collect();+ let mut outs: Vec<(usize, Stereo)> = Vec::new();+ let mut scratch = vec![0f32; n];+ // input map / mono fold (tracks)+ let mono = tr.channels == AudioChannels::Mono;+ if s.kind != Kind::Master {+ let [l, r] = &mut buf;+ match tr.mixer.input_map {+ InputMap::Stereo => {}+ InputMap::Left => r.copy_from_slice(l),+ InputMap::Right => l.copy_from_slice(r),+ InputMap::Swap => std::mem::swap(l, r),+ InputMap::Mono => {+ for (a, b) in l.iter_mut().zip(r.iter_mut()) {+ let m = (*a + *b) * 0.5;+ *a = m;+ *b = m;+ }+ }+ }+ if mono && tr.mixer.input_map != InputMap::Mono {+ for (a, b) in l.iter_mut().zip(r.iter_mut()) {+ let m = (*a + *b) * 0.5;+ *a = m;+ *b = m;+ }+ }+ }+ let lat_a = st.in_lat;+ run_inserts(&mut st.pre, &s.pre, &mut buf, x0, lat_a, sr);+ let lat_b = st.in_lat + st.lat_pre;+ let c_b = x0 - lat_b as i64;+ let send = |tap: Tap, buf: &Stereo, c0: i64, scratch: &mut [f32], st: &mut StripState, outs: &mut Vec<(usize, Stereo)>| {+ for (k, (ri, r)) in my_routes.iter().enumerate() {+ if r.tap != tap {+ continue;+ }+ let mut sig = buf.clone();+ if let Some(si) = r.send {+ let snd = &tr.mixer.sends[si];+ if snd.muted {+ sig = silent(n);+ } else {+ let lane = Lane::new(tr, id, &send_lane(si), ovs);+ let g = lane.fill(c0, sr, scratch, db_gain);+ apply_gain(&mut sig, g, scratch);+ let (gl, gr) = balance((snd.pan / 100.0) as f32);+ if gl != 1.0 || gr != 1.0 {+ sig[0].iter_mut().for_each(|x| *x *= gl);+ sig[1].iter_mut().for_each(|x| *x *= gr);+ }+ }+ }+ st.delays[k].run(&mut sig);+ outs.push((*ri, sig));+ }+ };+ send(Tap::Pre, &buf, c_b, &mut scratch, st, &mut outs);+ // mute → fader+ let mute = Lane::new(tr, id, LANE_MUTE, ovs);+ match mute.fill(c_b, sr, &mut scratch, |m| if m >= 0.5 { 0.0 } else { 1.0 }) {+ Some(g) => apply_gain(&mut buf, Some(g), &[]),+ None => apply_gain(&mut buf, None, &scratch),+ }+ let vol = Lane::new(tr, id, LANE_VOLUME, ovs);+ let g = vol.fill(c_b, sr, &mut scratch, db_gain);+ apply_gain(&mut buf, g, &scratch);+ let mut meter = [0f32; 2];+ for (c, m) in meter.iter_mut().enumerate() {+ *m = buf[c][skip.min(n)..].iter().fold(0f32, |a, x| a.max(x.abs()));+ }+ run_inserts(&mut st.post, &s.post, &mut buf, x0, lat_b, sr);+ let lat_c = lat_b + st.lat_post;+ let c_c = x0 - lat_c as i64;+ send(Tap::Post, &buf, c_c, &mut scratch, st, &mut outs);+ if s.kind == Kind::Master {+ return StripOut { routes: outs, meter, out: Some(buf) };+ }+ let pan = Lane::new(tr, id, LANE_PAN, ovs);+ apply_pan(&mut buf, &pan, c_c, sr, if mono { pan_law_mono } else { balance }, &mut scratch);+ send(Tap::Out, &buf, c_c, &mut scratch, st, &mut outs);+ StripOut { routes: outs, meter, out: None }+}++/// Mix `frames` stereo samples of the sequence starting at sample `start` through the mixer graph.+/// `live` adds the UI's held controls and receives the meters.+pub fn mix_graph(project: &Project, seq: &Sequence, start: i64, frames: usize, sources: &dyn SourceProvider, live: Option<&LiveMix>) -> AudioBuffer {+ let sr = seq.settings.sample_rate.max(1);+ let ovs = live.filter(|l| l.is_active()).map(LiveMix::overrides).unwrap_or_default();+ let plan = Plan::build(seq, &ovs);+ let key = plan.structure_hash(sr);+ let taken = {+ let mut c = lock(cache());+ c.get_mut(&key).and_then(|v| v.iter().position(|g| g.next_out == start).map(|i| v.swap_remove(i)))+ };+ let (mut st, skip) = match taken {+ Some(st) => (st, 0usize),+ None => {+ let st = build_state(&plan, sr);+ let pre = plan.preroll(Tick::from_units(start, sr as i64), sr).max(st.latency);+ (st, pre)+ }+ };+ let lat = st.latency as i64;+ let x0 = start + lat - skip as i64;+ let total = skip + frames;+ let ns = plan.strips.len();+ let mut bus: Vec<Option<Stereo>> = (0..ns).map(|_| None).collect();+ let mut meters: Vec<(TrackId, [f32; 2])> = Vec::new();+ let range = filmcraft_time::TimeRange::from_bounds(Tick::from_units(x0, sr as i64), Tick::from_units(x0 + total as i64, sr as i64));+ // tracks: independent, in parallel+ let ntr = plan.strips.iter().take_while(|s| s.kind == Kind::Track).count();+ let (track_states, rest) = st.strips.split_at_mut(ntr);+ let track_outs: Vec<Option<StripOut>> = track_states+ .par_iter_mut()+ .enumerate()+ .map(|(si, ss)| {+ let s = &plan.strips[si];+ if s.silent {+ ss.delays.iter_mut().for_each(DelayLine::clear);+ return None;+ }+ let has_clips = s.track.items.iter().any(|i| i.enabled && i.range().overlaps(&range));+ if !has_clips && s.pre.is_empty() && s.post.is_empty() && ss.delays.iter().all(|d| d.buf.is_empty()) {+ return None;+ }+ let input = if has_clips {+ let b = track_input(project, &s.track, x0, total, sr, sources);+ let mut it = b.channels.into_iter();+ [it.next().unwrap_or_else(|| vec![0.0; total]), it.next().unwrap_or_else(|| vec![0.0; total])]+ } else {+ silent(total)+ };+ Some(run_strip(&plan, si, ss, input, x0, skip, sr, &ovs))+ })+ .collect();+ let deliver = |o: StripOut, si: usize, bus: &mut Vec<Option<Stereo>>, meters: &mut Vec<(TrackId, [f32; 2])>| {+ meters.push((plan.strips[si].track.id, o.meter));+ for (ri, sig) in o.routes {+ let t = plan.routes[ri].target;+ let b = bus[t].get_or_insert_with(|| silent(total));+ for c in 0..2 {+ for (d, s) in b[c].iter_mut().zip(&sig[c]) {+ *d += *s;+ }+ }+ }+ o.out+ };+ for (si, o) in track_outs.into_iter().enumerate() {+ if let Some(o) = o {+ deliver(o, si, &mut bus, &mut meters);+ }+ }+ // submixes in order, then the Mix+ let mut out = silent(total);+ for (k, ss) in rest.iter_mut().enumerate() {+ let si = ntr + k;+ let s = &plan.strips[si];+ if s.silent {+ ss.delays.iter_mut().for_each(DelayLine::clear);+ continue;+ }+ let input = bus[si].take().unwrap_or_else(|| silent(total));+ let o = run_strip(&plan, si, ss, input, x0, skip, sr, &ovs);+ if let Some(fin) = deliver(o, si, &mut bus, &mut meters) {+ out = fin;+ }+ }+ st.next_out = start + frames as i64;+ {+ let mut c = lock(cache());+ let v = c.entry(key).or_default();+ v.push(st);+ if v.len() > 4 {+ v.remove(0);+ }+ if c.len() > 64 {+ c.clear();+ }+ }+ if let Some(l) = live {+ l.post_meters(&meters);+ }+ let [l, r] = out;+ AudioBuffer { sample_rate: sr, channels: vec![l[skip..].to_vec(), r[skip..].to_vec()] }+}diff --git a/crates/render/src/mixer_tests.rs b/crates/render/src/mixer_tests.rsnew file mode 100644index 000000000..d4270dae7--- /dev/null+++ b/crates/render/src/mixer_tests.rs@@ -0,0 +1,434 @@+//! Mixer graph tests: gain and pan laws, automation, solo/mute, sends, latency, identity, speed.++use std::sync::Arc;++use filmcraft_frame::{AudioBuffer, VideoFrame};+use filmcraft_media::{AudioStreamInfo, FrameRequest, MediaError, MediaInfo, MediaKind, MediaSource};+use filmcraft_project::mixer::{LANE_MUTE, LANE_PAN, LANE_VOLUME, send_lane};+use filmcraft_project::{+ AudioChannels, AutomationMode, ItemId, ItemKind, Keyframe, Label, MediaClip, MediaRef, ParamValue, Project, SequenceSettings, Track, TrackId, TrackKind,+ TrackSend,+};+use filmcraft_time::{FrameRate, TICKS_PER_SECOND, Tick, TimeRange};++use crate::SourceMap;+use crate::mixer::{LiveMix, balance, graph_latency, mix_graph, pan_law_mono};++const SR: i64 = 48_000;++/// A synthetic stereo source: `f(sample, channel)`.+struct FnSource {+ info: MediaInfo,+ f: fn(i64, usize) -> f32,+}++impl MediaSource for FnSource {+ fn info(&self) -> &MediaInfo {+ &self.info+ }+ fn video_frame(&self, _: FrameRequest) -> filmcraft_media::Result<Arc<VideoFrame>> {+ Err(MediaError::Unsupported("audio only".into()))+ }+ fn audio(&self, start: i64, frames: usize, sample_rate: u32) -> filmcraft_media::Result<AudioBuffer> {+ let f = self.f;+ Ok(AudioBuffer { sample_rate, channels: (0..2).map(|c| (0..frames).map(|i| f(start + i as i64, c)).collect()).collect() })+ }+}++struct Rig {+ p: Project,+ seq: ItemId,+ map: SourceMap,+}++impl Rig {+ /// A sequence with `n` audio tracks, each holding one 10 s clip of its signal.+ fn new(signals: &[fn(i64, usize) -> f32]) -> Rig {+ let mut p = Project::new("mix");+ let seq = p.new_sequence("s", SequenceSettings::default(), 0, signals.len(), None);+ let mut map = SourceMap::default();+ for (k, f) in signals.iter().enumerate() {+ let info = MediaInfo {+ name: format!("sig{k}"),+ kind: MediaKind::AudioOnly,+ duration: Tick(10 * TICKS_PER_SECOND),+ video: None,+ audio: Some(AudioStreamInfo { sample_rate: 48_000, channels: 2, codec: "test".into(), bits_per_sample: Some(32) }),+ container: "test".into(),+ start_timecode: None,+ file_size: None,+ };+ let id = p.add_item(+ &info.name.clone(),+ Label::Iris,+ ItemKind::Media(MediaClip {+ media: MediaRef::File { path: format!("/sig{k}.wav") },+ info: info.clone(),+ interpret: Default::default(),+ mark_in: None,+ mark_out: None,+ markers: vec![],+ offline: false,+ proxy: None,+ }),+ None,+ );+ map.0.insert(id, Arc::new(FnSource { info, f: *f }));+ let ti = p.make_track_item(id, TrackKind::Audio, Tick::ZERO, TimeRange::new(Tick::ZERO, Tick(10 * TICKS_PER_SECOND)), FrameRate::FPS_24).unwrap();+ p.sequence_mut(seq).unwrap().audio_tracks[k].items.push(ti);+ }+ Rig { p, seq, map }+ }+ fn track(&mut self, k: usize) -> &mut Track {+ &mut self.p.sequence_mut(self.seq).unwrap().audio_tracks[k]+ }+ fn add_submix(&mut self, name: &str) -> TrackId {+ let id = TrackId(self.p.alloc_id());+ self.p.sequence_mut(self.seq).unwrap().submix_tracks.push(Track::new(id, TrackKind::Audio, name.into()));+ id+ }+ fn submix(&mut self, id: TrackId) -> &mut Track {+ self.p.sequence_mut(self.seq).unwrap().mix_track_mut(id).unwrap()+ }+ fn mix(&self, start: i64, n: usize) -> [Vec<f32>; 2] {+ let b = mix_graph(&self.p, self.p.sequence(self.seq).unwrap(), start, n, &self.map, None);+ [b.channels[0].clone(), b.channels[1].clone()]+ }+ /// Mix `[start, start + n)` in consecutive requests of the given sizes (cycled).+ fn mix_cut(&self, start: i64, n: usize, sizes: &[usize], live: Option<&LiveMix>) -> [Vec<f32>; 2] {+ let mut out = [Vec::new(), Vec::new()];+ let (mut pos, mut k) = (start, 0);+ while pos < start + n as i64 {+ let m = sizes[k % sizes.len()].min((start + n as i64 - pos) as usize);+ let b = mix_graph(&self.p, self.p.sequence(self.seq).unwrap(), pos, m, &self.map, live);+ out[0].extend_from_slice(&b.channels[0]);+ out[1].extend_from_slice(&b.channels[1]);+ pos += m as i64;+ k += 1;+ }+ out+ }+}++fn dc(_: i64, _: usize) -> f32 {+ 0.5+}++fn kf(t_samples: i64, v: f64) -> Keyframe {+ Keyframe::new(Tick::from_units(t_samples, SR), ParamValue::Float(v))+}++fn close(a: f32, b: f32, tol: f32) -> bool {+ (a - b).abs() <= tol+}++#[test]+fn fader_gain_is_sample_exact() {+ let mut r = Rig::new(&[dc]);+ r.track(0).volume_db = -6.0;+ let [l, rr] = r.mix(1000, 256);+ let g = 0.5 * 10f32.powf(-6.0 / 20.0);+ assert!(l.iter().chain(&rr).all(|&s| close(s, g, 1e-6)), "{} vs {g}", l[0]);+ // −∞ silences; +15 dB is the top of the fader+ r.track(0).volume_db = -96.0;+ assert!(r.mix(0, 64)[0].iter().all(|&s| s == 0.0));+ r.track(0).volume_db = 15.0;+ assert!(close(r.mix(0, 64)[0][10], 0.5 * 10f32.powf(0.75), 1e-5));+ // Mix fader multiplies on top+ r.track(0).volume_db = -6.0;+ r.p.sequence_mut(r.seq).unwrap().master_volume_db = -6.0;+ assert!(close(r.mix(0, 64)[0][3], 0.5 * 10f32.powf(-12.0 / 20.0), 1e-6));+}++#[test]+fn pan_laws() {+ // mono track: −3 dB constant power (centre 0.7071 per side, power constant across the arc)+ for p in [-100.0, -50.0, 0.0, 25.0, 100.0] {+ let (l, r) = pan_law_mono((p / 100.0) as f32);+ assert!(close(l * l + r * r, 1.0, 1e-6), "power at {p}");+ }+ let (l, r) = pan_law_mono(0.0);+ assert!(close(20.0 * l.log10(), -3.0103, 1e-3) && close(l, r, 1e-7));+ let mut rig = Rig::new(&[dc]);+ rig.track(0).channels = AudioChannels::Mono;+ rig.track(0).pan = 50.0;+ let [l, r] = rig.mix(0, 128);+ let a = 1.5 * std::f32::consts::FRAC_PI_4;+ assert!(close(l[64], 0.5 * a.cos(), 1e-6) && close(r[64], 0.5 * a.sin(), 1e-6), "{} {}", l[64], r[64]);+ rig.track(0).pan = -100.0;+ let [l, r] = rig.mix(0, 128);+ assert!(close(l[1], 0.5, 1e-6) && r[1].abs() < 1e-6);+ // stereo track: balance (centre unity, far side attenuated)+ rig.track(0).channels = AudioChannels::Stereo;+ rig.track(0).pan = 0.0;+ let [l, r] = rig.mix(0, 64);+ assert!(close(l[5], 0.5, 1e-7) && close(r[5], 0.5, 1e-7));+ rig.track(0).pan = 50.0;+ let (bl, br) = balance(0.5);+ let [l, r] = rig.mix(0, 64);+ assert!(close(l[5], 0.5 * bl, 1e-6) && close(r[5], 0.5 * br, 1e-6) && br == 1.0 && bl < 0.6);+}++#[test]+fn volume_automation_is_sample_accurate_and_block_invariant() {+ let mut r = Rig::new(&[dc]);+ {+ let t = r.track(0);+ let lane = t.lane_mut(LANE_VOLUME).unwrap();+ lane.keyframes = vec![kf(0, 0.0), kf(1000, -20.0), kf(1500, -20.0), kf(1600, 0.0)];+ }+ let whole = r.mix(0, 2000);+ for k in [0usize, 1, 63, 64, 65, 127, 128, 500, 999, 1000, 1500, 1550, 1599, 1600] {+ let db = if k <= 1000 {+ -20.0 * k as f64 / 1000.0+ } else if k <= 1500 {+ -20.0+ } else if k <= 1600 {+ -20.0 + 20.0 * (k - 1500) as f64 / 100.0+ } else {+ 0.0+ };+ let want = 0.5 * 10f64.powf(db / 20.0);+ assert!((whole[0][k] as f64 - want).abs() < 1e-6, "sample {k}: {} vs {want}", whole[0][k]);+ }+ // the same range cut into odd-sized requests is bit-identical+ for sizes in [&[1usize, 63, 64, 65][..], &[333], &[7, 1024, 5]] {+ let cut = r.mix_cut(0, 2000, sizes, None);+ assert_eq!(cut, whole, "cut {sizes:?}");+ }+ // Off mode ignores the automation+ r.track(0).mixer.mode = AutomationMode::Off;+ assert!(close(r.mix(1200, 16)[0][0], 0.5, 1e-7));+}++#[test]+fn effect_and_pan_automation_on_the_block_grid() {+ let mut r = Rig::new(&[dc]);+ {+ let t = r.track(0);+ let mut amp = filmcraft_project::find_effect("amplify").unwrap().instance();+ let g = amp.param_mut("gain").unwrap();+ g.keyframes = vec![kf(0, 0.0), kf(4800, 6.0)];+ t.effects.push(amp);+ t.lane_mut(LANE_PAN).unwrap().keyframes = vec![kf(0, -100.0), kf(4800, 100.0)];+ }+ let whole = r.mix(0, 4800);+ for sizes in [&[100usize, 17][..], &[64], &[4800]] {+ assert_eq!(r.mix_cut(0, 4800, sizes, None), whole, "{sizes:?}");+ }+ // hard left at the start, hard right at the end+ assert!(whole[1][0].abs() < 1e-6 && whole[0][4799].abs() < 1e-3);+}++#[test]+fn clip_volume_and_track_automation_both_apply() {+ let mut r = Rig::new(&[dc]);+ {+ let t = r.track(0);+ let it = &mut t.items[0];+ let lvl = it.effect_mut("volume").unwrap().param_mut("level").unwrap();+ lvl.keyframes = vec![Keyframe::new(Tick::ZERO, ParamValue::Float(-6.0)), Keyframe::new(Tick(TICKS_PER_SECOND), ParamValue::Float(-6.0))];+ t.lane_mut(LANE_VOLUME).unwrap().keyframes = vec![kf(0, -6.0), kf(48_000, -6.0)];+ }+ let [l, _] = r.mix(100, 64);+ assert!(close(l[0], 0.5 * 10f32.powf(-12.0 / 20.0), 1e-6), "{}", l[0]);+}++fn level(r: &Rig) -> f32 {+ r.mix(2000, 64)[0][10]+}++fn dc1(_: i64, _: usize) -> f32 {+ 0.1+}+fn dc2(_: i64, _: usize) -> f32 {+ 0.2+}+fn dc4(_: i64, _: usize) -> f32 {+ 0.4+}++#[test]+fn solo_and_mute_logic() {+ let mut r = Rig::new(&[dc1, dc2, dc4]);+ let s1 = r.add_submix("Submix 1");+ r.track(1).mixer.output = Some(s1);+ assert!(close(level(&r), 0.7, 1e-6));+ r.track(0).solo = true;+ assert!(close(level(&r), 0.1, 1e-6), "solo A1");+ r.track(0).muted = true;+ assert!(close(level(&r), 0.0, 1e-6), "soloed but muted");+ r.track(0).muted = false;+ r.track(0).solo = false;+ // soloing a submix keeps its sources+ r.submix(s1).solo = true;+ assert!(close(level(&r), 0.2, 1e-6), "solo S1");+ r.submix(s1).solo = false;+ // soloing a track keeps its destination submix+ r.track(1).solo = true;+ assert!(close(level(&r), 0.2, 1e-6), "solo A2 through S1");+ // solo safe: a solo-safe submix and its sources stay audible while others solo+ let s2 = r.add_submix("Dialogue");+ r.track(2).mixer.output = Some(s2);+ r.submix(s2).mixer.solo_safe = true;+ assert!(close(level(&r), 0.6, 1e-6), "solo A2 + solo-safe S2");+ r.submix(s2).mixer.solo_safe = false;+ assert!(close(level(&r), 0.2, 1e-6));+ r.track(1).solo = false;+ // mute automation (hold)+ r.track(2).lane_mut(LANE_MUTE).unwrap().keyframes = vec![kf(0, 0.0), kf(2005, 1.0)];+ let x = r.mix(2000, 10)[0].clone();+ assert!(close(x[4], 0.7, 1e-6) && close(x[5], 0.3, 1e-6), "{x:?}");+}++#[test]+fn sends_route_to_submixes() {+ let mut r = Rig::new(&[dc]);+ let fx = r.add_submix("Reverb");+ {+ let t = r.track(0);+ let mut s = TrackSend::new(fx);+ s.level_db = -6.0;+ t.mixer.sends.push(s);+ }+ let g6 = 10f32.powf(-6.0 / 20.0);+ assert!(close(level(&r), 0.5 + 0.5 * g6, 1e-6), "post-fader send adds to the Mix");+ // post-fader send follows the fader+ r.track(0).volume_db = -6.0;+ assert!(close(level(&r), 0.5 * g6 + 0.5 * g6 * g6, 1e-6));+ // pre-fader send ignores fader and mute+ r.track(0).mixer.sends[0].pre_fader = true;+ r.track(0).muted = true;+ assert!(close(level(&r), 0.5 * g6, 1e-6), "pre-fader send of a muted track");+ r.track(0).muted = false;+ r.track(0).volume_db = -96.0;+ assert!(close(level(&r), 0.5 * g6, 1e-6));+ // send level automation and submix fader+ r.track(0).lane_mut(&send_lane(0)).unwrap().keyframes = vec![kf(0, 0.0), kf(4000, 0.0)];+ r.submix(fx).volume_db = -6.0;+ assert!(close(level(&r), 0.5 * g6, 1e-6));+ // the track output can go to a submix; submixes chain forward only+ r.track(0).volume_db = 0.0;+ r.track(0).mixer.sends.clear();+ r.track(0).mixer.output = Some(fx);+ let fx2 = r.add_submix("Bus 2");+ r.submix(fx).mixer.output = Some(fx2);+ r.submix(fx2).volume_db = -6.0;+ assert!(close(level(&r), 0.5 * g6 * g6, 1e-6));+ // a backwards route (feedback) falls back to the Mix+ r.submix(fx2).mixer.output = Some(fx);+ assert!(close(level(&r), 0.5 * g6 * g6, 1e-6));+}++fn impulse(i: i64, _: usize) -> f32 {+ if i == 10_000 { 0.25 } else { 0.0 }+}++#[test]+fn latency_compensation_aligns_paths() {+ // A1 goes through a look-ahead limiter (latency), A2 is dry; both carry the same impulse.+ let mut r = Rig::new(&[impulse, impulse]);+ let mut lim = filmcraft_project::find_effect("hard_limiter").unwrap().instance();+ lim.param_mut("max").unwrap().value = ParamValue::Float(0.0);+ r.track(0).effects.push(lim.clone());+ let lat = graph_latency(r.p.sequence(r.seq).unwrap());+ assert!(lat > 0, "limiter reports look-ahead");+ let [l, _] = r.mix(9_000, 2_000);+ let peak = l.iter().enumerate().fold((0usize, 0f32), |m, (i, &s)| if s.abs() > m.1 { (i, s.abs()) } else { m });+ assert_eq!(peak.0 + 9_000, 10_000, "aligned impulse lands on its timeline sample");+ assert!(close(peak.1, 0.5, 1e-3), "both paths sum coherently: {}", peak.1);+ // through a submix with its own latency, a send and a dry path stay aligned+ let bus = r.add_submix("Bus");+ r.submix(bus).effects.push(lim);+ r.track(1).mixer.sends.push(TrackSend::new(bus));+ let [l, _] = r.mix(9_000, 2_000);+ let peak = l.iter().enumerate().fold((0usize, 0f32), |m, (i, &s)| if s.abs() > m.1 { (i, s.abs()) } else { m });+ assert_eq!(peak.0 + 9_000, 10_000);+ assert!(close(peak.1, 0.75, 2e-3), "{}", peak.1);+ // automation is evaluated at content time: a volume step on A1 at the impulse applies to it+ r.track(0).lane_mut(LANE_VOLUME).unwrap().keyframes = vec![kf(0, 0.0), kf(9_999, 0.0), kf(10_000, -96.0)];+ r.track(0).lane_mut(LANE_VOLUME).unwrap().keyframes[1].interp = filmcraft_project::Interpolation::Hold;+ let [l, _] = r.mix(9_000, 2_000);+ assert!(close(l[1000], 0.5, 2e-3), "A1 silenced exactly at its content sample: {}", l[1000]);+}++fn noise(i: i64, c: usize) -> f32 {+ let x = (i as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15) ^ (c as u64 * 0x1234_5678);+ let x = x ^ (x >> 29);+ ((x.wrapping_mul(0xBF58_476D_1CE4_E5B9) >> 40) as f32 / (1u64 << 24) as f32 - 0.5) * 0.4+}++fn busy_rig(tracks: usize) -> Rig {+ let sig: Vec<fn(i64, usize) -> f32> = vec![noise; tracks];+ let mut r = Rig::new(&sig);+ let bus = r.add_submix("Bus");+ let mut comp = filmcraft_project::find_effect("dynamics").unwrap().instance();+ comp.param_mut("threshold").unwrap().value = ParamValue::Float(-20.0);+ r.submix(bus).effects.push(comp);+ for k in 0..tracks {+ let t = r.track(k);+ for (id, post) in [("parametric_eq", false), ("dynamics", false), ("studio_reverb", true)] {+ let mut e = filmcraft_project::find_effect(id).unwrap().instance();+ e.post_fader = post;+ t.effects.push(e);+ }+ t.pan = (k as f64 * 37.0) % 200.0 - 100.0;+ t.lane_mut(LANE_VOLUME).unwrap().keyframes = vec![kf(0, -6.0), kf(96_000, 0.0)];+ if k % 3 == 0 {+ t.mixer.sends.push(TrackSend::new(bus));+ }+ }+ r+}++#[test]+fn render_and_playback_paths_are_identical() {+ // export renders in large batches; playback pulls small device blocks with live meters+ let r = busy_rig(4);+ let export = r.mix_cut(0, 24_000, &[8_000], None);+ let live = LiveMix::new();+ let playback = r.mix_cut(0, 24_000, &[512, 480, 1024], Some(&live));+ assert_eq!(export, playback);+ assert!(export[0].iter().any(|s| s.abs() > 1e-3));+ let m = live.take_meters();+ assert!(m.get(&crate::mixer::MASTER).is_some_and(|p| p[0] > 0.0), "meters published");+ // deterministic: a second render from scratch is identical+ let again = Rig::new(&[]);+ drop(again);+ assert_eq!(busy_rig(4).mix_cut(0, 24_000, &[8_000], None), export);+}++#[test]+fn live_override_holds_and_ramps_back() {+ let mut r = Rig::new(&[dc]);+ r.track(0).lane_mut(LANE_VOLUME).unwrap().keyframes = vec![kf(0, 0.0), kf(96_000, 0.0)];+ let id = r.track(0).id;+ let live = LiveMix::new();+ live.hold(id, LANE_VOLUME, -6.0);+ let b = mix_graph(&r.p, r.p.sequence(r.seq).unwrap(), 0, 64, &r.map, Some(&live));+ assert!(close(b.channels[0][0], 0.5 * 10f32.powf(-0.3), 1e-6));+ // released at sample 4800 with a 4800-sample ramp: halfway back at 7200+ live.release(id, LANE_VOLUME, Tick::from_units(4800, SR), Tick::from_units(4800, SR));+ let b = mix_graph(&r.p, r.p.sequence(r.seq).unwrap(), 7200, 1, &r.map, Some(&live));+ assert!(close(b.channels[0][0], 0.5 * 10f32.powf(-3.0 / 20.0), 1e-6), "{}", b.channels[0][0]);+ let b = mix_graph(&r.p, r.p.sequence(r.seq).unwrap(), 9600, 1, &r.map, Some(&live));+ assert!(close(b.channels[0][0], 0.5, 1e-6));+}++/// 24 tracks × 3 inserts (EQ, Dynamics, Studio Reverb) + a compressed submix at 48 kHz, one core.+#[test]+fn perf_24_tracks_3_effects_realtime_factor() {+ let r = busy_rig(24);+ let secs = if cfg!(debug_assertions) { 2.0 } else { 10.0 };+ let n = (secs * SR as f64) as usize;+ let pool = rayon::ThreadPoolBuilder::new().num_threads(1).build().unwrap();+ // warm up (fresh graph + pre-roll), then time steady-state playback-sized blocks+ pool.install(|| r.mix_cut(0, 4_800, &[1024], None));+ let t0 = std::time::Instant::now();+ pool.install(|| r.mix_cut(4_800, n, &[1024], None));+ let el = t0.elapsed().as_secs_f64();+ let rt = secs / el;+ eprintln!("mixer perf: 24 tracks x 3 inserts + submix, {secs} s of 48 kHz stereo in {el:.3} s on one core = {rt:.1}x realtime");+ let min = if cfg!(debug_assertions) { 1.0 } else { 4.0 };+ assert!(rt > min, "realtime factor {rt:.2}");+}diff --git a/crates/render/src/preview.rs b/crates/render/src/preview.rsindex 11769c0a4..8f0a2a249 100644--- a/crates/render/src/preview.rs+++ b/crates/render/src/preview.rs@@ -247,10 +247,12 @@ pub fn audio_segments(project: &Project, seq_id: ItemId) -> Vec<AudioSegment> {cuts.dedup();let any_solo = seq.audio_tracks.iter().any(|t| t.solo);let mut global = Fnv128::new();- global.json(&(HASH_VERSION, "audio", sr, seq.master_volume_db, &seq.master_effects, any_solo));+ global.json(&(HASH_VERSION, "audio", sr, seq.master_volume_db, &seq.master_effects, &seq.master_mixer, any_solo));for (ti, tr) in seq.audio_tracks.iter().enumerate() {- global.json(&(ti, tr.muted, tr.solo, tr.volume_db, tr.pan, tr.channels, &tr.effects));+ global.json(&(ti, tr.muted, tr.solo, tr.volume_db, tr.pan, tr.channels, &tr.effects, &tr.mixer));}+ // submixes (routing, inserts, automation) affect every segment+ global.json(&seq.submix_tracks);let mut out = Vec::new();for w in cuts.windows(2) {let (a, b) = (w[0], w[1]);