From 245015fd89135eaa0f9b014091e4c8ed5fc0d86c Mon Sep 17 00:00:00 2001 From: Limestudio90 Date: Tue, 13 Oct 2026 14:55:34 +0200 Subject: [PATCH 01/52] VST3 host: IMessage and IAttributeList for plugins (Helix loads its database) `IHostApplication::createInstance` returned nothing, so plugins whose controller and processor exchange `IMessage`s through `IConnectionPoint::notify` could not create one. Line 6 Helix Stadium Native reported "Failed to get content database recovery info (Out of memory condition. [code -2])", loaded no models and exposed no parameters. The host now creates `IMessage` (an id plus its attribute list) and `IAttributeList` (ints, floats, UTF-16 strings and binary blobs, by NUL-terminated attribute id). Strings and blobs are kept in their own allocation so pointers from `getBinary` stay valid while the list holds the value; strings are capped at 1M UTF-16 units and blobs at 256 MiB. Null arguments are refused rather than read. Other classes are still not provided. Verified with Helix Stadium Native 1.03.3a on Windows: the error is gone, its model database and presets load, and its parameters appear in the generic plugin window. A unit test drives the objects through the COM interfaces the way a plugin does. Co-Authored-By: Claude Opus 5.5 --- ROADMAP.md | 1 + crates/vst3-host/src/ffi.rs | 267 +++++++++++++++++++++++++++++++++++- docs/plugin-parity.md | 3 +- 3 files changed, 264 insertions(+), 7 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 73197650..094a9a7d 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -122,6 +122,7 @@ mutated and truncated movies. Field reports from the first public week are track ## Progress log +- **2026-10-13 (VST3 host messages):** The VST3 host creates `IMessage` and `IAttributeList` objects for plugins (`IHostApplication::createInstance`), so plugins whose controller and processor talk through `IConnectionPoint::notify` work: Line 6 Helix Stadium Native now loads its content database (it reported "Failed to get content database recovery info (Out of memory condition)") and exposes its parameters. No readiness percentage change. - **2026-10-13:** `mix.instrument` takes the built-in instrument's parameters in `params` (validated, clamped) and refuses any other field, so a synth setting written beside `plugin` is an error instead of being accepted and ignored (#265) - **2026-10-13:** A bounce of a bus that an aux returns onto lines up with the timeline: the aux insert's lookahead is compensated like the main mix's (it left the bus late and cut the end off), and tracks routed to that bus wait for it too (#246) - **2026-10-13:** Delay compensation covers the inserts of the master faders: a bounce of the main mix with a Maximizer on the master lines up with the same mix without it (it came out 71 samples late) (#351) diff --git a/crates/vst3-host/src/ffi.rs b/crates/vst3-host/src/ffi.rs index d1ddea23..df42934a 100644 --- a/crates/vst3-host/src/ffi.rs +++ b/crates/vst3-host/src/ffi.rs @@ -1,4 +1,4 @@ -//! The FFI boundary: the only module of this crate allowed to use `unsafe`. +//! The FFI boundary: the only module of this rate allowed to use `unsafe`. //! //! It loads VST3 binaries (`libloading`), runs the platform module entry, calls the COM //! interfaces of the factory, component, audio processor and edit controller (`vst3` raw @@ -646,13 +646,32 @@ impl IHostApplicationTrait for HostContext { } } - unsafe fn createInstance(&self, _cid: *mut sb::TUID, _iid: *mut sb::TUID, obj: *mut *mut c_void) -> sb::tresult { - // IMessage / IAttributeList are not provided yet; plugins must cope with that. + /// Creates the objects plugins may ask the host for: `IMessage` (what a controller and its + /// processor send each other through `IConnectionPoint::notify`) and `IAttributeList`. + /// Plugins that talk between their halves this way fail without them (Line 6 Helix + /// reported "Failed to get content database recovery info (Out of memory condition)"). + unsafe fn createInstance(&self, cid: *mut sb::TUID, iid: *mut sb::TUID, obj: *mut *mut c_void) -> sb::tresult { // SAFETY: `obj` is the plugin's out-pointer (or null, handled). - if let Some(o) = unsafe { obj.as_mut() } { - *o = std::ptr::null_mut(); + let Some(out) = (unsafe { obj.as_mut() }) else { return sb::kInvalidArgument }; + *out = std::ptr::null_mut(); + // SAFETY: `cid` and `iid` point to 16-byte TUIDs (or are null, handled). + let (Some(cid), Some(iid)) = (unsafe { cid.as_ref() }, unsafe { iid.as_ref() }) else { return sb::kInvalidArgument }; + let (cid, iid) = (tuid_bytes(cid), tuid_bytes(iid)); + let wants = |class: [u8; 16]| cid == class && (iid == class || iid == FUnknown::IID); + let made = if wants(sv::IMessage::IID) { + ComWrapper::new(HostMessage::default()).to_com_ptr::().map(|p| p.into_raw().cast::()) + } else if wants(sv::IAttributeList::IID) { + ComWrapper::new(HostAttributes::default()).to_com_ptr::().map(|p| p.into_raw().cast::()) + } else { + None + }; + match made { + Some(p) => { + *out = p; + sb::kResultOk + } + None => sb::kResultFalse, } - sb::kResultFalse } } @@ -684,6 +703,191 @@ impl IComponentHandlerTrait for HostContext { } } +/// Longest string attribute kept, in UTF-16 units (longer ones are cut). +const ATTR_STRING_MAX: usize = 1 << 20; +/// Largest binary attribute kept. +const ATTR_BINARY_MAX: usize = 256 << 20; + +/// One `IAttributeList` value. Strings and blobs live in their own allocation, so a pointer +/// handed out by `getBinary` stays valid while the list holds the value. +enum Attr { + Int(i64), + Float(f64), + Str(Box<[u16]>), + Bin(Box<[u8]>), +} + +/// The host's `IAttributeList`: what a plugin puts in an `IMessage`. +#[derive(Default)] +pub(crate) struct HostAttributes { + values: Mutex, Attr>>, +} + +impl Class for HostAttributes { + type Interfaces = (sv::IAttributeList,); +} + +/// An attribute id's bytes (`None` for a null id). +fn attr_key(id: sv::IAttributeList_::AttrID) -> Option> { + // SAFETY: a non-null AttrID is a NUL-terminated C string owned by the caller. + (!id.is_null()).then(|| unsafe { std::ffi::CStr::from_ptr(id) }.to_bytes().to_vec()) +} + +impl HostAttributes { + fn values(&self) -> std::sync::MutexGuard<'_, std::collections::HashMap, Attr>> { + self.values.lock().unwrap_or_else(PoisonError::into_inner) + } + + fn set(&self, id: sv::IAttributeList_::AttrID, v: Attr) -> sb::tresult { + let Some(k) = attr_key(id) else { return sb::kInvalidArgument }; + self.values().insert(k, v); + sb::kResultOk + } +} + +impl sv::IAttributeListTrait for HostAttributes { + unsafe fn setInt(&self, id: sv::IAttributeList_::AttrID, value: sb::int64) -> sb::tresult { + self.set(id, Attr::Int(value)) + } + + unsafe fn getInt(&self, id: sv::IAttributeList_::AttrID, value: *mut sb::int64) -> sb::tresult { + // SAFETY: `value` is the caller's out-pointer (or null, handled). + match ( + attr_key(id).and_then(|k| match self.values().get(&k) { + Some(Attr::Int(v)) => Some(*v), + _ => None, + }), + unsafe { value.as_mut() }, + ) { + (Some(v), Some(out)) => { + *out = v; + sb::kResultOk + } + _ => sb::kResultFalse, + } + } + + unsafe fn setFloat(&self, id: sv::IAttributeList_::AttrID, value: f64) -> sb::tresult { + self.set(id, Attr::Float(value)) + } + + unsafe fn getFloat(&self, id: sv::IAttributeList_::AttrID, value: *mut f64) -> sb::tresult { + // SAFETY: `value` is the caller's out-pointer (or null, handled). + match ( + attr_key(id).and_then(|k| match self.values().get(&k) { + Some(Attr::Float(v)) => Some(*v), + _ => None, + }), + unsafe { value.as_mut() }, + ) { + (Some(v), Some(out)) => { + *out = v; + sb::kResultOk + } + _ => sb::kResultFalse, + } + } + + unsafe fn setString(&self, id: sv::IAttributeList_::AttrID, string: *const sv::TChar) -> sb::tresult { + if string.is_null() { + return sb::kInvalidArgument; + } + let mut s = Vec::new(); + // SAFETY: a non-null string is NUL-terminated UTF-16 owned by the caller; reading stops at + // the NUL or at ATTR_STRING_MAX units. + while s.len() < ATTR_STRING_MAX { + let c = unsafe { *string.add(s.len()) }; + if c == 0 { + break; + } + s.push(c); + } + self.set(id, Attr::Str(s.into_boxed_slice())) + } + + unsafe fn getString(&self, id: sv::IAttributeList_::AttrID, string: *mut sv::TChar, size_in_bytes: sb::uint32) -> sb::tresult { + let units = size_in_bytes as usize / 2; + if string.is_null() || units == 0 { + return sb::kInvalidArgument; + } + let Some(k) = attr_key(id) else { return sb::kInvalidArgument }; + let values = self.values(); + let Some(Attr::Str(s)) = values.get(&k) else { return sb::kResultFalse }; + let n = s.len().min(units - 1); + // SAFETY: the caller's buffer holds `units` UTF-16 units; `n + 1 <= units` are written. + unsafe { + std::ptr::copy_nonoverlapping(s.as_ptr(), string, n); + *string.add(n) = 0; + } + sb::kResultOk + } + + unsafe fn setBinary(&self, id: sv::IAttributeList_::AttrID, data: *const c_void, size_in_bytes: sb::uint32) -> sb::tresult { + let n = size_in_bytes as usize; + if n > ATTR_BINARY_MAX { + return sb::kOutOfMemory; + } + let bytes: Box<[u8]> = if n == 0 || data.is_null() { + Box::new([]) + } else { + // SAFETY: the caller's `data` holds `n` readable bytes. + unsafe { std::slice::from_raw_parts(data.cast::(), n) }.into() + }; + self.set(id, Attr::Bin(bytes)) + } + + unsafe fn getBinary(&self, id: sv::IAttributeList_::AttrID, data: *mut *const c_void, size_in_bytes: *mut sb::uint32) -> sb::tresult { + let Some(k) = attr_key(id) else { return sb::kInvalidArgument }; + let values = self.values(); + let Some(Attr::Bin(b)) = values.get(&k) else { return sb::kResultFalse }; + // SAFETY: both are the caller's out-pointers (or null, handled). The pointer handed out + // stays valid until this attribute is replaced or the list is released (VST3 contract). + match (unsafe { data.as_mut() }, unsafe { size_in_bytes.as_mut() }) { + (Some(d), Some(sz)) => { + *d = b.as_ptr().cast::(); + *sz = u32::try_from(b.len()).unwrap_or(u32::MAX); + sb::kResultOk + } + _ => sb::kInvalidArgument, + } + } +} + +/// The host's `IMessage`: an id and an attribute list, created for a plugin through +/// `IHostApplication::createInstance`. +pub(crate) struct HostMessage { + id: Mutex, + attributes: ComWrapper, +} + +impl Default for HostMessage { + fn default() -> Self { + HostMessage { id: Mutex::new(std::ffi::CString::default()), attributes: ComWrapper::new(HostAttributes::default()) } + } +} + +impl Class for HostMessage { + type Interfaces = (sv::IMessage,); +} + +impl sv::IMessageTrait for HostMessage { + unsafe fn getMessageID(&self) -> sb::FIDString { + // The string's buffer lives until the next `setMessageID`, as the interface expects. + self.id.lock().unwrap_or_else(PoisonError::into_inner).as_ptr() + } + + unsafe fn setMessageID(&self, id: sb::FIDString) { + // SAFETY: a non-null id is a NUL-terminated C string owned by the caller. + let s = if id.is_null() { std::ffi::CString::default() } else { unsafe { std::ffi::CStr::from_ptr(id) }.to_owned() }; + *self.id.lock().unwrap_or_else(PoisonError::into_inner) = s; + } + + unsafe fn getAttributes(&self) -> *mut sv::IAttributeList { + // Not add-ref'ed: the list belongs to the message (VST3 contract). + self.attributes.as_com_ref::().map_or(std::ptr::null_mut(), |r| r.as_ptr()) + } +} + /// One parameter's points for one block. SoundCraft sends at most one point per block; a /// plugin writing output changes may add more, of which only the last is kept. #[derive(Default)] @@ -2137,6 +2341,57 @@ mod window { #[cfg(test)] mod tests { use super::*; + use sv::{IAttributeListTrait as _, IMessageTrait as _}; + + fn tuid(iid: [u8; 16]) -> sb::TUID { + iid.map(|b| b as c_char) + } + + /// Asks the host for an object the way a plugin does. + fn create(host: &ComWrapper, cid: [u8; 16]) -> Option> { + let app = host.to_com_ptr::()?; + let (mut c, mut i) = (tuid(cid), tuid(I::IID)); + let mut obj: *mut c_void = std::ptr::null_mut(); + // SAFETY: valid TUIDs and out-pointer, as a plugin passes them. + let r = unsafe { app.createInstance(&mut c, &mut i, &mut obj) }; + // SAFETY: on success `obj` is an owned (add-ref'ed) pointer to `I`. + (r == sb::kResultOk).then(|| unsafe { ComPtr::from_raw(obj.cast::()) }).flatten() + } + + #[test] + fn plugins_get_messages_and_attribute_lists_from_the_host() { + let host = ComWrapper::new(HostContext::default()); + let msg = create::(&host, sv::IMessage::IID).expect("IMessage"); + // SAFETY: calls through the interface with valid C strings and buffers. + unsafe { + msg.setMessageID(c"DatabaseInfo".as_ptr()); + assert_eq!(std::ffi::CStr::from_ptr(msg.getMessageID()).to_str(), Ok("DatabaseInfo")); + let attrs = vst3::ComRef::from_raw(msg.getAttributes()).expect("attributes"); + assert_eq!(attrs.setInt(c"count".as_ptr(), 42), sb::kResultOk); + assert_eq!(attrs.setFloat(c"gain".as_ptr(), 0.5), sb::kResultOk); + let text: Vec = "Helix".encode_utf16().chain([0]).collect(); + assert_eq!(attrs.setString(c"name".as_ptr(), text.as_ptr()), sb::kResultOk); + assert_eq!(attrs.setBinary(c"blob".as_ptr(), [1u8, 2, 3].as_ptr().cast(), 3), sb::kResultOk); + + let (mut i, mut f) = (0i64, 0f64); + assert_eq!(attrs.getInt(c"count".as_ptr(), &mut i), sb::kResultOk); + assert_eq!(attrs.getFloat(c"gain".as_ptr(), &mut f), sb::kResultOk); + assert_eq!((i, f), (42, 0.5)); + assert_eq!(attrs.getInt(c"gain".as_ptr(), &mut i), sb::kResultFalse, "a float is not an int"); + assert_eq!(attrs.getInt(c"missing".as_ptr(), &mut i), sb::kResultFalse); + // A buffer of 4 units takes 3 characters and the NUL. + let mut buf = [0xFFFFu16; 4]; + assert_eq!(attrs.getString(c"name".as_ptr(), buf.as_mut_ptr(), 8), sb::kResultOk); + assert_eq!(buf, ['H' as u16, 'e' as u16, 'l' as u16, 0]); + let (mut p, mut n): (*const c_void, u32) = (std::ptr::null(), 0); + assert_eq!(attrs.getBinary(c"blob".as_ptr(), &mut p, &mut n), sb::kResultOk); + assert_eq!(std::slice::from_raw_parts(p.cast::(), n as usize), [1, 2, 3]); + assert_eq!(attrs.setInt(std::ptr::null(), 1), sb::kInvalidArgument, "a null id is refused"); + } + assert!(create::(&host, sv::IAttributeList::IID).is_some()); + // Anything else is still not provided. + assert!(create::(&host, sv::IComponentHandler::IID).is_none()); + } #[test] fn the_transport_fills_the_process_context() { diff --git a/docs/plugin-parity.md b/docs/plugin-parity.md index 9280d921..97532447 100644 --- a/docs/plugin-parity.md +++ b/docs/plugin-parity.md @@ -1,6 +1,6 @@ # Plugin parity: built-in processors and plugin hosting -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-13 · **Change:** trivial (mix.instrument sets built-in instrument parameters in params (#265); previously minor: plugin editors on Windows) · **Target:** Avid Pro Tools Ultimate 2026.4.1 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-13 · **Change:** minor (VST3 host messages: IMessage and IAttributeList; previously minor: plugin editors on Windows) · **Target:** Avid Pro Tools Ultimate 2026.4.1 Pro Tools users live in plugins: the bundled set covers everyday mixing, and third-party plugins cover the rest. This doc tracks both. Our plugins have our own names and are written from @@ -58,6 +58,7 @@ User report #152: a saved instrument level does not reach the bounce. | Date | Change | Summary | |---|---|---| +| 2026-10-13 | minor | VST3 host: IMessage and IAttributeList for plugins whose halves talk through messages (Line 6 Helix Stadium Native verified) | | 2026-10-13 | trivial | mix.instrument sets built-in instrument parameters in params (#265) | | 2026-10-12 | minor | Editors: VST3 and embedded CLAP editors on Windows | | 2026-10-10 | major | Created: built-in processor inventory by category and third-party hosting checklist | From f9d04ffc986cc1367e519fb0f088fd791ce89934 Mon Sep 17 00:00:00 2001 From: MarekSpodBiedry <73122968+MarekSpodBiedry@users.noreply.github.com> Date: Tue, 13 Oct 2026 17:48:38 +0200 Subject: [PATCH 02/52] Validate the full WAVE_FORMAT_EXTENSIBLE fmt chunk (#465) --- crates/audio-io/src/wav.rs | 24 +++++++++++++++------ crates/audio-io/tests/malformed.rs | 34 ++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+), 6 deletions(-) diff --git a/crates/audio-io/src/wav.rs b/crates/audio-io/src/wav.rs index 1aa847d4..22c89ae4 100644 --- a/crates/audio-io/src/wav.rs +++ b/crates/audio-io/src/wav.rs @@ -50,13 +50,25 @@ fn parse_fmt(c: &[u8]) -> Result { fmt.valid_bits = fmt.bits; if fmt.tag == WAVE_FORMAT_EXTENSIBLE { // cbSize(2) validBits(2) channelMask(4) subFormat GUID(16) - if let (Some(valid), Some(sub)) = (le_u16(c, 18), le_u16(c, 24)) { - if valid != 0 { - fmt.valid_bits = valid; - } - fmt.tag = sub; - } else { + let (Some(cb_size), Some(valid), Some(sub)) = (le_u16(c, 16), le_u16(c, 18), le_u16(c, 24)) else { return Err(AudioError::Malformed("WAVE_FORMAT_EXTENSIBLE fmt chunk too short".into())); + }; + let Some(tail) = c.get(26..40) else { + return Err(AudioError::Malformed("WAVE_FORMAT_EXTENSIBLE fmt chunk too short".into())); + }; + if cb_size < 22 { + return Err(AudioError::Malformed("WAVE_FORMAT_EXTENSIBLE cbSize is below 22".into())); + } + if valid > fmt.bits { + return Err(AudioError::Malformed("WAVE_FORMAT_EXTENSIBLE valid bits exceed the container size".into())); + } + if valid != 0 { + fmt.valid_bits = valid; + } + // A subtype outside the KSDATAFORMAT_SUBTYPE_* family is not PCM/float, whatever its first two bytes say: + // keep the extensible tag so the file goes to the foreign decoder. + if tail == GUID_TAIL { + fmt.tag = sub; } } Ok(fmt) diff --git a/crates/audio-io/tests/malformed.rs b/crates/audio-io/tests/malformed.rs index ed0d6e31..d9ac2459 100644 --- a/crates/audio-io/tests/malformed.rs +++ b/crates/audio-io/tests/malformed.rs @@ -485,3 +485,37 @@ proptest! { prop_assert_eq!(flac, wav); } } + +/// An extensible `fmt ` chunk: cbSize, valid bits, mask, then the 16-byte subtype GUID. +fn extensible_fmt(cb_size: u16, valid_bits: u16, guid: &[u8]) -> Vec { + let mut f = fmt(0xFFFE, 1, 44_100, 16); + f.extend_from_slice(&cb_size.to_le_bytes()); + f.extend_from_slice(&valid_bits.to_le_bytes()); + f.extend_from_slice(&4u32.to_le_bytes()); + f.extend_from_slice(guid); + f +} + +const PCM_GUID: [u8; 16] = [1, 0, 0, 0, 0, 0, 0x10, 0, 0x80, 0, 0, 0xAA, 0, 0x38, 0x9B, 0x71]; + +#[test] +fn extensible_fmt_is_checked_in_full() { + let data = vec![0u8; 8]; + let good = riff(&[(b"fmt ", extensible_fmt(22, 16, &PCM_GUID)), (b"data", data.clone())]); + assert_eq!(probe(&good, None).unwrap().sample_format, SampleFormat::Int16); + // Subtype GUID cut short after the format code. + let cut = riff(&[(b"fmt ", extensible_fmt(22, 16, &PCM_GUID[..4])), (b"data", data.clone())]); + assert!(matches!(probe(&cut, None), Err(AudioError::Malformed(_)))); + assert!(matches!(decode(&cut, None), Err(AudioError::Malformed(_)))); + // cbSize too small for the extension. + let small_cb = riff(&[(b"fmt ", extensible_fmt(0, 16, &PCM_GUID)), (b"data", data.clone())]); + assert!(matches!(probe(&small_cb, None), Err(AudioError::Malformed(_)))); + // More valid bits than the 16-bit container holds. + let wide = riff(&[(b"fmt ", extensible_fmt(22, 24, &PCM_GUID)), (b"data", data.clone())]); + assert!(matches!(probe(&wide, None), Err(AudioError::Malformed(_)))); + // PCM-like prefix but a foreign GUID tail is not read as native PCM. + let mut foreign = PCM_GUID; + foreign[15] ^= 0xFF; + let foreign = riff(&[(b"fmt ", extensible_fmt(22, 16, &foreign)), (b"data", data)]); + assert!(!matches!(probe(&foreign, None), Ok(i) if i.sample_format == SampleFormat::Int16)); +} From 9a398d79ff58e55b9e58cc0e9cf288d601ea641f Mon Sep 17 00:00:00 2001 From: MarekSpodBiedry <73122968+MarekSpodBiedry@users.noreply.github.com> Date: Tue, 13 Oct 2026 17:50:51 +0200 Subject: [PATCH 03/52] Load older sessions whose track height is the bare Fit string (#447) --- crates/model/src/session.rs | 13 +++++++++ crates/model/src/track.rs | 55 +++++++++++++++++++++++++++++++++++++ 2 files changed, 68 insertions(+) diff --git a/crates/model/src/session.rs b/crates/model/src/session.rs index 449d82da..b0f74214 100644 --- a/crates/model/src/session.rs +++ b/crates/model/src/session.rs @@ -681,6 +681,19 @@ mod tests { assert_eq!(back, s); } + #[test] + fn session_with_legacy_fit_height_loads() { + let mut s = Session::default(); + let t = s.add_track(TrackKind::Audio, ChannelFormat::Stereo, None); + if let Some(track) = s.track_mut(t) { + track.height = crate::TrackHeight::Large; + } + let text = s.to_json().unwrap().replace("\"height\": \"Large\"", "\"height\": \"Fit\""); + assert!(text.contains("\"height\": \"Fit\"")); + let back = Session::from_json(&text).unwrap(); + assert_eq!(back.track(t).map(|tr| tr.height), Some(crate::TrackHeight::Medium)); + } + #[test] fn video_clip_round_trips_and_old_sessions_load() { let mut s = Session::default(); diff --git a/crates/model/src/track.rs b/crates/model/src/track.rs index 9df78c35..663a6a4b 100644 --- a/crates/model/src/track.rs +++ b/crates/model/src/track.rs @@ -84,6 +84,7 @@ impl TrackKind { /// Track heights (View › Track Height presets). #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, serde::Serialize, serde::Deserialize)] +#[serde(from = "TrackHeightRepr")] pub enum TrackHeight { /// Any height from Micro to Extreme, in points. Custom(u16), @@ -99,6 +100,51 @@ pub enum TrackHeight { Fit(u16), } +/// What a saved track height may look like: the current form, or the bare `"Fit"` string older sessions used. +#[derive(serde::Deserialize)] +#[serde(untagged)] +enum TrackHeightRepr { + Current(TrackHeightCurrent), + LegacyFit(LegacyFit), +} + +#[derive(serde::Deserialize)] +enum LegacyFit { + Fit, +} + +/// Mirror of `TrackHeight` that derives the current serialized form. +#[derive(serde::Deserialize)] +enum TrackHeightCurrent { + Custom(u16), + Micro, + Mini, + Small, + Medium, + Large, + Jumbo, + Extreme, + Fit(u16), +} + +impl From for TrackHeight { + fn from(repr: TrackHeightRepr) -> Self { + match repr { + TrackHeightRepr::Current(TrackHeightCurrent::Custom(p)) => TrackHeight::Custom(p), + TrackHeightRepr::Current(TrackHeightCurrent::Micro) => TrackHeight::Micro, + TrackHeightRepr::Current(TrackHeightCurrent::Mini) => TrackHeight::Mini, + TrackHeightRepr::Current(TrackHeightCurrent::Small) => TrackHeight::Small, + TrackHeightRepr::Current(TrackHeightCurrent::Medium) => TrackHeight::Medium, + TrackHeightRepr::Current(TrackHeightCurrent::Large) => TrackHeight::Large, + TrackHeightRepr::Current(TrackHeightCurrent::Jumbo) => TrackHeight::Jumbo, + TrackHeightRepr::Current(TrackHeightCurrent::Extreme) => TrackHeight::Extreme, + TrackHeightRepr::Current(TrackHeightCurrent::Fit(p)) => TrackHeight::Fit(p), + // Older sessions stored Fit with no size, drawn 88 points tall: the default Medium height. + TrackHeightRepr::LegacyFit(LegacyFit::Fit) => TrackHeight::Medium, + } + } +} + impl TrackHeight { pub const ALL: [TrackHeight; 7] = [ TrackHeight::Micro, @@ -328,6 +374,15 @@ impl Track { mod tests { use super::*; + #[test] + fn legacy_fit_string_loads_as_default_height() { + assert_eq!(serde_json::from_str::("\"Fit\"").unwrap(), TrackHeight::Medium); + assert_eq!(serde_json::from_str::("{\"Fit\":120}").unwrap(), TrackHeight::Fit(120)); + assert_eq!(serde_json::to_string(&TrackHeight::Fit(120)).unwrap(), "{\"Fit\":120}"); + assert_eq!(serde_json::from_str::("\"Large\"").unwrap(), TrackHeight::Large); + assert_eq!(serde_json::from_str::("{\"Custom\":50}").unwrap(), TrackHeight::Custom(50)); + } + #[test] fn new_track_defaults() { let t = Track::new(TrackId(1), "Gtr", TrackKind::Audio, ChannelFormat::Stereo, TRACK_COLORS[0]); From b7329ee9047d47d80f3b3c8fd41f09f6c5236ab7 Mon Sep 17 00:00:00 2001 From: MarekSpodBiedry <73122968+MarekSpodBiedry@users.noreply.github.com> Date: Tue, 13 Oct 2026 17:50:42 +0200 Subject: [PATCH 04/52] Keep unrelated overlapping clips untouched when deleting fades (#449) --- crates/engine/src/edit.rs | 26 ++++++++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/edit.rs b/crates/engine/src/edit.rs index 5531953d..b26e14d8 100644 --- a/crates/engine/src/edit.rs +++ b/crates/engine/src/edit.rs @@ -812,8 +812,10 @@ pub fn create_fades(s: &mut Session, track: TrackId, range: Range, shape: FadeSh pub fn delete_fades(s: &mut Session, track: TrackId, range: Range) -> usize { let Some(pl) = s.track_mut(track).and_then(|t| t.playlist_mut()) else { return 0 }; let mut n = 0; + let mut touched: HashSet = HashSet::new(); for c in &mut pl.clips { if c.range().overlaps(&range) || (range.is_empty() && c.range().contains(range.start)) { + touched.insert(c.id); if c.fade_in.len > 0 || c.fade_out.len > 0 { n += 1; } @@ -821,11 +823,12 @@ pub fn delete_fades(s: &mut Session, track: TrackId, range: Range) -> usize { c.fade_out = Fade::default(); } } - // Overlapping (crossfaded) neighbours are trimmed back to the midpoint. + // Overlapping (crossfaded) neighbours in the range are trimmed back to the midpoint; other overlaps stay as they are. pl.sort(); for i in 0..pl.clips.len().saturating_sub(1) { let (Some(a_end), Some(b_start)) = (pl.clips.get(i).map(Clip::end), pl.clips.get(i + 1).map(|c| c.start)) else { continue }; - if a_end > b_start { + let in_range = pl.clips.get(i).is_some_and(|a| touched.contains(&a.id)) || pl.clips.get(i + 1).is_some_and(|b| touched.contains(&b.id)); + if in_range && a_end > b_start { let mid = b_start + (a_end - b_start) / 2; if let Some(a) = pl.clips.get_mut(i) { a.trim_end_to(mid); @@ -1041,4 +1044,23 @@ mod tests { s.find_clip_mut(id).unwrap().time_locked = true; assert_eq!(move_clips(&mut s, &[id], 500, &[]), 0); } + + #[test] + fn delete_fades_leaves_unrelated_overlaps_alone() { + let (mut s, t) = session_with_clip(); + let ids: Vec = (0..4).map(|_| s.new_clip_id()).collect(); + if let Some(pl) = s.track_mut(t).and_then(|t| t.playlist_mut()) { + pl.clips.clear(); + for (id, start, len) in [(ids[0], 0, 1100), (ids[1], 1000, 1000), (ids[2], 5000, 1100), (ids[3], 6000, 1000)] { + let mut c = Clip::audio(id, "c", SourceId(500), start, start, len); + c.fade_in = Fade { len: 100, shape: FadeShape::Linear, curvature: 0.0 }; + c.fade_out = Fade { len: 100, shape: FadeShape::Linear, curvature: 0.0 }; + pl.clips.push(c); + } + } + assert_eq!(delete_fades(&mut s, t, Range::new(900, 1200)), 2); + assert_eq!(clips(&s, t), vec![(0, 1050, 0), (1050, 950, 1050), (5000, 1100, 5000), (6000, 1000, 6000)]); + let c = s.track(t).unwrap().clips(); + assert_eq!((c[1].fade_in.len, c[2].fade_out.len, c[3].fade_in.len), (0, 100, 100)); + } } From bddc113f46d4326154a5bd01cb43311c17fdba19 Mon Sep 17 00:00:00 2001 From: MarekSpodBiedry <73122968+MarekSpodBiedry@users.noreply.github.com> Date: Tue, 13 Oct 2026 17:50:43 +0200 Subject: [PATCH 05/52] Heal keeps each clip's gain envelope and skips clips whose mute or stretch differ (#450) --- crates/engine/src/edit.rs | 58 ++++++++++++++++++++++++++++++++++++++- crates/model/src/clip.rs | 5 ++++ 2 files changed, 62 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/edit.rs b/crates/engine/src/edit.rs index 5531953d..9634cd3b 100644 --- a/crates/engine/src/edit.rs +++ b/crates/engine/src/edit.rs @@ -418,7 +418,11 @@ pub fn heal(s: &mut Session, track: TrackId, range: Range) -> usize { (ClipContent::Audio { source: a, offset: oa }, ClipContent::Audio { source: b, offset: ob }) => a == b && oa + prev.length == *ob, _ => false, }; - if contiguous && same && (prev.gain_db - c.gain_db).abs() < 1e-6 { + let same_playback = prev.muted == c.muted && (prev.stretch - c.stretch).abs() < 1e-9 && (prev.gain_db - c.gain_db).abs() < 1e-6; + if contiguous && same && same_playback { + if !prev.gain_env.is_empty() || !c.gain_env.is_empty() { + join_gain_env(prev, &c); + } prev.length += c.length; prev.fade_out = c.fade_out; healed += 1; @@ -431,6 +435,21 @@ pub fn heal(s: &mut Session, track: TrackId, range: Range) -> usize { healed } +/// Give `l` the gain envelope of `l` followed by `r`, which starts where `l` ends, so every sample keeps its gain. +fn join_gain_env(l: &mut Clip, r: &Clip) { + let cut = l.length; + let (end_db, start_db) = (l.env_db_at(cut - 1), r.env_db_at(0)); + l.gain_env.retain(|&(at, _)| at < cut); + l.gain_env.extend(r.gain_env.iter().filter(|&&(at, _)| at >= 0).map(|&(at, db)| (at.saturating_add(cut), db))); + // Pin both sides of the seam where the joined points would interpolate across it. + for (at, db) in [(cut, start_db), (cut - 1, end_db)] { + if (l.env_db_at(at) - db).abs() > 1e-4 { + let i = l.gain_env.partition_point(|&(t, _)| t < at); + l.gain_env.insert(i, (at, db)); + } + } +} + /// Move clips by `delta`, overwriting what they land on; `dest` sends whole tracks of them /// elsewhere (see [`destinations`]). pub fn move_clips(s: &mut Session, ids: &[ClipId], delta: Samples, dest: &[(TrackId, TrackId)]) -> usize { @@ -878,6 +897,43 @@ mod tests { assert_eq!(clips(&s, t), vec![(1000, 4000, 1000)]); } + #[test] + fn heal_skips_clips_with_different_playback() { + for tweak in [(|c: &mut Clip| c.muted = true) as fn(&mut Clip), |c: &mut Clip| c.stretch = 1.5] { + let (mut s, t) = session_with_clip(); + separate_at(&mut s, t, 3000); + if let Some(pl) = s.track_mut(t).and_then(|t| t.playlist_mut()) { + tweak(&mut pl.clips[1]); + } + assert_eq!(heal(&mut s, t, Range::new(0, 10_000)), 0); + assert_eq!(s.track(t).unwrap().clips().len(), 2); + } + } + + #[test] + fn heal_keeps_each_side_gain_envelope() { + let cases: [(Vec<(Samples, f32)>, Vec<(Samples, f32)>); 4] = [ + (vec![(500, -3.0), (2500, -12.0)], vec![]), + (vec![], vec![(0, -6.0), (1000, 0.0)]), + (vec![(0, 0.0), (1999, -20.0)], vec![(-100, 4.0), (300, -9.0)]), + (vec![(500, -3.0), (2500, -12.0)], vec![(0, -9.75), (500, -12.0)]), + ]; + for (left_env, right_env) in cases { + let (mut s, t) = session_with_clip(); + separate_at(&mut s, t, 3000); + let pl = s.track_mut(t).and_then(|t| t.playlist_mut()).unwrap(); + pl.clips[0].gain_env = left_env; + pl.clips[1].gain_env = right_env; + let (l, r) = (pl.clips[0].clone(), pl.clips[1].clone()); + assert_eq!(heal(&mut s, t, Range::new(0, 10_000)), 1); + let healed = &s.track(t).unwrap().clips()[0]; + for rel in 0..4000 { + let want = if rel < 2000 { l.gain_at(rel) } else { r.gain_at(rel - 2000) }; + assert!((healed.gain_at(rel) - want).abs() < 1e-4, "sample {rel}: {} != {want}", healed.gain_at(rel)); + } + } + } + #[test] fn clear_slip_and_shuffle() { let (mut s, t) = session_with_clip(); diff --git a/crates/model/src/clip.rs b/crates/model/src/clip.rs index 850cf044..7543a3ad 100644 --- a/crates/model/src/clip.rs +++ b/crates/model/src/clip.rs @@ -242,6 +242,11 @@ impl Clip { g } + /// Gain envelope value in dB at `rel` samples from the clip start (0 without an envelope). + pub fn env_db_at(&self, rel: Samples) -> f32 { + env_value(&self.gain_env, rel) + } + /// Move the start edge to `new_start` keeping material anchored (trim start). pub fn trim_start_to(&mut self, new_start: Samples) { let new_start = new_start.min(self.end() - 1); From d13f6657f8843c03dd1bb952ff2933f202093e4b Mon Sep 17 00:00:00 2001 From: MarekSpodBiedry <73122968+MarekSpodBiedry@users.noreply.github.com> Date: Tue, 13 Oct 2026 17:50:33 +0200 Subject: [PATCH 06/52] Keep MIDI note selection valid across clip, session and note-order changes (#443) --- crates/engine/src/cmd/midi.rs | 27 +++++++++++++++++- crates/ui-egui/src/lib.rs | 15 ++++++++++ crates/ui-egui/src/midi_editor.rs | 36 ++++++++++++++++++++++-- crates/ui-egui/tests/pro_tools_keys.rs | 38 ++++++++++++++++++++++++++ 4 files changed, 113 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/midi.rs b/crates/engine/src/cmd/midi.rs index 10bcd767..05f6b6ac 100644 --- a/crates/engine/src/cmd/midi.rs +++ b/crates/engine/src/cmd/midi.rs @@ -130,8 +130,19 @@ fn notes_move(e: &mut Engine, p: &Value) -> Result { n.pitch = (i64::from(n.pitch) + ds).clamp(0, 127) as u8; } } + let moved: Vec = seq.notes.iter().enumerate().filter(|(i, _)| idx.contains(i)).map(|(_, n)| *n).collect(); seq.sort(); - Ok(json!({"moved": idx.len()})) + // Where the moved notes ended up after sorting, so the editor can keep them selected. + let mut taken = vec![false; seq.notes.len()]; + let mut indices = Vec::with_capacity(moved.len()); + for m in &moved { + if let Some(j) = seq.notes.iter().enumerate().position(|(j, n)| !taken[j] && n == m) { + taken[j] = true; + indices.push(j); + } + } + indices.sort_unstable(); + Ok(json!({"moved": idx.len(), "indices": indices})) } #[cfg(test)] @@ -157,6 +168,20 @@ mod tests { assert!(e.execute("midi.note_edit", &json!({"clip": clip, "index": 99})).is_err()); } + #[test] + fn notes_move_reports_where_the_moved_notes_went() { + let mut e = Engine::default(); + let t = e.session_mut().add_track(TrackKind::Instrument, ChannelFormat::Stereo, Some("Keys")); + let clip = e.execute("midi.new_clip", &json!({"track": t.0})).unwrap()["clip"].as_u64().unwrap(); + for start in [0, 480, 960] { + e.execute("midi.note_add", &json!({"clip": clip, "pitch": 60, "start_ticks": start})).unwrap(); + } + let r = e.execute("midi.notes_move", &json!({"clip": clip, "indices": [0], "ticks": 720})).unwrap(); + assert_eq!(r["indices"], json!([1])); + let notes = e.execute("midi.notes", &json!({"clip": clip})).unwrap(); + assert_eq!(notes["notes"][1]["start"], 720); + } + #[test] fn rejects_audio_tracks() { let mut e = Engine::default(); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index ddd54275..87938518 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -425,6 +425,10 @@ impl SoundApp { let replacing = matches!(id, "session.new" | "session.open" | "session.close" | "session.revert"); match self.engine.execute(id, ¶ms) { Ok(v) => { + if replacing { + // Note indices and gestures belong to the old session's clips. + self.midi = midi_editor::MidiEditorState::default(); + } if replacing || (id.starts_with("session.save") && !self.engine.is_dirty()) { self.release_autosave(false); } @@ -1344,6 +1348,17 @@ mod tests { assert_eq!(super::failed_plugin_status(&s, t, soundcraft_mix::INSTRUMENT_SLOT), None); } + #[test] + fn replacing_the_session_drops_the_midi_note_selection() { + for command in ["session.new", "session.close"] { + let mut app = SoundApp::new(soundcraft_engine::demo::demo_engine(), None, Services::default()); + app.midi.selected = vec![0, 1]; + app.midi.clip = Some(soundcraft_model::ClipId(1)); + app.run(command, json!({})).unwrap(); + assert!(app.midi.selected.is_empty() && app.midi.clip.is_none(), "{command}"); + } + } + #[test] fn new_session_cancels_play_queued_before_the_next_frame() { let mut app = SoundApp::new(soundcraft_engine::demo::demo_engine(), None, Services::default()); diff --git a/crates/ui-egui/src/midi_editor.rs b/crates/ui-egui/src/midi_editor.rs index 8ea18699..dbd6f6d2 100644 --- a/crates/ui-egui/src/midi_editor.rs +++ b/crates/ui-egui/src/midi_editor.rs @@ -21,6 +21,19 @@ pub struct MidiEditorState { pub band: Option, } +impl MidiEditorState { + /// Start editing `id`. Note indices only mean something inside one clip, so the selection and + /// any gesture in progress are dropped when the clip changes. + fn switch_clip(&mut self, id: ClipId) { + if self.clip != Some(id) { + self.selected.clear(); + self.drag = None; + self.band = None; + } + self.clip = Some(id); + } +} + #[derive(Debug, Clone)] pub struct NoteDrag { pub index: usize, @@ -148,7 +161,7 @@ pub fn show(app: &mut SoundApp, ui: &mut Ui) { let hi = sequence.notes.iter().map(|n| i32::from(n.pitch)).max().unwrap_or(72); let lo = sequence.notes.iter().map(|n| i32::from(n.pitch)).min().unwrap_or(48); app.midi.scroll = (127 - (hi + lo) / 2 - rows / 2) as f32 * ROW_H; - app.midi.clip = Some(cid); + app.midi.switch_clip(cid); } if ui.rect_contains_pointer(roll) { app.midi.scroll -= ui.input(|i| i.smooth_scroll_delta.y); @@ -346,7 +359,10 @@ pub fn show(app: &mut SoundApp, ui: &mut Ui) { 0 }; if (semi != 0 || ticks != 0) && !app.midi.selected.is_empty() { - let _ = app.run("midi.notes_move", json!({"clip": cid.0, "indices": app.midi.selected, "ticks": ticks, "semitones": semi})); + let moved = app.run("midi.notes_move", json!({"clip": cid.0, "indices": app.midi.selected, "ticks": ticks, "semitones": semi})); + // The engine re-sorts the notes: follow the moved ones to their new indices, so the + // selection never points at other notes and the arrows can keep nudging it. + app.midi.selected = moved.ok().and_then(|v| serde_json::from_value(v["indices"].clone()).ok()).unwrap_or_default(); } } if !app.midi.selected.is_empty() @@ -376,3 +392,19 @@ pub fn show(app: &mut SoundApp, ui: &mut Ui) { let _ = app.engine.execute_merged("midi.note_edit", &json!({"clip": cid.0, "index": i, "velocity": v}), &format!("vel:{}", cid.0)); } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn switching_clip_drops_selection_and_gestures() { + let mut st = MidiEditorState { selected: vec![0, 2], clip: Some(ClipId(1)), band: Some(pos2(1.0, 2.0)), ..Default::default() }; + st.switch_clip(ClipId(1)); + assert_eq!(st.selected, vec![0, 2]); + st.switch_clip(ClipId(2)); + assert!(st.selected.is_empty()); + assert!(st.drag.is_none() && st.band.is_none()); + assert_eq!(st.clip, Some(ClipId(2))); + } +} diff --git a/crates/ui-egui/tests/pro_tools_keys.rs b/crates/ui-egui/tests/pro_tools_keys.rs index c87ede65..97952c1e 100644 --- a/crates/ui-egui/tests/pro_tools_keys.rs +++ b/crates/ui-egui/tests/pro_tools_keys.rs @@ -233,6 +233,44 @@ fn the_piano_roll_leaves_modified_arrows_to_the_shortcuts() { assert_eq!(pitch(&app), before + 1); } +#[test] +fn the_piano_roll_selection_follows_notes_the_arrows_move_past_others() { + let mut app = SoundApp::new(soundcraft_engine::demo::demo_engine(), None, Services::default()); + app.ui.show_midi_editor = true; + app.run("edit.select", json!({"tracks": ["Keys"]})).unwrap(); + let ctx = egui::Context::default(); + let frame = |app: &mut SoundApp, events: Vec| { + let raw = RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1600.0, 1000.0))), events, ..Default::default() }; + ctx.run_ui(raw, |ui| { + app.logic(ui.ctx()); + app.ui(ui); + }) + .textures_delta + .clear(); + }; + for _ in 0..6 { + frame(&mut app, vec![]); + } + let body = ctx.data(|d| d.get_temp::(egui::Id::new("soundcraft-midi-body"))).unwrap(); + frame(&mut app, vec![Event::PointerMoved(body.center())]); + let notes = |app: &SoundApp| { + let clip = soundcraft_ui_egui::midi_editor::target_clip(app).unwrap(); + match &app.engine.session().find_clip(clip).unwrap().1.content { + ClipContent::Midi { sequence } => sequence.notes.clone(), + _ => panic!("not a MIDI clip"), + } + }; + // The first chord's lowest note, an octave up, sorts after the other chord notes. + let first = notes(&app)[0]; + app.midi.selected = vec![0]; + for octaves in 1..=2u8 { + frame(&mut app, keys(Key::ArrowUp, Modifiers::SHIFT)); + let &[i] = app.midi.selected.as_slice() else { panic!("selection {:?}", app.midi.selected) }; + assert_ne!(i, 0); + assert_eq!((notes(&app)[i].start, notes(&app)[i].pitch), (first.start, first.pitch + 12 * octaves)); + } +} + #[test] fn shift_tab_extends_the_selection_and_tab_to_transient_stops_on_hits() { for (os, cmd) in OSES { From 2dd8f7da55c8ed919117b24dc309b4381b362e5e Mon Sep 17 00:00:00 2001 From: Billy Coleman III Date: Tue, 13 Oct 2026 13:39:46 -0400 Subject: [PATCH 07/52] Preserve exact channel formats when committing tracks Retain the source ChannelFormat for committed audio tracks and reject unsupported widths, overflowing ranges and incomplete renders before replacing selected tracks. Preserve current routing and rollback behavior and document the existing renderer limits with multichannel coverage. --- contributors/people.toml | 3 + crates/engine/src/io.rs | 23 ++- crates/engine/tests/commit_multichannel.rs | 160 +++++++++++++++++++++ docs/commit-multichannel.md | 41 ++++++ 4 files changed, 223 insertions(+), 4 deletions(-) create mode 100644 crates/engine/tests/commit_multichannel.rs create mode 100644 docs/commit-multichannel.md diff --git a/contributors/people.toml b/contributors/people.toml index 1c344199..f67fdd57 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -50,3 +50,6 @@ sync_github_name = false [people.Momentum96] sync_github_name = true + +[people.ProdByBuddha] +sync_github_name = true diff --git a/crates/engine/src/io.rs b/crates/engine/src/io.rs index 7b26e0b1..49d325c7 100644 --- a/crates/engine/src/io.rs +++ b/crates/engine/src/io.rs @@ -801,12 +801,27 @@ pub fn commit_track(e: &mut Engine, t: TrackId) -> Result> { if end <= 0 { return Ok(None); } - let range = Range::new(0, end + s.sample_rate.samples(2.0)); - // The track renders through a main mix of at least two channels. - refuse_longer(s, "track.commit", &tr.name, "commit", range.len(), render_limit(tr.channels().max(2)))?; + let fmt = tr.format; + if fmt.channels() > soundcraft_mix::MAX_CHANNELS { + return Err(EngineError::BadParams( + "track.commit".into(), + format!("track commit supports at most {} channels; cannot render {}", soundcraft_mix::MAX_CHANNELS, fmt.label()), + )); + } + let too_long = || EngineError::BadParams("track.commit".into(), format!("`{}` is too long to commit within the offline render limit", tr.name)); + let end = end.checked_add(s.sample_rate.samples(2.0)).ok_or_else(too_long)?; + let frames = usize::try_from(end).map_err(|_| too_long())?; + // The shared renderer uses a stereo main mix for mono, then folds it back to mono. + // Reject requests it would truncate before rendering or replacing the source track. + if frames > soundcraft_mix::MAX_RENDER_SAMPLES / fmt.channels().max(2) { + return Err(too_long()); + } + let range = Range::new(0, end); let audio = soundcraft_mix::render_track_pre_fader(s, t, range); + if audio.len() != fmt.channels() || audio.iter().any(|channel| channel.len() != frames) { + return Err(EngineError::Io("track commit did not render the complete channel format and range".into())); + } let name = format!("{}.cm", tr.name); - let fmt = ChannelFormat::for_channels(audio.len().clamp(1, 2)); let mixer = tr.mixer.clone(); let buf = AudioBuffer { sample_rate: s.sample_rate.hz(), channels: audio }; let s = e.session_mut(); diff --git a/crates/engine/tests/commit_multichannel.rs b/crates/engine/tests/commit_multichannel.rs new file mode 100644 index 00000000..e2900a48 --- /dev/null +++ b/crates/engine/tests/commit_multichannel.rs @@ -0,0 +1,160 @@ +use serde_json::json; +use soundcraft_audio_io::{AudioBuffer, BitDepth, EncodeOptions, FileFormat}; +use soundcraft_engine::{Engine, io}; +use soundcraft_model::{ChannelFormat, Clip, ClipContent, Insert, Route, SendSlot, Session, TrackId, TrackKind}; +use soundcraft_time::{Range, SampleRate}; +use std::sync::Arc; + +const SIGNAL_FRAMES: usize = 128; + +fn fixture(format: ChannelFormat) -> (Engine, TrackId, Vec>) { + let mut session = Session::new("Commit layout", SampleRate::new(8_000).unwrap()); + session.outputs[0].format = format; + let track = session.add_track(TrackKind::Audio, format, Some("Distinct channels")); + // Each channel has a different bipolar waveform: swapping, summing or dropping channels + // cannot pass a width-only assertion or an identical-signal comparison. + let channels: Vec> = (0..format.channels()) + .map(|ch| (0..SIGNAL_FRAMES).map(|frame| (((frame * (ch + 3)) % 31) as f32 - 15.0) * (ch + 1) as f32 / 3_200.0).collect()) + .collect(); + let source = + io::add_source(&mut session, "Distinct channels", AudioBuffer { sample_rate: 8_000, channels: channels.clone() }, None, FileFormat::Wav); + let clip = session.new_clip_id(); + let tr = session.track_mut(track).unwrap(); + tr.playlist_mut().unwrap().clips.push(Clip::audio(clip, "Signal", source, 0, 0, SIGNAL_FRAMES as i64)); + tr.mixer.inserts[0] = Some(Insert::new("invert")); + session.edit.selected_tracks = vec![track]; + (Engine::new(session), track, channels) +} + +fn commit(e: &mut Engine, track: TrackId) -> TrackId { + TrackId(e.execute("track.commit", &json!({"tracks": [track.0]})).unwrap()["tracks"][0].as_u64().unwrap()) +} + +fn committed_audio(e: &Engine, track: TrackId) -> &AudioBuffer { + let ClipContent::Audio { source, .. } = e.session().track(track).unwrap().clips()[0].content else { panic!("commit must create audio") }; + &e.session().pool.get(source).unwrap().buffer +} + +fn assert_audio_eq(actual: &[Vec], expected: &[Vec]) { + assert_eq!(actual.len(), expected.len()); + for (ch, (actual, expected)) in actual.iter().zip(expected).enumerate() { + assert_eq!(actual.len(), expected.len(), "channel {ch} length"); + for (frame, (actual, expected)) in actual.iter().zip(expected).enumerate() { + assert!((actual - expected).abs() < 1e-6, "channel {ch}, frame {frame}: {actual} != {expected}"); + } + } +} + +#[test] +fn commit_keeps_every_renderable_exact_format_and_processed_channel_order() { + for format in ChannelFormat::ALL.into_iter().filter(|format| format.channels() <= soundcraft_mix::MAX_CHANNELS) { + let (mut e, track, signal) = fixture(format); + let committed = commit(&mut e, track); + assert_eq!(e.session().track(committed).unwrap().format, format, "{}", format.label()); + let audio = committed_audio(&e, committed); + assert_eq!(audio.num_channels(), format.channels(), "{}", format.label()); + assert_eq!(audio.frames(), SIGNAL_FRAMES + 16_000); + // Existing mono rendering uses a -3 dB center pan followed by SQRT_2 compensation. + // Model that small baseline gain explicitly, retaining the same strict signal tolerance. + let gain = if format == ChannelFormat::Mono { 10.0_f32.powf(-3.0 / 20.0) * std::f32::consts::SQRT_2 } else { 1.0 }; + let expected: Vec> = signal.iter().map(|ch| ch.iter().map(|sample| -sample * gain).collect()).collect(); + let head: Vec> = audio.channels.iter().map(|ch| ch[..SIGNAL_FRAMES].to_vec()).collect(); + assert_audio_eq(&head, &expected); + assert!(audio.channels.iter().all(|ch| ch[SIGNAL_FRAMES..].iter().all(|sample| sample.abs() < 1e-6))); + assert!(e.session().track(track).unwrap().inactive && e.session().track(track).unwrap().hidden); + assert_eq!(e.session().track_index(committed), e.session().track_index(track).map(|index| index + 1)); + } +} + +#[test] +fn commit_preserves_bus_and_send_audio_after_undo_reopen_and_wav_export() { + for format in [ChannelFormat::Surround60, ChannelFormat::Atmos504, ChannelFormat::Ambisonics(1)] { + let (mut e, track, _) = fixture(format); + let s = e.session_mut(); + let bus = s.add_bus("Same-layout bus", format); + let aux = s.add_track(TrackKind::Aux, format, Some("Bus return")); + s.track_mut(aux).unwrap().mixer.input = Route::Bus(bus); + let tr = s.track_mut(track).unwrap(); + tr.mixer.output = Route::Bus(bus); + tr.mixer.volume_db = -4.5; + let mut send = SendSlot::new(Route::Main); + send.level_db = -9.0; + tr.mixer.sends[0] = Some(send); + let mixer = tr.mixer.clone(); + let range = Range::new(0, SIGNAL_FRAMES as i64); + let before = soundcraft_mix::render_range(e.session(), range, 64); + let committed = commit(&mut e, track); + let tr = e.session().track(committed).unwrap(); + assert_eq!(tr.mixer.output, mixer.output); + assert_eq!(tr.mixer.sends, mixer.sends); + assert_eq!(tr.mixer.volume_db, mixer.volume_db); + assert!(tr.mixer.inserts.iter().all(Option::is_none), "processing is baked once"); + assert_audio_eq(&soundcraft_mix::render_range(e.session(), range, 64), &before); + assert!(e.undo()); + assert!(e.session().track(committed).is_none()); + assert!(!e.session().track(track).unwrap().inactive); + assert_audio_eq(&soundcraft_mix::render_range(e.session(), range, 64), &before); + assert!(e.redo()); + + let dir = std::env::temp_dir().join(format!("soundcraft-commit-layout-{}-{}", std::process::id(), format.channels())); + let _ = std::fs::remove_dir_all(&dir); + let path = dir.join("Commit.scraft").to_string_lossy().into_owned(); + io::save_session(&mut e, &path).unwrap(); + let mut reopened = Engine::default(); + assert!(io::open_session(&mut reopened, &path).unwrap().is_empty()); + assert_eq!(reopened.session().track(committed).unwrap().format, format); + assert_audio_eq(&committed_audio(&reopened, committed).channels, &committed_audio(&e, committed).channels); + assert_audio_eq(&soundcraft_mix::render_range(reopened.session(), range, 64), &before); + + let opts = EncodeOptions { format: FileFormat::Wav, bit_depth: BitDepth::Float32, dither: false, bwf: None }; + let wav_path = dir.join("mix.wav"); + io::Bounce::new(reopened.session_arc(), &wav_path, range, &opts, None, false, false).unwrap().run().unwrap(); + let wav = std::fs::read(&wav_path).unwrap(); + let (_, decoded) = soundcraft_audio_io::decode(&wav, Some("wav")).unwrap(); + assert_audio_eq(&decoded.channels, &before); + // The WAV extensible mask must describe this layout, not another layout of equal width. + let fmt_at = wav.windows(4).position(|tag| tag == b"fmt ").unwrap(); + let mask = u32::from_le_bytes(wav[fmt_at + 28..fmt_at + 32].try_into().unwrap()); + assert_eq!(mask, format.channel_mask()); + std::fs::remove_dir_all(&dir).unwrap(); + } +} + +#[test] +fn oversized_or_overflowing_commit_rolls_back_all_selected_tracks() { + for (format, length) in [ + (ChannelFormat::Mono, (soundcraft_mix::MAX_RENDER_SAMPLES / 2 + 1) as i64), + (ChannelFormat::Surround51, (soundcraft_mix::MAX_RENDER_SAMPLES / 6 + 1) as i64), + (ChannelFormat::Ambisonics(3), (soundcraft_mix::MAX_RENDER_SAMPLES / 16 + 1) as i64), + (ChannelFormat::Surround51, i64::MAX), + ] { + let (mut e, first, _) = fixture(format); + let s = e.session_mut(); + let second = s.add_track(TrackKind::Audio, format, Some("Too long")); + let mut clip = s.track(first).unwrap().clips()[0].clone(); + clip.id = s.new_clip_id(); + clip.length = length; + s.track_mut(second).unwrap().playlist_mut().unwrap().clips.push(clip); + let before = e.session_arc(); + let dirty = e.is_dirty(); + let result = e.execute("track.commit", &json!({"tracks": [first.0, second.0]})); + assert!(result.unwrap_err().to_string().contains("offline render limit")); + assert!(Arc::ptr_eq(&before, &e.session_arc()), "no hidden track, truncated source or partially committed first track"); + assert_eq!(e.is_dirty(), dirty); + assert!(!e.can_undo(), "failed commit must not add an undo step"); + } +} + +#[test] +fn commit_rejects_formats_wider_than_the_renderer_without_replacing_tracks() { + for format in ChannelFormat::ALL.into_iter().filter(|format| format.channels() > soundcraft_mix::MAX_CHANNELS) { + let (mut e, track, _) = fixture(format); + let before = e.session_arc(); + let result = e.execute("track.commit", &json!({"tracks": [track.0]})); + assert!(result.unwrap_err().to_string().contains("at most 16 channels")); + assert!(Arc::ptr_eq(&before, &e.session_arc())); + assert!(!e.session().track(track).unwrap().inactive); + assert!(!e.session().track(track).unwrap().hidden); + assert!(!e.can_undo()); + } +} diff --git a/docs/commit-multichannel.md b/docs/commit-multichannel.md new file mode 100644 index 00000000..57874a03 --- /dev/null +++ b/docs/commit-multichannel.md @@ -0,0 +1,41 @@ +# Track Commit channel-format integrity + +**Last reviewed:** 2026-10-13 · **Last updated:** 2026-10-13 + +Track Commit retains the source track's exact `ChannelFormat`, including surround, height and +ambisonic layouts. Channel count alone cannot identify a layout: 5.1 and 6.0 both have six +channels, while Quad, LCRS and first-order ambisonics all have four. + +The shared pre-fader renderer already returns multichannel audio in the track's own layout. +Commit copies that format to the new audio track and checks the returned channel count and +frame count before adding the source or hiding the original track. Formats wider than the +renderer’s 16-channel limit are rejected before rendering. The fixed two-second tail uses +checked arithmetic; overflowing ranges or requests beyond the renderer’s sample limit return +an error. A command committing several tracks rolls back all of them if any selected track +fails. Current routing and mixer inheritance remain unchanged. + +The regression fixtures use distinct bipolar signals on each channel across all 30 declared +formats within the 16-channel limit, with an insert applied before committing. The four higher +ambisonic orders are rejected without replacing the source track. Additional cases check +bus/send routing, undo/redo, session save/reopen and float WAV export, including its output +speaker mask. + +Mono uses a two-channel frame limit because the existing renderer temporarily targets stereo +before folding back to mono. This frame limit does not bound total process memory. The shared +mono renderer’s -3 dB center-pan gain followed by `SQRT_2` compensation produces approximately ++0.0103 dB gain; the signal fixture accounts for that existing processing behavior. + +Session track metadata retains the exact layout. Generic source WAV saving still infers its +channel mask from channel count. This change preserves the shared renderer, the fixed tail +and the existing commit options. + +Implementation: `crates/engine/src/io.rs::commit_track` and +`crates/mix/src/lib.rs::render_track_pre_fader`. Regression fixtures: +`crates/engine/tests/commit_multichannel.rs`. + +## Revision history + +| Date | Change | +|---|---| +| 2026-10-13 | Refresh against current main; document source-supported format checks, existing renderer limits and regression fixtures. | +| 2026-10-12 | Preserve exact committed formats and reject incomplete or unsupported-width renders; add channel-signal, routing, persistence/export and rollback coverage. | From 28c936a256f43e354a334bd9e90d2d8259f6e4bb Mon Sep 17 00:00:00 2001 From: Billy Coleman III Date: Tue, 13 Oct 2026 20:42:34 -0400 Subject: [PATCH 08/52] Prevent track-name collisions after truncation Validate the trimmed 64-scalar stored track name before mutating the document, return that exact name, and preserve no-op document state. Retain routing-folder bus naming and repair with unique bus names, stable routes and undo/redo coverage. --- contributors/people.toml | 3 + crates/engine/src/cmd/track.rs | 15 +- crates/engine/tests/track_name_collisions.rs | 173 +++++++++++++++++++ 3 files changed, 189 insertions(+), 2 deletions(-) create mode 100644 crates/engine/tests/track_name_collisions.rs diff --git a/contributors/people.toml b/contributors/people.toml index 1c344199..f67fdd57 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -50,3 +50,6 @@ sync_github_name = false [people.Momentum96] sync_github_name = true + +[people.ProdByBuddha] +sync_github_name = true diff --git a/crates/engine/src/cmd/track.rs b/crates/engine/src/cmd/track.rs index 87912389..6f585dcf 100644 --- a/crates/engine/src/cmd/track.rs +++ b/crates/engine/src/cmd/track.rs @@ -613,15 +613,26 @@ fn delete(e: &mut Engine, p: &Value) -> Result { fn rename(e: &mut Engine, p: &Value) -> Result { let t = track_param(e, "track.rename", p, "track")?.ok_or_else(|| bad("track.rename", "`track` required"))?; let name = str_param(p, "name").map(str::trim).filter(|n| !n.is_empty()).ok_or_else(|| bad("track.rename", "`name` required"))?; - let s = e.session_mut(); + // Validate the stored name, including its existing 64-character limit. + let name: String = name.chars().take(64).collect(); + let s = e.session(); if s.tracks.iter().any(|x| x.name == name && x.id != t) { return Err(bad("track.rename", format!("a track named `{name}` already exists"))); } - let name: String = name.chars().take(64).collect(); let bus = s.track(t).and_then(|track| match (track.kind, &track.mixer.input) { (TrackKind::Folder, Route::Bus(bus)) => Some(*bus), _ => None, }); + let track = s.track(t).ok_or_else(|| bad("track.rename", "unknown track"))?; + if track.name == name + && bus.is_none_or(|id| { + let expected = unique_folder_bus_name(s, &format!("{name} Bus"), Some(id)); + s.bus(id).is_none_or(|bus| bus.name == expected) + }) + { + return Ok(json!({"name": name})); + } + let s = e.session_mut(); if let Some(track) = s.track_mut(t) { track.name.clone_from(&name); } diff --git a/crates/engine/tests/track_name_collisions.rs b/crates/engine/tests/track_name_collisions.rs new file mode 100644 index 00000000..cff5b277 --- /dev/null +++ b/crates/engine/tests/track_name_collisions.rs @@ -0,0 +1,173 @@ +use serde_json::json; +use soundcraft_engine::Engine; +use soundcraft_model::{ChannelFormat, Session, TrackKind}; +use std::sync::Arc; + +#[test] +fn truncated_ascii_and_unicode_names_cannot_collide_with_another_track() { + for character in ['A', '界'] { + let existing: String = std::iter::repeat_n(character, 64).collect(); + let mut session = Session::default(); + let occupied = session.add_track(TrackKind::Audio, ChannelFormat::Stereo, Some(&existing)); + let target = session.add_track(TrackKind::Aux, ChannelFormat::Mono, Some("Target")); + let mut engine = Engine::new(session); + let before = engine.session_arc(); + let revision = engine.revision; + + let result = engine.execute("track.rename", &json!({"track": target.0, "name": format!(" {existing} extra ")})); + assert!(result.is_err()); + assert!(Arc::ptr_eq(&before, &engine.session_arc())); + assert_eq!(engine.revision, revision); + assert_eq!(engine.session().track(occupied).unwrap().name, existing); + assert_eq!(engine.session().track(target).unwrap().name, "Target"); + assert!(!engine.is_dirty()); + assert!(!engine.can_undo()); + } +} + +#[test] +fn rename_returns_the_stored_unicode_name_and_undo_restores_the_document() { + let mut session = Session::default(); + let track = session.add_track(TrackKind::Audio, ChannelFormat::Surround51, Some("Original")); + session.track_mut(track).unwrap().comments = "Retain this comment".into(); + let mut engine = Engine::new(session); + let before = engine.session().to_json().unwrap(); + let stored = "é".repeat(64); + + let result = engine.execute("track.rename", &json!({"track": track.0, "name": format!(" {stored}extra ")})).unwrap(); + assert_eq!(result["name"], stored); + let renamed = engine.session().track(track).unwrap(); + assert_eq!(renamed.name, stored); + assert_eq!(renamed.name.chars().count(), 64); + assert_eq!(renamed.id, track); + assert_eq!(renamed.format, ChannelFormat::Surround51); + assert_eq!(renamed.comments, "Retain this comment"); + assert_eq!(engine.undo_history(), ["Rename Track"]); + assert!(engine.undo()); + assert_eq!(engine.session().to_json().unwrap(), before); + assert!(engine.redo()); + assert_eq!(engine.session().track(track).unwrap().name, stored); +} + +#[test] +fn unchanged_name_after_truncation_does_not_make_an_undo_step() { + let name = "A".repeat(64); + let mut session = Session::default(); + let track = session.add_track(TrackKind::Audio, ChannelFormat::Mono, Some(&name)); + let mut engine = Engine::new(session); + let before = engine.session_arc(); + let revision = engine.revision; + + let result = engine.execute("track.rename", &json!({"track": track.0, "name": format!("{name} suffix")})).unwrap(); + assert_eq!(result["name"], name); + assert!(Arc::ptr_eq(&before, &engine.session_arc())); + assert_eq!(engine.revision, revision); + assert!(!engine.is_dirty()); + assert!(!engine.can_undo()); +} + +#[test] +fn routing_folder_rename_preserves_unique_owned_bus_routes_and_history() { + use soundcraft_model::{BusId, Route, TrackId}; + + let stored = "界".repeat(64); + let first_name = format!("{stored} Bus"); + let second_name = format!("{stored} Bus 2"); + let mut session = Session::default(); + let member = session.add_track(TrackKind::Audio, ChannelFormat::Stereo, Some("Member")); + let user_bus = session.add_bus(&first_name, ChannelFormat::Stereo); + let second_user_bus = session.add_bus(&second_name, ChannelFormat::Stereo); + let mut engine = Engine::new(session); + let unrelated = engine.execute("track.new", &json!({"kind": "folder", "name": "Unrelated"})).unwrap(); + let unrelated = TrackId(unrelated["tracks"][0].as_u64().unwrap()); + let unrelated_route = engine.session().track(unrelated).unwrap().mixer.input.clone(); + let created = engine.execute("track.move_to_new_folder", &json!({"tracks": [member.0], "name": "Initial"})).unwrap(); + let folder = TrackId(created["folder"].as_u64().unwrap()); + let owned_bus = BusId(created["bus"].as_u64().unwrap()); + let before = engine.session().to_json().unwrap(); + let history = engine.undo_history(); + let bus_count = engine.session().busses.len(); + + let result = engine.execute("track.rename", &json!({"track": folder.0, "name": format!(" {stored} suffix ")})).unwrap(); + assert_eq!(result["name"], stored); + assert_eq!(engine.session().track(folder).unwrap().name, stored); + assert_eq!(engine.session().bus(owned_bus).unwrap().name, format!("{stored} Bus 3")); + assert_eq!(engine.session().bus(user_bus).unwrap().name, first_name); + assert_eq!(engine.session().bus(second_user_bus).unwrap().name, second_name); + assert_eq!(engine.session().track(unrelated).unwrap().mixer.input, unrelated_route); + assert_eq!(engine.session().track(folder).unwrap().mixer.input, Route::Bus(owned_bus)); + assert_eq!(engine.session().track(member).unwrap().mixer.output, Route::Bus(owned_bus)); + assert_eq!(engine.session().track(member).unwrap().folder, Some(folder)); + assert_eq!(engine.session().busses.len(), bus_count); + assert_eq!(engine.undo_history().len(), history.len() + 1); + assert_eq!(engine.undo_label(), Some("Rename Track")); + let renamed = engine.session().to_json().unwrap(); + + let document = engine.session_arc(); + let revision = engine.revision; + let history = engine.undo_history(); + engine.execute("track.rename", &json!({"track": folder.0, "name": format!("{stored} more")})).unwrap(); + assert!(Arc::ptr_eq(&document, &engine.session_arc())); + assert_eq!(engine.revision, revision); + assert_eq!(engine.undo_history(), history); + assert!(engine.undo()); + assert_eq!(engine.session().to_json().unwrap(), before); + assert!(engine.redo()); + assert_eq!(engine.session().to_json().unwrap(), renamed); + + // Current-main same-name folder rename also repairs the folder's own bus, without taking + // either colliding user bus or changing its members' bus identity. + engine.session_mut().busses.iter_mut().find(|bus| bus.id == owned_bus).unwrap().name = "Manually named owned bus".into(); + let manual = engine.session().to_json().unwrap(); + engine.execute("track.rename", &json!({"track": folder.0, "name": stored})).unwrap(); + assert_eq!(engine.session().bus(owned_bus).unwrap().name, format!("{stored} Bus 3")); + assert_eq!(engine.session().bus(user_bus).unwrap().name, first_name); + assert_eq!(engine.session().bus(second_user_bus).unwrap().name, second_name); + assert_eq!(engine.session().track(member).unwrap().mixer.output, Route::Bus(owned_bus)); + assert!(engine.undo()); + assert_eq!(engine.session().to_json().unwrap(), manual); + assert!(engine.redo()); + assert_eq!(engine.session().to_json().unwrap(), renamed); +} + +#[test] +fn truncated_folder_collision_refuses_bus_and_document_changes_with_redo_pending() { + use soundcraft_model::{Route, TrackId}; + + for character in ['B', '界'] { + let occupied_name: String = std::iter::repeat_n(character, 64).collect(); + let mut session = Session::default(); + let occupied = session.add_track(TrackKind::Audio, ChannelFormat::Stereo, Some(&occupied_name)); + let mut engine = Engine::new(session); + let created = engine.execute("track.new", &json!({"kind": "folder", "name": "Target"})).unwrap(); + let folder = TrackId(created["tracks"][0].as_u64().unwrap()); + let owned_bus = match engine.session().track(folder).unwrap().mixer.input { + Route::Bus(bus) => bus, + _ => panic!("the routing folder must own a bus"), + }; + engine.execute("mix.volume", &json!({"track": folder.0, "db": -3})).unwrap(); + assert!(engine.undo()); + engine.mark_clean(); + let document = engine.session_arc(); + let before = engine.session().to_json().unwrap(); + let revision = engine.revision; + let journal = engine.journal.clone(); + let undo = engine.undo_history(); + let redo = engine.redo_label().map(str::to_owned); + assert!(redo.is_some()); + + let result = engine.execute("track.rename", &json!({"track": folder.0, "name": format!(" {occupied_name} suffix ")})); + assert!(result.unwrap_err().to_string().contains(&occupied_name)); + assert!(Arc::ptr_eq(&document, &engine.session_arc())); + assert_eq!(engine.session().to_json().unwrap(), before); + assert_eq!(engine.revision, revision); + assert_eq!(engine.journal, journal); + assert_eq!(engine.undo_history(), undo); + assert_eq!(engine.redo_label(), redo.as_deref()); + assert!(!engine.is_dirty()); + assert_eq!(engine.session().track(occupied).unwrap().name, occupied_name); + assert_eq!(engine.session().track(folder).unwrap().name, "Target"); + assert_eq!(engine.session().bus(owned_bus).unwrap().name, "Target Bus"); + assert_eq!(engine.session().track(folder).unwrap().mixer.input, Route::Bus(owned_bus)); + } +} From d4096db1f08883c10dde0f10dfc834bb57c940e0 Mon Sep 17 00:00:00 2001 From: Gert Pellin Date: Wed, 14 Oct 2026 13:28:56 +0200 Subject: [PATCH 09/52] Bounce: a Dither option in the dialog and for stems (#522) The Bounce dialog never sent `dither`, so every 16- and 24-bit bounce was dithered, and file.bounce_stems hard-coded it. The dialog gets a Dither (TPDF) checkbox, off by default and disabled for 32-bit float, and file.bounce_stems takes the same `dither?: true` parameter as file.bounce_mix. --- README.md | 2 +- crates/engine/src/cmd/file.rs | 4 +-- crates/engine/src/io.rs | 43 +++++++++++++++++++++++++++ crates/ui-egui/src/dialogs.rs | 19 +++++++++--- crates/ui-egui/tests/bounce.rs | 54 ++++++++++++++++++++++++++++++++++ 5 files changed, 115 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index d88fee8a..6fef9815 100644 --- a/README.md +++ b/README.md @@ -131,7 +131,7 @@ where things are. pitch-preserving Elastic warping. - **Audio files:** WAV/BWF/RF64, AIFF/AIFC and FLAC in and out; MP3, Ogg Vorbis, AAC, ALAC, CAF and the audio of MP4/MOV movies in. Any sample rate and bit depth. -- **Bounce:** mix or stems to WAV, AIFF or FLAC at 16/24/32-bit float with dither and +- **Bounce:** mix or stems to WAV, AIFF or FLAC at 16/24/32-bit float with optional dither and normalisation, reporting peak, true peak and integrated loudness (LUFS). - **Fast:** a parallel mix engine, copy-on-write undo, and a UI that holds 120 frames per second with seventy-odd tracks playing. diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 87bba997..db70c200 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -85,7 +85,7 @@ pub fn specs() -> Vec { } ), cmd!(noundo "file.bounce_mix", "Bounce Mix...", ["File"], Some("Cmd+Alt+B"), "{path, format?: wav|aiff|flac, bit_depth?: 16|24|32f, start?, end?, source?: main|bus name, normalize?: false, dither?: true, fold_down?: stereo}", always, bounce), - cmd!(noundo "file.bounce_stems", "Bounce Stems...", [], None, "{dir, format?: wav|aiff|flac, bit_depth?: 16|24|32f, start?, end?, fold_down?: stereo}", has_tracks, |e, p| { + cmd!(noundo "file.bounce_stems", "Bounce Stems...", [], None, "{dir, format?: wav|aiff|flac, bit_depth?: 16|24|32f, start?, end?, dither?: true, fold_down?: stereo}", has_tracks, |e, p| { let dir = str_param(p, "dir").ok_or_else(|| bad("file.bounce_stems", "`dir` required"))?.to_string(); let r = range_param(e, "file.bounce_stems", p)?; let r = if r.is_empty() { soundcraft_time::Range::new(0, e.session().content_end().max(1)) } else { r }; @@ -100,7 +100,7 @@ pub fn specs() -> Vec { _ => soundcraft_audio_io::BitDepth::Int24, }; let fold = fold_down_param(p, "file.bounce_stems")?; - let files = crate::io::bounce_stems_with(e, &dir, r, &soundcraft_audio_io::EncodeOptions { format, bit_depth, dither: true, bwf: None }, fold)?; + let files = crate::io::bounce_stems_with(e, &dir, r, &soundcraft_audio_io::EncodeOptions { format, bit_depth, dither: bool_or(p, "dither", true), bwf: None }, fold)?; Ok(json!({"files": files})) }), cmd!(noundo "file.export_midi", "MIDI...", ["File", "Export"], None, "{path, tracks?}", always, |e, p| { diff --git a/crates/engine/src/io.rs b/crates/engine/src/io.rs index 7b26e0b1..ac202ecf 100644 --- a/crates/engine/src/io.rs +++ b/crates/engine/src/io.rs @@ -1823,6 +1823,49 @@ mod stem_tests { assert_eq!(n, 7, "{r}"); let _ = std::fs::remove_dir_all(&dir); } + + /// The largest gap between the 16-bit stem in `dir16` and the 32-bit float one in `dir32`, in LSBs. + fn max_error_lsb(dir16: &std::path::Path, dir32: &std::path::Path) -> f64 { + let mut worst = 0.0f64; + let mut names: Vec<_> = std::fs::read_dir(dir32).unwrap().map(|f| f.unwrap().file_name()).collect(); + names.sort(); + assert!(!names.is_empty()); + for name in names { + let (_, float) = soundcraft_audio_io::decode(&std::fs::read(dir32.join(&name)).unwrap(), None).unwrap(); + let (_, int) = soundcraft_audio_io::decode(&std::fs::read(dir16.join(&name)).unwrap(), None).unwrap(); + for (f, i) in float.channels.iter().zip(&int.channels) { + for (a, b) in f.iter().zip(i) { + worst = worst.max((f64::from(a.clamp(-1.0, 1.0)) - f64::from(*b)).abs() * 32768.0); + } + } + } + worst + } + + #[test] + fn stems_dither_only_when_asked() { + let mut e = crate::demo::demo_engine(); + let root = std::env::temp_dir().join(format!("soundcraft-stems-dither-{}", std::process::id())); + let mut bounce = |name: &str, extra: serde_json::Value| { + let dir = root.join(name); + let mut p = serde_json::json!({"dir": dir.to_string_lossy(), "start": {"seconds": 10.0}, "end": {"seconds": 10.5}}); + for (k, v) in extra.as_object().unwrap() { + p[k] = v.clone(); + } + e.execute("file.bounce_stems", &p).unwrap(); + dir + }; + let float = bounce("float", serde_json::json!({"bit_depth": "32f"})); + let plain = bounce("plain", serde_json::json!({"bit_depth": "16", "dither": false})); + let dithered = bounce("dithered", serde_json::json!({"bit_depth": "16"})); + // Without dither every sample is the float one rounded to the nearest step; TPDF dither of + // ±1 LSB moves some of them further than half a step. + let plain_error = max_error_lsb(&plain, &float); + let dithered_error = max_error_lsb(&dithered, &float); + assert!(plain_error <= 0.5 + 1e-3, "{plain_error}"); + assert!(dithered_error > 0.6, "{dithered_error}"); + let _ = std::fs::remove_dir_all(&root); + } } #[cfg(test)] diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 713e94b7..6effa628 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -12,7 +12,7 @@ use soundcraft_time::Samples; pub enum Dialog { NewTracks { count: u32, format: String, kind: String, timebase: String, name: String }, NewSession { name: String, sample_rate: u32, demo: bool }, - Bounce { path: String, format: String, bit_depth: String, normalize: bool }, + Bounce { path: String, format: String, bit_depth: String, normalize: bool, dither: bool }, RenameTrack { id: TrackId, name: String }, RenameClip { id: ClipId, name: String }, RenameMarker { id: soundcraft_model::MarkerId, name: String }, @@ -99,7 +99,13 @@ impl Dialogs { .and_then(|p| std::path::Path::new(p).parent()) .filter(|d| !d.as_os_str().is_empty()) .map_or(home.clone(), |d| d.display().to_string()); - Dialog::Bounce { path: format!("{dir}/{name} Bounce.wav"), format: "wav".into(), bit_depth: "24".into(), normalize: false } + Dialog::Bounce { + path: format!("{dir}/{name} Bounce.wav"), + format: "wav".into(), + bit_depth: "24".into(), + normalize: false, + dither: false, + } } "file.import_audio" => Dialog::PathPrompt { cmd: id.into(), title: "Import Audio".into(), path: home, key: "path".into() }, "file.import_midi" => Dialog::PathPrompt { cmd: id.into(), title: "Import MIDI".into(), path: home, key: "path".into() }, @@ -353,7 +359,7 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) { )); } } - Dialog::Bounce { path, format, bit_depth, normalize } => { + Dialog::Bounce { path, format, bit_depth, normalize, dither } => { ui.horizontal(|ui| { ui.label("File"); ui.add(egui::TextEdit::singleline(path).desired_width(420.0)); @@ -383,6 +389,11 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) { }); }); crate::widgets::checkbox(ui, normalize, "Normalize to -0.1 dBFS"); + // 32-bit float keeps every sample as it is: there is nothing to dither. + ui.add_enabled_ui(bit_depth.as_str() != "32f", |ui| { + crate::widgets::checkbox(ui, dither, "Dither (TPDF)") + .on_hover_text("Adds ±1 LSB triangular dither when writing 16- or 24-bit files. Leave it off when the master chain already dithers."); + }); ui.label( egui::RichText::new("Bounces the edit selection, or the whole session when nothing is selected.") .small() @@ -392,7 +403,7 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) { let p = std::path::Path::new(path.as_str()).with_extension(if format == "aiff" { "aif" } else { format.as_str() }); crate::bounce::start( app, - &json!({"path": p.to_string_lossy(), "format": format, "bit_depth": bit_depth, "normalize": normalize}), + &json!({"path": p.to_string_lossy(), "format": format, "bit_depth": bit_depth, "normalize": normalize, "dither": *dither && bit_depth.as_str() != "32f"}), ); keep = false; } diff --git a/crates/ui-egui/tests/bounce.rs b/crates/ui-egui/tests/bounce.rs index 9745ae4e..77e73fff 100644 --- a/crates/ui-egui/tests/bounce.rs +++ b/crates/ui-egui/tests/bounce.rs @@ -114,3 +114,57 @@ fn cancel_or_escape_stops_a_bounce_and_leaves_no_file() { assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0); let _ = std::fs::remove_dir_all(&dir); } + +/// The largest gap between `int` and `float` in 16-bit LSBs. +fn max_error_lsb(int: &Path, float: &Path) -> f64 { + let (_, a) = soundcraft_audio_io::decode(&std::fs::read(int).unwrap(), None).unwrap(); + let (_, b) = soundcraft_audio_io::decode(&std::fs::read(float).unwrap(), None).unwrap(); + let mut worst = 0.0f64; + for (i, f) in a.channels.iter().zip(&b.channels) { + for (x, y) in i.iter().zip(f) { + worst = worst.max((f64::from(*x) - f64::from(y.clamp(-1.0, 1.0))).abs() * 32768.0); + } + } + worst +} + +/// Bounces from the dialog at `bit_depth`, ticking Dither when `dither`, and waits for the file. +fn bounce_with(h: &mut Harness<'_, SoundApp>, file: &Path, bit_depth: &str, dither: bool) { + let app = h.state_mut(); + assert!(app.dialogs.open_for_command(&app.engine, "file.bounce_mix")); + if let Some(Dialog::Bounce { path, bit_depth: depth, .. }) = &mut app.dialogs.open { + *path = file.to_string_lossy().into_owned(); + *depth = bit_depth.into(); + } + h.run_steps(2); + if dither { + h.get_by_label("Dither (TPDF)").click(); + h.run_steps(2); + } + h.get_by_label("Bounce").click(); + h.run_steps(3); + h.run(); + assert!(h.state().bounce.is_none()); + assert!(file.exists(), "{}", h.state().ui.status); +} + +#[test] +fn the_bounce_dialog_dithers_only_when_dither_is_ticked() { + let dir = scratch("bounce-dither"); + let mut h = harness(); + let app = h.state_mut(); + assert!(app.dialogs.open_for_command(&app.engine, "file.bounce_mix")); + match &app.dialogs.open { + Some(Dialog::Bounce { dither, .. }) => assert!(!dither, "Dither starts off"), + other => panic!("{other:?}"), + } + app.dialogs.open = None; + bounce_with(&mut h, &dir.join("Float.wav"), "32f", false); + bounce_with(&mut h, &dir.join("Plain.wav"), "16", false); + bounce_with(&mut h, &dir.join("Dithered.wav"), "16", true); + let plain = max_error_lsb(&dir.join("Plain.wav"), &dir.join("Float.wav")); + let dithered = max_error_lsb(&dir.join("Dithered.wav"), &dir.join("Float.wav")); + assert!(plain <= 0.5 + 1e-3, "{plain}"); + assert!(dithered > 0.6, "{dithered}"); + let _ = std::fs::remove_dir_all(&dir); +} From f8b2f8ce2e0b611ae4b6ec3165c6af77777eb6de Mon Sep 17 00:00:00 2001 From: Hamza Date: Wed, 14 Oct 2026 16:59:15 +0500 Subject: [PATCH 10/52] cli: reject unknown options and missing option values `convert`, `run` and `script` read options with `arg_value`, which matches a flag exactly and takes the argument after it. A misspelling, an `--option=value` form or an option with no value therefore read as absent: the command ran without what was asked for and still exited 0. convert IN OUT --rate=44100 wrote IN's 48000 Hz unchanged convert IN OUT --bitdepth 16 wrote the default 24-bit convert IN OUT --bogus wrote the file, said nothing run --cmd session.new --bounce=OUT bounced nothing Check what each subcommand accepts and report an unknown option or a missing value with a non-zero exit, and read `--option=value` as the value it looks like. The documented space-separated form is unchanged. --- apps/soundcraft-cli/src/main.rs | 62 +++++++++++++- apps/soundcraft-cli/tests/options.rs | 122 +++++++++++++++++++++++++++ 2 files changed, 183 insertions(+), 1 deletion(-) create mode 100644 apps/soundcraft-cli/tests/options.rs diff --git a/apps/soundcraft-cli/src/main.rs b/apps/soundcraft-cli/src/main.rs index 9a51cc54..4655c43b 100644 --- a/apps/soundcraft-cli/src/main.rs +++ b/apps/soundcraft-cli/src/main.rs @@ -38,9 +38,57 @@ macro_rules! outln { } fn arg_value(args: &[String], flag: &str) -> Option { - args.iter().position(|a| a == flag).and_then(|i| args.get(i + 1)).cloned() + args.iter().enumerate().find_map(|(i, a)| { + if a == flag { args.get(i + 1).cloned() } else { a.strip_prefix(flag).and_then(|rest| rest.strip_prefix('=')).map(str::to_owned) } + }) } +/// Every option a subcommand accepts, with whether it carries a value. +type Options = [(&'static str, bool)]; + +/// A misspelled option, or one whose value is missing, reads as absent through `arg_value`, so the +/// subcommand would run without what was asked for and still report success. Reject both instead. +fn check_options(args: &[String], allowed: &Options) -> Result<(), String> { + let mut i = 0; + while i < args.len() { + let Some(name) = args[i].strip_prefix("--") else { + i += 1; + continue; + }; + let (name, inline) = name.split_once('=').map_or((name, None), |(n, v)| (n, Some(v))); + let flag = format!("--{name}"); + let Some(&(_, takes_value)) = allowed.iter().find(|(f, _)| f == &flag) else { + return Err(format!("unknown option {flag}")); + }; + match (takes_value, inline) { + (false, Some(_)) => return Err(format!("{flag} takes no value")), + (true, None) => { + // A following option is the next flag, not this one's value. + if args.get(i + 1).is_none_or(|v| v.starts_with("--")) { + return Err(format!("{flag} needs a value")); + } + i += 1; + } + _ => {} + } + i += 1; + } + Ok(()) +} + +/// `--in`, `--demo`/`--sample`, `--bounce`, `--start`, `--end`, `--save` and `--inspect`, read by +/// `load_engine` and `finish` and so shared by `run` and `script`. +const ENGINE_OPTIONS: &Options = &[ + ("--in", true), + ("--demo", false), + ("--sample", false), + ("--bounce", true), + ("--start", true), + ("--end", true), + ("--save", true), + ("--inspect", false), +]; + fn fail(msg: impl std::fmt::Display) -> ExitCode { eprintln!("soundcraft-cli: {msg}"); ExitCode::FAILURE @@ -122,6 +170,10 @@ fn info(args: &[String]) -> ExitCode { fn convert(args: &[String]) -> ExitCode { let (Some(input), Some(output)) = (args.first(), args.get(1)) else { return fail("convert IN OUT") }; + const OPTIONS: &Options = &[("--rate", true), ("--bit-depth", true), ("--normalize", false)]; + if let Err(e) = check_options(&args[2..], OPTIONS) { + return fail(e); + } let rate = match parse_rate(arg_value(args, "--rate").as_deref()) { Ok(r) => r, Err(e) => return fail(e), @@ -243,6 +295,10 @@ fn parse_cmd_spec(spec: &str) -> Result<(String, Value), String> { } fn run(args: &[String]) -> ExitCode { + let options: Vec<(&str, bool)> = ENGINE_OPTIONS.iter().copied().chain([("--cmd", true)]).collect(); + if let Err(e) = check_options(args, &options) { + return fail(e); + } let mut e = match load_engine(args) { Ok(e) => e, Err(err) => return fail(err), @@ -269,6 +325,10 @@ fn run(args: &[String]) -> ExitCode { fn script(args: &[String]) -> ExitCode { let Some(path) = args.first() else { return fail("script FILE") }; + let options: Vec<(&str, bool)> = ENGINE_OPTIONS.iter().copied().chain([("--keep-going", false)]).collect(); + if let Err(e) = check_options(&args[1..], &options) { + return fail(e); + } let text = match std::fs::read_to_string(path) { Ok(t) => t, Err(e) => return fail(format!("{path}: {e}")), diff --git a/apps/soundcraft-cli/tests/options.rs b/apps/soundcraft-cli/tests/options.rs new file mode 100644 index 00000000..e709a3d8 --- /dev/null +++ b/apps/soundcraft-cli/tests/options.rs @@ -0,0 +1,122 @@ +//! Unknown options and missing option values must be reported, not silently skipped (#549). +// Integration tests: unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md). +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::path::{Path, PathBuf}; +use std::process::{Command, Output}; + +fn bin() -> Command { + let mut cmd = Command::new(env!("CARGO_BIN_EXE_soundcraft-cli")); + cmd.env("SOUNDCRAFT_NO_PREFS", "1"); + cmd +} + +fn run(args: &[&str]) -> Output { + bin().args(args).output().unwrap() +} + +fn tmpdir(tag: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("sc-cli-options-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +/// A 0.1 s mono 48 kHz 16-bit WAV, written by hand so the test needs no fixture. +fn tone(dir: &Path) -> PathBuf { + let frames: u32 = 4800; + let data: Vec = (0..frames).flat_map(|_| [0x00, 0x10]).collect(); + let (bytes, rate, ch, bits) = (data.len() as u32, 48_000u32, 1u16, 16u16); + let mut wav = Vec::new(); + wav.extend_from_slice(b"RIFF"); + wav.extend_from_slice(&(36 + bytes).to_le_bytes()); + wav.extend_from_slice(b"WAVEfmt "); + wav.extend_from_slice(&16u32.to_le_bytes()); + wav.extend_from_slice(&1u16.to_le_bytes()); + wav.extend_from_slice(&ch.to_le_bytes()); + wav.extend_from_slice(&rate.to_le_bytes()); + wav.extend_from_slice(&(rate * u32::from(ch) * u32::from(bits) / 8).to_le_bytes()); + wav.extend_from_slice(&(ch * bits / 8).to_le_bytes()); + wav.extend_from_slice(&bits.to_le_bytes()); + wav.extend_from_slice(b"data"); + wav.extend_from_slice(&bytes.to_le_bytes()); + wav.extend_from_slice(&data); + let path = dir.join("tone.wav"); + std::fs::write(&path, wav).unwrap(); + path +} + +fn sample_format(cli_info: &str) -> String { + serde_json::from_str::(cli_info).unwrap()["sample_format"].as_str().unwrap().to_owned() +} + +#[test] +fn convert_rejects_an_unknown_option_instead_of_writing_the_file() { + let dir = tmpdir("convert-unknown"); + let input = tone(&dir); + let out = dir.join("out.wav"); + for bad in ["--bitdepth", "--normalise", "--bogus"] { + let o = run(&["convert", input.to_str().unwrap(), out.to_str().unwrap(), bad]); + assert!(!o.status.success(), "{bad} should fail"); + assert!(String::from_utf8_lossy(&o.stderr).contains(&format!("unknown option {bad}")), "{bad}: {}", String::from_utf8_lossy(&o.stderr)); + assert!(!out.exists(), "{bad} should not write the output"); + } +} + +#[test] +fn convert_rejects_an_option_whose_value_is_missing() { + let dir = tmpdir("convert-novalue"); + let input = tone(&dir); + let out = dir.join("out.wav"); + for bad in ["--rate", "--bit-depth"] { + let o = run(&["convert", input.to_str().unwrap(), out.to_str().unwrap(), bad]); + assert!(!o.status.success(), "{bad} should fail"); + assert!(String::from_utf8_lossy(&o.stderr).contains(&format!("{bad} needs a value")), "{bad}: {}", String::from_utf8_lossy(&o.stderr)); + assert!(!out.exists(), "{bad} should not write the output"); + } +} + +#[test] +fn convert_accepts_the_inline_value_form() { + let dir = tmpdir("convert-inline"); + let input = tone(&dir); + let out = dir.join("out.wav"); + let o = run(&["convert", input.to_str().unwrap(), out.to_str().unwrap(), "--bit-depth=32f"]); + assert!(o.status.success(), "{}", String::from_utf8_lossy(&o.stderr)); + let info = run(&["info", out.to_str().unwrap()]); + assert_eq!(sample_format(&String::from_utf8_lossy(&info.stdout)), "Float32"); +} + +#[test] +fn convert_still_accepts_the_documented_space_separated_form() { + let dir = tmpdir("convert-space"); + let input = tone(&dir); + let out = dir.join("out.wav"); + let o = run(&["convert", input.to_str().unwrap(), out.to_str().unwrap(), "--bit-depth", "16"]); + assert!(o.status.success(), "{}", String::from_utf8_lossy(&o.stderr)); + let info = run(&["info", out.to_str().unwrap()]); + assert_eq!(sample_format(&String::from_utf8_lossy(&info.stdout)), "Int16"); +} + +#[test] +fn run_rejects_a_misspelled_or_value_less_bounce() { + let dir = tmpdir("run-bounce"); + let out = dir.join("x.wav"); + let o = run(&["run", "--cmd", "session.new", "--bounce"]); + assert!(!o.status.success()); + assert!(String::from_utf8_lossy(&o.stderr).contains("--bounce needs a value"), "{}", String::from_utf8_lossy(&o.stderr)); + + let o = run(&["run", "--cmd", "session.new", "--bounces", out.to_str().unwrap()]); + assert!(!o.status.success()); + assert!(String::from_utf8_lossy(&o.stderr).contains("unknown option --bounces"), "{}", String::from_utf8_lossy(&o.stderr)); + assert!(!out.exists(), "nothing should be bounced"); +} + +#[test] +fn run_bounces_with_the_inline_value_form() { + let dir = tmpdir("run-inline"); + let out = dir.join("y.wav"); + let o = run(&["run", "--cmd", "session.new", &format!("--bounce={}", out.display())]); + assert!(o.status.success(), "{}", String::from_utf8_lossy(&o.stderr)); + assert!(out.exists(), "--bounce=PATH should write the file"); +} From 76696826cd95430e68e1d2fb9574b9effd7df2f7 Mon Sep 17 00:00:00 2001 From: midasmatterhorn <248507632+midasmatterhorn@users.noreply.github.com> Date: Wed, 14 Oct 2026 18:01:42 +0300 Subject: [PATCH 11/52] mix: clamp negative fractional source position in stretched-clip rendering --- crates/mix/src/lib.rs | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/crates/mix/src/lib.rs b/crates/mix/src/lib.rs index e8c4fbad..a354b000 100644 --- a/crates/mix/src/lib.rs +++ b/crates/mix/src/lib.rs @@ -1442,7 +1442,7 @@ fn render_clip(s: &Session, clip: &Clip, pos: Samples, frames: usize, buf: &mut let x0 = f.floor(); let fr = (f - x0) as f32; let a = if x0 >= 0.0 { src.get(x0 as usize).copied().unwrap_or(0.0) } else { 0.0 }; - let b = if x0 + 1.0 >= 0.0 { src.get((x0 as usize).saturating_add(1)).copied().unwrap_or(0.0) } else { 0.0 }; + let b = if x0 + 1.0 >= 0.0 { src.get((x0 + 1.0) as usize).copied().unwrap_or(0.0) } else { 0.0 }; a + (b - a) * fr }; let t = (k - i) as f32 / n; @@ -2369,6 +2369,30 @@ mod tests { assert!(out[0][100] > 0.49 && out[1][100].abs() < 1e-4); } + #[test] + fn a_stretched_clip_before_its_source_start_reads_from_the_first_sample() { + // A clip that extends before its source (a negative offset) plays silence there. When it + // is stretched, the read position passes through [-1, 0), which must interpolate from + // that silence towards sample 0 of the file -- not towards sample 1. + let mut s = Session::default(); + let t = s.add_track(TrackKind::Audio, ChannelFormat::Mono, None); + let buf = AudioBuffer { sample_rate: 48_000, channels: vec![vec![1.0, 0.5, 0.25, 0.125]] }; + s.pool.insert(SourceId(901), Arc::new(SourceAudio::new(buf))); + let id = s.new_clip_id(); + let mut c = Clip::audio(id, "late", SourceId(901), -1, 0, 4); + c.stretch = 2.0; + if let Some(pl) = s.track_mut(t).and_then(|t| t.playlist_mut()) { + pl.clips.push(c); + } + let out = render_clips(&s, t, Range::new(0, 4)); + // rel 0 -> source -1.0: silence; rel 1 -> source -0.5: halfway from silence to sample 0; + // rel 2 -> source 0.0: sample 0; rel 3 -> source 0.5: halfway to sample 1. + let want = [0.0, 0.5, 1.0, 0.75]; + for (i, w) in want.iter().enumerate() { + assert!((out[0][i] - w).abs() < 1e-6, "frame {i}: {} vs {w}", out[0][i]); + } + } + #[test] fn fade_curvature_reaches_the_rendered_audio() { for fade_in in [true, false] { From 1e1458caf1e4d9d0ec06956539fe3efade781118 Mon Sep 17 00:00:00 2001 From: Billy Coleman III Date: Wed, 14 Oct 2026 13:14:38 -0400 Subject: [PATCH 12/52] Compile exact dependency order for deep Aux routing Prepare longest-path depths for acyclic Aux and Folder input routes so reverse-created chains beyond eight returns preserve their audio. Count output and send destinations once per producer, retain depth ties in session order, and preserve the whole-graph bounded fallback for cycles. Add public PCM regressions for deep chains, routing edits, callback sizes and cycle compatibility, plus focused private ordering cases. --- contributors/people.toml | 3 + crates/mix/src/lib.rs | 157 +++++++++++-- crates/mix/tests/aux_routing_order.rs | 307 ++++++++++++++++++++++++++ docs/aux-routing-order.md | 17 ++ 4 files changed, 468 insertions(+), 16 deletions(-) create mode 100644 crates/mix/tests/aux_routing_order.rs create mode 100644 docs/aux-routing-order.md diff --git a/contributors/people.toml b/contributors/people.toml index 1c344199..f67fdd57 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -50,3 +50,6 @@ sync_github_name = false [people.Momentum96] sync_github_name = true + +[people.ProdByBuddha] +sync_github_name = true diff --git a/crates/mix/src/lib.rs b/crates/mix/src/lib.rs index e8c4fbad..2c482fbd 100644 --- a/crates/mix/src/lib.rs +++ b/crates/mix/src/lib.rs @@ -1306,26 +1306,97 @@ fn processing_order(s: &Session) -> Vec { (0..s.tracks.len()).filter(|&i| s.tracks.get(i).is_some_and(|t| !matches!(t.kind, TrackKind::Aux | TrackKind::Folder))).collect(); let mut auxes: Vec = (0..s.tracks.len()).filter(|&i| s.tracks.get(i).is_some_and(|t| matches!(t.kind, TrackKind::Aux | TrackKind::Folder))).collect(); - // Depth = how many aux hops feed this aux's input bus (bounded; cycles cap out). - let depth = |i: usize| -> usize { - let mut d = 0; - let mut cur = vec![i]; - for _ in 0..8 { - let inputs: Vec<&Route> = cur.iter().filter_map(|&k| s.tracks.get(k)).map(|t| &t.mixer.input).collect(); - let feeders: Vec = auxes_feeding(s, &inputs); - if feeders.is_empty() { - break; - } - d += 1; - cur = feeders; - } - d - }; - auxes.sort_by_key(|&i| depth(i)); + if let Some(depths) = acyclic_aux_depths(s, &auxes) { + // Stable sorting preserves session order among auxes at the same longest-path depth. + auxes.sort_by_key(|&i| depths.get(i).copied().unwrap_or(0)); + } else { + // A cycle keeps the existing bounded ordering for the entire graph, including any + // independent acyclic branches. Feedback does not have a finite longest-path depth. + auxes.sort_by_key(|&i| bounded_aux_depth(s, i)); + } order.extend(auxes); order } +/// Exact aux-hop depths when the whole Aux/Folder graph is acyclic. Bus joins retain only +/// producer counts and consumers, avoiding a producer-by-consumer adjacency matrix. +fn acyclic_aux_depths(s: &Session, auxes: &[usize]) -> Option> { + #[derive(Default)] + struct BusDependencies { + remaining: usize, + depth: usize, + last_producer: Option, + last_processed: Option, + consumers: Vec, + } + let mut busses = HashMap::::new(); + for &i in auxes { + for bus in aux_output_busses(s.tracks.get(i)?) { + let dependency = busses.entry(bus).or_default(); + // Output and multiple sends from this producer may name the same bus. + if dependency.last_producer != Some(i) { + dependency.last_producer = Some(i); + dependency.remaining = dependency.remaining.checked_add(1)?; + } + } + } + let mut depths = vec![0usize; s.tracks.len()]; + let mut ready = Vec::with_capacity(auxes.len()); + for &i in auxes { + if let Route::Bus(bus) = &s.tracks.get(i)?.mixer.input { + let dependency = busses.entry(*bus).or_default(); + dependency.consumers.push(i); + if dependency.remaining > 0 { + continue; + } + } + ready.push(i); + } + let mut processed = 0usize; + while let Some(&i) = ready.get(processed) { + processed = processed.checked_add(1)?; + let next_depth = depths.get(i)?.checked_add(1)?; + for bus in aux_output_busses(s.tracks.get(i)?) { + let dependency = busses.get_mut(&bus)?; + if dependency.last_processed == Some(i) { + continue; + } + dependency.last_processed = Some(i); + dependency.depth = dependency.depth.max(next_depth); + dependency.remaining = dependency.remaining.checked_sub(1)?; + if dependency.remaining == 0 { + for &consumer in &dependency.consumers { + *depths.get_mut(consumer)? = dependency.depth; + ready.push(consumer); + } + } + } + } + (processed == auxes.len()).then_some(depths) +} + +fn aux_output_busses(t: &Track) -> impl Iterator + '_ { + std::iter::once(&t.mixer.output) + .chain(t.mixer.sends.iter().flatten().map(|send| &send.target)) + .filter_map(|route| if let Route::Bus(bus) = route { Some(*bus) } else { None }) +} + +/// The previous bounded depth calculation, retained unchanged for any cyclic graph. +fn bounded_aux_depth(s: &Session, i: usize) -> usize { + let mut d = 0; + let mut cur = vec![i]; + for _ in 0..8 { + let inputs: Vec<&Route> = cur.iter().filter_map(|&k| s.tracks.get(k)).map(|t| &t.mixer.input).collect(); + let feeders: Vec = auxes_feeding(s, &inputs); + if feeders.is_empty() { + break; + } + d += 1; + cur = feeders; + } + d +} + fn auxes_feeding(s: &Session, inputs: &[&Route]) -> Vec { s.tracks .iter() @@ -1338,6 +1409,60 @@ fn auxes_feeding(s: &Session, inputs: &[&Route]) -> Vec { .collect() } +#[cfg(test)] +#[allow(clippy::unwrap_used)] +mod processing_order_tests { + use super::*; + use soundcraft_model::SendSlot; + + #[test] + fn acyclic_bus_joins_use_longest_depth_and_keep_session_order_for_ties() { + let mut s = Session::default(); + s.add_track(TrackKind::Audio, ChannelFormat::Stereo, None); + let consumer = s.add_track(TrackKind::Aux, ChannelFormat::Stereo, None); + let first_root = s.add_track(TrackKind::Aux, ChannelFormat::Stereo, None); + let second_root = s.add_track(TrackKind::Aux, ChannelFormat::Stereo, None); + let middle = s.add_track(TrackKind::Folder, ChannelFormat::Stereo, None); + let first_bus = s.add_bus("First", ChannelFormat::Stereo); + let join = s.add_bus("Join", ChannelFormat::Stereo); + s.track_mut(consumer).unwrap().mixer.input = Route::Bus(join); + let root = s.track_mut(first_root).unwrap(); + root.mixer.output = Route::Main; + root.mixer.sends[0] = Some(SendSlot::new(Route::Bus(first_bus))); + let root = s.track_mut(second_root).unwrap(); + root.mixer.output = Route::Bus(join); + root.mixer.sends[0] = Some(SendSlot::new(Route::Bus(join))); + root.mixer.sends[1] = Some(SendSlot::new(Route::Bus(join))); + let folder = s.track_mut(middle).unwrap(); + folder.mixer.input = Route::Bus(first_bus); + folder.mixer.output = Route::Bus(join); + folder.mixer.sends[0] = Some(SendSlot::new(Route::Bus(join))); + + assert_eq!(processing_order(&s), vec![0, 2, 3, 4, 1]); + } + + #[test] + fn a_cycle_preserves_bounded_order_for_the_whole_graph() { + let mut s = Session::default(); + let busses: Vec<_> = (0..10).map(|i| s.add_bus(&format!("Chain {i}"), ChannelFormat::Stereo)).collect(); + let tracks: Vec<_> = (0..10).map(|_| s.add_track(TrackKind::Aux, ChannelFormat::Stereo, None)).collect(); + for (i, id) in tracks.iter().enumerate() { + let track = s.track_mut(*id).unwrap(); + track.mixer.input = Route::Bus(busses[i]); + track.mixer.output = if i == 0 { Route::Main } else { Route::Bus(busses[i - 1]) }; + } + assert_eq!(processing_order(&s), vec![9, 8, 7, 6, 5, 4, 3, 2, 1, 0]); + let cycle_bus = s.add_bus("Feedback", ChannelFormat::Stereo); + let cycle = s.add_track(TrackKind::Aux, ChannelFormat::Stereo, None); + let track = s.track_mut(cycle).unwrap(); + track.mixer.input = Route::Bus(cycle_bus); + track.mixer.output = Route::Bus(cycle_bus); + + // Both deepest independent returns tie with the cycle at the legacy eight-hop cap. + assert_eq!(processing_order(&s), vec![9, 8, 7, 6, 5, 4, 3, 2, 0, 1, 10]); + } +} + /// Implicit solo: an aux is not muted when a soloed track feeds its input bus. fn receives_solo(s: &Session, t: &Track) -> bool { let Route::Bus(b) = &t.mixer.input else { return false }; diff --git a/crates/mix/tests/aux_routing_order.rs b/crates/mix/tests/aux_routing_order.rs new file mode 100644 index 00000000..4c557fa7 --- /dev/null +++ b/crates/mix/tests/aux_routing_order.rs @@ -0,0 +1,307 @@ +//! Aux and routing-folder dependencies preserve PCM beyond eight hops. Cyclic graphs keep +//! the established whole-graph fallback, including its session-order-dependent audio. +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use soundcraft_audio_io::AudioBuffer; +use soundcraft_mix::{MixEngine, render_range}; +use soundcraft_model::{BusId, ChannelFormat, Clip, Route, SendSlot, Session, SourceAudio, SourceId, TrackId, TrackKind}; +use soundcraft_time::Range; +use std::sync::Arc; + +const FRAMES: usize = 4097; +const DEPTH: usize = 12; + +fn signal() -> Vec> { + // Distinct, exactly representable channels expose lost, duplicated, swapped and delayed PCM. + vec![ + (0..FRAMES).map(|frame| ((frame % 31) as i32 - 15) as f32 / 256.0).collect(), + (0..FRAMES).map(|frame| ((frame % 17) as i32 - 8) as f32 / 512.0).collect(), + ] +} + +fn scaled_signal(gain: f32) -> Vec> { + signal().into_iter().map(|channel| channel.into_iter().map(|value| value * gain).collect()).collect() +} + +fn session(pdc: bool) -> Session { + let mut session = Session::default(); + session.edit.click = false; + session.edit.delay_compensation = pdc; + session +} + +fn add_source(session: &mut Session, output: Route) -> TrackId { + let source = SourceId(session.alloc()); + session.pool.insert(source, Arc::new(SourceAudio::new(AudioBuffer { sample_rate: 48_000, channels: signal() }))); + let clip = session.new_clip_id(); + let track = session.add_track(TrackKind::Audio, ChannelFormat::Stereo, Some("PCM source")); + let track_state = session.track_mut(track).unwrap(); + track_state.mixer.output = output; + track_state.playlist_mut().unwrap().clips.push(Clip::audio(clip, "PCM", source, 0, 0, FRAMES as i64)); + track +} + +fn add_aux(session: &mut Session, kind: TrackKind, input: BusId, output: Route) -> TrackId { + let track = session.add_track(kind, ChannelFormat::Stereo, None); + let mixer = &mut session.track_mut(track).unwrap().mixer; + mixer.input = Route::Bus(input); + mixer.output = output; + track +} + +fn send(bus: BusId) -> SendSlot { + let mut send = SendSlot::new(Route::Bus(bus)); + send.level_db = 0.0; + send +} + +struct Chain { + session: Session, + buses: Vec, + /// Logical routing order, deliberately different from the session's creation order. + tracks: Vec, +} + +fn reverse_chain(pdc: bool, send_links: bool, folders: bool) -> Chain { + let mut session = session(pdc); + let buses: Vec<_> = (0..DEPTH).map(|stage| session.add_bus(&format!("Stage {stage}"), ChannelFormat::Stereo)).collect(); + let mut tracks = Vec::new(); + for stage in (0..DEPTH).rev() { + let kind = if folders && stage % 3 == 1 { TrackKind::Folder } else { TrackKind::Aux }; + let output = if stage + 1 == DEPTH { + Route::Main + } else if send_links { + Route::None + } else { + Route::Bus(buses[stage + 1]) + }; + let track = add_aux(&mut session, kind, buses[stage], output); + if send_links && stage + 1 < DEPTH { + session.track_mut(track).unwrap().mixer.sends[0] = Some(send(buses[stage + 1])); + } + tracks.push(track); + } + tracks.reverse(); + add_source(&mut session, Route::Bus(buses[0])); + Chain { session, buses, tracks } +} + +fn assert_pcm(actual: &[Vec], expected: &[Vec], context: &str) { + assert_eq!(actual.len(), expected.len(), "{context}: channel count"); + for (channel, (actual, expected)) in actual.iter().zip(expected).enumerate() { + assert_eq!(actual.len(), expected.len(), "{context}: channel {channel} length"); + for (frame, (actual, expected)) in actual.iter().zip(expected).enumerate() { + assert_eq!(actual, expected, "{context}: channel {channel}, frame {frame}"); + } + } +} + +fn render(session: &Session, block: usize) -> Vec> { + render_range(session, Range::new(0, FRAMES as i64), block) +} + +fn engine_block(engine: &mut MixEngine, session: &Session) -> Vec> { + let mut out = vec![vec![0.0; 128]; 2]; + engine.render(session, 0, 128, &mut out); + out +} + +fn first_block(pcm: Vec>) -> Vec> { + pcm.into_iter().map(|channel| channel.into_iter().take(128).collect()).collect() +} + +#[test] +fn reverse_created_twelve_aux_chain_preserves_every_sample() { + for pdc in [false, true] { + let chain = reverse_chain(pdc, false, false); + assert_pcm(&render(&chain.session, 1024), &signal(), "deep output chain"); + } +} + +#[test] +fn deep_dependencies_through_sends_without_outputs_preserve_every_sample() { + for pdc in [false, true] { + let chain = reverse_chain(pdc, true, false); + assert_pcm(&render(&chain.session, 97), &signal(), "deep send-only chain"); + } +} + +#[test] +fn output_and_send_to_the_same_bus_sum_audio_without_duplicate_dependency() { + for pdc in [false, true] { + let mut chain = reverse_chain(pdc, false, false); + chain.session.track_mut(chain.tracks[4]).unwrap().mixer.sends[0] = Some(send(chain.buses[5])); + assert_pcm(&render(&chain.session, 256), &scaled_signal(2.0), "duplicate destination"); + } +} + +#[test] +fn short_and_deep_branches_both_reach_the_join() { + for pdc in [false, true] { + let mut chain = reverse_chain(pdc, false, false); + add_aux(&mut chain.session, TrackKind::Aux, chain.buses[0], Route::Bus(chain.buses[DEPTH - 1])); + assert_pcm(&render(&chain.session, 512), &scaled_signal(2.0), "branch join"); + } +} + +#[test] +fn routing_folders_participate_in_deep_dependencies() { + for pdc in [false, true] { + let chain = reverse_chain(pdc, true, true); + assert_pcm(&render(&chain.session, 63), &signal(), "aux and folder send chain"); + } +} + +#[test] +fn output_edit_reorders_the_same_engine_before_the_next_block() { + let mut session = session(true); + let root = session.add_bus("Root", ChannelFormat::Stereo); + let join = session.add_bus("Join", ChannelFormat::Stereo); + add_aux(&mut session, TrackKind::Aux, join, Route::Main); + let producer = add_aux(&mut session, TrackKind::Aux, root, Route::Main); + add_source(&mut session, Route::Bus(root)); + let mut engine = MixEngine::new(48_000.0, 128); + let expected = first_block(signal()); + assert_pcm(&engine_block(&mut engine, &session), &expected, "before output edit"); + session.track_mut(producer).unwrap().mixer.output = Route::Bus(join); + assert_pcm(&engine_block(&mut engine, &session), &expected, "after output edit"); +} + +#[test] +fn input_edit_reorders_the_same_engine_before_the_next_block() { + let mut session = session(true); + let root = session.add_bus("Root", ChannelFormat::Stereo); + let join = session.add_bus("Join", ChannelFormat::Stereo); + let consumer = add_aux(&mut session, TrackKind::Folder, root, Route::Main); + add_aux(&mut session, TrackKind::Aux, root, Route::Bus(join)); + add_source(&mut session, Route::Bus(root)); + let mut engine = MixEngine::new(48_000.0, 128); + let expected = first_block(signal()); + assert_pcm(&engine_block(&mut engine, &session), &expected, "before input edit"); + session.track_mut(consumer).unwrap().mixer.input = Route::Bus(join); + assert_pcm(&engine_block(&mut engine, &session), &expected, "after input edit"); +} + +#[test] +fn send_add_retarget_remove_and_readd_update_the_same_engine() { + let mut session = session(true); + let root = session.add_bus("Root", ChannelFormat::Stereo); + let join = session.add_bus("Join", ChannelFormat::Stereo); + let unused = session.add_bus("Unused", ChannelFormat::Stereo); + add_aux(&mut session, TrackKind::Aux, join, Route::Main); + let producer = add_aux(&mut session, TrackKind::Folder, root, Route::None); + add_source(&mut session, Route::Bus(root)); + let mut engine = MixEngine::new(48_000.0, 128); + let expected = first_block(signal()); + let silence = vec![vec![0.0; 128]; 2]; + assert_pcm(&engine_block(&mut engine, &session), &silence, "before send"); + session.track_mut(producer).unwrap().mixer.sends[0] = Some(send(join)); + assert_pcm(&engine_block(&mut engine, &session), &expected, "send added"); + session.track_mut(producer).unwrap().mixer.sends[0].as_mut().unwrap().target = Route::Bus(unused); + assert_pcm(&engine_block(&mut engine, &session), &silence, "send retargeted"); + session.track_mut(producer).unwrap().mixer.sends[0].as_mut().unwrap().target = Route::Bus(join); + assert_pcm(&engine_block(&mut engine, &session), &expected, "send retargeted back"); + session.track_mut(producer).unwrap().mixer.sends[0] = None; + assert_pcm(&engine_block(&mut engine, &session), &silence, "send removed"); + session.track_mut(producer).unwrap().mixer.sends[0] = Some(send(join)); + assert_pcm(&engine_block(&mut engine, &session), &expected, "send readded"); +} + +#[test] +fn track_reorder_removal_and_new_identity_rebuild_the_same_engine() { + let mut chain = reverse_chain(true, false, false); + let mut engine = MixEngine::new(48_000.0, 128); + let expected = first_block(signal()); + assert_pcm(&engine_block(&mut engine, &chain.session), &expected, "initial track order"); + chain.session.tracks.reverse(); + assert_pcm(&engine_block(&mut engine, &chain.session), &expected, "tracks reordered"); + chain.session.tracks.retain(|track| track.id != chain.tracks[6]); + let silence = vec![vec![0.0; 128]; 2]; + assert_pcm(&engine_block(&mut engine, &chain.session), &silence, "track removed"); + let replacement = add_aux(&mut chain.session, TrackKind::Aux, chain.buses[6], Route::Bus(chain.buses[7])); + assert_ne!(replacement, chain.tracks[6]); + assert_pcm(&engine_block(&mut engine, &chain.session), &expected, "track readded with new identity"); +} + +#[test] +fn strip_and_bus_format_edits_refresh_the_same_engine_workspace() { + let mut chain = reverse_chain(true, false, false); + let mut engine = MixEngine::new(48_000.0, 128); + let stereo = first_block(signal()); + assert_pcm(&engine_block(&mut engine, &chain.session), &stereo, "initial stereo formats"); + chain.session.track_mut(chain.tracks[5]).unwrap().format = ChannelFormat::Mono; + // A stereo bus folds to mono at -6 dB; the retained hard-left pan sends that mono to L. + let mono: Vec<_> = stereo[0].iter().zip(&stereo[1]).map(|(left, right)| 0.5 * (left + right)).collect(); + assert_pcm(&engine_block(&mut engine, &chain.session), &[mono.clone(), vec![0.0; 128]], "mono strip"); + chain.session.track_mut(chain.tracks[5]).unwrap().format = ChannelFormat::Stereo; + assert_pcm(&engine_block(&mut engine, &chain.session), &stereo, "stereo strip restored"); + chain.session.busses.iter_mut().find(|bus| bus.id == chain.buses[5]).unwrap().format = ChannelFormat::Mono; + // A mono bus feeds both channels of the following stereo aux at unity. + assert_pcm(&engine_block(&mut engine, &chain.session), &[mono.clone(), mono], "mono bus"); +} + +#[test] +fn deep_routing_is_invariant_to_offline_and_callback_block_sizes() { + let chain = reverse_chain(true, true, true); + let expected = signal(); + for block in [16, 63, 97, 256, 512, 1024] { + assert_pcm(&render(&chain.session, block), &expected, "offline block size"); + } + let mut engine = MixEngine::new(48_000.0, 1024); + let callbacks = [1, 63, 257, 17, 511, 1024]; + let mut out = vec![Vec::new(), Vec::new()]; + let mut position = 0; + let mut callback = 0; + while position < FRAMES { + let frames = callbacks[callback % callbacks.len()].min(FRAMES - position); + let mut block = vec![vec![0.0; frames]; 2]; + engine.render(&chain.session, position as i64, frames, &mut block); + for (destination, channel) in out.iter_mut().zip(block) { + destination.extend(channel); + } + position += frames; + callback += 1; + } + assert_pcm(&out, &expected, "varying callback sizes"); +} + +#[test] +fn self_loop_preserves_audio_and_selects_fallback_for_the_whole_graph() { + for pdc in [false, true] { + let mut chain = reverse_chain(pdc, false, false); + let loop_bus = chain.session.add_bus("Self loop", ChannelFormat::Stereo); + let aux = add_aux(&mut chain.session, TrackKind::Aux, loop_bus, Route::Main); + chain.session.track_mut(aux).unwrap().mixer.sends[0] = Some(send(loop_bus)); + add_source(&mut chain.session, Route::Bus(loop_bus)); + // The self-loop reads its source once, then writes back to the already-read bus. + // The disconnected deep chain remains silent under the established eight-hop fallback. + assert_pcm(&render(&chain.session, 97), &signal(), "self-loop whole-graph fallback"); + } +} + +#[test] +fn two_aux_cycle_preserves_session_order_audio_and_whole_graph_fallback() { + for pdc in [false, true] { + for reverse in [false, true] { + let mut chain = reverse_chain(pdc, false, false); + let a_bus = chain.session.add_bus("Cycle A", ChannelFormat::Stereo); + let b_bus = chain.session.add_bus("Cycle B", ChannelFormat::Stereo); + let (a, b) = if reverse { + let b = add_aux(&mut chain.session, TrackKind::Aux, b_bus, Route::Main); + let a = add_aux(&mut chain.session, TrackKind::Folder, a_bus, Route::Main); + (a, b) + } else { + let a = add_aux(&mut chain.session, TrackKind::Folder, a_bus, Route::Main); + let b = add_aux(&mut chain.session, TrackKind::Aux, b_bus, Route::Main); + (a, b) + }; + chain.session.track_mut(a).unwrap().mixer.sends[0] = Some(send(b_bus)); + chain.session.track_mut(b).unwrap().mixer.sends[0] = Some(send(a_bus)); + add_source(&mut chain.session, Route::Bus(a_bus)); + // A then B: both hear the source. B then A: B reads its still-empty bus. + // Buses clear each block, so neither order feeds a previous block back into this one. + let expected = scaled_signal(if reverse { 1.0 } else { 2.0 }); + assert_pcm(&render(&chain.session, 256), &expected, "two-aux whole-graph fallback"); + } + } +} diff --git a/docs/aux-routing-order.md b/docs/aux-routing-order.md new file mode 100644 index 00000000..3c93eddd --- /dev/null +++ b/docs/aux-routing-order.md @@ -0,0 +1,17 @@ +# Aux and Folder routing order + +Updated: 2026-10-14 + +Aux and Folder strips read audio from busses populated by earlier strips. The mixer prepares their execution order when the existing session-structure fingerprint changes, then reuses that order for subsequent blocks. + +For an acyclic routing graph, preparation computes the longest producer path to every Aux or Folder input. Producers reach a bus before its consumers read it, even when tracks were created in reverse routing order or the chain contains more than eight returns. Output and send routes both create dependencies. Multiple routes from the same producer to the same bus contribute audio normally but count as one producer dependency. Strips at the same depth retain session order, preserving the previous ordering for ordinary short acyclic graphs. + +The earlier ordering calculation capped every depth at eight. In a sufficiently deep reverse-created chain, that made a consumer tie with its producer and execute first. Because bus buffers are cleared each block, the consumer could receive silence. Exact acyclic depths remove that tie. + +If any cycle exists, the whole graph retains the previous bounded depth calculation and deterministic session-order ties. Preparation does not reject a cyclic session or change its feedback policy. This increment does not alter PDC accounting, plugin processing or failure containment, render-helper APIs, pan coefficients, Master insert order, playback ownership, or device selection. + +This is the routing-order increment of the remaining runtime work discussed in #394. Further runtime changes require independent treatment of prepared routing coefficients, workspace and instance lifetime, hosted automation delivery, graph latency, and explicit render failures. This increment does not claim to complete that rewrite or move all preparation off the audio callback. + +Regression tests use synthetic source samples and public mixer APIs. They cover deep reverse-created chains, output/send dependencies, duplicate routes, branching, Folder consumers, callback-size invariance, edits on an existing mixer and preserved cyclic behavior with PDC enabled or disabled. The same public fixture can run against the previous main to demonstrate the depth-cap failure independently of the new preparation helper. + +Revision history: 2026-10-14 — exact acyclic routing order with the existing whole-graph cyclic fallback. From b50373d6db9a89e32406bdb659fab6d112b39f1a Mon Sep 17 00:00:00 2001 From: Marco Arnulfo Date: Wed, 14 Oct 2026 19:25:20 +0200 Subject: [PATCH 13/52] A Pencil click on a MIDI clip selects it, so the MIDI Editor follows (fixes #562) --- crates/ui-egui/src/edit_window.rs | 9 +++++++-- crates/ui-egui/tests/new_midi_clip.rs | 15 +++++++++++++++ 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/edit_window.rs b/crates/ui-egui/src/edit_window.rs index f77560a5..78fc4ff2 100644 --- a/crates/ui-egui/src/edit_window.rs +++ b/crates/ui-egui/src/edit_window.rs @@ -2177,8 +2177,13 @@ fn lane_interaction(app: &mut SoundApp, ui: &mut Ui, track: &Track, lane: Rect, "automation.set_point", json!({"track": track.id.0, "param": automation_id(param), "at": at, "value": lo + (hi - lo) * k}), ); - } else if track.kind.is_midi() && hit.is_none() { - new_midi_clip(app, &s, track.id, at, at); + } else if track.kind.is_midi() { + match &hit { + Some(c) => { + let _ = app.run("edit.select", json!({"clips": [c.id.0]})); + } + None => new_midi_clip(app, &s, track.id, at, at), + } } } _ if !selector_press => place_insertion(app, ui, &s, track.id, at, mods.shift), diff --git a/crates/ui-egui/tests/new_midi_clip.rs b/crates/ui-egui/tests/new_midi_clip.rs index ec3fb07b..46b54616 100644 --- a/crates/ui-egui/tests/new_midi_clip.rs +++ b/crates/ui-egui/tests/new_midi_clip.rs @@ -135,3 +135,18 @@ fn a_click_in_the_empty_midi_editor_adds_a_clip_at_the_insertion_point() { assert_eq!(r.clips(), vec![(r.bar(3), r.bar(4))]); assert_eq!(midi_editor::target_clip(&r.app), Some(r.app.engine.session().tracks[0].clips()[0].id)); } + +#[test] +fn a_pencil_click_on_a_clip_selects_it_for_the_midi_editor() { + let mut r = Rig::new("instrument"); + r.app.ui.show_midi_editor = true; + r.drag((r.bar(2) + r.bar(3)) / 2, (r.bar(3) + r.bar(4)) / 2); + r.drag((r.bar(6) + r.bar(7)) / 2, (r.bar(7) + r.bar(8)) / 2); + let ids: Vec<_> = r.app.engine.session().tracks[0].clips().iter().map(|c| c.id).collect(); + assert_eq!(r.clips(), vec![(r.bar(2), r.bar(4)), (r.bar(6), r.bar(8))]); + assert_eq!(midi_editor::target_clip(&r.app), Some(ids[1])); + r.click((r.bar(2) + r.bar(3)) / 2); + assert_eq!(r.clips().len(), 2); + assert_eq!(r.app.engine.session().edit.selected_clips, vec![ids[0]]); + assert_eq!(midi_editor::target_clip(&r.app), Some(ids[0])); +} From 800b27013df9f82a5c427e3247a18834c9122a7b Mon Sep 17 00:00:00 2001 From: midasmatterhorn <248507632+midasmatterhorn@users.noreply.github.com> Date: Wed, 14 Oct 2026 23:22:31 +0300 Subject: [PATCH 14/52] session: reject duplicate ids and an exhausted id space on load (#448) --- crates/model/src/session.rs | 58 +++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) diff --git a/crates/model/src/session.rs b/crates/model/src/session.rs index 449d82da..1c5c229c 100644 --- a/crates/model/src/session.rs +++ b/crates/model/src/session.rs @@ -541,6 +541,7 @@ impl Session { } let mut s: Session = serde_json::from_value(v).map_err(|e| SessionError::Format(e.to_string()))?; s.sanitize(); + s.validate()?; Ok(s) } @@ -633,6 +634,25 @@ impl Session { } self.tempo.sanitize(); } + + /// Reject a document whose ids are ambiguous or exhausted, run after [`Session::sanitize`] on + /// untrusted data. Duplicate ids in a namespace make commands, selections and source + /// associations act on an arbitrary one of the objects; a maximal `next_id` -- or a maximal + /// existing id, which `sanitize` folds into `next_id` -- makes every later allocation return + /// `u64::MAX` and repeat itself. + fn validate(&self) -> Result<(), SessionError> { + if self.next_id == u64::MAX { + return Err(SessionError::Invalid("the session id space is exhausted".into())); + } + distinct("track", self.tracks.iter().map(|t| t.id.0))?; + distinct("clip", self.tracks.iter().flat_map(|t| t.playlists.iter().flat_map(|p| p.clips.iter().map(|c| c.id.0))))?; + distinct("source", self.sources.iter().map(|s| s.id.0))?; + distinct("video", self.videos.iter().map(|v| v.id.0))?; + distinct("bus", self.busses.iter().map(|b| b.id.0))?; + distinct("marker", self.markers.iter().map(|m| m.id.0))?; + distinct("group", self.groups.iter().map(|g| g.id.0))?; + Ok(()) + } } /// The most characters kept of a name read from a file: longer ones can't be shown, and drawing @@ -648,6 +668,17 @@ pub fn truncate_chars(s: &mut String, max: usize) { } } +/// Every id in `ids` distinct, or an error naming the namespace and the repeated id. +fn distinct(kind: &str, ids: impl Iterator) -> Result<(), SessionError> { + let mut seen = std::collections::HashSet::new(); + for id in ids { + if !seen.insert(id) { + return Err(SessionError::Invalid(format!("duplicate {kind} id {id}"))); + } + } + Ok(()) +} + #[cfg(test)] mod tests { use super::*; @@ -758,6 +789,33 @@ mod tests { assert!(matches!(Session::from_json(&v.to_string()), Err(SessionError::Version(999)))); } + #[test] + fn duplicate_ids_are_rejected_on_load() { + let mut s = Session::default(); + s.add_track(TrackKind::Audio, ChannelFormat::Mono, None); + s.add_track(TrackKind::Audio, ChannelFormat::Mono, None); + let mut v = serde_json::to_value(&s).unwrap(); + v["tracks"][1]["id"] = v["tracks"][0]["id"].clone(); + let err = Session::from_json(&v.to_string()).unwrap_err(); + assert!(matches!(&err, SessionError::Invalid(m) if m.contains("duplicate track id")), "{err}"); + } + + #[test] + fn an_exhausted_id_space_is_rejected_on_load() { + let mut s = Session::default(); + s.add_track(TrackKind::Audio, ChannelFormat::Mono, None); + let mut v = serde_json::to_value(&s).unwrap(); + v["next_id"] = serde_json::json!(u64::MAX); + let err = Session::from_json(&v.to_string()).unwrap_err(); + assert!(matches!(&err, SessionError::Invalid(m) if m.contains("exhausted")), "{err}"); + // A maximal existing id is exhausted too, however `next_id` was written: every later + // allocation would return `u64::MAX` again. + let mut v = serde_json::to_value(&s).unwrap(); + v["tracks"][0]["id"] = serde_json::json!(u64::MAX); + let err = Session::from_json(&v.to_string()).unwrap_err(); + assert!(matches!(&err, SessionError::Invalid(m) if m.contains("exhausted")), "{err}"); + } + #[test] fn sanitize_repairs() { let mut s = Session::default(); From 952ca5e4ed66a09da6ac51606d7659a072b921e8 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Wed, 14 Oct 2026 23:16:37 +0200 Subject: [PATCH 15/52] Round negative timecode and feet+frames positions symmetrically Found while testing crates/time/src/timecode.rs:111 Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 --- crates/time/src/format.rs | 13 +++++++++++++ crates/time/src/timecode.rs | 16 +++++++++++++++- 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/crates/time/src/format.rs b/crates/time/src/format.rs index bdd2fcb1..995b3265 100644 --- a/crates/time/src/format.rs +++ b/crates/time/src/format.rs @@ -185,6 +185,19 @@ mod tests { } } + #[test] + fn parse_round_trips_timecode_negative() { + let (sr, map, _) = ctx(); + let rate = FrameRate::Fps25; + for fmt in [TimeFormat::Timecode, TimeFormat::FeetFrames] { + for s in [-48_000i64, -96_000 * 3, -1_440_000] { + let text = format_position(s, fmt, sr, &map, rate, 0, 0); + let back = parse_position(&text, fmt, sr, &map, rate, 0, 0).unwrap(); + assert_eq!(back, s, "{fmt:?} {s} → {text} → {back}"); + } + } + } + #[test] fn parse_rejects_garbage() { let (sr, map, rate) = ctx(); diff --git a/crates/time/src/timecode.rs b/crates/time/src/timecode.rs index f8f6041b..b16f392c 100644 --- a/crates/time/src/timecode.rs +++ b/crates/time/src/timecode.rs @@ -108,7 +108,9 @@ impl FrameRate { if n == 0 { return 0; } - let v = (i128::from(f) * i128::from(sr.hz()) * i128::from(d) + i128::from(n) / 2) / i128::from(n); + // Round half away from zero so negative frames mirror positive ones. + let mag = (i128::from(f.unsigned_abs()) * i128::from(sr.hz()) * i128::from(d) + i128::from(n) / 2) / i128::from(n); + let v = if f < 0 { -mag } else { mag }; i64::try_from(v).unwrap_or(if v < 0 { i64::MIN } else { i64::MAX }) } @@ -221,6 +223,18 @@ mod tests { assert_eq!(tc.to_samples(FrameRate::Fps25, sr), 48_000 * 3661); } + #[test] + fn negative_timecode_rounds_symmetrically() { + let sr = SampleRate::HZ_48000; + let tc = Timecode::parse("-00:00:01:00").unwrap(); + assert_eq!(tc.to_samples(FrameRate::Fps25, sr), -48_000); + for r in [FrameRate::Fps25, FrameRate::Fps29_97, FrameRate::Fps29_97Drop, FrameRate::Fps23_976] { + for f in [1i64, 7, 25, 1799, 107_892] { + assert_eq!(r.samples_at_frame(-f, sr), -r.samples_at_frame(f, sr), "{r:?} frame {f}"); + } + } + } + #[test] fn drop_frame_labels() { let r = FrameRate::Fps29_97Drop; From 315745b02207b29b3d8bdec5586f3091a6e0f7ea Mon Sep 17 00:00:00 2001 From: midasmatterhorn <248507632+midasmatterhorn@users.noreply.github.com> Date: Thu, 15 Oct 2026 00:36:03 +0300 Subject: [PATCH 16/52] ui: MIDI Real-Time Properties submits only the property that changed (#444) --- crates/ui-egui/src/ops_windows.rs | 92 +++++++++++++++++++++++++++--- crates/ui-egui/tests/rtp_window.rs | 54 ++++++++++++++++++ 2 files changed, 139 insertions(+), 7 deletions(-) create mode 100644 crates/ui-egui/tests/rtp_window.rs diff --git a/crates/ui-egui/src/ops_windows.rs b/crates/ui-egui/src/ops_windows.rs index beba5237..45a2f3a9 100644 --- a/crates/ui-egui/src/ops_windows.rs +++ b/crates/ui-egui/src/ops_windows.rs @@ -30,6 +30,9 @@ pub struct OpsState { pub rtp_transpose: i64, pub rtp_duration: f64, pub rtp_delay: i64, + /// The MIDI tracks the Real-Time Properties form was last filled from: the form re-reads the + /// tracks when the target selection changes (#444). + pub rtp_targets: Vec, pub identify_bars: u32, } @@ -57,6 +60,7 @@ impl Default for OpsState { rtp_transpose: 0, rtp_duration: 100.0, rtp_delay: 0, + rtp_targets: Vec::new(), identify_bars: 1, } } @@ -261,15 +265,25 @@ fn rtp(app: &mut SoundApp, ctx: &egui::Context) { if !open { return; } + // Fill the form from the tracks it edits whenever the target selection changes, so it never + // shows (and a control change never writes back) stale defaults (#444). + let targets = app.engine.target_tracks(); + if app.ops.rtp_targets != targets { + app.ops.rtp_targets = targets.clone(); + let (velocity, transpose, duration, delay) = rtp_form_values(app.engine.session(), &targets); + app.ops.rtp_velocity = velocity; + app.ops.rtp_transpose = transpose; + app.ops.rtp_duration = duration; + app.ops.rtp_delay = delay; + } egui::Window::new("MIDI Real-Time Properties").open(&mut open).default_size(vec2(340.0, 200.0)).show(ctx, |ui| { ui.label("Non-destructive, applied at playback to the selected MIDI tracks."); - let mut changed = false; - changed |= ui.add(egui::Slider::new(&mut app.ops.rtp_velocity, -127..=127).text("Velocity +")).changed(); - changed |= ui.add(egui::Slider::new(&mut app.ops.rtp_transpose, -48..=48).text("Transpose")).changed(); - changed |= ui.add(egui::Slider::new(&mut app.ops.rtp_duration, 1.0..=400.0).text("Duration %")).changed(); - changed |= ui.add(egui::Slider::new(&mut app.ops.rtp_delay, -960..=960).text("Delay (ticks)")).changed(); - if changed { - let p = json!({"velocity": app.ops.rtp_velocity, "transpose": app.ops.rtp_transpose, "duration": app.ops.rtp_duration, "delay": app.ops.rtp_delay}); + let mut changed = RtpChanged::default(); + changed.velocity = ui.add(egui::Slider::new(&mut app.ops.rtp_velocity, -127..=127).text("Velocity +")).changed(); + changed.transpose = ui.add(egui::Slider::new(&mut app.ops.rtp_transpose, -48..=48).text("Transpose")).changed(); + changed.duration = ui.add(egui::Slider::new(&mut app.ops.rtp_duration, 1.0..=400.0).text("Duration %")).changed(); + changed.delay = ui.add(egui::Slider::new(&mut app.ops.rtp_delay, -960..=960).text("Delay (ticks)")).changed(); + if let Some(p) = rtp_params(changed, &app.ops) { let _ = app.engine.execute_merged("event.midi_rtp", &p, "rtp"); } ui.horizontal(|ui| { @@ -288,6 +302,47 @@ fn rtp(app: &mut SoundApp, ctx: &egui::Context) { app.ui.show_rtp = open; } +/// Which of the form's controls the user changed this frame. +#[derive(Default, Clone, Copy)] +struct RtpChanged { + velocity: bool, + transpose: bool, + duration: bool, + delay: bool, +} + +/// A form change submits only the properties the user touched: the command stores each key it is +/// sent, so sending untouched ones would overwrite the target's values with the form's (#444). +fn rtp_params(changed: RtpChanged, ops: &OpsState) -> Option { + let mut p = serde_json::Map::new(); + if changed.velocity { + p.insert("velocity".into(), json!(ops.rtp_velocity)); + } + if changed.transpose { + p.insert("transpose".into(), json!(ops.rtp_transpose)); + } + if changed.duration { + p.insert("duration".into(), json!(ops.rtp_duration)); + } + if changed.delay { + p.insert("delay".into(), json!(ops.rtp_delay)); + } + (!p.is_empty()).then_some(Value::Object(p)) +} + +/// The values the form shows for `targets`: the first target's own Real-Time Properties, or the +/// neutral defaults when nothing is selected. +fn rtp_form_values(s: &soundcraft_model::Session, targets: &[soundcraft_model::TrackId]) -> (i64, i64, f64, i64) { + let Some(&t) = targets.first() else { return (0, 0, 100.0, 0) }; + let value = |key: &str, d: f64| s.edit.value(&format!("rtp.{}.{key}", t.0), d); + ( + value("velocity", 0.0).clamp(-127.0, 127.0) as i64, + value("transpose", 0.0).clamp(-127.0, 127.0) as i64, + value("duration", 100.0).clamp(1.0, 1000.0), + value("delay", 0.0).clamp(-1e7, 1e7) as i64, + ) +} + #[cfg(test)] mod tests { use super::*; @@ -308,4 +363,27 @@ mod tests { assert_eq!(id, "event.tempo_linear"); assert_eq!(p["end_bpm"], 140.0); } + + /// One control moved: only its property is submitted, so the command cannot overwrite the + /// target's other Real-Time Properties with the form's values (#444). + #[test] + fn rtp_submits_only_the_property_that_changed() { + let ops = OpsState { rtp_velocity: 12, rtp_transpose: 7, rtp_duration: 50.0, rtp_delay: 480, ..OpsState::default() }; + let only_velocity = RtpChanged { velocity: true, ..RtpChanged::default() }; + assert_eq!(rtp_params(only_velocity, &ops), Some(json!({"velocity": 12}))); + let only_duration = RtpChanged { duration: true, ..RtpChanged::default() }; + assert_eq!(rtp_params(only_duration, &ops), Some(json!({"duration": 50.0}))); + assert_eq!(rtp_params(RtpChanged::default(), &ops), None, "no control moved, no command"); + } + + /// The form reads the target's own values when the window opens or the selection changes. + #[test] + fn the_rtp_form_shows_the_target_tracks_values() { + let mut e = soundcraft_engine::Engine::default(); + e.execute("track.new", &json!({"kind": "instrument", "name": "Synth"})).unwrap(); + let t = e.session().tracks.last().unwrap().id; + e.execute("event.midi_rtp", &json!({"track": t.0, "velocity": -12, "transpose": 7, "duration": 50.0, "delay": 480})).unwrap(); + assert_eq!(rtp_form_values(e.session(), &[]), (0, 0, 100.0, 0), "no target: the neutral defaults"); + assert_eq!(rtp_form_values(e.session(), &[t]), (-12, 7, 50.0, 480)); + } } diff --git a/crates/ui-egui/tests/rtp_window.rs b/crates/ui-egui/tests/rtp_window.rs new file mode 100644 index 00000000..cd62eb53 --- /dev/null +++ b/crates/ui-egui/tests/rtp_window.rs @@ -0,0 +1,54 @@ +use egui::accesskit::Role; +use egui::{Event, Modifiers, PointerButton, Pos2, vec2}; +use egui_kittest::{Harness, kittest::Queryable}; +use serde_json::json; +use soundcraft_ui_egui::{Services, SoundApp, menus}; + +fn press(h: &mut Harness<'_, SoundApp>, pos: Pos2, pressed: bool) { + h.event(Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); + h.run_steps(2); +} + +/// #444: the MIDI Real-Time Properties window submitted all four properties from its form on any +/// change, so editing Velocity reset the target's Transpose, Duration and Delay to the form's +/// (stale) defaults — and the form never showed the target's own values. +#[test] +fn editing_rtp_velocity_leaves_the_other_properties_alone() { + let mut app = SoundApp::new(soundcraft_engine::Engine::default(), None, Services::default()); + app.engine.execute("track.new", &json!({"kind": "instrument", "name": "Synth"})).unwrap(); + let t = app.engine.session().tracks.last().unwrap().id; + app.engine.execute("event.midi_rtp", &json!({"track": t.0, "transpose": 7, "duration": 50.0})).unwrap(); + app.run("edit.select", json!({"tracks": [t.0], "exact": true})).unwrap(); + menus::invoke_menu(&mut app, "window.rtp", "Event > MIDI Real-Time Properties"); + + let mut h = Harness::builder().with_size(vec2(1600.0, 1000.0)).build_ui_state( + |ui, app: &mut SoundApp| { + let ctx = ui.ctx().clone(); + app.logic(&ctx); + app.ui(ui); + }, + app, + ); + h.run_steps(3); + assert!(h.state().ui.show_rtp, "the window did not open"); + let rtp = |h: &Harness<'_, SoundApp>, key: &str, d: f64| h.state().engine.session().edit.value(&format!("rtp.{}.{key}", t.0), d); + + // Drag the Velocity slider right: the velocity changes, the rest must stay as the track had it. + let rect = h.get_by_role_and_label(Role::Slider, "Velocity +").rect(); + let from = rect.center(); + let to = from + vec2(30.0, 0.0); + h.event(Event::PointerMoved(from)); + h.run_steps(1); + press(&mut h, from, true); + h.event(Event::PointerMoved(to)); + h.run_steps(2); + press(&mut h, to, false); + assert!(rtp(&h, "velocity", 0.0) > 0.0, "the velocity drag did not reach the engine"); + assert_eq!(rtp(&h, "transpose", 0.0), 7.0, "editing Velocity reset Transpose"); + assert_eq!(rtp(&h, "duration", 100.0), 50.0, "editing Velocity reset Duration"); + assert_eq!(rtp(&h, "delay", 0.0), 0.0, "editing Velocity reset Delay"); + + // The form shows the target track's values, not its defaults. + assert_eq!(h.state().ops.rtp_transpose, 7, "the form did not show the track's Transpose"); + assert_eq!(h.state().ops.rtp_duration, 50.0, "the form did not show the track's Duration"); +} From 2cba9ed4cd748f4c6c233ad9ff5f0bc1d667a2f7 Mon Sep 17 00:00:00 2001 From: vxMacDev <77440838+vxMacDev@users.noreply.github.com> Date: Wed, 14 Oct 2026 16:54:56 -0500 Subject: [PATCH 17/52] Save a session bundle only if it opens again (#433) The bundle reader refuses more than 10,000 files or 1 GiB unpacked, but the writer had no limits, so a browser save of a long session could succeed, mark the session clean and produce a file SoundCraft won't open. The writer now counts files and bytes the way the reader does and refuses the save before anything is delivered or marked clean. Both use one BundleLimits. --- crates/engine/src/io.rs | 56 +++++++++++++++++++++++++++++++++++------ 1 file changed, 49 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/io.rs b/crates/engine/src/io.rs index 7b26e0b1..c937d315 100644 --- a/crates/engine/src/io.rs +++ b/crates/engine/src/io.rs @@ -1154,9 +1154,15 @@ pub(crate) fn decode_file(files: &mut DecodedFiles, p: &Path, rate: u32) -> std: /// saves and opens sessions as bundles. pub const BUNDLE_EXTENSION: &str = "scraftz"; -/// Most entries and bytes a bundle may unpack to (bundles are hostile input). -const MAX_BUNDLE_ENTRIES: usize = 10_000; -const MAX_BUNDLE_BYTES: u64 = 1 << 30; +/// Most entries and bytes a bundle may unpack to (bundles are hostile input). The writer keeps to +/// them too, so a bundle it saves always opens again (#433). +#[derive(Clone, Copy, Debug)] +struct BundleLimits { + entries: usize, + bytes: u64, +} + +const BUNDLE_LIMITS: BundleLimits = BundleLimits { entries: 10_000, bytes: 1 << 30 }; /// Hands a finished file (name, bytes) to the person on a host without a filesystem: the web app /// installs one that starts a download. Native builds write files and never install it. @@ -1185,6 +1191,11 @@ pub fn write_file(path: &str, bytes: &[u8]) -> Result<()> { /// `Audio Files/` (stored, not compressed: audio barely compresses). Returns the bytes and the /// session with its source paths pointing into the bundle. pub fn session_bundle(session: &Session) -> Result<(Vec, Session)> { + session_bundle_within(session, BUNDLE_LIMITS) +} + +/// [`session_bundle`], refused when it would hold more than `limits` allows. +fn session_bundle_within(session: &Session, limits: BundleLimits) -> Result<(Vec, Session)> { use std::io::Write as _; let zerr = |err: zip::result::ZipError| EngineError::Io(format!("bundle: {err}")); let ioerr = |err: std::io::Error| EngineError::Io(format!("bundle: {err}")); @@ -1192,6 +1203,20 @@ pub fn session_bundle(session: &Session) -> Result<(Vec, Session)> { let mut w = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); let opts = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored).large_file(true); let mut taken = std::collections::HashSet::new(); + let (mut entries, mut total) = (0usize, 0u64); + // Counted as the reader counts them: files, and the bytes they unpack to. + let mut fits = |len: usize| { + entries += 1; + total = total.saturating_add(len as u64); + if entries > limits.entries || total > limits.bytes { + return Err(EngineError::Io(format!( + "bundle: too large to save (a bundle holds at most {} files and {} MiB, or it can't be opened again)", + limits.entries, + limits.bytes >> 20 + ))); + } + Ok(()) + }; for src in &mut s.sources { let Some(audio) = s.pool.get(src.id) else { continue }; let base = sanitize_name(&src.name); @@ -1203,6 +1228,7 @@ pub fn session_bundle(session: &Session) -> Result<(Vec, Session)> { } let opts_wav = EncodeOptions { format: FileFormat::Wav, bit_depth: soundcraft_audio_io::BitDepth::Float32, dither: false, bwf: None }; let bytes = soundcraft_audio_io::encode(&audio.buffer, &opts_wav).map_err(|err| EngineError::Io(err.to_string()))?; + fits(bytes.len())?; w.start_file(target.as_str(), opts).map_err(zerr)?; w.write_all(&bytes).map_err(ioerr)?; taken.insert(target.clone()); @@ -1211,6 +1237,7 @@ pub fn session_bundle(session: &Session) -> Result<(Vec, Session)> { src.format = FileFormat::Wav; } let text = s.to_json().map_err(|err| EngineError::Io(err.to_string()))?; + fits(text.len())?; w.start_file(format!("{}.{}", sanitize_name(&s.name), soundcraft_model::SESSION_EXTENSION), opts).map_err(zerr)?; w.write_all(text.as_bytes()).map_err(ioerr)?; let bytes = w.finish().map_err(zerr)?.into_inner(); @@ -1239,7 +1266,7 @@ fn save_session_bundle(e: &mut Engine, path: &str) -> Result { /// [`open_session`]. pub fn open_session_bytes(e: &mut Engine, name: &str, bytes: &[u8]) -> Result> { let (text, mut files) = if bytes.starts_with(b"PK\x03\x04") { - read_bundle(bytes)? + read_bundle(bytes, BUNDLE_LIMITS)? } else { ( String::from_utf8(bytes.to_vec()).map_err(|_| EngineError::Io(format!("{name}: not a SoundCraft session")))?, @@ -1269,11 +1296,11 @@ pub fn open_session_bytes(e: &mut Engine, name: &str, bytes: &[u8]) -> Result Result<(String, std::collections::HashMap>)> { +fn read_bundle(bytes: &[u8], limits: BundleLimits) -> Result<(String, std::collections::HashMap>)> { use std::io::Read as _; let zerr = |err: zip::result::ZipError| EngineError::Io(format!("bundle: {err}")); let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).map_err(zerr)?; - if z.len() > MAX_BUNDLE_ENTRIES { + if z.len() > limits.entries { return Err(EngineError::Io("bundle: too many files".into())); } let (mut text, mut files, mut total) = (None, std::collections::HashMap::new(), 0u64); @@ -1285,7 +1312,7 @@ fn read_bundle(bytes: &[u8]) -> Result<(String, std::collections::HashMap MAX_BUNDLE_BYTES { + if total > limits.bytes { return Err(EngineError::Io("bundle: too large".into())); } let mut data = Vec::new(); @@ -1886,6 +1913,21 @@ mod bundle_tests { assert_eq!(r.path.as_deref(), Some("Midnight Groove.scraftz")); } + #[test] + fn a_bundle_is_saved_only_if_it_opens_again() { + // #433: the writer keeps to the reader's limits. + let e = crate::demo::demo_engine(); + let (bytes, _) = session_bundle(e.session()).unwrap(); + let mut z = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap(); + let entries = z.len(); + let size: u64 = (0..entries).map(|i| z.by_index(i).unwrap().size()).sum(); + let exact = BundleLimits { entries, bytes: size }; + let (at_limit, _) = session_bundle_within(e.session(), exact).unwrap(); + assert!(read_bundle(&at_limit, exact).is_ok(), "what the writer takes, the reader opens"); + assert!(session_bundle_within(e.session(), BundleLimits { entries: entries - 1, ..exact }).is_err()); + assert!(session_bundle_within(e.session(), BundleLimits { bytes: size - 1, ..exact }).is_err()); + } + #[test] fn same_named_sources_get_distinct_files() { let mut e = crate::demo::demo_engine(); From ea0e4719fcb20db268f2d784b752855e6d713634 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Thu, 15 Oct 2026 04:00:26 +0200 Subject: [PATCH 18/52] Release held VST3 notes on reset instead of discarding them Fixes #441 Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Opus 5.5 --- crates/vst3-host/src/plugin.rs | 8 +++++++- crates/vst3-host/tests/fixture_e2e.rs | 23 +++++++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/crates/vst3-host/src/plugin.rs b/crates/vst3-host/src/plugin.rs index 2975465f..20d5fa6f 100644 --- a/crates/vst3-host/src/plugin.rs +++ b/crates/vst3-host/src/plugin.rs @@ -213,8 +213,14 @@ impl Plugin for Vst3Plugin { } fn reset(&mut self) { - self.notes.clear(); + // Keep pending releases and release whatever is still held, so the processor's voices stop + // on the next block instead of sounding on while the host forgets them. + self.notes.retain(|e| matches!(e, NoteEvent::Off { .. })); + for e in &mut self.notes { + e.set_time(0); + } self.controls.clear(); + self.all_notes_off(); self.held = [false; 128]; } diff --git a/crates/vst3-host/tests/fixture_e2e.rs b/crates/vst3-host/tests/fixture_e2e.rs index 5efd33cc..9c87b8bb 100644 --- a/crates/vst3-host/tests/fixture_e2e.rs +++ b/crates/vst3-host/tests/fixture_e2e.rs @@ -144,6 +144,29 @@ fn synth_plays_notes_at_their_offsets() { assert!(mono[0].iter().all(|&x| (x - 1.0).abs() < 1e-6), "the note is still held"); } +#[test] +fn reset_after_all_notes_off_still_releases_held_voices() { + let mut p = soundcraft_vst3_host::create(&id_of("Fixture Synth")).unwrap(); + p.prepare(48_000.0, 64, 2); + p.note_on(0, 60, 127); + let mut io = vec![vec![0.0f32; 64], vec![0.0f32; 64]]; + p.process(&mut io, 64); + assert!((io[0][63] - 1.0).abs() < 1e-6, "the note sounds"); + // Mixer::reset calls these two in a row on an instrument (stop / seek). + p.all_notes_off(); + p.reset(); + let mut io = vec![vec![9.0f32; 64], vec![9.0f32; 64]]; + p.process(&mut io, 64); + assert!(io[0].iter().all(|x| x.abs() < 1e-6), "voice still sounding after reset: {}", io[0][63]); + // A reset alone also releases what the host still holds. + p.note_on(0, 61, 127); + p.process(&mut io, 64); + assert!((io[0][63] - 1.0).abs() < 1e-6); + p.reset(); + p.process(&mut io, 64); + assert!(io[0].iter().all(|x| x.abs() < 1e-6), "voice still sounding after reset: {}", io[0][63]); +} + #[test] fn many_instances_create_and_drop_cleanly() { let (g, s) = (id_of("Fixture Gain"), id_of("Fixture Synth")); From 075104f44800c2aa7cc7538e96619b7ea22f81a0 Mon Sep 17 00:00:00 2001 From: Billy Coleman III Date: Thu, 15 Oct 2026 04:35:33 -0400 Subject: [PATCH 19/52] Apply strip mute automation within each processing block Gate ordinary strip output and pre-fader copies at each represented sample using the existing mute lane, mode, held values and threshold. Preserve the fader and pan schedules, static suppression and hosted processing blocks. --- contributors/people.toml | 3 + crates/mix/src/lib.rs | 20 +- crates/mix/tests/strip_mute_automation.rs | 243 ++++++++++++++++++++++ docs/strip-mute-automation.md | 9 + 4 files changed, 273 insertions(+), 2 deletions(-) create mode 100644 crates/mix/tests/strip_mute_automation.rs create mode 100644 docs/strip-mute-automation.md diff --git a/contributors/people.toml b/contributors/people.toml index 1c344199..f67fdd57 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -50,3 +50,6 @@ sync_github_name = false [people.Momentum96] sync_github_name = true + +[people.ProdByBuddha] +sync_github_name = true diff --git a/crates/mix/src/lib.rs b/crates/mix/src/lib.rs index e8c4fbad..cf3b21e6 100644 --- a/crates/mix/src/lib.rs +++ b/crates/mix/src/lib.rs @@ -1040,9 +1040,8 @@ fn process_strip( } strip.gr = gr; strip.latency = latency.min(MAX_LATENCY); - let auto_mute = t.mixer.automation_mode.reads() && t.lane(&AutoParam::Mute).is_some_and(|l| l.value_at(pos, 0.0) >= 0.5); let soloed_out = any_solo && !t.mixer.solo && !t.mixer.solo_safe && !receives_solo(s, t); - strip.muted = t.mixer.mute || auto_mute || soloed_out; + strip.muted = t.mixer.mute || soloed_out; if t.mixer.sends.iter().flatten().any(|x| x.pre_fader) { strip.pre.resize_with(strip.buf.len(), Vec::new); for (d, src) in strip.pre.iter_mut().zip(strip.buf.iter()) { @@ -1083,6 +1082,23 @@ fn process_strip( } } } + // Track mute gates the audio and its pre-fader tap without splitting processor blocks. + // Keep the existing curve interpolation, first-lane and mode policy, and render-position + // clock. Processor/bus age and Master/VCA automation policy are separate concerns. + if t.mixer.automation_mode.reads() + && let Some(lane) = t.lane(&AutoParam::Mute).filter(|lane| !lane.points.is_empty()) + { + for i in 0..frames { + let at = pos.saturating_add(i64::try_from(i).unwrap_or(i64::MAX)); + if lane.value_at(at, 0.0) >= 0.5 { + for channel in strip.buf.iter_mut().chain(strip.pre.iter_mut()) { + if let Some(sample) = channel.get_mut(i) { + *sample = 0.0; + } + } + } + } + } } /// Silences a block the plugin filled with NaN or infinity and takes the plugin out until the diff --git a/crates/mix/tests/strip_mute_automation.rs b/crates/mix/tests/strip_mute_automation.rs new file mode 100644 index 00000000..fba6ab23 --- /dev/null +++ b/crates/mix/tests/strip_mute_automation.rs @@ -0,0 +1,243 @@ +//! Ordinary strip mute changes sample gates without splitting processor blocks. +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +use soundcraft_audio_io::AudioBuffer; +use soundcraft_dsp::Plugin; +use soundcraft_mix::{MixEngine, PreparedInstance, render_range}; +use soundcraft_model::{ + AutoParam, AutomationLane, AutomationMode, ChannelFormat, Clip, Insert, Route, SendSlot, Session, SourceAudio, SourceId, TrackId, TrackKind, +}; +use soundcraft_time::Range; +use std::sync::{Arc, Mutex}; + +const LEN: usize = 768; +fn fixture() -> (Session, TrackId) { + let mut s = Session::default(); + s.pool.insert(SourceId(901), Arc::new(SourceAudio::new(AudioBuffer { sample_rate: 48_000, channels: vec![vec![0.25; LEN]; 2] }))); + let t = s.add_track(TrackKind::Audio, ChannelFormat::Stereo, Some("Source")); + let clip = s.new_clip_id(); + let tr = s.track_mut(t).unwrap(); + tr.playlist_mut().unwrap().clips.push(Clip::audio(clip, "tone", SourceId(901), 0, 0, LEN as i64)); + tr.mixer.pan = vec![-1.0, 1.0]; + tr.mixer.output = Route::Main; + (s, t) +} +fn mute(s: &mut Session, t: TrackId, start: i64, end: i64) { + let lane = s.track_mut(t).unwrap().lane_mut(&AutoParam::Mute); + for (at, value) in [(0, 0.0), (start - 1, 0.0), (start, 1.0), (end - 1, 1.0), (end, 0.0)] { + lane.set_point(at, value); + } +} +fn rendered(s: &Session, block: usize) -> Vec> { + render_range(s, Range::new(0, LEN as i64), block) +} +fn gated(actual: &[Vec], reference: &[Vec], start: usize, end: usize) { + assert_eq!(actual.len(), reference.len()); + assert!(reference.iter().flatten().any(|x| x.abs() > 0.01)); + for (got, want) in actual.iter().zip(reference) { + assert_eq!(got.len(), LEN); + for i in 0..LEN { + assert_eq!(got[i], if (start..end).contains(&i) { 0.0 } else { want[i] }, "frame {i}"); + } + } +} +#[test] +fn internal_and_exact_block_edges_are_partition_independent() { + for (start, end) in [(101, 200), (128, 256), (1, 767)] { + let (mut s, t) = fixture(); + let reference = rendered(&s, 512); + mute(&mut s, t, start, end); + for block in [16, 63, 128, 512, 1024] { + gated(&rendered(&s, block), &reference, start as usize, end as usize); + } + } +} +#[test] +fn existing_held_mute_curve_and_threshold_are_preserved() { + let (mut s, t) = fixture(); + let reference = rendered(&s, 512); + let lane = s.track_mut(t).unwrap().lane_mut(&AutoParam::Mute); + lane.set_point(0, 0.49); + lane.set_point(200, 0.5); + gated(&rendered(&s, 512), &reference, 200, LEN); +} +#[test] +fn pre_and_post_fader_send_audio_share_the_track_mute_gate() { + for pre in [false, true] { + let (mut s, t) = fixture(); + let bus = s.add_bus("Send", ChannelFormat::Stereo); + let aux = s.add_track(TrackKind::Aux, ChannelFormat::Stereo, Some("Return")); + s.track_mut(aux).unwrap().mixer.input = Route::Bus(bus); + s.track_mut(aux).unwrap().mixer.output = Route::Main; + let tr = s.track_mut(t).unwrap(); + tr.mixer.output = Route::None; + tr.mixer.volume_db = -9.0; + let mut send = SendSlot::new(Route::Bus(bus)); + send.pre_fader = pre; + send.level_db = -3.0; + tr.mixer.sends[0] = Some(send); + let reference = rendered(&s, 512); + mute(&mut s, t, 101, 200); + for block in [63, 512] { + gated(&rendered(&s, block), &reference, 101, 200); + } + } +} +#[test] +fn off_empty_and_first_empty_lane_keep_exact_unautomated_pcm() { + let (mut s, t) = fixture(); + let reference = rendered(&s, 512); + s.track_mut(t).unwrap().lane_mut(&AutoParam::Mute); + assert_eq!(rendered(&s, 512), reference); + let mut second = AutomationLane::new(AutoParam::Mute); + second.set_point(0, 1.0); + s.track_mut(t).unwrap().automation.push(second); + assert_eq!(rendered(&s, 512), reference, "first empty lane remains authoritative"); + s.track_mut(t).unwrap().automation.clear(); + mute(&mut s, t, 101, 200); + s.track_mut(t).unwrap().mixer.automation_mode = AutomationMode::Off; + assert_eq!(rendered(&s, 512), reference); +} +#[test] +fn reading_modes_retain_existing_policy() { + for mode in AutomationMode::ALL.into_iter().filter(|mode| mode.reads()) { + let (mut s, t) = fixture(); + let reference = rendered(&s, 512); + mute(&mut s, t, 101, 200); + s.track_mut(t).unwrap().mixer.automation_mode = mode; + gated(&rendered(&s, 512), &reference, 101, 200); + } +} +#[test] +fn static_mute_and_solo_suppression_cannot_be_reopened_by_automation() { + for solo in [false, true] { + let (mut s, t) = fixture(); + if solo { + let other = s.add_track(TrackKind::Audio, ChannelFormat::Stereo, None); + s.track_mut(other).unwrap().mixer.solo = true; + } else { + s.track_mut(t).unwrap().mixer.mute = true; + } + let reference = rendered(&s, 512); + assert!(reference.iter().flatten().all(|x| x.abs() < 1e-6)); + mute(&mut s, t, 101, 200); + gated_silent(&rendered(&s, 512)); + } +} +fn gated_silent(output: &[Vec]) { + assert!(output.iter().flatten().all(|x| x.abs() < 1e-6)); +} +#[test] +fn aux_and_folder_inputs_gate_their_audio_inside_the_block() { + for kind in [TrackKind::Aux, TrackKind::Folder] { + let (mut s, source) = fixture(); + let bus = s.add_bus("Input", ChannelFormat::Stereo); + s.track_mut(source).unwrap().mixer.output = Route::Bus(bus); + let target = s.add_track(kind, ChannelFormat::Stereo, Some("Return")); + s.track_mut(target).unwrap().mixer.input = Route::Bus(bus); + s.track_mut(target).unwrap().mixer.output = Route::Main; + let reference = rendered(&s, 512); + mute(&mut s, target, 101, 200); + gated(&rendered(&s, 512), &reference, 101, 200); + } +} +#[test] +fn no_active_mute_lane_preserves_fader_and_pan_schedules_exactly() { + let (mut s, t) = fixture(); + for (param, a, b) in [(AutoParam::Volume, -12.0, -3.0), (AutoParam::Pan(0), -1.0, 0.5)] { + let lane = s.track_mut(t).unwrap().lane_mut(¶m); + lane.set_point(0, a); + lane.set_point(LEN as i64, b); + } + for block in [63, 256, 512] { + let reference = rendered(&s, block); + let mut with_lane = s.clone(); + with_lane.track_mut(t).unwrap().lane_mut(&AutoParam::Mute).set_point(0, 0.0); + assert_eq!(rendered(&with_lane, block), reference); + with_lane.track_mut(t).unwrap().mixer.automation_mode = AutomationMode::Off; + let mut no_lane = with_lane.clone(); + no_lane.track_mut(t).unwrap().automation.retain(|lane| lane.param != AutoParam::Mute); + assert_eq!(rendered(&with_lane, block), rendered(&no_lane, block)); + } +} +#[test] +fn static_vca_mute_remains_dominant_over_member_mute_automation() { + let (mut s, t) = fixture(); + let vca = s.add_track(TrackKind::Vca, ChannelFormat::Stereo, Some("VCA")); + s.track_mut(vca).unwrap().mixer.mute = true; + s.track_mut(t).unwrap().mixer.vca = Some(vca.0); + let reference = rendered(&s, 512); + gated_silent(&reference); + mute(&mut s, t, 101, 200); + gated_silent(&rendered(&s, 512)); +} + +struct Counted { + inner: Box, + calls: Arc>>, + instrument: bool, +} +impl Plugin for Counted { + fn info(&self) -> &'static soundcraft_dsp::PluginInfo { + self.inner.info() + } + fn prepare(&mut self, sr: f32, block: usize, ch: usize) { + self.inner.prepare(sr, block, ch); + } + fn reset(&mut self) { + self.inner.reset(); + } + fn set_param(&mut self, id: &str, value: f32) -> bool { + self.inner.set_param(id, value) + } + fn param(&self, id: &str) -> Option { + self.inner.param(id) + } + fn process(&mut self, io: &mut [Vec], frames: usize) { + self.calls.lock().unwrap().push(frames); + if self.instrument { + for channel in io { + channel.iter_mut().take(frames).for_each(|sample| *sample = 0.25); + } + } else { + self.inner.process(io, frames); + } + } +} +#[test] +fn hosted_processing_keeps_the_callers_blocks_and_unmuted_pcm() { + for instrument in [false, true] { + let (mut s, t) = fixture(); + let reference = rendered(&s, 256); + mute(&mut s, t, 101, 200); + let slot = if instrument { + s.track_mut(t).unwrap().kind = TrackKind::Instrument; + s.track_mut(t).unwrap().instrument = Some(Insert::new("clap:test.mute-cadence")); + soundcraft_mix::INSTRUMENT_SLOT + } else { + s.track_mut(t).unwrap().mixer.inserts[0] = Some(Insert::new("clap:test.mute-cadence")); + 0 + }; + let calls = Arc::new(Mutex::new(Vec::with_capacity(4))); + let mut plugin = soundcraft_dsp::create("gain").unwrap(); + plugin.prepare(48_000.0, 256, 2); + let mut mix = MixEngine::new(48_000.0, 256); + mix.set_external_instances(true); + mix.adopt(vec![PreparedInstance { + track: t, + slot, + id: "clap:test.mute-cadence".into(), + ch: 2, + plugin: Box::new(Counted { inner: plugin, calls: Arc::clone(&calls), instrument }), + }]); + let mut output = vec![Vec::new(); 2]; + for (pos, frames) in [(0, 256), (256, 128), (384, 256), (640, 128)] { + let mut block = vec![vec![0.0; frames]; 2]; + mix.render(&s, pos, frames, &mut block); + for (out, channel) in output.iter_mut().zip(block) { + out.extend(channel); + } + } + assert_eq!(*calls.lock().unwrap(), vec![256, 128, 256, 128]); + gated(&output, &reference, 101, 200); + } +} diff --git a/docs/strip-mute-automation.md b/docs/strip-mute-automation.md new file mode 100644 index 00000000..59907b9e --- /dev/null +++ b/docs/strip-mute-automation.md @@ -0,0 +1,9 @@ +# Ordinary strip mute automation + +Audio, instrument, Aux and Folder strips evaluate their existing mute lane at each sample represented by a render block. Values at or above 0.5 silence both the processed output and its pre-fader send copy. A mute and unmute inside one block therefore take effect without splitting that block into smaller processor calls. + +The first mute lane, existing interpolation, and existing automation-mode policy remain authoritative. An empty lane or Off mode leaves ordinary audio unchanged. Static mute, solo suppression and static VCA mute remain dominant. Fader ramps, pan scheduling and hosted processor call sizes remain unchanged. + +Mute reads use the current render-position clock. Signal alignment, Master/VCA automation and send-control policies retain their existing behavior. + +Synthetic regressions cover interior and boundary transitions, different block partitions, pre/post-fader sends, Aux/Folder input paths, mode/empty-lane fallbacks, static/solo/VCA suppression, unchanged fader/pan scheduling, and an explicitly adopted mock hosted processor's call cadence. No installed hosted plugin is required. From fb087c879b31b4ecd44e5a3f5a2e3a9c7e9d923c Mon Sep 17 00:00:00 2001 From: MarekSpodBiedry <73122968+MarekSpodBiedry@users.noreply.github.com> Date: Thu, 15 Oct 2026 17:14:38 +0200 Subject: [PATCH 20/52] Give the New Tracks name field its own row so it stays wide (#626) --- crates/ui-egui/src/dialogs.rs | 4 +++- crates/ui-egui/tests/new_tracks.rs | 10 ++++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 713e94b7..87a29f59 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -327,8 +327,10 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) { ui.selectable_value(timebase, "ticks".to_string(), "Ticks"); }, ); + }); + ui.horizontal(|ui| { ui.label("Name:"); - ui.add(egui::TextEdit::singleline(name).desired_width(140.0)); + ui.add(egui::TextEdit::singleline(name).desired_width(240.0)); }); if buttons(ui, "Create", enter) { action = diff --git a/crates/ui-egui/tests/new_tracks.rs b/crates/ui-egui/tests/new_tracks.rs index 86f9132f..3a6d37a6 100644 --- a/crates/ui-egui/tests/new_tracks.rs +++ b/crates/ui-egui/tests/new_tracks.rs @@ -65,3 +65,13 @@ fn double_click_right_of_the_last_strip_opens_new_tracks() { click(&mut h, at); assert_eq!(h.state().dialogs.open_name(), Some("new_tracks")); } + +#[test] +fn the_new_tracks_name_field_is_wide_enough_to_read_a_name() { + let mut h = harness(0); + h.get_by_label_contains("New Tracks").click(); + h.run_steps(4); + assert_eq!(h.state().dialogs.open_name(), Some("new_tracks")); + let width = h.get_by_value("Audio").rect().width(); + assert!(width >= 200.0, "the Name field is only {width}px wide"); +} From 05fe56ec1a3346fbac5819a220f9f2e936d9ee1b Mon Sep 17 00:00:00 2001 From: Paul G <4waymedia@gmail.com> Date: Thu, 15 Oct 2026 11:21:28 -0700 Subject: [PATCH 21/52] Import audio off the UI thread (#597) Decode, resample and build peaks on a worker; file.import_audio then only places the clip. CLI/MCP/control unchanged. Co-Authored-By: Claude Opus 5.5 --- apps/soundcraft/src/main.rs | 4 +- crates/engine/src/cmd/file.rs | 52 +++++++- crates/engine/src/io.rs | 74 ++++++++++-- crates/engine/src/lib.rs | 29 +++++ crates/ui-egui/src/dialogs.rs | 16 ++- crates/ui-egui/src/import.rs | 217 ++++++++++++++++++++++++++++++++++ crates/ui-egui/src/lib.rs | 5 + crates/ui-egui/src/windows.rs | 2 +- 8 files changed, 380 insertions(+), 19 deletions(-) create mode 100644 crates/ui-egui/src/import.rs diff --git a/apps/soundcraft/src/main.rs b/apps/soundcraft/src/main.rs index 808cdef8..818f77d9 100644 --- a/apps/soundcraft/src/main.rs +++ b/apps/soundcraft/src/main.rs @@ -112,8 +112,10 @@ fn open_path(app: &mut SoundApp, p: &str) { } else if lower.ends_with(".mid") || lower.ends_with(".midi") || lower.ends_with(".smf") { app.run("file.import_midi", serde_json::json!({"path": p})) } else { + // Decoded in the background so a long file doesn't freeze the window (#597). let at = app.engine.session().edit.selection.start; - app.run("file.import_audio", serde_json::json!({"path": p, "at": at})) + soundcraft_ui_egui::import::start(app, serde_json::json!({"path": p, "at": at})); + Ok(serde_json::Value::Null) }; if let Err(e) = r { log::warn!("{p}: {e}"); diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 87bba997..527e6ec1 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -237,9 +237,17 @@ fn import_audio(e: &mut Engine, p: &Value) -> Result { let target = import_audio_target(e, p)?; let mut out = Vec::new(); for path in &paths { - let bytes = crate::io::read_file(path)?; let name = std::path::Path::new(path).file_name().and_then(|n| n.to_str()).unwrap_or("Audio").to_string(); - let r = crate::io::import_audio_bytes(e, &name, &bytes, Some(path.as_str()), target, at)?; + // Audio the app decoded on a worker thread (`Engine::offer_import`) is only placed here; + // the path is checked the same way either way. + crate::file_access::check_read(std::path::Path::new(path)).map_err(crate::EngineError::Io)?; + let r = match e.take_import(std::path::Path::new(path)) { + Some(d) => crate::io::place_decoded(e, &name, d, Some(path.as_str()), target, at)?, + None => { + let bytes = crate::io::read_file(path)?; + crate::io::import_audio_bytes(e, &name, &bytes, Some(path.as_str()), target, at)? + } + }; out.push(r); } Ok(json!({"imported": out})) @@ -350,6 +358,46 @@ mod tests { path.to_string_lossy().into_owned() } + /// Issue #597: the app decodes on a worker thread and hands the audio over; the command then + /// only places it. Audio decoded for another rate is ignored and the file is read again. + #[test] + fn import_audio_places_audio_offered_by_a_worker() { + let dir = std::env::temp_dir().join(format!("sc-import-offered-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let wav = tone_wav(&dir, "tone.wav"); + + let mut e = Engine::default(); + let rate = e.session().sample_rate.hz(); + let decoded = std::thread::spawn({ + let wav = wav.clone(); + move || crate::io::decode_import(&wav, rate) + }) + .join() + .unwrap() + .unwrap(); + assert_eq!(decoded.frames(), 4_800); + e.offer_import(decoded); + // The file changes after decoding: the offered audio is placed, not the new bytes. + std::fs::write(&wav, b"not audio").unwrap(); + let r = e.execute("file.import_audio", &json!({"path": wav, "at": 960})).unwrap(); + assert_eq!(r["imported"][0]["frames"], 4_800); + assert_eq!(e.session().tracks.len(), 1); + assert_eq!(e.session().tracks[0].clips()[0].start, 960); + assert_eq!(e.session().sources[0].path, wav); + // Taken once: the next import reads the (now broken) file. + assert!(e.execute("file.import_audio", &json!({"path": wav})).is_err()); + + // Decoded for another rate: ignored, so the broken file is read and refused. + let good = tone_wav(&dir, "good.wav"); + let other = crate::io::decode_import(&good, rate / 2).unwrap(); + std::fs::write(&good, b"not audio").unwrap(); + e.offer_import(other); + assert!(e.execute("file.import_audio", &json!({"path": good})).is_err()); + e.drop_offered_imports(); + let _ = std::fs::remove_dir_all(&dir); + } + #[test] fn import_audio_honours_new_tracks() { let dir = std::env::temp_dir().join(format!("sc-import-new-tracks-{}", std::process::id())); diff --git a/crates/engine/src/io.rs b/crates/engine/src/io.rs index 7b26e0b1..4429a061 100644 --- a/crates/engine/src/io.rs +++ b/crates/engine/src/io.rs @@ -102,6 +102,11 @@ pub fn add_source(s: &mut Session, name: &str, mut buf: AudioBuffer, path: Optio buf.channels = soundcraft_dsp::offline::resample(&buf.channels, buf.sample_rate, sr); buf.sample_rate = sr; } + add_source_audio(s, name, Arc::new(SourceAudio::new(buf)), path, format) +} + +/// Register audio already at the session rate, with its peaks built, as a new source. +fn add_source_audio(s: &mut Session, name: &str, audio: Arc, path: Option<&str>, format: FileFormat) -> SourceId { let id = SourceId(s.alloc()); let stem = Path::new(name).file_stem().and_then(|x| x.to_str()).unwrap_or(name).to_string(); let stored = match path { @@ -112,14 +117,14 @@ pub fn add_source(s: &mut Session, name: &str, mut buf: AudioBuffer, path: Optio id, name: stem.clone(), path: stored, - channels: u16::try_from(buf.num_channels()).unwrap_or(u16::MAX), - frames: buf.frames() as u64, - sample_rate: sr, + channels: u16::try_from(audio.buffer.num_channels()).unwrap_or(u16::MAX), + frames: audio.frames() as u64, + sample_rate: s.sample_rate.hz(), format, time_reference: 0, unsaved: true, }); - s.pool.insert(id, Arc::new(SourceAudio::new(buf))); + s.pool.insert(id, audio); id } @@ -132,20 +137,69 @@ fn stamp_at_rate(stamp: u64, file_rate: u32, session_rate: u32) -> u64 { u64::try_from((u128::from(stamp) * to + from / 2) / from).unwrap_or(u64::MAX) } -/// Decode and place an audio file. With no target track, a new track of matching width is made. -pub fn import_audio_bytes(e: &mut Engine, name: &str, bytes: &[u8], path: Option<&str>, target: Option, at: Samples) -> Result { +/// An audio file decoded, resampled to a session rate and given its waveform peaks: everything an +/// import costs except placing the clip. Making one needs no engine, so the app makes it on a +/// worker thread ([`decode_import`]) and hands it over with [`Engine::offer_import`] before it +/// runs `file.import_audio`, which then only places the clip (issue #597). +#[derive(Debug, Clone)] +pub struct DecodedImport { + pub(crate) key: PathBuf, + pub(crate) rate: u32, + info: soundcraft_audio_io::AudioInfo, + audio: Arc, +} + +impl DecodedImport { + /// Frames at the session rate it was decoded for. + pub fn frames(&self) -> usize { + self.audio.frames() + } +} + +/// Reads and decodes the audio file at `path` for a session at `rate`. Thread-safe and slow (the +/// whole file is read, decoded, resampled and given peaks): run it off the UI thread. +pub fn decode_import(path: &str, rate: u32) -> Result { + let bytes = read_file(path)?; + let name = Path::new(path).file_name().and_then(|n| n.to_str()).unwrap_or("Audio"); + let (info, audio) = decode_import_bytes(name, &bytes, rate)?; + Ok(DecodedImport { key: file_key(Path::new(path)), rate, info, audio }) +} + +fn decode_import_bytes(name: &str, bytes: &[u8], rate: u32) -> Result<(soundcraft_audio_io::AudioInfo, Arc)> { let ext = Path::new(name).extension().and_then(|x| x.to_str()).map(str::to_ascii_lowercase); let (info, buf) = soundcraft_audio_io::decode(bytes, ext.as_deref()).map_err(|err| EngineError::Io(format!("{name}: {err}")))?; - let buf = at_rate(buf, e.session().sample_rate.hz(), MAX_IMPORT_SAMPLES) - .ok_or_else(|| EngineError::Io(format!("{name}: file is too large to import")))?; + let buf = at_rate(buf, rate, MAX_IMPORT_SAMPLES).ok_or_else(|| EngineError::Io(format!("{name}: file is too large to import")))?; if buf.frames() == 0 { return Err(EngineError::Io(format!("{name}: no audio"))); } - let channels = buf.num_channels(); + Ok((info, Arc::new(SourceAudio::new(buf)))) +} + +/// Decode and place an audio file. With no target track, a new track of matching width is made. +pub fn import_audio_bytes(e: &mut Engine, name: &str, bytes: &[u8], path: Option<&str>, target: Option, at: Samples) -> Result { + let (info, audio) = decode_import_bytes(name, bytes, e.session().sample_rate.hz())?; + place_import(e, name, &info, audio, path, target, at) +} + +/// Place audio from [`decode_import`] (made for this session's rate) as `import_audio_bytes` does. +pub(crate) fn place_decoded(e: &mut Engine, name: &str, d: DecodedImport, path: Option<&str>, target: Option, at: Samples) -> Result { + place_import(e, name, &d.info, d.audio, path, target, at) +} + +fn place_import( + e: &mut Engine, + name: &str, + info: &soundcraft_audio_io::AudioInfo, + audio: Arc, + path: Option<&str>, + target: Option, + at: Samples, +) -> Result { + let channels = audio.buffer.num_channels(); let file_rate = info.sample_rate; let s = e.session_mut(); let session_rate = s.sample_rate.hz(); - let src = add_source(s, name, buf, path, info.format); + let src = add_source_audio(s, name, audio, path, info.format); if let (Some(bwf), Some(sx)) = (info.bwf.as_ref(), s.sources.last_mut()) { sx.time_reference = stamp_at_rate(bwf.time_reference, file_rate, session_rate); } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 6cc1c90a..9321539d 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -110,6 +110,9 @@ struct HistoryEntry { doc: Arc, } +/// Most decoded imports [`Engine::offer_import`] holds at once (each can be gigabytes). +const MAX_OFFERED_IMPORTS: usize = 4; + /// Engine state: the document, history, clipboard and transport plumbing. pub struct Engine { doc: Arc, @@ -139,6 +142,8 @@ pub struct Engine { /// The edit selection (range, tracks) before the last change, for Restore Last Selection. /// Kept out of the document so selecting never marks the session modified. pub last_selection: Option<(soundcraft_time::Range, Vec)>, + /// Audio decoded off the UI thread, waiting for its `file.import_audio` (see `offer_import`). + imports: Vec, } impl Default for Engine { @@ -169,9 +174,33 @@ impl Engine { merge_hold: None, messages: Vec::new(), last_selection: None, + imports: Vec::new(), } } + /// Hands over audio [`io::decode_import`] made off the UI thread: the next `file.import_audio` + /// of the same file at the session's rate places it instead of reading the file again. The + /// command still checks the path may be read. Only the few newest are kept. + pub fn offer_import(&mut self, d: io::DecodedImport) { + self.imports.retain(|x| x.key != d.key); + self.imports.push(d); + let extra = self.imports.len().saturating_sub(MAX_OFFERED_IMPORTS); + self.imports.drain(..extra); + } + + /// Drops audio offered for imports that never ran (the command failed or was not sent). + pub fn drop_offered_imports(&mut self) { + self.imports.clear(); + } + + /// The offered audio of the file at `path`, if it was decoded for the session's current rate. + pub(crate) fn take_import(&mut self, path: &std::path::Path) -> Option { + let key = io::file_key(path); + let rate = self.session().sample_rate.hz(); + let i = self.imports.iter().position(|d| d.key == key && d.rate == rate)?; + Some(self.imports.remove(i)) + } + pub fn session(&self) -> &Session { &self.doc } diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 713e94b7..bc745393 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -265,6 +265,7 @@ fn default_dir() -> String { pub fn show(app: &mut SoundApp, ctx: &egui::Context) { audiosuite_window(app, ctx); crate::bounce::show(app, ctx); + crate::import::show(app, ctx); let Some(mut d) = app.dialogs.open.take() else { return }; let mut keep = true; let mut action: Option<(String, Value)> = None; @@ -613,12 +614,17 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) { let saving = action.as_ref().is_some_and(|(cmd, _)| cmd.starts_with("session.save")); if let Some((cmd, params)) = action { keep = false; - match app.run(&cmd, params) { - Ok(v) if cmd == "file.export_clips" => { - app.ui.status = format!("Exported {} clip(s) to {}", v["written"], v["dir"].as_str().unwrap_or_default()); + if cmd == "file.import_audio" { + // Decoded in the background so a long file doesn't freeze the app (#597). + crate::import::start(app, params); + } else { + match app.run(&cmd, params) { + Ok(v) if cmd == "file.export_clips" => { + app.ui.status = format!("Exported {} clip(s) to {}", v["written"], v["dir"].as_str().unwrap_or_default()); + } + Ok(_) => {} + Err(e) => app.ui.status = e, } - Ok(_) => {} - Err(e) => app.ui.status = e, } } if saving diff --git a/crates/ui-egui/src/import.rs b/crates/ui-egui/src/import.rs new file mode 100644 index 00000000..e9c2d83f --- /dev/null +++ b/crates/ui-egui/src/import.rs @@ -0,0 +1,217 @@ +//! Import Audio reads and decodes on a worker thread, so the app keeps drawing and stays usable +//! while a long file loads (issue #597). When the audio is ready it is handed to the engine +//! (`Engine::offer_import`) and `file.import_audio` runs as before, now only placing the clip: +//! undo, the journal, the CLI, MCP and the control channel see the same command, and calls from +//! the control channel still run synchronously. + +use crate::SoundApp; +use serde_json::Value; +use std::collections::VecDeque; + +/// Imports waiting and the one decoding now. One file decodes at a time: each can take gigabytes. +#[derive(Default)] +pub struct Imports { + queue: VecDeque, + #[cfg(not(target_arch = "wasm32"))] + running: Option, +} + +#[cfg(not(target_arch = "wasm32"))] +struct Running { + params: Value, + name: String, + /// The session rate the audio is decoded for. + rate: u32, + rx: std::sync::mpsc::Receiver>, +} + +impl Imports { + /// Whether a file is decoding or waiting. + pub fn busy(&self) -> bool { + #[cfg(not(target_arch = "wasm32"))] + if self.running.is_some() { + return true; + } + !self.queue.is_empty() + } + + /// The file decoding now and how many wait after it. + fn label(&self) -> Option<(String, usize)> { + #[cfg(not(target_arch = "wasm32"))] + if let Some(r) = &self.running { + return Some((r.name.clone(), self.queue.len())); + } + None + } +} + +/// Imports the audio file `params["path"]` names (the `file.import_audio` params) in the +/// background. Anything else (several `paths`, no path, the browser) runs the command now. +pub fn start(app: &mut SoundApp, params: Value) { + if cfg!(target_arch = "wasm32") || params.get("path").and_then(Value::as_str).is_none() { + run_now(app, params); + return; + } + app.imports.queue.push_back(params); +} + +/// Starts the next import, and places a finished one. Called every frame from `logic`. +pub fn step(app: &mut SoundApp, ctx: &egui::Context) { + #[cfg(not(target_arch = "wasm32"))] + { + finish(app); + if app.imports.running.is_none() + && let Some(params) = app.imports.queue.pop_front() + { + spawn(app, params, ctx); + } + } + #[cfg(target_arch = "wasm32")] + { + let _ = ctx; + while let Some(params) = app.imports.queue.pop_front() { + run_now(app, params); + } + } +} + +#[cfg(not(target_arch = "wasm32"))] +fn spawn(app: &mut SoundApp, params: Value, ctx: &egui::Context) { + let path = params.get("path").and_then(Value::as_str).unwrap_or_default().to_string(); + let name = std::path::Path::new(&path).file_name().map_or_else(|| path.clone(), |n| n.to_string_lossy().into_owned()); + let rate = app.engine.session().sample_rate.hz(); + let (tx, rx) = std::sync::mpsc::channel(); + let ctx = ctx.clone(); + let work = move || { + let r = soundcraft_engine::io::decode_import(&path, rate).map_err(|e| e.to_string()); + let _ = tx.send(r); + ctx.request_repaint(); + }; + match std::thread::Builder::new().name("audio-import".into()).spawn(work) { + Ok(_) => { + app.ui.status = format!("Importing {name}…"); + app.imports.running = Some(Running { params, name, rate, rx }); + } + // No thread to spare: import the old way rather than not at all. + Err(_) => { + run_now(app, params); + } + } +} + +#[cfg(not(target_arch = "wasm32"))] +fn finish(app: &mut SoundApp) { + let Some(r) = &app.imports.running else { return }; + let done = match r.rx.try_recv() { + Ok(done) => done, + Err(std::sync::mpsc::TryRecvError::Empty) => return, + Err(std::sync::mpsc::TryRecvError::Disconnected) => Err(format!("{}: the import stopped", r.name)), + }; + let Some(Running { params, name, rate, .. }) = app.imports.running.take() else { return }; + // The session changed rate meanwhile (another session was opened): decode again for it. + if rate != app.engine.session().sample_rate.hz() { + app.imports.queue.push_front(params); + return; + } + match done { + Ok(decoded) => { + app.engine.offer_import(decoded); + if run_now(app, params) { + app.ui.status = format!("Imported {name}"); + } + app.engine.drop_offered_imports(); + } + Err(e) => app.ui.status = e, + } +} + +/// Runs `file.import_audio` on this thread; the status line shows a failure. True on success. +fn run_now(app: &mut SoundApp, params: Value) -> bool { + match app.run("file.import_audio", params) { + Ok(_) => true, + Err(e) => { + app.ui.status = e; + false + } + } +} + +/// A small, non-blocking note while files import: the rest of the app stays usable. +pub fn show(app: &SoundApp, ctx: &egui::Context) { + let Some((name, waiting)) = app.imports.label() else { return }; + egui::Area::new(egui::Id::new("audio_import_progress")).anchor(egui::Align2::RIGHT_BOTTOM, egui::vec2(-16.0, -40.0)).interactable(false).show( + ctx, + |ui| { + egui::Frame::popup(ui.style()).show(ui, |ui| { + ui.horizontal(|ui| { + ui.add(egui::Spinner::new()); + let more = if waiting > 0 { format!(" ({waiting} more)") } else { String::new() }; + ui.label(format!("Importing {name}{more}")); + }); + }); + }, + ); +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{Services, SoundApp}; + use serde_json::json; + + fn tone_wav(name: &str) -> String { + let dir = std::env::temp_dir().join(format!("sc-ui-import-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let tone: Vec = (0..9_600).map(|i| (i as f32 * 0.05).sin() * 0.2).collect(); + let buf = soundcraft_audio_io::AudioBuffer { sample_rate: 48_000, channels: vec![tone.clone(), tone] }; + let bytes = soundcraft_audio_io::encode(&buf, &soundcraft_audio_io::EncodeOptions::default()).unwrap(); + let path = dir.join(name); + std::fs::write(&path, bytes).unwrap(); + path.to_string_lossy().into_owned() + } + + fn settle(app: &mut SoundApp, ctx: &egui::Context) { + for _ in 0..2_000 { + step(app, ctx); + if !app.imports.busy() { + return; + } + std::thread::sleep(std::time::Duration::from_millis(5)); + } + panic!("import never finished"); + } + + /// Issue #597: starting an import returns at once; the clip lands, as one undo step, later. + #[test] + fn import_runs_in_the_background_and_places_one_undoable_clip() { + let ctx = egui::Context::default(); + let mut app = SoundApp::new(soundcraft_engine::Engine::default(), None, Services::default()); + let wav = tone_wav("bg.wav"); + start(&mut app, json!({"path": wav, "at": 480})); + assert!(app.imports.busy()); + assert!(app.engine.session().tracks.is_empty(), "nothing is placed before the audio is ready"); + settle(&mut app, &ctx); + let s = app.engine.session(); + assert_eq!(s.tracks.len(), 1); + assert_eq!(s.tracks[0].clips()[0].start, 480); + assert_eq!(s.sources[0].frames, 9_600); + assert!(app.ui.status.starts_with("Imported bg.wav"), "{}", app.ui.status); + app.run("edit.undo", json!({})).unwrap(); + assert!(app.engine.session().tracks.is_empty()); + } + + #[test] + fn imports_queue_and_a_bad_file_reports_without_stopping_the_rest() { + let ctx = egui::Context::default(); + let mut app = SoundApp::new(soundcraft_engine::Engine::default(), None, Services::default()); + let junk = tone_wav("junk.wav"); + std::fs::write(&junk, b"not audio").unwrap(); + let good = tone_wav("good.wav"); + start(&mut app, json!({"path": junk})); + start(&mut app, json!({"path": good})); + step(&mut app, &ctx); + assert_eq!(app.imports.label().map(|l| l.1), Some(1), "the second waits for the first"); + settle(&mut app, &ctx); + assert_eq!(app.engine.session().tracks.len(), 1, "the good file still imports"); + } +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index ddd54275..3e791a61 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -13,6 +13,7 @@ pub mod edit_window; pub mod extra_windows; pub mod fonts; pub mod icons; +pub mod import; pub mod menus; pub mod midi_editor; pub mod mix_window; @@ -326,6 +327,8 @@ pub struct SoundApp { pub video: video_track::VideoPool, /// The Bounce Mix in progress, rendered a slice per frame. pub bounce: Option, + /// Audio files importing in the background (issue #597). + pub imports: import::Imports, /// Test-only: owns the process-wide palette lock while this app exists, so frames painted /// and colour assertions in one test can never straddle another test's palette change. #[cfg(test)] @@ -400,6 +403,7 @@ impl SoundApp { last_meter_poll: f64::NEG_INFINITY, video: video_track::VideoPool::default(), bounce: None, + imports: import::Imports::default(), #[cfg(test)] _palette_lock: theme::lock_test_palette(), } @@ -1134,6 +1138,7 @@ impl SoundApp { self.note_recent_session(); self.apply_editor_edits(); bounce::step(self, ctx); + import::step(self, ctx); if !ctx.input(|i| i.pointer.any_down()) { if matches!(self.gesture, Some(Gesture::Fader { .. })) { self.gesture = None; diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index 78a91081..0ac0253a 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -363,7 +363,7 @@ fn workspace(app: &mut SoundApp, ctx: &egui::Context) { let _ = app.run("file.import_midi", json!({"path": path})); } else { let at = app.engine.session().edit.selection.start; - let _ = app.run("file.import_audio", json!({"path": path, "at": at})); + crate::import::start(app, json!({"path": path, "at": at})); } } } From adab577f9a472b92bf781cbc2a0c70d4bbb59e84 Mon Sep 17 00:00:00 2001 From: Paul G <4waymedia@gmail.com> Date: Thu, 15 Oct 2026 15:50:13 -0700 Subject: [PATCH 22/52] Resample through a polyphase bank: 5x faster rate-converting imports Precompute the windowed-sinc weights once per phase of the reduced from/to ratio; each output is one dot product. Same weights, order and edges as the per-tap kernel; large ratios fall back to it. Co-Authored-By: Claude Opus 5.5 --- crates/dsp/src/offline.rs | 111 +++++++++++++++++++++++++++++++++++++- 1 file changed, 110 insertions(+), 1 deletion(-) diff --git a/crates/dsp/src/offline.rs b/crates/dsp/src/offline.rs index 8bbc80a6..6884c4ec 100644 --- a/crates/dsp/src/offline.rs +++ b/crates/dsp/src/offline.rs @@ -216,16 +216,95 @@ fn resample_ratio(ch: &[Vec], ratio: f64, out_len: usize) -> Vec> ch.iter().map(|c| resample_channel(c, ratio, out_len, &table)).collect() } +/// Most kernel weights a [`Polyphase`] bank may hold (16 MiB of f32). +const MAX_POLYPHASE_WEIGHTS: usize = 1 << 22; + +/// The windowed-sinc kernel of [`resample_channel`] precomputed for every phase of a rational +/// rate change `from` → `to` (reduced to `step` / `phases`). Output sample `n` reads input time +/// `n * step / phases`: whole part `i`, phase `p`. Its taps are input samples `i + first ..`, one +/// weight each, so every output is one dot product over contiguous memory instead of a table +/// lookup and interpolation per tap. The weights are the ones `resample_channel` computes, taps +/// beyond the kernel's half width weigh 0, and taps are summed in the same order. +struct Polyphase { + phases: u64, + step: u64, + /// Offset of the first tap from `i`. + first: i64, + taps: usize, + /// `phases * taps` weights, phase-major. + weights: Vec, +} + +impl Polyphase { + /// `None` when the bank would be too large (rates with no small common ratio); the caller + /// then falls back to [`resample_channel`]. + fn new(from: u32, to: u32, table: &SincTable) -> Option { + let g = gcd(from, to); + let (step, phases) = (u64::from(from / g), u64::from(to / g)); + let hw = table.half_width; + let first = (-hw).floor() as i64; + let last = hw.ceil() as i64 + 1; + let taps = usize::try_from(last - first + 1).ok()?; + if usize::try_from(phases).ok()?.checked_mul(taps)? > MAX_POLYPHASE_WEIGHTS { + return None; + } + let mut weights = Vec::with_capacity(taps * phases as usize); + for p in 0..phases { + let frac = p as f64 / phases as f64; + for k in first..first + taps as i64 { + let d = frac - k as f64; + weights.push(if d.abs() <= hw { table.at(d) } else { 0.0 }); + } + } + Some(Polyphase { phases, step, first, taps, weights }) + } + + fn run(&self, x: &[f32], out_len: usize) -> Vec { + let len = x.len() as i64; + let mut out = Vec::with_capacity(out_len); + for n in 0..out_len as u64 { + let Some(pos) = n.checked_mul(self.step) else { break }; + let (i, p) = ((pos / self.phases) as i64, (pos % self.phases) as usize); + let w = self.weights.get(p * self.taps..(p + 1) * self.taps).unwrap_or_default(); + let start = i + self.first; + let acc = match usize::try_from(start).ok().and_then(|s| x.get(s..s + self.taps)) { + // Inside the signal: a plain dot product. + Some(xs) => xs.iter().zip(w).fold(0.0f32, |a, (v, k)| a + v * k), + // At the edges, taps outside the signal are skipped, as `resample_channel` does. + None => (0..self.taps as i64) + .filter(|k| (0..len).contains(&(start + k))) + .fold(0.0f32, |a, k| a + x.get((start + k) as usize).copied().unwrap_or(0.0) * w.get(k as usize).copied().unwrap_or(0.0)), + }; + out.push(acc); + } + out.resize(out_len, 0.0); + out + } +} + +fn gcd(mut a: u32, mut b: u32) -> u32 { + while b != 0 { + (a, b) = (b, a % b); + } + a.max(1) +} + /// High-quality windowed-sinc sample-rate conversion from `from` Hz to `to` Hz. pub fn resample(ch: &[Vec], from: u32, to: u32) -> Vec> { if from == 0 || to == 0 || from == to { return ch.to_vec(); } let ratio = f64::from(to) / f64::from(from); + let cutoff = if ratio < 1.0 { ratio * 0.94 } else { 0.97 }; + let table = SincTable::new(cutoff); + let bank = Polyphase::new(from, to, &table); ch.iter() .map(|c| { let out_len = ((c.len() as f64 * ratio).round() as usize).min(MAX_OFFLINE_SAMPLES); - resample_ratio(std::slice::from_ref(c), ratio, out_len).into_iter().next().unwrap_or_default() + match &bank { + Some(b) => b.run(c, out_len), + None => resample_channel(c, ratio, out_len, &table), + } }) .collect() } @@ -652,6 +731,36 @@ pub fn peak_db(ch: &[Vec]) -> f32 { mod tests { use super::*; + /// The polyphase bank gives what the per-tap kernel gives (it only moves where the weights + /// are computed), at common rate pairs, both directions, and at the signal's edges. + #[test] + fn polyphase_resample_matches_the_per_tap_kernel() { + let x: Vec = (0..3_000).map(|i| (i as f32 * 0.071).sin() * 0.6 + (i as f32 * 0.53).sin() * 0.3).collect(); + let pairs = [(44_100, 48_000), (48_000, 44_100), (48_000, 96_000), (96_000, 48_000), (22_050, 48_000), (8_000, 44_100), (48_000, 22_050)]; + for (from, to) in pairs { + let ratio = f64::from(to) / f64::from(from); + let out_len = ((x.len() as f64 * ratio).round() as usize).min(MAX_OFFLINE_SAMPLES); + let cutoff = if ratio < 1.0 { ratio * 0.94 } else { 0.97 }; + let table = SincTable::new(cutoff); + let reference = resample_channel(&x, ratio, out_len, &table); + let bank = Polyphase::new(from, to, &table).expect("small common ratio"); + let fast = bank.run(&x, out_len); + assert_eq!(fast.len(), reference.len(), "{from}->{to}"); + let worst = fast.iter().zip(&reference).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max); + assert!(worst < 1e-5, "{from}->{to}: worst difference {worst}"); + assert_eq!(resample(std::slice::from_ref(&x), from, to)[0], fast, "resample uses the bank"); + } + // Signals shorter than the kernel are all edge. + let short = [0.5f32, -0.25, 0.75]; + let table = SincTable::new(0.97); + let reference = resample_channel(&short, 48_000.0 / 44_100.0, 3, &table); + let fast = Polyphase::new(44_100, 48_000, &table).expect("bank").run(&short, 3); + assert!(fast.iter().zip(&reference).all(|(a, b)| (a - b).abs() < 1e-6), "{fast:?} {reference:?}"); + // Rates with no small common ratio fall back to the per-tap kernel. + assert!(Polyphase::new(44_100, 96_001, &table).is_none()); + assert_eq!(resample(&[short.to_vec()], 44_100, 96_001)[0].len(), 7); + } + #[test] fn fade_shapes_endpoints() { for s in FadeShape::ALL { From 7a086baa7b11602d7d2099f1f6a7aae12f8d37a4 Mon Sep 17 00:00:00 2001 From: euisuh <55032583+euisuh@users.noreply.github.com> Date: Fri, 16 Oct 2026 13:36:19 +0900 Subject: [PATCH 23/52] fix(ui): capture live plugin state before saving track presets Track presets serialized the insert model's earlier capture instead of the hosted plugin's current state. Reuse the existing save/bounce capture path before preset serialization and exercise it with the real CLAP fixture. Closes #661 Related #639 Co-Authored-By: OpenAI Codex --- crates/clap-host/tests/common/mod.rs | 2 +- crates/clap-host/tests/fixture/Cargo.toml | 2 +- crates/ui-egui/src/lib.rs | 2 +- crates/ui-egui/tests/track_preset_state.rs | 36 ++++++++++++++++++++++ docs/gaps.md | 9 ++++-- 5 files changed, 45 insertions(+), 6 deletions(-) create mode 100644 crates/ui-egui/tests/track_preset_state.rs diff --git a/crates/clap-host/tests/common/mod.rs b/crates/clap-host/tests/common/mod.rs index 2da23955..6ae4ef74 100644 --- a/crates/clap-host/tests/common/mod.rs +++ b/crates/clap-host/tests/common/mod.rs @@ -9,7 +9,7 @@ use std::sync::OnceLock; pub fn fixture_dir() -> &'static Path { static DIR: OnceLock = OnceLock::new(); DIR.get_or_init(|| { - let manifest = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixture/Cargo.toml"); + let manifest = Path::new(env!("CARGO_MANIFEST_DIR")).join("../clap-host/tests/fixture/Cargo.toml"); let target = Path::new(env!("CARGO_TARGET_TMPDIR")).join("clap-fixture-target"); let cargo = std::env::var("CARGO").unwrap_or_else(|_| "cargo".into()); let st = Command::new(cargo) diff --git a/crates/clap-host/tests/fixture/Cargo.toml b/crates/clap-host/tests/fixture/Cargo.toml index dac4af39..18efb527 100644 --- a/crates/clap-host/tests/fixture/Cargo.toml +++ b/crates/clap-host/tests/fixture/Cargo.toml @@ -1,4 +1,4 @@ -# A tiny CLAP plugin used only by soundcraft-clap-host's integration tests. Not part of the +# A tiny CLAP plugin used only by SoundCraft's integration tests. Not part of the # SoundCraft workspace (the empty [workspace] table makes it its own root); the test builds it # with `cargo build` and loads the resulting library. Never shipped. [package] diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index ddd54275..cd756716 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -418,7 +418,7 @@ impl SoundApp { if let Some(r) = menus::run_ui_command(self, id, ¶ms) { return r; } - if id.starts_with("session.save") || id.starts_with("file.bounce") { + if id.starts_with("session.save") || id.starts_with("file.bounce") || id == "track.save_preset" { // Third-party plugins keep state the session can't see: store it first. self.capture_plugin_states(); } diff --git a/crates/ui-egui/tests/track_preset_state.rs b/crates/ui-egui/tests/track_preset_state.rs new file mode 100644 index 00000000..155a7997 --- /dev/null +++ b/crates/ui-egui/tests/track_preset_state.rs @@ -0,0 +1,36 @@ +//! Track presets capture the hosted plugin's current state before writing the model. + +#[path = "../../clap-host/tests/common/mod.rs"] +mod common; + +use serde_json::{Value, json}; +use soundcraft_engine::Engine; +use soundcraft_model::{ChannelFormat, Insert, TrackKind, b64}; +use soundcraft_playback::Player; +use soundcraft_ui_egui::{Services, SoundApp}; + +#[test] +fn track_preset_captures_live_plugin_state_before_serializing() { + common::fixture_dir(); + let mut engine = Engine::default(); + let track = engine.session_mut().add_track(TrackKind::Audio, ChannelFormat::Mono, Some("Vox")); + engine.session_mut().track_mut(track).unwrap().mixer.inserts[0] = Some(Insert::new("clap:org.soundcraft.test.gain")); + let player = Player::new(engine.session_arc()); + let states = player.capture_states(); + assert_eq!(states.len(), 1, "the synthetic CLAP plugin must load even without an audio device"); + assert_eq!((states[0].0, states[0].1), (track, 0)); + let live = states[0].2.clone(); + + // The model still holds the earlier capture while the live plugin has its current settings. + let stale: Vec = [0.25_f64, 0.0].into_iter().flat_map(f64::to_le_bytes).collect(); + assert_ne!(live, stale); + engine.session_mut().track_mut(track).unwrap().mixer.inserts[0].as_mut().unwrap().set_state_bytes(&stale); + let mut app = SoundApp::new(engine, Some(player), Services::default()); + assert_eq!(app.engine.session().track(track).unwrap().mixer.inserts[0].as_ref().unwrap().state_bytes(), Some(stale)); + + let path = std::path::Path::new(env!("CARGO_TARGET_TMPDIR")).join(format!("track-preset-state-{}.json", std::process::id())); + app.run("track.save_preset", json!({"track": track.0, "path": path.to_string_lossy()})).unwrap(); + let preset: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); + std::fs::remove_file(path).unwrap(); + assert_eq!(preset["mixer"]["inserts"][0]["state"], b64::encode(&live), "the preset must contain the current hosted state"); +} diff --git a/docs/gaps.md b/docs/gaps.md index f8c39b8a..6703b6f9 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Where SoundCraft falls short of Pro Tools -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-12 · **Change:** minor (G-01: audio device settings and opt-in ASIO) · **Target:** Avid Pro Tools Ultimate 2026.4.1 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-16 · **Change:** minor (G-16: live plugin state in track-preset saves) · **Target:** Avid Pro Tools Ultimate 2026.4.1 Every known shortfall, one entry each, ranked by how much it stops a Pro Tools user from doing real work in SoundCraft. This is the work list: pick from the top. Rows marked **alpha blocker** @@ -163,8 +163,10 @@ varispeed, high-quality offline) plus Elastic Pitch and warp-marker editing dept ### G-16. Session management -No session templates, track presets, workspace/sound browser with previews, batch rename (new in -2026.4), disk-usage and relink depth. ≈ 25–40 h. +Session templates, track-preset recall UI and browser, workspace/sound browser with previews, +batch rename (new in 2026.4), disk-usage and relink depth remain. Track-preset saves capture the +current hosted-plugin state before writing (#661); recall UI, partial recall and preset browsing remain +tracked in #639. ≈ 25–40 h. ### G-17. Video and post @@ -199,6 +201,7 @@ missing. Out of scope unless the owner decides otherwise. | Date | Change | Summary | |---|---|---| +| 2026-10-16 | minor | G-16: capture current hosted-plugin state before saving a track preset (#661); broader preset work remains (#639) | | 2026-10-12 | minor | G-01 shrunk: audio device, rate and buffer choice; opt-in ASIO | | 2026-10-10 | minor | Marked the alpha blockers (G-01, G-02, G-03; parts of G-05 and G-06) from the core-workflow gate | | 2026-10-10 | major | Created from the full re-measure against Pro Tools Ultimate 2026.4.1: 22 ranked gaps with evidence and estimates | From 3ea890496e108aa0432d0f7a8f9d628b6e5867af Mon Sep 17 00:00:00 2001 From: reoniazx <76652649+reoniazx@users.noreply.github.com> Date: Fri, 16 Oct 2026 12:33:09 +0800 Subject: [PATCH 24/52] fix(engine): preserve channels when splitting tracks into mono --- ROADMAP.md | 4 +- crates/engine/src/cmd/track.rs | 42 ++++++- crates/engine/tests/split_into_mono.rs | 159 +++++++++++++++++++++++++ docs/gaps.md | 7 +- 4 files changed, 207 insertions(+), 5 deletions(-) create mode 100644 crates/engine/tests/split_into_mono.rs diff --git a/ROADMAP.md b/ROADMAP.md index 73197650..7af8c561 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: pre-alpha** · next: alpha, ~5% and ~110–180 h away (the alpha gate's three failing workflows) -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-10 · **Change:** minor (readiness by audience with hours to ~95 %) · **Target:** Avid Pro Tools Ultimate 2026.4.1 +> **Last reviewed:** 2026-10-16 · **Last updated:** 2026-10-16 · **Change:** trivial (Split into Mono channel preservation) · **Target:** Avid Pro Tools Ultimate 2026.4.1 SoundCraft is a clean-room, pure-Rust digital audio workstation that aims at full parity with Avid Pro Tools, and then beyond it: faster, open, scriptable and agent-controllable. This page is @@ -122,6 +122,7 @@ mutated and truncated movies. Field reports from the first public week are track ## Progress log +- **2026-10-16:** Split into Mono extracts the correct source channel for each mono track instead of playing channel zero on every track. Clip offsets, gain, fades and stretch, source timestamps, Undo/Redo and saved audio are preserved; repeated clips share each extracted mono source. Unavailable media returns an error without partial edits. No readiness percentage change. - **2026-10-13:** `mix.instrument` takes the built-in instrument's parameters in `params` (validated, clamped) and refuses any other field, so a synth setting written beside `plugin` is an error instead of being accepted and ignored (#265) - **2026-10-13:** A bounce of a bus that an aux returns onto lines up with the timeline: the aux insert's lookahead is compensated like the main mix's (it left the bus late and cut the end off), and tracks routed to that bus wait for it too (#246) - **2026-10-13:** Delay compensation covers the inserts of the master faders: a bounce of the main mix with a Maximizer on the master lines up with the same mix without it (it came out 71 samples late) (#351) @@ -155,6 +156,7 @@ mutated and truncated movies. Field reports from the first public week are track | Date | Change | Summary | |---|---|---| +| 2026-10-16 | trivial | Split into Mono preserves each source channel, clip edits and saved audio; readiness estimates unchanged | | 2026-10-13 | trivial | Progress log: mix.instrument params, unknown fields refused (#265) | | 2026-10-13 | trivial | Progress log: bus bounce compensates aux returns (#246) | | 2026-10-13 | trivial | Progress log: master insert latency compensated (#351) | diff --git a/crates/engine/src/cmd/track.rs b/crates/engine/src/cmd/track.rs index 87912389..c0ebcbee 100644 --- a/crates/engine/src/cmd/track.rs +++ b/crates/engine/src/cmd/track.rs @@ -3,7 +3,7 @@ use super::*; use crate::cmd; use serde_json::json; -use soundcraft_model::{ChannelFormat, Group, GroupId, Playlist, Route, Session, Track, TrackHeight, TrackKind}; +use soundcraft_model::{ChannelFormat, ClipContent, Group, GroupId, Playlist, Route, Session, Track, TrackHeight, TrackKind}; pub fn specs() -> Vec { vec![ @@ -362,6 +362,8 @@ fn split_mono(e: &mut Engine, p: &Value) -> Result { let tracks = tracks_required(e, "track.split_into_mono", p)?; let s = e.session_mut(); let mut out = Vec::new(); + let mut mono_sources = std::collections::BTreeMap::new(); + let mut copied_samples = 0usize; for t in tracks { let Some(src) = s.track(t).cloned() else { continue }; if src.channels() < 2 || src.kind != TrackKind::Audio { @@ -377,12 +379,46 @@ fn split_mono(e: &mut Engine, p: &Value) -> Result { let mut clips = src.clips().to_vec(); for c in &mut clips { c.id = s.new_clip_id(); - // Mono tracks read channel 0 of the source; record the channel in the name for now. + if let ClipContent::Audio { source, .. } = &mut c.content { + let audio = + s.pool.get(*source).ok_or_else(|| bad("track.split_into_mono", format!("audio unavailable for clip `{}`", c.name)))?; + let channels = audio.buffer.channels.len(); + if channels == 0 { + return Err(bad("track.split_into_mono", format!("audio has no channels for clip `{}`", c.name))); + } + // Match the renderer's channel wrapping when a track is wider than its source. + // An already-mono source can be shared without copying it. + if channels > 1 { + let key = (*source, ch % channels); + let mono = if let Some(&id) = mono_sources.get(&key) { + id + } else { + let samples = + audio.buffer.channels.get(key.1).ok_or_else(|| bad("track.split_into_mono", "source channel unavailable"))?; + copied_samples = copied_samples + .checked_add(samples.len()) + .filter(|&n| n <= crate::io::MAX_IMPORT_SAMPLES) + .ok_or_else(|| bad("track.split_into_mono", "split would copy too much audio"))?; + // Keep the full channel: the cloned clips retain their offsets, stretch, + // gain and fades, and every reader sees genuine mono media (including saves). + let buf = soundcraft_audio_io::AudioBuffer { sample_rate: s.sample_rate.hz(), channels: vec![samples.clone()] }; + let original = s.source(*source); + let name = format!("{}.{suffix}.wav", original.map_or(c.name.as_str(), |source| source.name.as_str())); + let time_reference = original.map_or(0, |source| source.time_reference); + let id = crate::io::add_source(s, &name, buf, None, soundcraft_audio_io::FileFormat::Wav); + if let Some(source) = s.sources.iter_mut().find(|source| source.id == id) { + source.time_reference = time_reference; + } + mono_sources.insert(key, id); + id + }; + *source = mono; + } + } c.name = format!("{}.{suffix}", c.name); } if let Some(tr) = s.track_mut(id) { tr.mixer.pan = vec![if ch == 0 { -1.0 } else { 1.0 }]; - tr.comments = format!("source_channel={ch}"); if let Some(pl) = tr.playlist_mut() { pl.clips = clips; } diff --git a/crates/engine/tests/split_into_mono.rs b/crates/engine/tests/split_into_mono.rs new file mode 100644 index 00000000..7925af58 --- /dev/null +++ b/crates/engine/tests/split_into_mono.rs @@ -0,0 +1,159 @@ +//! Split tracks into mono without replacing the right/surround channels with channel zero. + +use serde_json::json; +use soundcraft_audio_io::{AudioBuffer, FileFormat}; +use soundcraft_engine::{Engine, io}; +use soundcraft_model::{ChannelFormat, Clip, Session, SourceAudio, SourceId, TrackId, TrackKind}; +use soundcraft_time::Range; +use std::sync::Arc; + +fn fixture(format: ChannelFormat, channels: usize) -> (Engine, TrackId, SourceId) { + let mut s = Session::default(); + let track = s.add_track(TrackKind::Audio, format, Some("Original")); + let channels = (0..channels).map(|ch| (0..256).map(|i| (ch + 1) as f32 * 0.1 + i as f32 * 0.0001).collect()).collect(); + let source = io::add_source(&mut s, "Original.wav", AudioBuffer { sample_rate: 48_000, channels }, None, FileFormat::Wav); + s.sources[0].time_reference = 123_456; + let mut clip = Clip::audio(s.new_clip_id(), "Edited", source, 7, 13, 47); + clip.gain_db = -6.0; + clip.gain_env = vec![(0, -3.0), (20, 0.0), (46, -9.0)]; + clip.fade_in.len = 5; + clip.fade_out.len = 9; + clip.stretch = 1.25; + let mut second = clip.clone(); + second.id = s.new_clip_id(); + second.start = 100; + second.content = soundcraft_model::ClipContent::Audio { source, offset: 90 }; + s.track_mut(track).unwrap().playlist_mut().unwrap().clips = vec![clip, second]; + (Engine::new(s), track, source) +} + +fn split(e: &mut Engine, track: TrackId) -> Vec { + let result = e.execute("track.split_into_mono", &json!({"track": track.0})).unwrap(); + result["tracks"].as_array().unwrap().iter().map(|id| TrackId(id.as_u64().unwrap())).collect() +} + +#[test] +fn split_into_mono_preserves_every_channel_and_clip_edit() { + for (format, channels) in [(ChannelFormat::Stereo, 2), (ChannelFormat::Surround51, 6)] { + let (mut e, track, source) = fixture(format, channels); + let original = e.session().track(track).unwrap().clone(); + let audio = Arc::clone(e.session().pool.get(source).unwrap()); + let expected = soundcraft_mix::render_clips(e.session(), track, Range::new(0, 192)); + let tracks = split(&mut e, track); + assert_eq!(tracks.len(), channels); + assert_eq!(e.session().track(track).unwrap(), &original); + assert!(Arc::ptr_eq(e.session().pool.get(source).unwrap(), &audio)); + // Two clips referencing the same source share one extracted source per channel. + assert_eq!(e.session().sources.len(), 1 + channels); + for (ch, &id) in tracks.iter().enumerate() { + let mono = e.session().track(id).unwrap(); + assert_eq!(mono.format, ChannelFormat::Mono); + let actual = soundcraft_mix::render_clips(e.session(), id, Range::new(0, 192)); + assert_eq!(actual[0], expected[ch], "{format:?} channel {ch}"); + let mono_source = mono.clips()[0].source().unwrap(); + assert_ne!(mono_source, source); + assert!(mono.clips().iter().all(|clip| clip.source() == Some(mono_source))); + let data = e.session().pool.get(mono_source).unwrap(); + assert_eq!(data.buffer.channels, vec![audio.buffer.channels[ch].clone()]); + assert_eq!(data.peaks.len(), 1); + let metadata = e.session().source(mono_source).unwrap(); + assert_eq!((metadata.channels, metadata.time_reference), (1, 123_456)); + assert!(metadata.unsaved); + for (clip, original) in mono.clips().iter().zip(original.clips()) { + let mut expected_clip = original.clone(); + expected_clip.id = clip.id; + expected_clip.name = clip.name.clone(); + expected_clip.content = soundcraft_model::ClipContent::Audio { source: mono_source, offset: original.source_offset() }; + assert_eq!(clip, &expected_clip); + } + } + } +} + +#[test] +fn split_stereo_matches_the_original_mix_in_playback_and_bounce_blocks() { + let (mut e, track, _) = fixture(ChannelFormat::Stereo, 2); + let original = e.session().clone(); + let tracks = split(&mut e, track); + assert_eq!(e.session().track(tracks[0]).unwrap().name, "Original.L"); + assert_eq!(e.session().track(tracks[1]).unwrap().name, "Original.R"); + e.session_mut().track_mut(track).unwrap().inactive = true; + for block in [37, 512, 1024] { + let expected = soundcraft_mix::render_range(&original, Range::new(0, 192), block); + let actual = soundcraft_mix::render_range(e.session(), Range::new(0, 192), block); + assert_eq!(actual, expected, "block {block}"); + } +} + +#[test] +fn split_stereo_preserves_distinct_left_and_right_levels() { + let (mut e, track, source) = fixture(ChannelFormat::Stereo, 2); + let s = e.session_mut(); + s.pool.insert(source, Arc::new(SourceAudio::new(AudioBuffer { sample_rate: 48_000, channels: vec![vec![0.2; 256], vec![0.7; 256]] }))); + let clip = Clip::audio(s.new_clip_id(), "Distinct channels", source, 0, 0, 256); + s.track_mut(track).unwrap().playlist_mut().unwrap().clips = vec![clip]; + split(&mut e, track); + e.session_mut().track_mut(track).unwrap().inactive = true; + let audio = soundcraft_mix::render_range(e.session(), Range::new(0, 128), 64); + eprintln!("Split into Mono output: L={}, R={}", audio[0][64], audio[1][64]); + assert_eq!(audio[0][64], 0.2); + assert_eq!(audio[1][64], 0.7); +} + +#[test] +fn split_sources_survive_save_and_reopen_with_distinct_audio_files() { + let (mut e, track, _) = fixture(ChannelFormat::Stereo, 2); + let tracks = split(&mut e, track); + let (bytes, saved) = io::session_bundle(e.session()).unwrap(); + let paths: std::collections::BTreeSet<_> = saved.sources.iter().map(|source| &source.path).collect(); + assert_eq!(paths.len(), 3); + let mut reopened = Engine::default(); + assert!(io::open_session_bytes(&mut reopened, "split.scraftz", &bytes).unwrap().is_empty()); + for id in tracks { + let expected = soundcraft_mix::render_clips(e.session(), id, Range::new(0, 192)); + let actual = soundcraft_mix::render_clips(reopened.session(), id, Range::new(0, 192)); + assert_eq!(actual, expected); + } +} + +#[test] +fn split_tracks_and_sources_undo_and_redo_together() { + let (mut e, track, _) = fixture(ChannelFormat::Stereo, 2); + let before = e.session().clone(); + split(&mut e, track); + let after = e.session().clone(); + assert_eq!(e.undo_history().len(), 1); + assert!(e.undo()); + assert_eq!(e.session(), &before); + assert!(e.redo()); + assert_eq!(e.session(), &after); +} + +#[test] +fn split_reuses_a_mono_source_on_a_stereo_track() { + let (mut e, track, source) = fixture(ChannelFormat::Stereo, 1); + let expected = soundcraft_mix::render_clips(e.session(), track, Range::new(0, 192)); + for id in split(&mut e, track) { + assert!(e.session().track(id).unwrap().clips().iter().all(|clip| clip.source() == Some(source))); + assert_eq!(soundcraft_mix::render_clips(e.session(), id, Range::new(0, 192))[0], expected[0]); + } + assert_eq!(e.session().sources.len(), 1); +} + +#[test] +fn missing_or_empty_media_refuses_the_split_without_partial_changes() { + for empty in [false, true] { + let (mut e, track, _) = fixture(ChannelFormat::Stereo, 2); + let missing = SourceId(9999); + if empty { + e.session_mut().pool.insert(missing, Arc::new(SourceAudio::new(AudioBuffer { sample_rate: 48_000, channels: vec![] }))); + } + let clip = Clip::audio(e.session_mut().new_clip_id(), "Unavailable", missing, 0, 160, 16); + e.session_mut().track_mut(track).unwrap().playlist_mut().unwrap().clips.push(clip); + let before = e.session().clone(); + let error = e.execute("track.split_into_mono", &json!({"track": track.0})).unwrap_err(); + assert!(matches!(error, soundcraft_engine::EngineError::BadParams(..)), "{error}"); + assert_eq!(e.session(), &before); + assert!(e.undo_history().is_empty()); + } +} diff --git a/docs/gaps.md b/docs/gaps.md index f8c39b8a..21420705 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Where SoundCraft falls short of Pro Tools -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-12 · **Change:** minor (G-01: audio device settings and opt-in ASIO) · **Target:** Avid Pro Tools Ultimate 2026.4.1 +> **Last reviewed:** 2026-10-16 · **Last updated:** 2026-10-16 · **Change:** trivial (G-04: Split into Mono channel fix) · **Target:** Avid Pro Tools Ultimate 2026.4.1 Every known shortfall, one entry each, ranked by how much it stops a Pro Tools user from doing real work in SoundCraft. This is the work list: pick from the top. Rows marked **alpha blocker** @@ -80,6 +80,10 @@ When you close a gap, delete its entry (or shrink it) in the same PR, and bump t ### G-04. Correctness bugs in "done" features +**Fixed (2026-10-16):** Split into Mono now gives each output track its own source channel, +including surround channels, instead of repeating channel zero. Clip edits, source timestamps, +Undo/Redo and save/reopen are covered by regression tests; missing or empty media fails atomically. + Open on 2026-10-10 (several have PRs open): editing #3, #5, #140, #144; clip/session #86 (PR #123), #88 (PR #130), #91 (PR #124), #92 (PR #132); automation #104 (PR #134); mix/bounce #59 (PR #131), #103 (PR #133), #152; playback #101 (PR #129); @@ -199,6 +203,7 @@ missing. Out of scope unless the owner decides otherwise. | Date | Change | Summary | |---|---|---| +| 2026-10-16 | trivial | G-04: Split into Mono channel preservation fixed and regression-tested; estimates unchanged | | 2026-10-12 | minor | G-01 shrunk: audio device, rate and buffer choice; opt-in ASIO | | 2026-10-10 | minor | Marked the alpha blockers (G-01, G-02, G-03; parts of G-05 and G-06) from the core-workflow gate | | 2026-10-10 | major | Created from the full re-measure against Pro Tools Ultimate 2026.4.1: 22 ranked gaps with evidence and estimates | From a4b6bd01794302b0815ce8b3ec69db7431a115e9 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Fri, 16 Oct 2026 11:09:42 +0000 Subject: [PATCH 25/52] Fix source offset when trimming the start of a stretched audio clip Found while testing crates/model/src/clip.rs:246 (Clip::trim_start_to, used by crates/engine/src/edit.rs:36 split_clip) Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 --- crates/model/src/clip.rs | 29 +++++++++++++++++++++++++++-- 1 file changed, 27 insertions(+), 2 deletions(-) diff --git a/crates/model/src/clip.rs b/crates/model/src/clip.rs index 850cf044..3153259f 100644 --- a/crates/model/src/clip.rs +++ b/crates/model/src/clip.rs @@ -246,8 +246,16 @@ impl Clip { pub fn trim_start_to(&mut self, new_start: Samples) { let new_start = new_start.min(self.end() - 1); let delta = new_start - self.start; - if let ClipContent::Audio { offset, .. } | ClipContent::Video { offset, .. } = &mut self.content { - *offset = offset.saturating_add(delta); + // The mixer plays a stretched audio clip from `offset + rel / stretch`. + let stretch = if self.stretch.is_finite() && self.stretch > 0.0 { self.stretch } else { 1.0 }; + match &mut self.content { + ClipContent::Audio { offset, .. } if (stretch - 1.0).abs() >= 1e-9 => { + *offset = offset.saturating_add((delta as f64 / stretch).round() as Samples); + } + ClipContent::Audio { offset, .. } | ClipContent::Video { offset, .. } => { + *offset = offset.saturating_add(delta); + } + ClipContent::Midi { .. } => {} } // MIDI note ticks are re-anchored by the engine, which knows the tempo map. self.length -= delta; @@ -479,4 +487,21 @@ mod tests { c.trim_start_to(900); assert!(c.fade_out.len <= c.length); } + + #[test] + fn trim_start_of_stretched_audio_advances_offset_by_source_time() { + // The mixer plays source `offset + rel / stretch`, so a split at timeline 1000 of a 2x clip + // must start the right half at source sample 500. + let mut c = Clip::audio(ClipId(1), "a", SourceId(1), 0, 0, 2000); + c.stretch = 2.0; + c.trim_start_to(1000); + assert_eq!(c.source_offset(), 500); + let mut c = Clip::audio(ClipId(2), "b", SourceId(1), 0, 0, 2000); + c.stretch = 0.5; + c.trim_start_to(1000); + assert_eq!(c.source_offset(), 2000); + let mut c = Clip::audio(ClipId(3), "c", SourceId(1), 0, 0, 2000); + c.trim_start_to(1000); + assert_eq!(c.source_offset(), 1000); + } } From 6f3591ae113283a2a2cb20d0fda9b2daca38873b Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Sat, 17 Oct 2026 13:43:37 +0000 Subject: [PATCH 26/52] Keep the existing volume lane in automation.clip_gain_to_volume Found while testing crates/engine/src/cmd/mix.rs:676-681 (clip_gain_to_vol) Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 --- crates/engine/src/cmd/mix.rs | 82 ++++++++++++++++++++++++++++++++---- 1 file changed, 74 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/cmd/mix.rs b/crates/engine/src/cmd/mix.rs index c0569429..01e96372 100644 --- a/crates/engine/src/cmd/mix.rs +++ b/crates/engine/src/cmd/mix.rs @@ -669,23 +669,34 @@ fn clip_gain_to_vol(e: &mut Engine, p: &Value) -> Result { for t in &tracks { let Some(tr) = s.track_mut(*t) else { continue }; let base = tr.mixer.volume_db; + // An existing lane overrides the fader, so the clip gain rides on top of the lane value. + let old = tr.lane(&AutoParam::Volume).cloned(); + let level = |at: i64| old.as_ref().map_or(base, |l| l.value_at(at, base)); + let mut pins = Vec::new(); let mut pts = Vec::new(); if let Some(pl) = tr.playlist_mut() { for c in pl.clips.iter_mut().filter(|c| c.range().overlaps(&r)) { - if c.gain_env.is_empty() { - pts.push((c.start, base + c.gain_db)); - pts.push((c.end() - 1, base + c.gain_db)); - } else { - for (o, db) in &c.gain_env { - pts.push((c.start + o, base + c.gain_db + db)); - } + // Pin the unchanged level just outside the clip so the neighbouring segments keep their shape. + if c.start > 0 { + pins.push((c.start - 1, level(c.start - 1))); + } + pins.push((c.end(), level(c.end()))); + let mut ats: Vec = + if c.gain_env.is_empty() { vec![c.start, c.end() - 1] } else { c.gain_env.iter().map(|&(o, _)| c.start + o).collect() }; + // The lane's own points inside the clip carry the clip gain too. + if let Some(l) = &old { + ats.extend(l.points.iter().map(|pt| pt.at).filter(|&at| at > c.start && at < c.end() - 1)); + } + for at in ats { + pts.push((at, level(at) + c.gain_db + env_db(&c.gain_env, at - c.start))); } c.gain_db = 0.0; c.gain_env.clear(); } } let lane = tr.lane_mut(&AutoParam::Volume); - for (at, v) in pts { + // Pins first, so a neighbouring clip's converted points win where they meet. + for (at, v) in pins.into_iter().chain(pts) { lane.set_point(at, v); } } @@ -838,6 +849,61 @@ mod tests { } } + #[test] + fn clip_gain_to_volume_keeps_the_existing_lane() { + let clip_gain_to_volume = |points: &[(i64, f32)], env: Vec<(i64, f32)>| { + let (mut e, t) = tone_session(points); + let clip = e.session().track(t).unwrap().clips()[0].id; + let c = e.session_mut().find_clip_mut(clip).unwrap(); + c.gain_db = 6.0; + c.gain_env = env; + let before = rendered(e.session()); + e.execute("automation.clip_gain_to_volume", &json!({"track": t.0, "start": 0, "end": 8192})).unwrap(); + let after = rendered(e.session()); + assert!(e.session().find_clip(clip).unwrap().1.gain_db == 0.0); + (before, after) + }; + let (before, after) = clip_gain_to_volume(&[(0, -6.0), (8192, -6.0)], Vec::new()); + let delta = rms_db(&before, &after); + assert!(delta.abs() < 0.02, "level changed by {delta} dB"); + + // A moving lane keeps its shape, and its points inside the clip carry the gain. + let (before, after) = clip_gain_to_volume(&[(0, -12.0), (4096, -6.0), (8192, -12.0)], Vec::new()); + for (start, end) in [(0, 2048), (2048, 4096), (4096, 6144), (6144, 8192)] { + let delta = rms_db(&before[start..end], &after[start..end]); + assert!(delta.abs() < 0.1, "{start}..{end} changed by {delta} dB"); + } + + // The clip's own gain envelope rides on the lane value as well. + let (before, after) = clip_gain_to_volume(&[(0, -6.0), (8192, -6.0)], vec![(2000, 0.0), (6000, -10.0)]); + for (start, end) in [(3900, 4100), (5000, 5200)] { + let delta = rms_db(&before[start..end], &after[start..end]); + assert!(delta.abs() < 0.2, "{start}..{end} changed by {delta} dB"); + } + } + + #[test] + fn clip_gain_to_volume_leaves_audio_outside_the_clip_alone() { + // Three clips in a row; only the middle one is converted, and the lane extends past it on both sides. + let (mut e, t) = tone_session(&[(0, -6.0), (16384, -6.0)]); + let (middle, last) = (e.session_mut().new_clip_id(), e.session_mut().new_clip_id()); + let pl = e.session_mut().track_mut(t).unwrap().playlist_mut().unwrap(); + if let Some(c) = pl.clips.first_mut() { + c.length = 2048; + } + pl.clips.push(Clip::audio(middle, "mid", SourceId(910), 2048, 2048, 4096)); + pl.clips.push(Clip::audio(last, "end", SourceId(910), 6144, 6144, 2048)); + e.session_mut().find_clip_mut(middle).unwrap().gain_db = 6.0; + let before = rendered(e.session()); + e.execute("automation.clip_gain_to_volume", &json!({"track": t.0, "start": 2048, "end": 6144})).unwrap(); + let after = rendered(e.session()); + assert!(e.session().find_clip(middle).unwrap().1.gain_db == 0.0); + for (start, end) in [(0, 2040), (2056, 6136), (6152, 8192)] { + let delta = rms_db(&before[start..end], &after[start..end]); + assert!(delta.abs() < 0.1, "{start}..{end} changed by {delta} dB"); + } + } + #[test] fn insert_params_rejects_unknown_and_non_numeric_keys() { let mut e = Engine::default(); From a72e46e7b68e13930b437d990d53b8897f6a0b3e Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Sun, 18 Oct 2026 19:04:41 +0200 Subject: [PATCH 27/52] Bounce the whole session when CLI --bounce has no range Fixes #745 Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Opus 5.5 --- apps/soundcraft-cli/src/main.rs | 8 +++++++- apps/soundcraft-cli/tests/cli.rs | 25 +++++++++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/apps/soundcraft-cli/src/main.rs b/apps/soundcraft-cli/src/main.rs index 9a51cc54..0207a1f4 100644 --- a/apps/soundcraft-cli/src/main.rs +++ b/apps/soundcraft-cli/src/main.rs @@ -4,7 +4,8 @@ //! soundcraft-cli info FILE audio file or .scraft summary //! soundcraft-cli convert IN OUT [--bit-depth 16|24|32f] [--rate HZ] [--normalize] //! soundcraft-cli run [--in S.scraft | --demo] [--cmd ID[=JSON]]… [--bounce OUT] [--start T --end T] [--save S.scraft] [--inspect] -//! soundcraft-cli script FILE [--in S | --demo] [--save S] [--bounce OUT] (one `ID JSON` per line) +//! soundcraft-cli script FILE [--in S | --demo] [--save S] [--bounce OUT [--start T --end T]] (one `ID JSON` per line; +//! without --start/--end, --bounce covers the whole session) //! soundcraft-cli commands [FILTER] list commands //! soundcraft-cli describe ID one command's details //! soundcraft-cli app [--port P] METHOD [JSON] call a running app's control channel @@ -212,6 +213,11 @@ fn finish(e: &mut Engine, args: &[String]) -> ExitCode { if let Some(s) = arg_value(args, "--end") { p["end"] = time_arg(&s); } + // No range given: bounce the whole session, not whatever edit selection the commands left. + if p.get("start").is_none() && p.get("end").is_none() { + p["start"] = json!(0); + p["end"] = json!(e.session().content_end().max(1)); + } match e.execute("file.bounce_mix", &p) { Ok(v) => outln!("{v}"), Err(err) => return fail(err), diff --git a/apps/soundcraft-cli/tests/cli.rs b/apps/soundcraft-cli/tests/cli.rs index ef2fb881..6074999d 100644 --- a/apps/soundcraft-cli/tests/cli.rs +++ b/apps/soundcraft-cli/tests/cli.rs @@ -138,3 +138,28 @@ fn usage_lists_the_root_flags() { let help = String::from_utf8_lossy(&o.stdout).into_owned(); assert!(help.contains("--automation-read-root DIR") && help.contains("--automation-write-root DIR"), "{help}"); } + +/// Without `--start`/`--end`, `--bounce` covers the whole session, not a stray edit selection +/// left by the script (a bare `19.2` in command params is 19 samples). +#[test] +fn script_bounce_without_range_covers_the_session() { + let base = tmpdir("bounce-range"); + let script = base.join("cmds.txt"); + std::fs::write( + &script, + concat!( + "track.new {\"count\":1,\"kind\":\"instrument\",\"name\":\"Keys\"}\n", + "midi.new_clip {\"track\":\"Keys\",\"start\":0,\"end\":{\"seconds\":19.2}}\n", + "edit.select {\"start\":0,\"end\":19.2}\n", + ), + ) + .unwrap(); + let out = base.join("out.wav"); + let o = run(&["script", script.to_str().unwrap(), "--bounce", out.to_str().unwrap()]); + assert!(o.status.success(), "{}", String::from_utf8_lossy(&o.stderr)); + let stdout = String::from_utf8_lossy(&o.stdout).into_owned(); + let last: Value = serde_json::from_str(stdout.lines().last().unwrap()).unwrap(); + let secs = last["seconds"].as_f64().unwrap(); + assert!((secs - 19.2).abs() < 0.01, "bounced {secs} s: {stdout}"); + let _ = std::fs::remove_dir_all(base); +} From 4110f5ff10b6ddf35e9588ad251e958745d0920d Mon Sep 17 00:00:00 2001 From: Derek Wright Date: Sun, 18 Oct 2026 13:07:27 -0400 Subject: [PATCH 28/52] Mix tests: never load real plug-ins stored_state_comes_first_then_session_params ends with an offline render_range over a vst3: insert. That reached create_plugin and the real VST3 host, which scans the machine's plug-in folders and loads every installed plug-in in-process; some (Native Instruments) hang on unload, so the test binary never exited on a developer machine. CI has no plug-ins installed, so it stayed green. Under cfg(test), create_plugin now returns None for third-party ids, so a test reaching the real hosts sees an absent plug-in instead of hanging. The rule, stated in the tests module doc: tests adopt fakes under clap:test.* ids and never call the real hosts. --- crates/mix/src/lib.rs | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/crates/mix/src/lib.rs b/crates/mix/src/lib.rs index e8c4fbad..c7c2a592 100644 --- a/crates/mix/src/lib.rs +++ b/crates/mix/src/lib.rs @@ -2220,6 +2220,13 @@ pub fn render_track_pre_fader(s: &Session, track: TrackId, range: Range) -> Vec< /// A built-in plugin, else a hosted CLAP plugin (`clap:`). fn create_plugin(id: &str) -> Option> { + // Tests never load real plug-ins; adopt a fake instead. Scanning the machine's plug-in folders + // loads every installed plug-in in-process, and some never unload, so a test that reached the + // real hosts would hang on a developer machine (CI has none installed). + #[cfg(test)] + if is_third_party(id) { + return None; + } soundcraft_dsp::create(id) .or_else(|| soundcraft_clap_host::create(id)) .or_else(|| soundcraft_vst3_host::create(id)) @@ -2272,6 +2279,10 @@ mod audio_thread_tests { #[cfg(test)] mod tests { + //! Rule: tests never call the real plug-in hosts. Third-party ids are not created here + //! (create_plugin returns None under cfg(test)); a test that needs a hosted plug-in + //! adopts a fake under a clap:test.* id via MixEngine::adopt. + use super::*; use soundcraft_audio_io::AudioBuffer; use soundcraft_model::{Insert, SourceAudio, SourceId}; @@ -2832,7 +2843,7 @@ mod tests { s.track_mut(t).unwrap().mixer.inserts[0].as_mut().unwrap().params.insert("gain".into(), -12.0); render_block(&mut eng, &s, 1024); assert_eq!(sets.load(std::sync::atomic::Ordering::Relaxed), 2, "later session edits apply"); - // Offline (not external): unknown third-party plugins are simply absent. + // Offline (not external): third-party plugins are simply absent (tests never load real ones). let out = render_range(&s, Range::new(0, 1024), 512); assert!(out[0][100] > 0.3); } From c09dab9fef0f5c604897554d2ce9de832e2ca3d3 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Mon, 19 Oct 2026 07:20:18 +0000 Subject: [PATCH 29/52] fix: heal split halves of stretched audio clips Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 --- crates/engine/src/edit.rs | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/edit.rs b/crates/engine/src/edit.rs index 5531953d..b7e49e97 100644 --- a/crates/engine/src/edit.rs +++ b/crates/engine/src/edit.rs @@ -405,6 +405,11 @@ pub fn trim_end_to(s: &mut Session, track: TrackId, at: Samples) -> usize { n } +/// Source samples covered by `length` timeline samples of a clip with the given `stretch`. +fn source_len(length: Samples, stretch: f64) -> Samples { + if stretch.is_finite() && stretch > 0.0 && (stretch - 1.0).abs() >= 1e-9 { (length as f64 / stretch).round() as Samples } else { length } +} + /// Heal separations inside `range`: merge neighbouring audio clips that continue the same file. pub fn heal(s: &mut Session, track: TrackId, range: Range) -> usize { let Some(pl) = s.track_mut(track).and_then(|t| t.playlist_mut()) else { return 0 }; @@ -415,7 +420,9 @@ pub fn heal(s: &mut Session, track: TrackId, range: Range) -> usize { if let Some(prev) = out.last_mut() { let contiguous = prev.end() == c.start && c.start >= range.start && c.start <= range.end; let same = match (&prev.content, &c.content) { - (ClipContent::Audio { source: a, offset: oa }, ClipContent::Audio { source: b, offset: ob }) => a == b && oa + prev.length == *ob, + (ClipContent::Audio { source: a, offset: oa }, ClipContent::Audio { source: b, offset: ob }) => { + a == b && oa.saturating_add(source_len(prev.length, prev.stretch)) == *ob + } _ => false, }; if contiguous && same && (prev.gain_db - c.gain_db).abs() < 1e-6 { @@ -878,6 +885,18 @@ mod tests { assert_eq!(clips(&s, t), vec![(1000, 4000, 1000)]); } + #[test] + fn split_then_heal_rejoins_stretched_clip() { + let (mut s, t) = session_with_clip(); + if let Some(c) = s.track_mut(t).and_then(|t| t.playlist_mut()).and_then(|p| p.clips.first_mut()) { + c.stretch = 2.0; + } + assert_eq!(separate_at(&mut s, t, 3000), 1); + assert_eq!(clips(&s, t), vec![(1000, 2000, 1000), (3000, 2000, 2000)]); + assert_eq!(heal(&mut s, t, Range::new(0, 10_000)), 1); + assert_eq!(clips(&s, t), vec![(1000, 4000, 1000)]); + } + #[test] fn clear_slip_and_shuffle() { let (mut s, t) = session_with_clip(); From 3c04a3c36fe841c3e0d4e07f72a6999bcf33289f Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Mon, 19 Oct 2026 11:04:51 +0000 Subject: [PATCH 30/52] Fix empty SMF export re-importing as one phantom empty track Found while testing crates/midi/src/smf.rs:207 Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 --- crates/midi/src/smf.rs | 31 ++++++++++++++++++++++++++++--- 1 file changed, 28 insertions(+), 3 deletions(-) diff --git a/crates/midi/src/smf.rs b/crates/midi/src/smf.rs index 7747a061..3fe84678 100644 --- a/crates/midi/src/smf.rs +++ b/crates/midi/src/smf.rs @@ -204,7 +204,12 @@ pub fn read_smf(bytes: &[u8]) -> Result { tracks.push(track); } - if format == 1 && tracks.len() > 1 && tracks.first().is_some_and(|t| t.sequence.notes.is_empty() && t.sequence.ctrls.is_empty()) { + // A lone track is only a conductor track if it carried global data and has no name; otherwise it is kept. + let globals_present = !(globals.tempos.is_empty() && globals.meters.is_empty() && globals.markers.is_empty() && globals.key_sigs.is_empty()); + if format == 1 + && (tracks.len() > 1 || globals_present) + && tracks.first().is_some_and(|t| t.sequence.notes.is_empty() && t.sequence.ctrls.is_empty() && (tracks.len() > 1 || t.name.is_empty())) + { tracks.remove(0); } @@ -444,7 +449,12 @@ fn write_track(out: &mut Vec, mut events: Vec) -> Result<(), MidiErr /// Errors: invalid tempo (non-finite or <= 0 bpm), meter denominator that is not a power of two /// (1..=128), more than 65535 tracks, or a gap between events beyond the 28-bit delta limit. pub fn write_smf(smf: &Smf) -> Result, MidiError> { - let ntrks = u16::try_from(smf.tracks.len().saturating_add(1)).map_err(|_| MidiError::Write("more than 65535 tracks".into()))?; + // The conductor track is omitted when there is nothing to put in it and no content tracks, so an + // empty `Smf` is written as a file with zero tracks and reads back as zero tracks. + let has_conductor = + !(smf.tempos.is_empty() && smf.meters.is_empty() && smf.key_sigs.is_empty() && smf.markers.is_empty() && smf.tracks.is_empty()); + let ntrks = + u16::try_from(smf.tracks.len().saturating_add(usize::from(has_conductor))).map_err(|_| MidiError::Write("more than 65535 tracks".into()))?; let mut out = Vec::new(); out.extend_from_slice(b"MThd"); out.extend_from_slice(&6u32.to_be_bytes()); @@ -476,7 +486,9 @@ pub fn write_smf(smf: &Smf) -> Result, MidiError> { for (t, text) in &smf.markers { ev.push(WEvent { tick: clamp_tick(*t), order: 3, bytes: meta(0x06, text.as_bytes())? }); } - write_track(&mut out, ev)?; + if has_conductor { + write_track(&mut out, ev)?; + } for track in &smf.tracks { let mut ev = Vec::new(); @@ -527,6 +539,19 @@ mod tests { assert!(push_vlq(&mut Vec::new(), MAX_VLQ + 1).is_err()); } + #[test] + fn empty_smf_round_trips_with_no_tracks() { + let r = read_smf(&write_smf(&Smf::default()).unwrap()).unwrap(); + assert_eq!(r.tracks.len(), 0); + let one = Smf { tracks: vec![SmfTrack::default()], ..Smf::default() }; + let r = read_smf(&write_smf(&one).unwrap()).unwrap(); + assert_eq!(r.tracks.len(), 1); + let cond = Smf { tempos: vec![(0, 90.0)], ..Smf::default() }; + let r = read_smf(&write_smf(&cond).unwrap()).unwrap(); + assert_eq!(r.tracks.len(), 0); + assert_eq!(r.tempos.len(), 1); + } + #[test] fn spec_vlq_examples() { let mut b = Vec::new(); From c8f8fc45eb88d694018b67242d146d6be9a32a8b Mon Sep 17 00:00:00 2001 From: Gert Pellin Date: Wed, 14 Oct 2026 14:55:21 +0200 Subject: [PATCH 31/52] convert: dither only when the output loses resolution (#548) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit soundcraft-cli convert always passed dither: true, so a same-depth or wider conversion still added ±1 LSB TPDF noise and digital silence came out as noise. It now dithers only when writing integer samples that cannot hold the source exactly: fewer bits than the source, a float or lossy source, or samples changed by --rate/--normalize. 32-bit float output never dithers. --dither and --no-dither override the choice, like the Bounce option in #551. --- ROADMAP.md | 1 + apps/soundcraft-cli/src/main.rs | 79 +++++++++++++++++++++-- apps/soundcraft-cli/tests/convert.rs | 95 ++++++++++++++++++++++++++++ 3 files changed, 171 insertions(+), 4 deletions(-) create mode 100644 apps/soundcraft-cli/tests/convert.rs diff --git a/ROADMAP.md b/ROADMAP.md index f214e1e0..3d673d9c 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -126,6 +126,7 @@ mutated and truncated movies. Field reports from the first public week are track - **2026-10-16:** Master fader volume automation uses each render block's actual last sample, matching track faders. Breakpoints in the next block no longer pull the preceding block's level toward them, and ramps reach their last-sample value. Regression tests cover nonzero starts, one-sample callbacks and several block sizes. No readiness percentage change. - **2026-10-16:** Aux, folder and master latency calculations exclude inserts already taken out for producing NaN or infinity, matching audio tracks. Subsequent blocks no longer compensate for an insert that is bypassed after failure. Regression tests check impulse timing, healthy insert latency and reset/retry at 64- and 512-sample blocks. No readiness percentage change. - **2026-10-14:** MCP `batch` rejects more than 1000 calls before executing any command, instead of silently running only the first 1000 (#460). No readiness percentage change. +- **2026-10-14:** `soundcraft-cli convert` dithers only when the output loses resolution (fewer bits than the source, a float or lossy source, or resampled/normalized samples); a same-depth, wider or 32-bit float conversion copies the samples exactly and digital silence stays silent. `--dither` and `--no-dither` override the choice (#548) - **2026-10-13:** WAV: an empty data chunk followed by metadata (LIST, bext) reads as no audio; a recording that was never finalised (sizes left at 0) still gives what was written (#466) - **2026-10-13:** Sampler: a ping-pong loop keeps its phase and direction when a step is wider than the loop (a narrow loop with high transposition), instead of reflecting once and dropping the rest of the travel (#463) - **2026-10-13:** `mix.instrument` takes the built-in instrument's parameters in `params` (validated, clamped) and refuses any other field, so a synth setting written beside `plugin` is an error instead of being accepted and ignored (#265) diff --git a/apps/soundcraft-cli/src/main.rs b/apps/soundcraft-cli/src/main.rs index 9a51cc54..5a6645ca 100644 --- a/apps/soundcraft-cli/src/main.rs +++ b/apps/soundcraft-cli/src/main.rs @@ -2,7 +2,8 @@ //! //! ```text //! soundcraft-cli info FILE audio file or .scraft summary -//! soundcraft-cli convert IN OUT [--bit-depth 16|24|32f] [--rate HZ] [--normalize] +//! soundcraft-cli convert IN OUT [--bit-depth 16|24|32f] [--rate HZ] [--normalize] [--dither | --no-dither] +//! dithers only when the output loses resolution, unless told //! soundcraft-cli run [--in S.scraft | --demo] [--cmd ID[=JSON]]… [--bounce OUT] [--start T --end T] [--save S.scraft] [--inspect] //! soundcraft-cli script FILE [--in S | --demo] [--save S] [--bounce OUT] (one `ID JSON` per line) //! soundcraft-cli commands [FILTER] list commands @@ -130,12 +131,16 @@ fn convert(args: &[String]) -> ExitCode { Ok(b) => b, Err(e) => return fail(e), }; + let dither_flag = match parse_dither(args) { + Ok(d) => d, + Err(e) => return fail(e), + }; let bytes = match std::fs::read(input) { Ok(b) => b, Err(e) => return fail(format!("{input}: {e}")), }; let ext = std::path::Path::new(input).extension().and_then(|x| x.to_str()); - let (_, mut buf) = match soundcraft_audio_io::decode(&bytes, ext) { + let (info, mut buf) = match soundcraft_audio_io::decode(&bytes, ext) { Ok(x) => x, Err(e) => return fail(format!("{input}: {e}")), }; @@ -143,14 +148,17 @@ fn convert(args: &[String]) -> ExitCode { buf.channels = soundcraft_dsp::offline::resample(&buf.channels, buf.sample_rate, rate); buf.sample_rate = rate; } - if args.iter().any(|a| a == "--normalize") { + let normalize = args.iter().any(|a| a == "--normalize"); + if normalize { soundcraft_dsp::offline::normalize(&mut buf.channels, -0.1, false); } + let processed = rate.is_some_and(|r| r != info.sample_rate) || normalize; + let dither = dither_flag.unwrap_or_else(|| auto_dither(info.sample_format, bit_depth, processed)); let out_ext = std::path::Path::new(output).extension().and_then(|x| x.to_str()).unwrap_or("wav").to_ascii_lowercase(); let Some(format) = soundcraft_audio_io::encode_format_for(&out_ext) else { return fail(format!("{output}: cannot write `.{out_ext}` files (supported: {})", soundcraft_audio_io::ENCODE_EXTENSIONS)); }; - let opts = soundcraft_audio_io::EncodeOptions { format, bit_depth, dither: true, bwf: None }; + let opts = soundcraft_audio_io::EncodeOptions { format, bit_depth, dither, bwf: None }; match soundcraft_audio_io::encode(&buf, &opts).map_err(|e| e.to_string()).and_then(|b| std::fs::write(output, b).map_err(|e| e.to_string())) { Ok(()) => { outln!("wrote {output} ({} ch, {} Hz, {:.2} s)", buf.num_channels(), buf.sample_rate, buf.duration_secs()); @@ -179,6 +187,41 @@ fn parse_bit_depth(v: Option<&str>) -> Result Result, String> { + match (args.iter().any(|a| a == "--dither"), args.iter().any(|a| a == "--no-dither")) { + (true, true) => Err("--dither and --no-dither: choose one".into()), + (true, false) => Ok(Some(true)), + (false, true) => Ok(Some(false)), + (false, false) => Ok(None), + } +} + +/// Whether `convert` dithers when not told: only when writing integer samples that cannot hold the +/// source exactly, i.e. the output has fewer bits than the source, the source is float or lossy, or +/// resampling/normalizing produced new sample values. A 16-bit file written as 16 or 24-bit, or +/// anything written as 32-bit float, is copied sample for sample (digital silence stays silent). +fn auto_dither(source: soundcraft_audio_io::SampleFormat, target: soundcraft_audio_io::BitDepth, processed: bool) -> bool { + use soundcraft_audio_io::{BitDepth, SampleFormat}; + let target_bits = match target { + BitDepth::Float32 => return false, + BitDepth::Int16 => 16, + BitDepth::Int24 => 24, + BitDepth::Int32 => 32, + }; + if processed { + return true; + } + match source { + SampleFormat::Int8 => target_bits < 8, + SampleFormat::Int16 => target_bits < 16, + SampleFormat::Int24 => target_bits < 24, + // Decoded through f32, which holds 24 bits: a 32-bit integer source has already lost + // resolution, so treat it like float. + SampleFormat::Int32 | SampleFormat::Float32 | SampleFormat::Float64 | SampleFormat::Compressed => true, + } +} + /// One stderr line per media file a session refers to but could not load (the exit code is unchanged). fn missing_warnings(missing: &[String]) -> Vec { missing.iter().map(|m| format!("warning: missing media: {m}")).collect() @@ -511,6 +554,34 @@ mod tests { assert!(parse_bit_depth(Some("8")).is_err()); } + #[test] + fn convert_dither_flags() { + let args = |a: &[&str]| a.iter().map(|s| s.to_string()).collect::>(); + assert_eq!(parse_dither(&args(&["in.wav", "out.wav"])), Ok(None)); + assert_eq!(parse_dither(&args(&["in.wav", "out.wav", "--dither"])), Ok(Some(true))); + assert_eq!(parse_dither(&args(&["in.wav", "out.wav", "--no-dither"])), Ok(Some(false))); + assert!(parse_dither(&args(&["in.wav", "out.wav", "--dither", "--no-dither"])).is_err()); + } + + #[test] + fn convert_dithers_only_when_resolution_is_lost() { + use soundcraft_audio_io::{BitDepth, SampleFormat}; + // Same depth or wider: the samples fit exactly. + assert!(!auto_dither(SampleFormat::Int16, BitDepth::Int16, false)); + assert!(!auto_dither(SampleFormat::Int16, BitDepth::Int24, false)); + assert!(!auto_dither(SampleFormat::Int24, BitDepth::Int24, false)); + assert!(!auto_dither(SampleFormat::Int8, BitDepth::Int16, false)); + // Float output never dithers. + assert!(!auto_dither(SampleFormat::Float32, BitDepth::Float32, true)); + assert!(!auto_dither(SampleFormat::Int24, BitDepth::Float32, false)); + // Fewer bits, a float or lossy source, or processed samples: dither. + assert!(auto_dither(SampleFormat::Int24, BitDepth::Int16, false)); + assert!(auto_dither(SampleFormat::Float32, BitDepth::Int24, false)); + assert!(auto_dither(SampleFormat::Compressed, BitDepth::Int16, false)); + assert!(auto_dither(SampleFormat::Int32, BitDepth::Int24, false)); + assert!(auto_dither(SampleFormat::Int16, BitDepth::Int16, true)); + } + #[test] fn missing_media_gets_one_warning_each() { assert!(missing_warnings(&[]).is_empty()); diff --git a/apps/soundcraft-cli/tests/convert.rs b/apps/soundcraft-cli/tests/convert.rs new file mode 100644 index 00000000..eb62ac77 --- /dev/null +++ b/apps/soundcraft-cli/tests/convert.rs @@ -0,0 +1,95 @@ +//! `soundcraft-cli convert` dithers only when the output loses resolution (#548), run as the real binary. +// Integration tests: unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md). +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::path::{Path, PathBuf}; +use std::process::Command; + +use soundcraft_audio_io::{AudioBuffer, BitDepth, EncodeOptions, FileFormat}; + +fn tmpdir(tag: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("sc-cli-convert-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +/// A 16-bit mono WAV of `samples`, written without dither so the file holds exactly these values. +fn write_wav16(path: &Path, samples: &[i16]) { + let mut buf = AudioBuffer::new(48_000, 1, samples.len()); + for (d, s) in buf.channels[0].iter_mut().zip(samples) { + *d = f32::from(*s) / 32768.0; + } + let opts = EncodeOptions { format: FileFormat::Wav, bit_depth: BitDepth::Int16, dither: false, bwf: None }; + std::fs::write(path, soundcraft_audio_io::encode(&buf, &opts).unwrap()).unwrap(); +} + +fn convert(input: &Path, output: &Path, extra: &[&str]) { + let o = Command::new(env!("CARGO_BIN_EXE_soundcraft-cli")) + .env("SOUNDCRAFT_NO_PREFS", "1") + .arg("convert") + .arg(input) + .arg(output) + .args(extra) + .output() + .unwrap(); + assert!(o.status.success(), "{}", String::from_utf8_lossy(&o.stderr)); +} + +/// The decoded samples of `path`, scaled to 16-bit steps. +fn steps16(path: &Path) -> Vec { + let (_, buf) = soundcraft_audio_io::decode(&std::fs::read(path).unwrap(), None).unwrap(); + buf.channels[0].iter().map(|s| f64::from(*s) * 32768.0).collect() +} + +#[test] +fn convert_copies_samples_when_nothing_is_lost() { + let dir = tmpdir("exact"); + let (silence, tone) = (dir.join("silence.wav"), dir.join("tone.wav")); + let tone_samples: Vec = (0..4800).map(|i| (8000.0 * (f64::from(i) * 0.05).sin()) as i16).collect(); + write_wav16(&silence, &[0; 4800]); + write_wav16(&tone, &tone_samples); + let want: Vec = tone_samples.iter().map(|s| f64::from(*s)).collect(); + + // Same depth, wider and float: every sample comes back unchanged, silence stays silent. + for (depth, name) in [("16", "s16.wav"), ("24", "s24.wav"), ("32f", "s32.wav")] { + let out = dir.join(name); + convert(&silence, &out, &["--bit-depth", depth]); + assert!(steps16(&out).iter().all(|s| *s == 0.0), "silence at {depth} is not silent"); + let out = dir.join(format!("t{name}")); + convert(&tone, &out, &["--bit-depth", depth]); + assert_eq!(steps16(&out), want, "tone at {depth} changed"); + } + // The default output depth (24-bit) too. + let out = dir.join("default.wav"); + convert(&tone, &out, &[]); + assert_eq!(steps16(&out), want); + + // Asked for, dither is still applied. + let out = dir.join("forced.wav"); + convert(&silence, &out, &["--bit-depth", "16", "--dither"]); + assert!(steps16(&out).iter().any(|s| *s != 0.0), "--dither did not dither"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn convert_dithers_when_reducing_depth_unless_told_not_to() { + let dir = tmpdir("reduce"); + let src = dir.join("src24.wav"); + // A 24-bit file with detail below one 16-bit step. + let mut buf = AudioBuffer::new(48_000, 1, 4800); + for (i, s) in buf.channels[0].iter_mut().enumerate() { + *s = 0.3 / 32768.0 * (i as f32 * 0.01).sin(); + } + let opts = EncodeOptions { format: FileFormat::Wav, bit_depth: BitDepth::Int24, dither: false, bwf: None }; + std::fs::write(&src, soundcraft_audio_io::encode(&buf, &opts).unwrap()).unwrap(); + + let dithered = dir.join("d16.wav"); + convert(&src, &dithered, &["--bit-depth", "16"]); + assert!(steps16(&dithered).iter().any(|s| *s != 0.0), "24 to 16-bit was not dithered"); + // Plain rounding: everything is below half a step, so it all rounds to zero. + let plain = dir.join("p16.wav"); + convert(&src, &plain, &["--bit-depth", "16", "--no-dither"]); + assert!(steps16(&plain).iter().all(|s| *s == 0.0), "--no-dither still dithered"); + let _ = std::fs::remove_dir_all(&dir); +} From 82616dcfb800d2cb8f768281dfcb380bdbbb47f9 Mon Sep 17 00:00:00 2001 From: Limestudio90 Date: Mon, 19 Oct 2026 18:01:38 +0200 Subject: [PATCH 32/52] vst3-host: restore "crate" in the ffi module doc Co-Authored-By: Claude Opus 5.5 --- crates/vst3-host/src/ffi.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/vst3-host/src/ffi.rs b/crates/vst3-host/src/ffi.rs index 0e7acdc2..8b20e4ef 100644 --- a/crates/vst3-host/src/ffi.rs +++ b/crates/vst3-host/src/ffi.rs @@ -1,4 +1,4 @@ -//! The FFI boundary: the only module of this rate allowed to use `unsafe`. +//! The FFI boundary: the only module of this crate allowed to use `unsafe`. //! //! It loads VST3 binaries (`libloading`), runs the platform module entry, calls the COM //! interfaces of the factory, component, audio processor and edit controller (`vst3` raw From 4eee6b17a82b95bf34eb6506cd0ab2b22c207868 Mon Sep 17 00:00:00 2001 From: Matthew Burlage Date: Mon, 19 Oct 2026 12:58:35 -0400 Subject: [PATCH 33/52] Preserve finite Float32 headroom during audio encoding --- ROADMAP.md | 4 +- contributors/people.toml | 3 + crates/audio-io/src/lib.rs | 1 + crates/audio-io/src/pcm.rs | 16 ++-- crates/audio-io/tests/float_headroom.rs | 101 ++++++++++++++++++++++++ crates/audio-io/tests/roundtrip.rs | 4 +- crates/engine/tests/bounce.rs | 52 ++++++++++++ docs/file-format-parity.md | 7 +- docs/gaps.md | 5 +- 9 files changed, 181 insertions(+), 12 deletions(-) create mode 100644 crates/audio-io/tests/float_headroom.rs diff --git a/ROADMAP.md b/ROADMAP.md index f214e1e0..e9534ba1 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: pre-alpha** · next: alpha, ~5% and ~110–180 h away (the alpha gate's three failing workflows) -> **Last reviewed:** 2026-10-18 · **Last updated:** 2026-10-18 · **Change:** trivial (mono device playback fold-down) · **Target:** Avid Pro Tools Ultimate 2026.4.1 +> **Last reviewed:** 2026-10-19 · **Last updated:** 2026-10-19 · **Change:** trivial (Float32 file headroom) · **Target:** Avid Pro Tools Ultimate 2026.4.1 SoundCraft is a clean-room, pure-Rust digital audio workstation that aims at full parity with Avid Pro Tools, and then beyond it: faster, open, scriptable and agent-controllable. This page is @@ -122,6 +122,7 @@ mutated and truncated movies. Field reports from the first public week are track ## Progress log +- **2026-10-19:** Float32 WAV and AIFF-C encoding preserve finite samples above full scale. Integer PCM still clips at full scale. Tests cover whole-file and streaming encoders, non-finite samples, and bounce output with normalization on and off. No readiness percentage change. - **2026-10-18:** Mono audio devices receive the average of the stereo channels before output clipping, retaining right-only audio. Surround mixes use the same average after their ITU stereo fold-down. Regression tests cover channel balance, polarity cancellation, clipping, centered mono tracks, each 5.1 channel and several callback sizes. No readiness percentage change. - **2026-10-16:** Master fader volume automation uses each render block's actual last sample, matching track faders. Breakpoints in the next block no longer pull the preceding block's level toward them, and ramps reach their last-sample value. Regression tests cover nonzero starts, one-sample callbacks and several block sizes. No readiness percentage change. - **2026-10-16:** Aux, folder and master latency calculations exclude inserts already taken out for producing NaN or infinity, matching audio tracks. Subsequent blocks no longer compensate for an insert that is bypassed after failure. Regression tests check impulse timing, healthy insert latency and reset/retry at 64- and 512-sample blocks. No readiness percentage change. @@ -161,6 +162,7 @@ mutated and truncated movies. Field reports from the first public week are track | Date | Change | Summary | |---|---|---| +| 2026-10-19 | trivial | Float32 file encoding preserves finite headroom (#791); readiness estimates unchanged | | 2026-10-18 | trivial | Mono device playback retains both stereo sides and surround fold-down channels; readiness estimates unchanged | | 2026-10-16 | trivial | Master volume automation block boundaries corrected; readiness estimates unchanged | | 2026-10-16 | trivial | Failed inserts no longer contribute aux, folder or master latency after containment; readiness estimates unchanged | diff --git a/contributors/people.toml b/contributors/people.toml index 7799757f..8ce926b2 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -55,3 +55,6 @@ sync_github_name = true real_name = "Marco Arnulfo" display_name = "Marco Arnulfo" sync_github_name = false + +[people.mattburlage] +display_name = "Matt Smith-Burlage" diff --git a/crates/audio-io/src/lib.rs b/crates/audio-io/src/lib.rs index 4a871946..3fc7372c 100644 --- a/crates/audio-io/src/lib.rs +++ b/crates/audio-io/src/lib.rs @@ -115,6 +115,7 @@ pub enum BitDepth { Int16, Int24, Int32, + /// Preserve finite samples, including values above full scale; map NaN to 0 and infinities to ±1. Float32, } diff --git a/crates/audio-io/src/pcm.rs b/crates/audio-io/src/pcm.rs index 35c761aa..eaa9ca73 100644 --- a/crates/audio-io/src/pcm.rs +++ b/crates/audio-io/src/pcm.rs @@ -193,8 +193,8 @@ pub(crate) fn write_interleaved( for (c, q) in quantizers.iter_mut().enumerate() { let s = block.get(c).and_then(|ch| ch.get(f)).copied().unwrap_or(0.0); match (is_float, big_endian) { - (true, false) => scratch.extend_from_slice(&clamp_float(s).to_le_bytes()), - (true, true) => scratch.extend_from_slice(&clamp_float(s).to_be_bytes()), + (true, false) => scratch.extend_from_slice(&sanitize_float(s).to_le_bytes()), + (true, true) => scratch.extend_from_slice(&sanitize_float(s).to_be_bytes()), (false, false) => scratch.extend_from_slice(q.quantize(s).to_le_bytes().get(..size).unwrap_or_default()), (false, true) => scratch.extend_from_slice(q.quantize(s).to_be_bytes().get(4 - size..).unwrap_or_default()), } @@ -206,9 +206,15 @@ pub(crate) fn write_interleaved( Ok(()) } -/// Clamp a float sample to [-1, 1], mapping NaN to 0. -pub(crate) fn clamp_float(x: f32) -> f32 { - if x.is_nan() { 0.0 } else { x.clamp(-1.0, 1.0) } +/// Preserve finite float samples, mapping NaN to 0 and infinities to their sign (±1). +fn sanitize_float(x: f32) -> f32 { + if x.is_finite() { + x + } else if x.is_nan() { + 0.0 + } else { + x.signum() + } } /// Check that a buffer is encodable: at least one channel and a non-zero sample rate. diff --git a/crates/audio-io/tests/float_headroom.rs b/crates/audio-io/tests/float_headroom.rs new file mode 100644 index 00000000..d1fc5283 --- /dev/null +++ b/crates/audio-io/tests/float_headroom.rs @@ -0,0 +1,101 @@ +use soundcraft_audio_io::{AudioBuffer, BitDepth, EncodeOptions, FileEncoder, FileFormat, SampleFormat, decode, encode}; +use std::io::Cursor; + +fn encoded(audio: &AudioBuffer, options: &EncodeOptions, streaming: bool) -> Vec { + if !streaming { + return encode(audio, options).unwrap(); + } + let mut writer = FileEncoder::new(Cursor::new(Vec::new()), options, audio.num_channels(), audio.sample_rate, None).unwrap(); + // Cross the writer's 4096-frame scratch boundary, then write a short final block. + for start in (0..audio.frames()).step_by(4097) { + let end = (start + 4097).min(audio.frames()); + let block: Vec> = audio.channels.iter().map(|channel| channel[start..end].to_vec()).collect(); + writer.write(&block, end - start).unwrap(); + } + writer.finish().unwrap().into_inner() +} + +fn assert_float_headroom(streaming: bool) { + let samples = [ + -f32::MAX, + -2.0, + -1.25, + -1.0, + -0.5, + -f32::MIN_POSITIVE, + -f32::from_bits(1), + -0.0, + 0.0, + f32::from_bits(1), + f32::MIN_POSITIVE, + 0.5, + 1.0, + 1.25, + 2.0, + f32::MAX, + ]; + for format in [FileFormat::Wav, FileFormat::Aiff] { + for dither in [false, true] { + for channels in [1, 2] { + let audio = AudioBuffer { + sample_rate: 48_000, + channels: (0..channels).map(|c| samples.iter().copied().cycle().skip(c).take(4103).collect()).collect(), + }; + let options = EncodeOptions { format, bit_depth: BitDepth::Float32, dither, bwf: None }; + let bytes = encoded(&audio, &options, streaming); + let pcm: Vec = + audio.interleaved().iter().flat_map(|v| if format == FileFormat::Wav { v.to_le_bytes() } else { v.to_be_bytes() }).collect(); + assert!(bytes.ends_with(&pcm), "{format:?}, dither={dither}: stored sample bytes changed"); + let (info, decoded) = decode(&bytes, None).unwrap(); + assert_eq!(info.sample_format, SampleFormat::Float32); + assert_eq!((decoded.sample_rate, decoded.num_channels(), decoded.frames()), (48_000, channels, 4103)); + for (channel, (actual, expected)) in decoded.channels.iter().zip(&audio.channels).enumerate() { + for (frame, (actual, expected)) in actual.iter().zip(expected).enumerate() { + assert_eq!(actual.to_bits(), expected.to_bits(), "{format:?}, dither={dither}, channel={channel}, frame={frame}"); + } + } + } + } + } +} + +#[test] +fn whole_file_float32_preserves_finite_headroom() { + assert_float_headroom(false); +} + +#[test] +fn streaming_float32_preserves_finite_headroom() { + assert_float_headroom(true); +} + +#[test] +fn float32_keeps_non_finite_sample_handling() { + let audio = AudioBuffer { sample_rate: 48_000, channels: vec![vec![f32::NAN, f32::NEG_INFINITY, f32::INFINITY]] }; + let expected = [0.0_f32, -1.0, 1.0]; + for format in [FileFormat::Wav, FileFormat::Aiff] { + for streaming in [false, true] { + let options = EncodeOptions { format, bit_depth: BitDepth::Float32, dither: false, bwf: None }; + let bytes = encoded(&audio, &options, streaming); + // Inspect stored samples too: the decoder itself replaces non-finite values. + let pcm: Vec = expected.iter().flat_map(|v| if format == FileFormat::Wav { v.to_le_bytes() } else { v.to_be_bytes() }).collect(); + assert!(bytes.ends_with(&pcm), "{format:?}, streaming={streaming}"); + assert_eq!(decode(&bytes, None).unwrap().1.channels[0], expected); + } + } +} + +#[test] +fn integer_pcm_still_clips_at_full_scale() { + let audio = AudioBuffer { sample_rate: 48_000, channels: vec![vec![-2.0, -1.25, -1.0, -0.5, 0.0, 0.5, 1.0, 1.25, 2.0]] }; + for (depth, max) in [(BitDepth::Int16, 32767.0 / 32768.0), (BitDepth::Int24, 8_388_607.0 / 8_388_608.0), (BitDepth::Int32, 1.0)] { + for format in [FileFormat::Wav, FileFormat::Aiff, FileFormat::Flac] { + for streaming in [false, true] { + let options = EncodeOptions { format, bit_depth: depth, dither: false, bwf: None }; + let bytes = encoded(&audio, &options, streaming); + let (_, decoded) = decode(&bytes, None).unwrap(); + assert_eq!(decoded.channels[0], [-1.0, -1.0, -1.0, -0.5, 0.0, 0.5, max, max, max], "{format:?} {depth:?}, streaming={streaming}"); + } + } + } +} diff --git a/crates/audio-io/tests/roundtrip.rs b/crates/audio-io/tests/roundtrip.rs index 867bb84e..70042966 100644 --- a/crates/audio-io/tests/roundtrip.rs +++ b/crates/audio-io/tests/roundtrip.rs @@ -205,7 +205,7 @@ fn encode_rejects_bad_buffers_and_formats() { for f in [FileFormat::Mp3, FileFormat::Ogg, FileFormat::Aac, FileFormat::Alac, FileFormat::Caf, FileFormat::Other] { assert!(encode(&sine(48_000, 1, 10), &EncodeOptions { format: f, ..EncodeOptions::default() }).is_err()); } - // Non-finite and out-of-range samples are clamped, not errors. + // Non-finite samples are sanitized; only integer output clips finite samples. let mut b = AudioBuffer::new(48_000, 1, 4); b.channels[0] = vec![f32::NAN, f32::INFINITY, -5.0, 0.5]; for format in [FileFormat::Wav, FileFormat::Aiff, FileFormat::Flac] { @@ -217,7 +217,7 @@ fn encode_rejects_bad_buffers_and_formats() { let (_, out) = decode(&bytes, None).unwrap(); assert_eq!(out.channels[0][0], 0.0); assert!(out.channels[0][1] > 0.99 && out.channels[0][1] <= 1.0); - assert_eq!(out.channels[0][2], -1.0); + assert_eq!(out.channels[0][2], if depth == BitDepth::Float32 { -5.0 } else { -1.0 }); } } // Ragged buffers encode the common length. diff --git a/crates/engine/tests/bounce.rs b/crates/engine/tests/bounce.rs index ea4cf127..688be40d 100644 --- a/crates/engine/tests/bounce.rs +++ b/crates/engine/tests/bounce.rs @@ -5,6 +5,58 @@ use soundcraft_engine::io::{Bounce, bounce_stems}; use soundcraft_time::Range; use std::path::PathBuf; +#[test] +fn float_bounce_preserves_headroom_and_reports_the_written_levels() { + let mut e = soundcraft_engine::Engine::default(); + let sr = e.session().sample_rate.hz(); + let frames = sr as usize + 17; + let samples: Vec = (0..frames).map(|i| 1.5 * (std::f32::consts::TAU * 440.0 * i as f32 / sr as f32).sin()).collect(); + let audio = soundcraft_audio_io::AudioBuffer { sample_rate: sr, channels: vec![samples.clone(), samples] }; + let s = e.session_mut(); + // A new track has no inserts, so no limiter can mask encoder clipping. + let track = s.add_track(soundcraft_model::TrackKind::Audio, soundcraft_model::ChannelFormat::Stereo, Some("Headroom")); + let source = soundcraft_engine::io::add_source(s, "headroom", audio, None, FileFormat::Wav); + let clip = soundcraft_model::Clip::audio(s.new_clip_id(), "headroom", source, 0, 0, frames as i64); + soundcraft_engine::edit::place_clip(s, track, clip); + let mix = soundcraft_mix::render_range(e.session(), Range::new(0, frames as i64), 1024); + assert!(soundcraft_dsp::offline::peak(&mix) > 1.0); + let dir = scratch("bounce-float-headroom"); + for extension in ["wav", "aiff"] { + for normalize in [false, true] { + let path = dir.join(format!("Mix.{extension}")); + let result = e + .execute( + "file.bounce_mix", + &serde_json::json!({ + "path": path, "bit_depth": "32f", "dither": false, "normalize": normalize, + "start": 0, "end": frames, + }), + ) + .unwrap(); + let bytes = std::fs::read(&path).unwrap(); + let (_, file) = soundcraft_audio_io::decode(&bytes, None).unwrap(); + let mut expected = mix.clone(); + if normalize { + soundcraft_dsp::offline::normalize(&mut expected, -0.1, false); + assert!(file.peak() < 1.0); + } else { + assert!(file.peak() > 1.0, "{extension}: headroom was clipped"); + } + assert_eq!(file.channels, expected, "{extension}, normalize={normalize}"); + let mut meter = soundcraft_dsp::meter::LoudnessMeter::new(sr as f32, file.num_channels()); + meter.process(&file.channels, file.frames()); + for (key, value) in [ + ("peak_db", soundcraft_dsp::offline::peak_db(&file.channels)), + ("lufs", meter.integrated_lufs()), + ("true_peak_db", meter.true_peak_db()), + ] { + assert_eq!(result[key].as_f64(), Some(f64::from(value)), "{extension}, normalize={normalize}, {key}"); + } + } + } + let _ = std::fs::remove_dir_all(&dir); +} + fn scratch(name: &str) -> PathBuf { let dir = std::env::temp_dir().join(format!("soundcraft-{name}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 2c322c83..924546d8 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File-format parity -> **Last reviewed:** 2026-10-13 · **Last updated:** 2026-10-13 · **Change:** trivial (WAV: empty data chunk with trailing metadata (#466); previously minor: continuous fade curvature in SoundCraft sessions) · **Target:** Avid Pro Tools Ultimate 2026.4.1 +> **Last reviewed:** 2026-10-19 · **Last updated:** 2026-10-19 · **Change:** trivial (Float32 file headroom, #791) · **Target:** Avid Pro Tools Ultimate 2026.4.1 Every format Pro Tools reads or writes, and ours. The Pro Tools list comes from the document types its bundle declares (`CFBundleDocumentTypes` in Info.plist: names only, nothing else read) and its @@ -33,10 +33,10 @@ Legend: ✅ supported and tested · 🟡 partial · ❌ missing · — not appli | Format | Pro Tools | Read | Write | Tests / notes | |---|---|---|---|---| -| WAV / BWF (PCM 16/24/32, float 32), `bext` | native | ✅ | ✅ | Native reader/writer, TPDF dither option; also 8-bit and float 64 read. An empty data chunk followed by metadata reads as no audio; an unfinalised recording's audio is still read (#466). | +| WAV / BWF (PCM 16/24/32, float 32), `bext` | native | ✅ | ✅ | Native reader/writer, TPDF dither option; Float32 retains finite headroom (#791); also 8-bit and float 64 read. An empty data chunk followed by metadata reads as no audio; an unfinalised recording's audio is still read (#466). | | RF64 / BW64 (> 4 GiB) | read/write | ✅ | ✅ | `encode_wav_rf64` | | WAV `WAVE_FORMAT_EXTENSIBLE` multichannel with channel mask | read/write | ✅ | ✅ | `encode_with_channel_mask`; default 5.1 import creates a stereo track (#89, PR #128) | -| AIFF / AIFF-C | native | ✅ | ✅ (`fl32`) | Native | +| AIFF / AIFF-C | native | ✅ | ✅ (`fl32`) | Native; `fl32` retains finite headroom (#791) | | FLAC | import | ✅ | ✅ | Own encoder | | MP3 | import, bounce | ✅ (symphonia) | ❌ | G-21 | | AAC / M4A / MP4 audio | import, bounce | ✅ (symphonia) | ❌ | G-21 | @@ -80,6 +80,7 @@ Legend: ✅ supported and tested · 🟡 partial · ❌ missing · — not appli | Date | Change | Summary | |---|---|---| +| 2026-10-19 | trivial | WAV and AIFF-C Float32 encoders retain finite headroom (#791); whole-file, streaming and bounce regression tests | | 2026-10-13 | trivial | WAV: empty data chunk with trailing metadata (#466) | | 2026-10-13 | minor | Fade curvature round-trips in sessions with a zero default for older files. Format version and readiness estimate unchanged | | 2026-10-10 | major | Created: format inventory against Pro Tools 2026.4.1's declared document types and import/bounce options | diff --git a/docs/gaps.md b/docs/gaps.md index 3601a2a4..1b7c074e 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Where SoundCraft falls short of Pro Tools -> **Last reviewed:** 2026-10-18 · **Last updated:** 2026-10-18 · **Change:** trivial (G-04: mono device playback fold-down) · **Target:** Avid Pro Tools Ultimate 2026.4.1 +> **Last reviewed:** 2026-10-19 · **Last updated:** 2026-10-19 · **Change:** trivial (G-04: Float32 file headroom) · **Target:** Avid Pro Tools Ultimate 2026.4.1 Every known shortfall, one entry each, ranked by how much it stops a Pro Tools user from doing real work in SoundCraft. This is the work list: pick from the top. Rows marked **alpha blocker** @@ -80,6 +80,8 @@ When you close a gap, delete its entry (or shrink it) in the same PR, and bump t ### G-04. Correctness bugs in "done" features +**Fixed (2026-10-19, #791):** Float32 WAV and AIFF-C encoding retain finite samples above full scale. Whole-file and streaming tests cover both formats, integer clipping, and the existing NaN/infinity behavior. A bounce regression checks preserved headroom and file/report agreement with normalization off, then checks normalized output. + **Fixed (2026-10-18):** Mono device playback averages the stereo channels before output clipping, **Fixed (2026-10-16):** Master fader volume automation uses the first and last samples of each **Fixed (2026-10-16):** Aux, folder and master latency calculations now skip inserts already @@ -214,6 +216,7 @@ missing. Out of scope unless the owner decides otherwise. | Date | Change | Summary | |---|---|---| +| 2026-10-19 | trivial | G-04: Float32 encoding retains finite headroom (#791); integer clipping and non-finite handling retained | | 2026-10-18 | trivial | G-04: mono device stereo/surround fold-down fixed and regression-tested; estimates unchanged | | 2026-10-16 | trivial | G-04: master volume automation block boundaries fixed and regression-tested; estimates unchanged | | 2026-10-16 | trivial | G-04: failed aux/folder/master inserts excluded from latency compensation after containment; estimates unchanged | From b5bcf577b213fd6844bbf6f60e771a60f058adc1 Mon Sep 17 00:00:00 2001 From: MarekSpodBiedry <73122968+MarekSpodBiedry@users.noreply.github.com> Date: Mon, 19 Oct 2026 22:27:44 +0200 Subject: [PATCH 34/52] Fix saved audio trust test on Windows by joining path parts separately (#789) --- crates/engine/src/io.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/io.rs b/crates/engine/src/io.rs index eff105ec..bc60fd03 100644 --- a/crates/engine/src/io.rs +++ b/crates/engine/src/io.rs @@ -1710,7 +1710,7 @@ mod save_tests { let mut r = Engine::default(); assert_eq!( open_session(&mut r, &path("B/Moved.scraft")).unwrap(), - vec![dir.join("A").join("Audio Files/Audio 1_02.wav").display().to_string()] + vec![dir.join("A").join("Audio Files").join("Audio 1_02.wav").display().to_string()] ); let _ = std::fs::remove_dir_all(&dir); } From 24fa4668ef968b78ae0c902fa104ee4dbdcab783 Mon Sep 17 00:00:00 2001 From: lucasegen <281051305+lucasegen@users.noreply.github.com> Date: Tue, 20 Oct 2026 11:37:35 +0200 Subject: [PATCH 35/52] Name F12 in the Record button's tooltip The tooltip only offered Cmd+Space, which macOS gives to Spotlight unless the user frees it, so on a stock Mac the advertised shortcut opens Spotlight. F12 already records (shortcuts.rs), as on the incumbent; the tooltip now names it first. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/toolbar.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 41d83ac4..0dd217b6 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -338,7 +338,8 @@ fn transport(app: &mut SoundApp, ui: &mut Ui) { let (r, resp) = ui.allocate_exact_size(vec2(38.0, 28.0), Sense::click()); key(ui.painter(), r, &resp, if recording { Color32::from_rgb(110, 30, 30) } else { key_fill(&resp) }); icons::draw(ui.painter(), r.shrink(5.0), "record", t.rec); - let resp = resp.on_hover_text("Record (Cmd+Space)"); + // macOS gives Cmd+Space to Spotlight unless the user frees it, so name F12 first. + let resp = resp.on_hover_text("Record (F12 or Cmd+Space)"); if let Some(why) = app.record_hint() { // Below the whole group, so the hint covers none of its buttons. let below = Rect::from_min_max(r.min, pos2(r.max.x, g.max.y)); From 1f72dc30be7fac44b874ee1b60fca2ccf5a6c7fa Mon Sep 17 00:00:00 2001 From: lucasegen <281051305+lucasegen@users.noreply.github.com> Date: Sat, 24 Oct 2026 00:29:51 +0200 Subject: [PATCH 36/52] Import registry in au-host's macOS api module #988 replaced `use super::*;` in the macOS `api` module with an explicit list that leaves `registry` out, so soundcraft-au-host, and with it the app, no longer builds on macOS: four E0433 errors. Linux CI compiles this module out, so it stayed green. Co-Authored-By: Claude Opus 5.5 --- crates/au-host/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/au-host/src/lib.rs b/crates/au-host/src/lib.rs index 3a664a4d..7aa3b2eb 100644 --- a/crates/au-host/src/lib.rs +++ b/crates/au-host/src/lib.rs @@ -192,7 +192,7 @@ pub enum AuError { #[cfg(target_os = "macos")] mod api { - use super::{AuDescriptor, AuError, Plugin, PluginInfo}; + use super::{AuDescriptor, AuError, Plugin, PluginInfo, registry}; pub fn scan() -> Vec { registry::scan() From c2da4cf912bb6bf13163194308164931c7d0da6f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 23 Oct 2026 21:41:04 -0700 Subject: [PATCH 37/52] Add a built-in Ring Modulator plugin The built-in plugins had no ring modulator, and AudioSuite > Modulation > Sci-Fi ran the Flanger instead. Ring Modulator (`ring_mod`, Modulation category, also offline as AudioSuite) has four effects: Ring multiplies the input by a sine carrier, Frequency Mod reads the input through a delay the carrier swings by 1 ms, and Resonator + and Resonator - feed the output back after one period of the frequency with a positive or a negative sign. At full depth an LFO or sample and hold moves the frequency by up to two octaves either way, and an envelope follower raises it by up to two octaves. AudioSuite > Modulation > Sci-Fi now opens it. The Total row in docs/plugin-parity.md now counts 25 processors and 3 instruments, the entries in the built-in registry. --- README.md | 10 +- ROADMAP.md | 4 +- crates/dsp/src/plugins/mod.rs | 2 + crates/dsp/src/plugins/modulation.rs | 222 ++++++++++++++++++++++++++- crates/dsp/tests/it/plugins.rs | 92 +++++++++++ crates/ui-egui/src/menus.rs | 11 +- docs/plugin-parity.md | 7 +- 7 files changed, 336 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index c31fc87a..3699d23a 100644 --- a/README.md +++ b/README.md @@ -122,11 +122,11 @@ where things are. - **Automation:** volume, pan, mute, send and every plugin parameter; Write, Touch, Latch and Trim passes recorded live from the faders; thin, glide, coalesce and convert to clip gain. - **Plugins:** 7-band and 1-band EQ, compressor/limiter, expander/gate, de-esser, maximizer, - channel strip, room and plate reverbs, mod delay, chorus, flanger, phaser, saturator, lo-fi, - rectifier, pitch shifter, time shift, gain, trim, invert, DC removal, signal generator, dither, - a subtractive synth, a drum synth and a sampler (plays any WAV, AIFF, FLAC, MP3 or OGG across the - keyboard), all original. **CLAP plugins** load too. Any processor - runs offline as AudioSuite, and user presets save per plugin. + channel strip, room and plate reverbs, mod delay, chorus, flanger, phaser, ring modulator, + saturator, lo-fi, rectifier, pitch shifter, time shift, gain, trim, invert, DC removal, + signal generator, dither, a subtractive synth, a drum synth and a sampler (plays any WAV, + AIFF, FLAC, MP3 or OGG across the keyboard), all original. **CLAP plugins** load too. Any + processor runs offline as AudioSuite, and user presets save per plugin. - **MIDI:** instrument and MIDI tracks, a piano-roll MIDI editor with a velocity lane, an event list, a score view, step input, quantize, transpose, real-time properties, Standard MIDI Files, and Audio-to-MIDI from a sung or played melody. diff --git a/ROADMAP.md b/ROADMAP.md index f214e1e0..a6da72f6 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: pre-alpha** · next: alpha, ~5% and ~110–180 h away (the alpha gate's three failing workflows) -> **Last reviewed:** 2026-10-18 · **Last updated:** 2026-10-18 · **Change:** trivial (mono device playback fold-down) · **Target:** Avid Pro Tools Ultimate 2026.4.1 +> **Last reviewed:** 2026-10-18 · **Last updated:** 2026-10-23 · **Change:** trivial (Ring Modulator plugin) · **Target:** Avid Pro Tools Ultimate 2026.4.1 SoundCraft is a clean-room, pure-Rust digital audio workstation that aims at full parity with Avid Pro Tools, and then beyond it: faster, open, scriptable and agent-controllable. This page is @@ -122,6 +122,7 @@ mutated and truncated movies. Field reports from the first public week are track ## Progress log +- **2026-10-23:** A built-in Ring Modulator (`ring_mod`) applies ring modulation, frequency modulation or a positive or negative resonator, and an LFO, an envelope follower or sample and hold moves its frequency. AudioSuite › Modulation › Sci-Fi now runs it instead of the Flanger. No readiness percentage change. - **2026-10-18:** Mono audio devices receive the average of the stereo channels before output clipping, retaining right-only audio. Surround mixes use the same average after their ITU stereo fold-down. Regression tests cover channel balance, polarity cancellation, clipping, centered mono tracks, each 5.1 channel and several callback sizes. No readiness percentage change. - **2026-10-16:** Master fader volume automation uses each render block's actual last sample, matching track faders. Breakpoints in the next block no longer pull the preceding block's level toward them, and ramps reach their last-sample value. Regression tests cover nonzero starts, one-sample callbacks and several block sizes. No readiness percentage change. - **2026-10-16:** Aux, folder and master latency calculations exclude inserts already taken out for producing NaN or infinity, matching audio tracks. Subsequent blocks no longer compensate for an insert that is bypassed after failure. Regression tests check impulse timing, healthy insert latency and reset/retry at 64- and 512-sample blocks. No readiness percentage change. @@ -161,6 +162,7 @@ mutated and truncated movies. Field reports from the first public week are track | Date | Change | Summary | |---|---|---| +| 2026-10-23 | trivial | Progress log: Ring Modulator plugin; readiness estimates unchanged | | 2026-10-18 | trivial | Mono device playback retains both stereo sides and surround fold-down channels; readiness estimates unchanged | | 2026-10-16 | trivial | Master volume automation block boundaries corrected; readiness estimates unchanged | | 2026-10-16 | trivial | Failed inserts no longer contribute aux, folder or master latency after containment; readiness estimates unchanged | diff --git a/crates/dsp/src/plugins/mod.rs b/crates/dsp/src/plugins/mod.rs index aef3e39d..97d672e9 100644 --- a/crates/dsp/src/plugins/mod.rs +++ b/crates/dsp/src/plugins/mod.rs @@ -29,6 +29,7 @@ pub(crate) static REGISTRY: &[&PluginInfo] = &[ &modulation::CHORUS_INFO, &modulation::FLANGER_INFO, &modulation::PHASER_INFO, + &modulation::RING_INFO, &harmonic::SAT_INFO, &harmonic::LOFI_INFO, &harmonic::RECT_INFO, @@ -61,6 +62,7 @@ pub(crate) fn instantiate(id: &str) -> Option> { "chorus" => Box::new(modulation::ModFx::chorus()), "flanger" => Box::new(modulation::ModFx::flanger()), "phaser" => Box::new(modulation::Phaser::new()), + "ring_mod" => Box::new(modulation::RingMod::new()), "saturator" => Box::new(harmonic::Saturator::new()), "lofi" => Box::new(harmonic::LoFi::new()), "rectifier" => Box::new(harmonic::Rectifier::new()), diff --git a/crates/dsp/src/plugins/modulation.rs b/crates/dsp/src/plugins/modulation.rs index 962f57de..80d48cc1 100644 --- a/crates/dsp/src/plugins/modulation.rs +++ b/crates/dsp/src/plugins/modulation.rs @@ -1,7 +1,7 @@ -//! Delay and modulation effects: Mod Delay, Chorus, Flanger, Phaser. +//! Delay and modulation effects: Mod Delay, Chorus, Flanger, Phaser, Ring Modulator. use crate::params::{Params, choice, lin, log, param_plumbing}; -use crate::util::{DelayLine, Lfo, Smoother, flush, frames_in, ms_to_samples, sane_channels, sane_sr}; +use crate::util::{DelayLine, Lfo, Rng, Smoother, flush, frames_in, ms_to_samples, sane_channels, sane_sr, time_coef}; use crate::{Category, ParamInfo, Plugin, PluginInfo, Unit}; /// Per-channel LFO phase offset for stereo movement (channel 1 is offset by `spread` cycles). @@ -459,3 +459,221 @@ impl Plugin for Phaser { ms_to_samples(100.0, self.sr) as usize } } + +// --------------------------------------------------------------------------------------------- + +const RING_EFFECTS: &[&str] = &["Ring", "Frequency Mod", "Resonator +", "Resonator -"]; +const RING_SOURCES: &[&str] = &["LFO", "Envelope", "Sample & Hold"]; +const RING_MIN_HZ: f32 = 20.0; +/// Octaves the frequency moves at full modulation depth. +const RING_MOD_OCTAVES: f32 = 2.0; +/// Peak delay swing of Frequency Mod. +const RING_FM_SWING_MS: f32 = 1.0; +/// Sample-and-hold noise seed (the same sequence after every reset). +const RING_SEED: u32 = 0x5EED_1234; + +static RING_PARAMS: [ParamInfo; 7] = [ + choice("effect", "Effect", RING_EFFECTS, 0), + log("frequency", "Frequency", RING_MIN_HZ, 5000.0, 440.0, Unit::Hz), + lin("resonance", "Resonance", 0.0, 95.0, 50.0, Unit::Percent), + choice("mod_source", "Mod Source", RING_SOURCES, 0), + log("mod_rate", "Mod Rate", 0.05, 20.0, 1.0, Unit::Hz), + lin("mod_depth", "Mod Depth", 0.0, 100.0, 0.0, Unit::Percent), + lin("mix", "Mix", 0.0, 100.0, 100.0, Unit::Percent), +]; + +pub static RING_INFO: PluginInfo = PluginInfo { + id: "ring_mod", + name: "Ring Modulator", + short_name: "RingMod", + category: Category::Modulation, + params: &RING_PARAMS, + is_instrument: false, + audiosuite: true, +}; + +/// Ring modulation, frequency modulation and positive or negative comb resonators, with the +/// frequency moved by an LFO, an envelope follower or a sample-and-hold source. +/// +/// - Ring multiplies the input by a sine carrier at the frequency. +/// - Frequency Mod reads the input through a delay that the carrier swings by ±1 ms. +/// - Resonator + and Resonator - feed the output back after one period of the frequency, with +/// a positive or a negative sign. The output is scaled by `1 - resonance`, so the peak gain at +/// resonance is unity. +/// +/// At 100 % depth the modulation moves the frequency by up to two octaves either way. The +/// envelope follower moves it up only. +pub struct RingMod { + p: Params, + sr: f32, + lines: Vec, + lfo: Lfo, + rng: Rng, + carrier: f32, + env: f32, + env_attack: f32, + env_release: f32, + held: f32, + hold_left: usize, + last_effect: usize, + freq: Smoother, + res: Smoother, + depth: Smoother, + mix: Smoother, +} + +impl Default for RingMod { + fn default() -> Self { + Self::new() + } +} + +impl RingMod { + pub fn new() -> Self { + let mut r = Self { + p: Params::new(&RING_PARAMS), + sr: 48_000.0, + lines: Vec::new(), + lfo: Lfo::new(), + rng: Rng::new(RING_SEED), + carrier: 0.0, + env: 0.0, + env_attack: 0.0, + env_release: 0.0, + held: 0.0, + hold_left: 0, + last_effect: 0, + freq: Smoother::new(440.0), + res: Smoother::new(0.0), + depth: Smoother::new(0.0), + mix: Smoother::new(1.0), + }; + r.update(); + r + } + + fn update(&mut self) { + self.freq.set(self.p.v(1)); + self.res.set(self.p.v(2) / 100.0); + self.depth.set(self.p.v(5) / 100.0); + self.mix.set(self.p.v(6) / 100.0); + } + + /// Samples in one period of the lowest frequency the modulation can reach. + fn longest_period(&self) -> f32 { + self.sr / (self.p.v(1) * 2f32.powf(-RING_MOD_OCTAVES * self.p.v(5) / 100.0)).max(1.0) + } +} + +impl Plugin for RingMod { + param_plumbing!(RING_INFO); + + fn prepare(&mut self, sample_rate: f32, _max_block: usize, channels: usize) { + self.sr = sane_sr(sample_rate); + let comb = self.sr / (RING_MIN_HZ * 2f32.powf(-RING_MOD_OCTAVES)); + let max = comb.max(ms_to_samples(2.0 * RING_FM_SWING_MS, self.sr)) as usize + 8; + self.lines = (0..sane_channels(channels)) + .map(|_| { + let mut d = DelayLine::default(); + d.allocate(max); + d + }) + .collect(); + self.env_attack = time_coef(5.0, self.sr); + self.env_release = time_coef(100.0, self.sr); + for s in [&mut self.freq, &mut self.res, &mut self.depth, &mut self.mix] { + s.set_time(20.0, self.sr); + } + self.update(); + self.reset(); + } + + fn reset(&mut self) { + self.lines.iter_mut().for_each(DelayLine::clear); + self.lfo.reset(); + self.rng = Rng::new(RING_SEED); + self.carrier = 0.0; + self.env = 0.0; + self.held = 0.0; + self.hold_left = 0; + self.last_effect = self.p.choice(0); + for s in [&mut self.freq, &mut self.res, &mut self.depth, &mut self.mix] { + s.snap(); + } + } + + fn process(&mut self, io: &mut [Vec], frames: usize) { + let ch = self.lines.len().min(io.len()); + let frames = frames_in(io, frames, ch); + let effect = self.p.choice(0); + if effect != self.last_effect { + // The lines hold the previous effect's state. + self.lines.iter_mut().for_each(DelayLine::clear); + self.last_effect = effect; + } + let source = self.p.choice(3); + let rate = self.p.v(4); + let inc = rate / self.sr; + let hold = ((self.sr / rate.max(0.05)) as usize).max(1); + let nyq = self.sr * 0.45; + let swing = ms_to_samples(RING_FM_SWING_MS, self.sr); + for n in 0..frames { + let level = io.iter().take(ch).filter_map(|b| b.get(n)).filter(|x| x.is_finite()).fold(0.0f32, |m, x| m.max(x.abs())); + let k = if level > self.env { self.env_attack } else { self.env_release }; + self.env = flush(level + (self.env - level) * k); + let lfo = Lfo::sin_at(self.lfo.tick(inc)); + let m = match source { + 1 => self.env.min(1.0), + 2 => { + if self.hold_left == 0 { + self.held = self.rng.bipolar(); + self.hold_left = hold; + } + self.hold_left -= 1; + self.held + } + _ => lfo, + }; + let f = (self.freq.next() * 2f32.powf(RING_MOD_OCTAVES * self.depth.next() * m)).clamp(1.0, nyq); + let fb = self.res.next(); + let mix = self.mix.next(); + self.carrier += f / self.sr; + if self.carrier >= 1.0 { + self.carrier -= 1.0; + } + let carrier = Lfo::sin_at(self.carrier); + for c in 0..ch { + let (Some(buf), Some(line)) = (io.get_mut(c), self.lines.get_mut(c)) else { continue }; + let Some(x) = buf.get_mut(n) else { continue }; + let dry = if x.is_finite() { *x } else { 0.0 }; + let wet = match effect { + 1 => { + line.push(dry); + line.read_cubic(2.0 + swing * (1.0 + carrier)) + } + 2 | 3 => { + let sign = if effect == 2 { 1.0 } else { -1.0 }; + let y = flush(dry + sign * fb * line.read_cubic(self.sr / f)); + line.push(y); + y * (1.0 - fb) + } + _ => dry * carrier, + }; + *x = dry * (1.0 - mix) + wet * mix; + } + } + } + + fn tail_samples(&self) -> usize { + match self.p.choice(0) { + 1 => ms_to_samples(2.0 * RING_FM_SWING_MS, self.sr) as usize + 4, + 2 | 3 => { + // Time for the feedback to fall by 60 dB at the longest period the modulation reaches. + let fb = (self.p.v(2) / 100.0).clamp(0.0, 0.99); + let repeats = if fb < 1e-3 { 1.0 } else { (-60.0 / (20.0 * fb.log10())).min(500.0) + 1.0 }; + (self.longest_period() * repeats) as usize + } + _ => 0, + } + } +} diff --git a/crates/dsp/tests/it/plugins.rs b/crates/dsp/tests/it/plugins.rs index ad55d838..ceb68c09 100644 --- a/crates/dsp/tests/it/plugins.rs +++ b/crates/dsp/tests/it/plugins.rs @@ -524,3 +524,95 @@ fn lofi_quantizes() { levels.dedup(); assert!(levels.len() <= 5, "{levels:?}"); } + +fn ring_mod(params: &[(&str, f32)]) -> Box { + let mut p = prepared("ring_mod"); + for &(id, v) in params { + assert!(p.set_param(id, v), "ring_mod.{id}"); + } + p.reset(); + p +} + +/// Loudest bin within two bins of `hz` in an 8192-point spectrum. +fn band_db(spec: &[f32], hz: f32) -> f32 { + let bin = (hz / (SR / 8192.0)).round() as usize; + spec[bin - 2..=bin + 2].iter().cloned().fold(f32::MIN, f32::max) +} + +fn zero_crossings(x: &[f32]) -> usize { + x.windows(2).filter(|w| (w[0] < 0.0) != (w[1] < 0.0)).count() +} + +#[test] +fn ring_mod_makes_sum_and_difference_tones() { + let mut p = ring_mod(&[("effect", 0.0), ("frequency", 300.0), ("mod_depth", 0.0), ("mix", 100.0)]); + let out = run(p.as_mut(), &[sine(1000.0, 0.5, 48_000)]); + let spec = soundcraft_dsp::spectrum::magnitude_db(&out[0][8192..], 8192); + let (low, high, input) = (band_db(&spec, 700.0), band_db(&spec, 1300.0), band_db(&spec, 1000.0)); + // The two tones fall at different places between bins, so their bin peaks differ a little. + assert!((low - high).abs() < 2.0, "700 Hz {low} dB, 1300 Hz {high} dB"); + assert!(low - input > 40.0, "the 1000 Hz input is left at {input} dB against {low} dB"); +} + +#[test] +fn ring_mod_frequency_mod_adds_sidebands() { + let x = sine(1000.0, 0.5, 48_000); + let dry = soundcraft_dsp::spectrum::magnitude_db(&x[8192..], 8192); + assert!(band_db(&dry, 1000.0) - band_db(&dry, 1200.0) > 40.0); + let mut p = ring_mod(&[("effect", 1.0), ("frequency", 200.0), ("mix", 100.0)]); + let out = run(p.as_mut(), &[x]); + let spec = soundcraft_dsp::spectrum::magnitude_db(&out[0][8192..], 8192); + for hz in [800.0, 1200.0] { + assert!(band_db(&spec, 1000.0) - band_db(&spec, hz) < 20.0, "no sideband at {hz} Hz"); + } +} + +#[test] +fn ring_mod_resonators_ring_at_the_frequency_with_their_sign() { + // 480 Hz at 48 kHz is a 100-sample period. + for (effect, sign) in [(2.0, 1.0), (3.0, -1.0)] { + let mut p = ring_mod(&[("effect", effect), ("frequency", 480.0), ("resonance", 90.0), ("mix", 100.0)]); + let mut x = vec![0.0f32; 9600]; + x[0] = 1.0; + let out = run(p.as_mut(), &[x]); + let y = &out[0]; + assert!((y[0] - 0.1).abs() < 1e-4, "effect {effect}: direct {}", y[0]); + assert!((y[100] - sign * 0.09).abs() < 1e-4, "effect {effect}: first echo {}", y[100]); + assert!((y[200] - 0.081).abs() < 1e-4, "effect {effect}: second echo {}", y[200]); + assert!(y[50].abs() < 1e-6 && y[150].abs() < 1e-6, "effect {effect}: sound between the echoes"); + let last = y.iter().rposition(|v| v.abs() > 0.1e-3).unwrap(); + assert!(last < p.tail_samples(), "effect {effect}: ringing at {last}, tail {}", p.tail_samples()); + } +} + +#[test] +fn ring_mod_modulation_sources_move_the_frequency() { + // A constant input through Ring gives the carrier itself. + let dc = vec![1.0f32; 48_000]; + + // The envelope of a full-scale input lifts 100 Hz by one octave at 50 % depth. + let mut p = ring_mod(&[("effect", 0.0), ("frequency", 100.0), ("mod_source", 1.0), ("mod_depth", 50.0), ("mix", 100.0)]); + let out = run(p.as_mut(), std::slice::from_ref(&dc)); + let n = zero_crossings(&out[0][24_000..]); + assert!((195..=205).contains(&n), "envelope: {n} crossings in 0.5 s, 200 expected for 200 Hz"); + + // A 1 Hz LFO raises the frequency for its first half cycle and lowers it for the second. + let mut p = ring_mod(&[("effect", 0.0), ("frequency", 100.0), ("mod_source", 0.0), ("mod_rate", 1.0), ("mod_depth", 100.0), ("mix", 100.0)]); + let out = run(p.as_mut(), std::slice::from_ref(&dc)); + let (up, down) = (zero_crossings(&out[0][..12_000]), zero_crossings(&out[0][24_000..36_000])); + assert!(up > 3 * down, "LFO: {up} crossings rising, {down} falling"); + + // Sample and hold at 4 Hz keeps one frequency for each 12,000-sample step. + let mut p = ring_mod(&[("effect", 0.0), ("frequency", 100.0), ("mod_source", 2.0), ("mod_rate", 4.0), ("mod_depth", 100.0), ("mix", 100.0)]); + let out = run(p.as_mut(), std::slice::from_ref(&dc)); + let mut steps = Vec::new(); + for s in out[0].chunks(12_000) { + let (a, b) = (zero_crossings(&s[..6000]), zero_crossings(&s[6000..])); + assert!(a.abs_diff(b) <= 2, "sample and hold changed within a step: {a} then {b}"); + steps.push(a); + } + steps.sort_unstable(); + steps.dedup_by(|a, b| a.abs_diff(*b) <= 2); + assert!(steps.len() >= 3, "sample and hold steps: {steps:?}"); +} diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 9ba795ca..66d444d3 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -130,7 +130,7 @@ pub const AUDIOSUITE: &[(&str, &str)] = &[ ("AudioSuite > Pitch Shift > Vari-Fi", "varispeed"), ("AudioSuite > Reverb > D-Verb", "room_reverb"), ("AudioSuite > Delay > Mod Delay III", "mod_delay"), - ("AudioSuite > Modulation > Sci-Fi", "flanger"), + ("AudioSuite > Modulation > Sci-Fi", "ring_mod"), ("AudioSuite > Harmonic > Eleven Lite", "saturator"), ("AudioSuite > Harmonic > Lo-Fi", "lofi"), ("AudioSuite > Harmonic > Recti-Fi", "rectifier"), @@ -757,4 +757,13 @@ mod tests { e.execute("edit.select", &json!({"tracks": [audio, inst]})).unwrap(); assert_eq!(instrument_track(e.session()).map(|t| t.0), Some(inst)); } + + #[test] + fn audiosuite_sci_fi_opens_the_ring_modulator() { + let mut app = SoundApp::new(soundcraft_engine::Engine::default(), None, Services::default()); + invoke_menu(&mut app, "audiosuite.process", "AudioSuite > Modulation > Sci-Fi"); + assert_eq!(app.ui.audiosuite.as_deref(), Some("ring_mod")); + let info = soundcraft_dsp::plugin_info("ring_mod").unwrap(); + assert!(info.audiosuite && info.category == soundcraft_dsp::Category::Modulation); + } } diff --git a/docs/plugin-parity.md b/docs/plugin-parity.md index 6aa796b5..c055a15a 100644 --- a/docs/plugin-parity.md +++ b/docs/plugin-parity.md @@ -1,6 +1,6 @@ # Plugin parity: built-in processors and plugin hosting -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-13 · **Change:** trivial (Sampler ping-pong loop phase (#463); previously trivial: mix.instrument sets built-in instrument parameters in params (#265); previously minor: plugin editors on Windows) · **Target:** Avid Pro Tools Ultimate 2026.4.1 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-23 · **Change:** trivial (Ring Modulator; previously trivial: Sampler ping-pong loop phase (#463); previously minor: plugin editors on Windows) · **Target:** Avid Pro Tools Ultimate 2026.4.1 Pro Tools users live in plugins: the bundled set covers everyday mixing, and third-party plugins cover the rest. This doc tracks both. Our plugins have our own names and are written from @@ -17,12 +17,12 @@ scratch (clean-room rule): Avid plugin names are not used here, only categories. | Dynamics | compressor/limiter, expander/gate, de-esser, maximizer, vintage compressors, multiband | `compressor`, `expander_gate`, `de_esser`, `maximizer` | Vintage/opto models, multiband, sidechain input (no key input anywhere) | | Reverb | algorithmic room/plate/hall; convolution (paid tier) | `room_reverb`, `plate_reverb` | Hall/chamber, convolution, early-reflection editor | | Delay | modulated delay, tape/analog delays | `mod_delay` | Tape, ping-pong, multi-tap, tempo-sync depth | -| Modulation | chorus, flanger, phaser, tremolo, ring/frequency shift | `chorus`, `flanger`, `phaser` | Tremolo, auto-pan, ring modulation | +| Modulation | chorus, flanger, phaser, tremolo, ring/frequency shift | `chorus`, `flanger`, `phaser`, `ring_mod` (ring, frequency modulation, positive and negative resonators; LFO, envelope or sample-and-hold modulation) | Tremolo, auto-pan, frequency shift | | Harmonic | lo-fi, rectifier, amp simulation, saturation, tape | `lofi`, `rectifier`, `saturator` | Amp and cabinet models, tape | | Pitch and time | pitch shift, varispeed effects, time shift | `pitch_shifter`, `time_shift` | Formant control, varispeed effect, pitch correction | | Utility | trim, gain, invert, DC offset, signal generator, dither, time adjuster | `trim`, `gain`, `invert`, `dc_offset_removal`, `signal_generator`, `dither` | Time adjuster, meter/analyzer plugins, noise shaping options | | Instruments | several virtual instruments (multi-sampler, piano, drum machine, organ, synths, sample player; Massive X Player added in 2026.4) | `subtractive_synth`, `drum_synth`; `mix.instrument` takes the instrument's parameters in `params` and refuses unknown fields (#265). The sampler's ping-pong loop keeps its phase when a step is wider than the loop (#463). | Sampler (PR #108 open), piano, organ, wavetable, content library | -| **Total** | **≈ 80 processors and instruments** (estimate from Avid's bundle documentation) | **26 processors + 2 instruments** | | +| **Total** | **≈ 80 processors and instruments** (estimate from Avid's bundle documentation) | **25 processors + 3 instruments** | | AudioSuite: every catalog AudioSuite leaf maps to one of our processes (`AUDIOSUITE` in `crates/ui-egui/src/menus.rs`), so the AudioSuite menu is 100 % present. Depth: no preview, @@ -58,6 +58,7 @@ User report #152: a saved instrument level does not reach the bounce. | Date | Change | Summary | |---|---|---| +| 2026-10-23 | trivial | Modulation: Ring Modulator (`ring_mod`), also used by the AudioSuite Modulation menu | | 2026-10-13 | trivial | Sampler ping-pong loop phase (#463) | | 2026-10-13 | trivial | mix.instrument sets built-in instrument parameters in params (#265) | | 2026-10-12 | minor | Editors: VST3 and embedded CLAP editors on Windows | From 6c03d7e8deae8c3c30f4ed2509ccbe1ea4b206c5 Mon Sep 17 00:00:00 2001 From: SusieeTheLinuxUser <96988330+SusieeTheLinuxUser@users.noreply.github.com> Date: Sat, 24 Oct 2026 06:30:31 +0200 Subject: [PATCH 38/52] Tracks: clip track and group names to their rows in the side lists (fixes #990) Co-Authored-By: GLM-5.3-Flash --- crates/ui-egui/src/panels.rs | 10 +++- crates/ui-egui/tests/it/main.rs | 1 + crates/ui-egui/tests/it/side_lists_text.rs | 57 ++++++++++++++++++++++ 3 files changed, 66 insertions(+), 2 deletions(-) create mode 100644 crates/ui-egui/tests/it/side_lists_text.rs diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 5522e4cf..778af47b 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -77,7 +77,13 @@ pub fn tracks_and_groups(app: &mut SoundApp, ui: &mut Ui) { let _ = app.run("track.hide", json!({"tracks": [id], "hidden": shown})); } ui.painter().rect_filled(Rect::from_min_size(pos2(r.min.x + 20.0, r.min.y + 3.0), vec2(4.0, 11.0)), 0.0, rgb(color)); - ui.painter().text(pos2(r.min.x + 30.0, r.center().y), Align2::LEFT_CENTER, &name, regular(11.5), if shown { t.text } else { t.text_dim }); + ui.painter().with_clip_rect(r).text( + pos2(r.min.x + 30.0, r.center().y), + Align2::LEFT_CENTER, + &name, + regular(11.5), + if shown { t.text } else { t.text_dim }, + ); if resp.clicked() { crate::edit_window::click_track(app, soundcraft_model::TrackId(id), ui.input(|i| i.modifiers), |_, _| true); } @@ -118,7 +124,7 @@ pub fn tracks_and_groups(app: &mut SoundApp, ui: &mut Ui) { bold(10.0), if active { t.text_dark } else { t.text_dim }, ); - ui.painter().text(pos2(r.min.x + 30.0, r.center().y), Align2::LEFT_CENTER, &name, regular(11.5), t.text); + ui.painter().with_clip_rect(r).text(pos2(r.min.x + 30.0, r.center().y), Align2::LEFT_CENTER, &name, regular(11.5), t.text); if resp.clicked() { let _ = app.run("track.group_toggle", json!({"group": id})); } diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index eb09a58b..df71ff82 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -43,6 +43,7 @@ mod send_window; mod shared_controls; mod shortcuts; mod side_lists_access; +mod side_lists_text; mod toolbar_scroll; mod toolbar_tempo; mod track_height; diff --git a/crates/ui-egui/tests/it/side_lists_text.rs b/crates/ui-egui/tests/it/side_lists_text.rs new file mode 100644 index 00000000..a99929a8 --- /dev/null +++ b/crates/ui-egui/tests/it/side_lists_text.rs @@ -0,0 +1,57 @@ +//! #990: track and group names in the side lists are clipped to their row, so a long name cannot +//! paint across the scrollbar gutter and over the panel's edge. + +use egui::{Shape, vec2}; +use egui_kittest::{Harness, kittest::Queryable}; +use serde_json::json; +use soundcraft_ui_egui::{Services, SoundApp}; + +fn harness() -> Harness<'static, SoundApp> { + let mut app = SoundApp::new(soundcraft_engine::demo::demo_engine(), None, Services::default()); + let first = app.engine.session().tracks.first().map(|t| t.id.0).unwrap_or_default(); + app.run("track.rename", json!({"track": first, "name": LONG_TRACK})).unwrap(); + app.run("track.group", json!({"name": LONG_GROUP, "tracks": [first]})).unwrap(); + app.engine.session_mut().edit.selected_tracks.clear(); + let mut h = Harness::builder().with_size(vec2(1600.0, 1000.0)).build_ui_state( + |ui, app: &mut SoundApp| { + let ctx = ui.ctx().clone(); + app.logic(&ctx); + app.ui(ui); + }, + app, + ); + h.run_steps(3); + h +} + +const LONG_TRACK: &str = "24H2026_27_JANVIER_SESSION_AUDIO_BED_A"; +const LONG_GROUP: &str = "Rhythm section drums bass and percussion group"; + +/// The name's paint must not be clipped any further right than its row: a wider clip lets the text +/// run over the lists' scrollbar gutter and across the panel's edge. Only the paint inside the row +/// counts — the name is drawn in its own clipped column in the edit window's headers, too. +fn name_is_clipped_to_its_row(h: &Harness<'_, SoundApp>, name: &str) { + let row = h.get_by_label(name).rect(); + let painted = h.output().shapes.iter().filter_map(|s| match &s.shape { + Shape::Text(t) if t.galley.text().contains(name) && s.clip_rect.intersects(row) => Some(s.clip_rect), + _ => None, + }); + let mut count = 0; + for clip in painted { + count += 1; + assert!(clip.right() <= row.right() + 0.5, "the name's paint is clipped at x {}, past its row's right edge {}", clip.right(), row.right()); + } + assert!(count > 0, "no painted text found for {name:?}"); +} + +#[test] +fn a_long_track_name_stays_inside_its_row() { + let h = harness(); + name_is_clipped_to_its_row(&h, LONG_TRACK); +} + +#[test] +fn a_long_group_name_stays_inside_its_row() { + let h = harness(); + name_is_clipped_to_its_row(&h, LONG_GROUP); +} From 2adec7f1287dee3944810cee89b14fb4c4c2dd88 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 24 Oct 2026 06:16:40 +0000 Subject: [PATCH 39/52] Integration: #509 accept the Ambisonic WAVEX subtype GUIDs as PCM/float --- crates/audio-io/src/wav.rs | 4 +++- crates/audio-io/tests/it/malformed.rs | 4 ++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/crates/audio-io/src/wav.rs b/crates/audio-io/src/wav.rs index 32f86ab4..f7979404 100644 --- a/crates/audio-io/src/wav.rs +++ b/crates/audio-io/src/wav.rs @@ -10,6 +10,8 @@ const WAVE_FORMAT_IEEE_FLOAT: u16 = 3; const WAVE_FORMAT_EXTENSIBLE: u16 = 0xFFFE; /// Tail of the KSDATAFORMAT_SUBTYPE_* GUIDs (bytes 2..16); bytes 0..2 hold the format tag. const GUID_TAIL: [u8; 14] = [0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71]; +/// Tail of the Ambisonic subtype GUIDs {0000000x-0721-11D3-8644-C8C1CA000000}: PCM (x = 1) and float (x = 3) as well. +const AMBISONIC_TAIL: [u8; 14] = [0x00, 0x00, 0x21, 0x07, 0xD3, 0x11, 0x86, 0x44, 0xC8, 0xC1, 0xCA, 0x00, 0x00, 0x00]; const BEXT_MIN_LEN: usize = 602; /// Parsed WAV layout (no sample data decoded yet). @@ -67,7 +69,7 @@ fn parse_fmt(c: &[u8]) -> Result { } // A subtype outside the KSDATAFORMAT_SUBTYPE_* family is not PCM/float, whatever its first two bytes say: // keep the extensible tag so the file goes to the foreign decoder. - if tail == GUID_TAIL { + if tail == GUID_TAIL || tail == AMBISONIC_TAIL { fmt.tag = sub; } } diff --git a/crates/audio-io/tests/it/malformed.rs b/crates/audio-io/tests/it/malformed.rs index d09ad8ba..ec862f66 100644 --- a/crates/audio-io/tests/it/malformed.rs +++ b/crates/audio-io/tests/it/malformed.rs @@ -544,4 +544,8 @@ fn extensible_fmt_is_checked_in_full() { foreign[15] ^= 0xFF; let foreign = riff(&[(b"fmt ", extensible_fmt(22, 16, &foreign)), (b"data", data)]); assert!(!matches!(probe(&foreign, None), Ok(i) if i.sample_format == SampleFormat::Int16)); + // The Ambisonic PCM subtype is PCM. + let ambi = [1, 0, 0, 0, 0x21, 0x07, 0xD3, 0x11, 0x86, 0x44, 0xC8, 0xC1, 0xCA, 0, 0, 0]; + let ambi = riff(&[(b"fmt ", extensible_fmt(22, 16, &ambi)), (b"data", vec![0u8; 8])]); + assert_eq!(probe(&ambi, None).unwrap().sample_format, SampleFormat::Int16); } From 9719f955a4ac3b56130af79f60bfda65a6176682 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 24 Oct 2026 06:17:33 +0000 Subject: [PATCH 40/52] Integration: #552 allow --dither and --no-dither in convert's options --- apps/soundcraft-cli/src/main.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/soundcraft-cli/src/main.rs b/apps/soundcraft-cli/src/main.rs index 276333c8..2c22b689 100644 --- a/apps/soundcraft-cli/src/main.rs +++ b/apps/soundcraft-cli/src/main.rs @@ -173,7 +173,7 @@ fn info(args: &[String]) -> ExitCode { fn convert(args: &[String]) -> ExitCode { let (Some(input), Some(output)) = (args.first(), args.get(1)) else { return fail("convert IN OUT") }; - const OPTIONS: &Options = &[("--rate", true), ("--bit-depth", true), ("--normalize", false)]; + const OPTIONS: &Options = &[("--rate", true), ("--bit-depth", true), ("--normalize", false), ("--dither", false), ("--no-dither", false)]; if let Err(e) = check_options(&args[2..], OPTIONS) { return fail(e); } From 678cb0f57d298ba1bbfec26eaa7003d506d81909 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 24 Oct 2026 06:18:49 +0000 Subject: [PATCH 41/52] Integration: #517 join_gain_env places the right envelope at the seam when heal bridges a gap --- crates/engine/src/edit.rs | 28 ++++++++++++++++++++++++---- 1 file changed, 24 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/edit.rs b/crates/engine/src/edit.rs index 4b8dac8b..4e8b2532 100644 --- a/crates/engine/src/edit.rs +++ b/crates/engine/src/edit.rs @@ -441,14 +441,17 @@ pub fn heal(s: &mut Session, track: TrackId, range: Range) -> usize { healed } -/// Give `l` the gain envelope of `l` followed by `r`, which starts where `l` ends, so every sample keeps its gain. +/// Give `l` the gain envelope of `l` followed by `r`, which starts at or after where `l` ends, so +/// every sample keeps its gain. Call it before `l.length` grows to cover `r`. fn join_gain_env(l: &mut Clip, r: &Clip) { let cut = l.length; - let (end_db, start_db) = (l.env_db_at(cut - 1), r.env_db_at(0)); + let seam = r.start.saturating_sub(l.start); + let last = cut.saturating_sub(1); + let (end_db, start_db) = (l.env_db_at(last), r.env_db_at(0)); l.gain_env.retain(|&(at, _)| at < cut); - l.gain_env.extend(r.gain_env.iter().filter(|&&(at, _)| at >= 0).map(|&(at, db)| (at.saturating_add(cut), db))); + l.gain_env.extend(r.gain_env.iter().filter(|&&(at, _)| at >= 0).map(|&(at, db)| (at.saturating_add(seam), db))); // Pin both sides of the seam where the joined points would interpolate across it. - for (at, db) in [(cut, start_db), (cut - 1, end_db)] { + for (at, db) in [(seam, start_db), (last, end_db)] { if (l.env_db_at(at) - db).abs() > 1e-4 { let i = l.gain_env.partition_point(|&(t, _)| t < at); l.gain_env.insert(i, (at, db)); @@ -990,6 +993,23 @@ mod tests { } } + #[test] + fn heal_keeps_gain_envelopes_across_a_gap() { + let (mut s, t) = session_with_clip(); + clear_range(&mut s, t, Range::new(2000, 3000), false); + let pl = s.track_mut(t).and_then(|t| t.playlist_mut()).unwrap(); + pl.clips[0].gain_env = vec![(0, 0.0), (999, -6.0)]; + pl.clips[1].gain_env = vec![(0, -12.0), (1999, -3.0)]; + let (l, r) = (pl.clips[0].clone(), pl.clips[1].clone()); + assert_eq!(heal(&mut s, t, Range::new(1500, 3500)), 1); + let healed = &s.track(t).unwrap().clips()[0]; + assert_eq!(healed.length, 4000); + for rel in (0..1000).chain(2000..4000) { + let want = if rel < 1000 { l.gain_at(rel) } else { r.gain_at(rel - 2000) }; + assert!((healed.gain_at(rel) - want).abs() < 1e-4, "sample {rel}: {} != {want}", healed.gain_at(rel)); + } + } + #[test] fn clear_slip_and_shuffle() { let (mut s, t) = session_with_clip(); From 045938728f5597112ae9ea2218083650e0b4c9af Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 24 Oct 2026 06:19:09 +0000 Subject: [PATCH 42/52] Integration: #674 advance the source offset by delta/stretch on start trims and compare heal offsets in source time --- crates/engine/src/edit.rs | 2 +- crates/model/src/clip.rs | 12 ++++++++++-- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/edit.rs b/crates/engine/src/edit.rs index 9863ab2c..698a6624 100644 --- a/crates/engine/src/edit.rs +++ b/crates/engine/src/edit.rs @@ -425,7 +425,7 @@ pub fn heal(s: &mut Session, track: TrackId, range: Range) -> usize { let gap = if contiguous { c.start.saturating_sub(prev.end()) } else { 0 }; let same = match (&prev.content, &c.content) { (ClipContent::Audio { source: a, offset: oa }, ClipContent::Audio { source: b, offset: ob }) => { - a == b && oa.saturating_add(prev.length).saturating_add(gap) == *ob + a == b && oa.saturating_add(source_len(prev.length.saturating_add(gap), prev.stretch)) == *ob } _ => false, }; diff --git a/crates/model/src/clip.rs b/crates/model/src/clip.rs index cda10e74..f5be30b2 100644 --- a/crates/model/src/clip.rs +++ b/crates/model/src/clip.rs @@ -256,8 +256,16 @@ impl Clip { let end = self.end(); let new_start = new_start.max(end.saturating_sub(MAX_POSITION)).clamp(-MAX_POSITION, MAX_POSITION).min(end.saturating_sub(1)); let delta = new_start.saturating_sub(self.start); - if let ClipContent::Audio { offset, .. } | ClipContent::Video { offset, .. } = &mut self.content { - *offset = offset.saturating_add(delta); + // The mixer plays a stretched audio clip from `offset + rel / stretch`. + let stretch = if self.stretch.is_finite() && self.stretch > 0.0 { self.stretch } else { 1.0 }; + match &mut self.content { + ClipContent::Audio { offset, .. } if (stretch - 1.0).abs() >= 1e-9 => { + *offset = offset.saturating_add((delta as f64 / stretch).round() as Samples); + } + ClipContent::Audio { offset, .. } | ClipContent::Video { offset, .. } => { + *offset = offset.saturating_add(delta); + } + ClipContent::Midi { .. } => {} } // MIDI note ticks are re-anchored by the engine, which knows the tempo map. self.length = self.length.saturating_sub(delta).clamp(1, MAX_POSITION); From 3fe53ee834f29ef6b4c1468fff3e85de6465da51 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 24 Oct 2026 06:19:20 +0000 Subject: [PATCH 43/52] Integration: #595 pass BUNDLE_LIMITS in main's sources_sharing_one_file test --- crates/engine/src/io.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/io.rs b/crates/engine/src/io.rs index b41eabbc..0618edd6 100644 --- a/crates/engine/src/io.rs +++ b/crates/engine/src/io.rs @@ -2256,7 +2256,7 @@ mod bundle_tests { use std::io::Write as _; let e = crate::demo::demo_engine(); let (bytes, _) = session_bundle(e.session()).unwrap(); - let (text, files) = read_bundle(&bytes).unwrap(); + let (text, files) = read_bundle(&bytes, BUNDLE_LIMITS).unwrap(); let mut s = Session::from_json(&text).unwrap(); s.sources[1].path = s.sources[0].path.clone(); let mut w = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); From 42f22369fba1befb52998ddbea8379c65ddbab20 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 24 Oct 2026 06:41:56 +0000 Subject: [PATCH 44/52] Integration: build the batch's new integration tests into each crate's tests/it binary --- crates/audio-io/tests/{ => it}/float_headroom.rs | 0 crates/audio-io/tests/it/main.rs | 1 + crates/engine/tests/{ => it}/commit_multichannel.rs | 0 crates/engine/tests/it/main.rs | 3 +++ crates/engine/tests/{ => it}/split_into_mono.rs | 0 crates/engine/tests/{ => it}/track_name_collisions.rs | 0 crates/mix/tests/{ => it}/aux_routing_order.rs | 1 - crates/mix/tests/it/main.rs | 4 ++++ crates/mix/tests/{ => it}/strip_mute_automation.rs | 1 - crates/ui-egui/tests/it/main.rs | 2 ++ crates/ui-egui/tests/{ => it}/rtp_window.rs | 0 crates/ui-egui/tests/{ => it}/track_preset_state.rs | 2 +- 12 files changed, 11 insertions(+), 3 deletions(-) rename crates/audio-io/tests/{ => it}/float_headroom.rs (100%) rename crates/engine/tests/{ => it}/commit_multichannel.rs (100%) rename crates/engine/tests/{ => it}/split_into_mono.rs (100%) rename crates/engine/tests/{ => it}/track_name_collisions.rs (100%) rename crates/mix/tests/{ => it}/aux_routing_order.rs (99%) rename crates/mix/tests/{ => it}/strip_mute_automation.rs (99%) rename crates/ui-egui/tests/{ => it}/rtp_window.rs (100%) rename crates/ui-egui/tests/{ => it}/track_preset_state.rs (97%) diff --git a/crates/audio-io/tests/float_headroom.rs b/crates/audio-io/tests/it/float_headroom.rs similarity index 100% rename from crates/audio-io/tests/float_headroom.rs rename to crates/audio-io/tests/it/float_headroom.rs diff --git a/crates/audio-io/tests/it/main.rs b/crates/audio-io/tests/it/main.rs index 36b5129f..84b90aa1 100644 --- a/crates/audio-io/tests/it/main.rs +++ b/crates/audio-io/tests/it/main.rs @@ -1,6 +1,7 @@ //! Integration tests, built as one test binary: each file is a module. mod encode_format; +mod float_headroom; mod malformed; mod roundtrip; mod stream; diff --git a/crates/engine/tests/commit_multichannel.rs b/crates/engine/tests/it/commit_multichannel.rs similarity index 100% rename from crates/engine/tests/commit_multichannel.rs rename to crates/engine/tests/it/commit_multichannel.rs diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index f021c292..611c7266 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -2,6 +2,7 @@ mod bounce; mod clap_e2e; +mod commit_multichannel; mod consolidate_selection; mod current_feet_frames_position; mod edit_modes; @@ -14,4 +15,6 @@ mod mix_required_params; mod random_edits; mod recording; mod session_transport; +mod split_into_mono; +mod track_name_collisions; mod trim_to_selection; diff --git a/crates/engine/tests/split_into_mono.rs b/crates/engine/tests/it/split_into_mono.rs similarity index 100% rename from crates/engine/tests/split_into_mono.rs rename to crates/engine/tests/it/split_into_mono.rs diff --git a/crates/engine/tests/track_name_collisions.rs b/crates/engine/tests/it/track_name_collisions.rs similarity index 100% rename from crates/engine/tests/track_name_collisions.rs rename to crates/engine/tests/it/track_name_collisions.rs diff --git a/crates/mix/tests/aux_routing_order.rs b/crates/mix/tests/it/aux_routing_order.rs similarity index 99% rename from crates/mix/tests/aux_routing_order.rs rename to crates/mix/tests/it/aux_routing_order.rs index 4c557fa7..4ea9d814 100644 --- a/crates/mix/tests/aux_routing_order.rs +++ b/crates/mix/tests/it/aux_routing_order.rs @@ -1,6 +1,5 @@ //! Aux and routing-folder dependencies preserve PCM beyond eight hops. Cyclic graphs keep //! the established whole-graph fallback, including its session-order-dependent audio. -#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] use soundcraft_audio_io::AudioBuffer; use soundcraft_mix::{MixEngine, render_range}; diff --git a/crates/mix/tests/it/main.rs b/crates/mix/tests/it/main.rs index 77997334..de468bfe 100644 --- a/crates/mix/tests/it/main.rs +++ b/crates/mix/tests/it/main.rs @@ -1,6 +1,10 @@ //! Integration tests, built as one test binary: each file is a module. +#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +mod aux_routing_order; #[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] mod bus_aux_interval; #[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] mod master_insert_latency; +#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +mod strip_mute_automation; diff --git a/crates/mix/tests/strip_mute_automation.rs b/crates/mix/tests/it/strip_mute_automation.rs similarity index 99% rename from crates/mix/tests/strip_mute_automation.rs rename to crates/mix/tests/it/strip_mute_automation.rs index fba6ab23..7e37ba89 100644 --- a/crates/mix/tests/strip_mute_automation.rs +++ b/crates/mix/tests/it/strip_mute_automation.rs @@ -1,5 +1,4 @@ //! Ordinary strip mute changes sample gates without splitting processor blocks. -#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] use soundcraft_audio_io::AudioBuffer; use soundcraft_dsp::Plugin; use soundcraft_mix::{MixEngine, PreparedInstance, render_range}; diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index df71ff82..6214f0a0 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -35,6 +35,7 @@ mod plugin_window; mod pro_tools_keys; mod record_hint; mod rename_dialog; +mod rtp_window; mod sampler_window; mod save_as_replace; mod save_changes; @@ -49,6 +50,7 @@ mod toolbar_tempo; mod track_height; mod track_list; mod track_name_menu; +mod track_preset_state; mod trackpad; mod tracks_scroll_bar; mod waveform; diff --git a/crates/ui-egui/tests/rtp_window.rs b/crates/ui-egui/tests/it/rtp_window.rs similarity index 100% rename from crates/ui-egui/tests/rtp_window.rs rename to crates/ui-egui/tests/it/rtp_window.rs diff --git a/crates/ui-egui/tests/track_preset_state.rs b/crates/ui-egui/tests/it/track_preset_state.rs similarity index 97% rename from crates/ui-egui/tests/track_preset_state.rs rename to crates/ui-egui/tests/it/track_preset_state.rs index 155a7997..048f6f28 100644 --- a/crates/ui-egui/tests/track_preset_state.rs +++ b/crates/ui-egui/tests/it/track_preset_state.rs @@ -1,6 +1,6 @@ //! Track presets capture the hosted plugin's current state before writing the model. -#[path = "../../clap-host/tests/common/mod.rs"] +#[path = "../../../clap-host/tests/common/mod.rs"] mod common; use serde_json::{Value, json}; From 1cc7b40e6a63d63f94a360c1a28506548f813a9a Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 24 Oct 2026 06:51:27 +0000 Subject: [PATCH 45/52] Integration: #631 find the New Tracks name field by its text-input role --- crates/ui-egui/tests/it/new_tracks.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/tests/it/new_tracks.rs b/crates/ui-egui/tests/it/new_tracks.rs index 3a6d37a6..ff4c97ce 100644 --- a/crates/ui-egui/tests/it/new_tracks.rs +++ b/crates/ui-egui/tests/it/new_tracks.rs @@ -1,9 +1,10 @@ //! New Tracks opens from the Tracks list's + button, and from a double-click below the last //! track (Edit) or right of the last strip (Mix). +use egui::accesskit::Role; use egui::{Pos2, pos2, vec2}; use egui_kittest::Harness; -use egui_kittest::kittest::Queryable; +use egui_kittest::kittest::{Queryable, by}; use soundcraft_ui_egui::{MainWindow, Services, SoundApp}; fn harness(tracks: usize) -> Harness<'static, SoundApp> { @@ -72,6 +73,7 @@ fn the_new_tracks_name_field_is_wide_enough_to_read_a_name() { h.get_by_label_contains("New Tracks").click(); h.run_steps(4); assert_eq!(h.state().dialogs.open_name(), Some("new_tracks")); - let width = h.get_by_value("Audio").rect().width(); + // The field's text run carries the same value as the field itself. + let width = h.get(by().role(Role::TextInput).value("Audio")).rect().width(); assert!(width >= 200.0, "the Name field is only {width}px wide"); } From c29510af86bcce1b5f767da4e080c9e568650565 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 24 Oct 2026 06:56:33 +0000 Subject: [PATCH 46/52] Integration: regenerate docs/parity-checklist.md --- docs/parity-checklist.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 229b7835..de89a1c5 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -1,7 +1,5 @@ # Parity report -> **Generated:** 2026-10-06 (last run of `cargo xtask parity`; the catalog and aliases are unchanged since) · **Target:** Avid Pro Tools Ultimate 2026.4.1 menu tree - Generated by `soundcraft-cli parity --write docs/parity-checklist.md` (also `cargo xtask parity`). It compares the incumbent's menu tree (feature names observed black-box, `crates/engine/catalog/menus.txt`) with SoundCraft's command registry. UI-layer commands (windows, AudioSuite) are counted by the app's own report (`engine.parity` over the control channel). From 93800e0764ca62435ee66a4770f355df954b7fcd Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sat, 24 Oct 2026 04:30:47 -0400 Subject: [PATCH 47/52] refactor(video): use method paths instead of closures for first_chunk (S1612) (#1012) Co-authored-by: Claude Sonnet 5.5 --- crates/video/src/h264/deblock.rs | 6 +++--- crates/video/src/h264/picture.rs | 2 +- crates/video/src/h264/slicedec.rs | 8 ++++---- crates/video/src/h264/transform.rs | 4 ++-- crates/video/src/prores/decode.rs | 2 +- 5 files changed, 11 insertions(+), 11 deletions(-) diff --git a/crates/video/src/h264/deblock.rs b/crates/video/src/h264/deblock.rs index 887c93e5..12ba8da5 100644 --- a/crates/video/src/h264/deblock.rs +++ b/crates/video/src/h264/deblock.rs @@ -232,7 +232,7 @@ fn filter_vertical(pix: &mut [u8], stride: usize, x: usize, y: u let mut w = [0u64; N]; for (i, w) in w.iter_mut().enumerate() { let o = (y + i) * stride + x - 4; - let Some(&b) = pix.get(o..).and_then(|p| p.first_chunk::<8>()) else { + let Some(&b) = pix.get(o..).and_then(<[_]>::first_chunk::<8>) else { return; }; *w = u64::from_le_bytes(b); @@ -259,7 +259,7 @@ fn filter_horizontal(pix: &mut [u8], stride: usize, x: usize, y: let base = (y - 4) * stride + x; let mut s = [[0i16; N]; 8]; for (k, row) in s.iter_mut().enumerate() { - let Some(src) = pix.get(base + k * stride..).and_then(|p| p.first_chunk::()) else { + let Some(src) = pix.get(base + k * stride..).and_then(<[_]>::first_chunk::) else { return; }; for i in 0..N { @@ -269,7 +269,7 @@ fn filter_horizontal(pix: &mut [u8], stride: usize, x: usize, y: filter_lanes(&mut s, ep, chroma); let (k0, k1) = if chroma { (3, 5) } else { (1, 7) }; for (k, row) in s.iter().enumerate().take(k1).skip(k0) { - let Some(dst) = pix.get_mut(base + k * stride..).and_then(|p| p.first_chunk_mut::()) else { + let Some(dst) = pix.get_mut(base + k * stride..).and_then(<[_]>::first_chunk_mut::) else { return; }; for i in 0..N { diff --git a/crates/video/src/h264/picture.rs b/crates/video/src/h264/picture.rs index 5e52f074..d1cbe225 100644 --- a/crates/video/src/h264/picture.rs +++ b/crates/video/src/h264/picture.rs @@ -319,7 +319,7 @@ fn plane_allocator() -> fn(usize) -> Vec { fn copy_line(line: &[u8], x0: i32, out: &mut [u8], w: usize) { if w <= N && x0 >= 0 - && let Some(src) = line.get(x0 as usize..).and_then(|l| l.first_chunk::()) + && let Some(src) = line.get(x0 as usize..).and_then(<[_]>::first_chunk::) && let Some(dst) = out.first_chunk_mut::() { *dst = *src; diff --git a/crates/video/src/h264/slicedec.rs b/crates/video/src/h264/slicedec.rs index 7e5529dd..5f2b436e 100644 --- a/crates/video/src/h264/slicedec.rs +++ b/crates/video/src/h264/slicedec.rs @@ -918,7 +918,7 @@ impl<'a> SliceDecoder<'a> { let stride = self.pic.planes.width; let px = self.mb_x * 16 + (raster & 3) * 4; let py = self.mb_y * 16 + (raster >> 2) * 4; - let Some(blk) = self.s.coef.get_mut(raster * 16..).and_then(|c| c.first_chunk_mut::<16>()) else { + let Some(blk) = self.s.coef.get_mut(raster * 16..).and_then(<[_]>::first_chunk_mut::<16>) else { return; }; transform::idct4_add(blk, &mut self.pic.planes.y[py * stride + px..], stride); @@ -932,7 +932,7 @@ impl<'a> SliceDecoder<'a> { let stride = self.pic.planes.width; let px = self.mb_x * 16 + (b8 & 1) * 8; let py = self.mb_y * 16 + (b8 >> 1) * 8; - let Some(blk) = self.s.coef.get_mut(b8 * 64..).and_then(|c| c.first_chunk_mut::<64>()) else { + let Some(blk) = self.s.coef.get_mut(b8 * 64..).and_then(<[_]>::first_chunk_mut::<64>) else { return; }; transform::idct8_add(blk, &mut self.pic.planes.y[py * stride + px..], stride); @@ -951,7 +951,7 @@ impl<'a> SliceDecoder<'a> { } let px = self.mb_x * 8 + (b & 1) * 4; let py = self.mb_y * 8 + (b >> 1) * 4; - let Some(blk) = self.s.coef_c[c].get_mut(b * 16..).and_then(|c| c.first_chunk_mut::<16>()) else { + let Some(blk) = self.s.coef_c[c].get_mut(b * 16..).and_then(<[_]>::first_chunk_mut::<16>) else { continue; }; let plane = if c == 0 { &mut self.pic.planes.cb } else { &mut self.pic.planes.cr }; @@ -1252,7 +1252,7 @@ impl<'a> SliceDecoder<'a> { let pos = r.byte_pos(); let data = r.data(); ensure!(data.len() >= pos + 384, "truncated I_PCM macroblock"); - let Some(&samples) = data.get(pos..).and_then(|d| d.first_chunk::<384>()) else { + let Some(&samples) = data.get(pos..).and_then(<[_]>::first_chunk::<384>) else { return invalid("truncated I_PCM macroblock"); }; r.skip(384 * 8)?; diff --git a/crates/video/src/h264/transform.rs b/crates/video/src/h264/transform.rs index de01c09c..4f4fdf83 100644 --- a/crates/video/src/h264/transform.rs +++ b/crates/video/src/h264/transform.rs @@ -126,7 +126,7 @@ pub fn idct4_add(d: &[i32; 16], dst: &mut [u8], stride: usize) { o[3][j] = e - h; } for (i, row) in o.iter().enumerate() { - let Some(line) = dst.get_mut(i * stride..).and_then(|d| d.first_chunk_mut::<4>()) else { + let Some(line) = dst.get_mut(i * stride..).and_then(<[_]>::first_chunk_mut::<4>) else { return; }; for (p, &v) in line.iter_mut().zip(row) { @@ -182,7 +182,7 @@ pub fn idct8_add(d: &[i32; 64], dst: &mut [u8], stride: usize) { } } for (i, row) in o.iter().enumerate() { - let Some(line) = dst.get_mut(i * stride..).and_then(|d| d.first_chunk_mut::<8>()) else { + let Some(line) = dst.get_mut(i * stride..).and_then(<[_]>::first_chunk_mut::<8>) else { return; }; for (p, &v) in line.iter_mut().zip(row) { diff --git a/crates/video/src/prores/decode.rs b/crates/video/src/prores/decode.rs index 01b1900f..4fc5101a 100644 --- a/crates/video/src/prores/decode.rs +++ b/crates/video/src/prores/decode.rs @@ -492,7 +492,7 @@ fn put_block(f: &[f32; 64], plane: &mut [u16], stride: usize, x0: usize, y0: usi if xn == 8 && (y0 + 7) * step + parity < rows { for yy in 0..8 { let o = ((y0 + yy) * step + parity) * stride + x0; - let (Some(row), Some(src)) = (plane.get_mut(o..).and_then(|p| p.first_chunk_mut::<8>()), f.as_chunks::<8>().0.get(yy)) else { + let (Some(row), Some(src)) = (plane.get_mut(o..).and_then(<[_]>::first_chunk_mut::<8>), f.as_chunks::<8>().0.get(yy)) else { return; }; for x in 0..8 { From 08679d5a655eab4611729c218b19723d3d0523c3 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 24 Oct 2026 09:11:44 +0000 Subject: [PATCH 48/52] Integration: cli: run the inline --cmd=ID form --- apps/soundcraft-cli/src/main.rs | 32 +++++++++++++++------------- apps/soundcraft-cli/tests/options.rs | 8 +++++++ 2 files changed, 25 insertions(+), 15 deletions(-) diff --git a/apps/soundcraft-cli/src/main.rs b/apps/soundcraft-cli/src/main.rs index ccec6697..899ba71e 100644 --- a/apps/soundcraft-cli/src/main.rs +++ b/apps/soundcraft-cli/src/main.rs @@ -354,22 +354,24 @@ fn run(args: &[String]) -> ExitCode { Ok(e) => e, Err(err) => return fail(err), }; - let mut i = 0; - while i < args.len() { - if args.get(i).is_some_and(|a| a == "--cmd") - && let Some(spec) = args.get(i + 1) - { - let (id, params) = match parse_cmd_spec(spec) { - Ok(v) => v, - Err(err) => return fail(err), - }; - match e.execute(&id, ¶ms) { - Ok(v) => outln!("{id}: {v}"), - Err(err) => return fail(format!("{id}: {err}")), - } - i += 1; + let mut it = args.iter(); + while let Some(a) = it.next() { + let spec = match a.strip_prefix("--cmd=") { + Some(inline) => inline, + None if a == "--cmd" => match it.next() { + Some(next) => next, + None => continue, + }, + None => continue, + }; + let (id, params) = match parse_cmd_spec(spec) { + Ok(v) => v, + Err(err) => return fail(err), + }; + match e.execute(&id, ¶ms) { + Ok(v) => outln!("{id}: {v}"), + Err(err) => return fail(format!("{id}: {err}")), } - i += 1; } finish(&mut e, args) } diff --git a/apps/soundcraft-cli/tests/options.rs b/apps/soundcraft-cli/tests/options.rs index e709a3d8..5ca67031 100644 --- a/apps/soundcraft-cli/tests/options.rs +++ b/apps/soundcraft-cli/tests/options.rs @@ -120,3 +120,11 @@ fn run_bounces_with_the_inline_value_form() { assert!(o.status.success(), "{}", String::from_utf8_lossy(&o.stderr)); assert!(out.exists(), "--bounce=PATH should write the file"); } + +#[test] +fn run_executes_the_inline_cmd_form() { + let o = run(&["run", "--cmd=track.new", "--cmd", "track.new"]); + assert!(o.status.success(), "{}", String::from_utf8_lossy(&o.stderr)); + let stdout = String::from_utf8_lossy(&o.stdout); + assert_eq!(stdout.lines().filter(|l| l.starts_with("track.new: ")).count(), 2, "both --cmd forms should run: {stdout}"); +} From f6a27c2ccf21cc9a357c209df7b8cb2fb677f181 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 24 Oct 2026 09:13:19 +0000 Subject: [PATCH 49/52] Integration: automation: hold clip gain envelope ends to the clip edges --- crates/engine/src/cmd/mix.rs | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/mix.rs b/crates/engine/src/cmd/mix.rs index d5cfcdee..8daacedf 100644 --- a/crates/engine/src/cmd/mix.rs +++ b/crates/engine/src/cmd/mix.rs @@ -709,8 +709,9 @@ fn clip_gain_to_vol(e: &mut Engine, p: &Value) -> Result { pins.push((c.start - 1, level(c.start - 1))); } pins.push((c.end(), level(c.end()))); - let mut ats: Vec = - if c.gain_env.is_empty() { vec![c.start, c.end() - 1] } else { c.gain_env.iter().map(|&(o, _)| c.start + o).collect() }; + // The clip edges always get a point, so the envelope's first and last values hold out to them. + let mut ats = vec![c.start, c.end() - 1]; + ats.extend(c.gain_env.iter().map(|&(o, _)| c.start + o).filter(|&at| at > c.start && at < c.end() - 1)); // The lane's own points inside the clip carry the clip gain too. if let Some(l) = &old { ats.extend(l.points.iter().map(|pt| pt.at).filter(|&at| at > c.start && at < c.end() - 1)); @@ -916,6 +917,22 @@ mod tests { } } + #[test] + fn clip_gain_to_volume_holds_the_envelope_ends_out_to_the_clip_edges() { + let (mut e, t) = tone_session(&[(0, -6.0), (8192, -6.0)]); + let clip = e.session().track(t).unwrap().clips()[0].id; + let c = e.session_mut().find_clip_mut(clip).unwrap(); + c.gain_db = 6.0; + c.gain_env = vec![(2000, 0.0), (6000, -10.0)]; + let before = rendered(e.session()); + e.execute("automation.clip_gain_to_volume", &json!({"track": t.0, "start": 0, "end": 8192})).unwrap(); + let after = rendered(e.session()); + for (start, end) in [(0, 1000), (1000, 2000), (6000, 7000), (7000, 8192)] { + let delta = rms_db(&before[start..end], &after[start..end]); + assert!(delta.abs() < 0.2, "{start}..{end} changed by {delta} dB"); + } + } + #[test] fn clip_gain_to_volume_leaves_audio_outside_the_clip_alone() { // Three clips in a row; only the middle one is converted, and the lane extends past it on both sides. From 824cf5cecbeba3e6491cdf5aaa47bda99ba7cc46 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 24 Oct 2026 09:14:21 +0000 Subject: [PATCH 50/52] Integration: import: keep a failed import's error on the status line --- crates/ui-egui/src/import.rs | 26 ++++++++++++++++++++++---- 1 file changed, 22 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/import.rs b/crates/ui-egui/src/import.rs index e9c2d83f..44f1c201 100644 --- a/crates/ui-egui/src/import.rs +++ b/crates/ui-egui/src/import.rs @@ -88,10 +88,8 @@ fn spawn(app: &mut SoundApp, params: Value, ctx: &egui::Context) { ctx.request_repaint(); }; match std::thread::Builder::new().name("audio-import".into()).spawn(work) { - Ok(_) => { - app.ui.status = format!("Importing {name}…"); - app.imports.running = Some(Running { params, name, rate, rx }); - } + // No status line here: it may hold the previous file's failure, and the progress note names this file. + Ok(_) => app.imports.running = Some(Running { params, name, rate, rx }), // No thread to spare: import the old way rather than not at all. Err(_) => { run_now(app, params); @@ -214,4 +212,24 @@ mod tests { settle(&mut app, &ctx); assert_eq!(app.engine.session().tracks.len(), 1, "the good file still imports"); } + + #[test] + fn a_failed_import_stays_on_the_status_line_while_the_next_one_starts() { + let ctx = egui::Context::default(); + let mut app = SoundApp::new(soundcraft_engine::Engine::default(), None, Services::default()); + let junk = tone_wav("junk-status.wav"); + std::fs::write(&junk, b"not audio").unwrap(); + start(&mut app, json!({"path": junk})); + start(&mut app, json!({"path": tone_wav("next-status.wav")})); + for _ in 0..2_000 { + step(&mut app, &ctx); + if app.imports.label().is_some_and(|(name, _)| name == "next-status.wav") { + break; + } + std::thread::sleep(std::time::Duration::from_millis(5)); + } + assert!(app.imports.label().is_some_and(|(name, _)| name == "next-status.wav"), "the second import never started"); + assert!(!app.ui.status.is_empty() && !app.ui.status.starts_with("Importing"), "the failure was overwritten: {}", app.ui.status); + settle(&mut app, &ctx); + } } From 4ab3bde39bee4c0a35ac1e4b6485fef693c93503 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 24 Oct 2026 09:15:31 +0000 Subject: [PATCH 51/52] Integration: MIDI real-time properties: reload the form when stored values change --- crates/ui-egui/src/ops_windows.rs | 54 +++++++++++++++++++++++-------- 1 file changed, 41 insertions(+), 13 deletions(-) diff --git a/crates/ui-egui/src/ops_windows.rs b/crates/ui-egui/src/ops_windows.rs index 45a2f3a9..c4a492ca 100644 --- a/crates/ui-egui/src/ops_windows.rs +++ b/crates/ui-egui/src/ops_windows.rs @@ -30,9 +30,10 @@ pub struct OpsState { pub rtp_transpose: i64, pub rtp_duration: f64, pub rtp_delay: i64, - /// The MIDI tracks the Real-Time Properties form was last filled from: the form re-reads the - /// tracks when the target selection changes (#444). + /// The MIDI tracks the Real-Time Properties form was last filled from, and the values it read: + /// the form re-reads the tracks when either changes (#444). pub rtp_targets: Vec, + pub rtp_loaded: Option, pub identify_bars: u32, } @@ -61,6 +62,7 @@ impl Default for OpsState { rtp_duration: 100.0, rtp_delay: 0, rtp_targets: Vec::new(), + rtp_loaded: None, identify_bars: 1, } } @@ -265,17 +267,8 @@ fn rtp(app: &mut SoundApp, ctx: &egui::Context) { if !open { return; } - // Fill the form from the tracks it edits whenever the target selection changes, so it never - // shows (and a control change never writes back) stale defaults (#444). let targets = app.engine.target_tracks(); - if app.ops.rtp_targets != targets { - app.ops.rtp_targets = targets.clone(); - let (velocity, transpose, duration, delay) = rtp_form_values(app.engine.session(), &targets); - app.ops.rtp_velocity = velocity; - app.ops.rtp_transpose = transpose; - app.ops.rtp_duration = duration; - app.ops.rtp_delay = delay; - } + sync_rtp_form(&mut app.ops, app.engine.session(), targets, ctx.dragged_id().is_some()); egui::Window::new("MIDI Real-Time Properties").open(&mut open).default_size(vec2(340.0, 200.0)).show(ctx, |ui| { ui.label("Non-destructive, applied at playback to the selected MIDI tracks."); let mut changed = RtpChanged::default(); @@ -330,9 +323,28 @@ fn rtp_params(changed: RtpChanged, ops: &OpsState) -> Option { (!p.is_empty()).then_some(Value::Object(p)) } +/// Velocity, transpose, duration % and delay, as the form shows them. +pub type RtpValues = (i64, i64, f64, i64); + +/// Fills the form from the tracks it edits whenever the targets or their stored values change +/// (selection, undo, a command), so it never shows (and a control change never writes back) stale +/// values (#444). A slider being dragged keeps its value until it is released. +fn sync_rtp_form(ops: &mut OpsState, s: &soundcraft_model::Session, targets: Vec, dragging: bool) { + let values = rtp_form_values(s, &targets); + if ops.rtp_targets != targets || (ops.rtp_loaded != Some(values) && !dragging) { + let (velocity, transpose, duration, delay) = values; + ops.rtp_targets = targets; + ops.rtp_loaded = Some(values); + ops.rtp_velocity = velocity; + ops.rtp_transpose = transpose; + ops.rtp_duration = duration; + ops.rtp_delay = delay; + } +} + /// The values the form shows for `targets`: the first target's own Real-Time Properties, or the /// neutral defaults when nothing is selected. -fn rtp_form_values(s: &soundcraft_model::Session, targets: &[soundcraft_model::TrackId]) -> (i64, i64, f64, i64) { +fn rtp_form_values(s: &soundcraft_model::Session, targets: &[soundcraft_model::TrackId]) -> RtpValues { let Some(&t) = targets.first() else { return (0, 0, 100.0, 0) }; let value = |key: &str, d: f64| s.edit.value(&format!("rtp.{}.{key}", t.0), d); ( @@ -386,4 +398,20 @@ mod tests { assert_eq!(rtp_form_values(e.session(), &[]), (0, 0, 100.0, 0), "no target: the neutral defaults"); assert_eq!(rtp_form_values(e.session(), &[t]), (-12, 7, 50.0, 480)); } + + /// Undo keeps the same targets but changes their stored values: the form follows. + #[test] + fn the_rtp_form_follows_an_undo_on_the_same_targets() { + let mut e = soundcraft_engine::Engine::default(); + e.execute("track.new", &json!({"kind": "instrument", "name": "Synth"})).unwrap(); + let t = e.session().tracks.last().unwrap().id; + let mut ops = OpsState::default(); + sync_rtp_form(&mut ops, e.session(), vec![t], false); + e.execute("event.midi_rtp", &json!({"track": t.0, "velocity": -12})).unwrap(); + sync_rtp_form(&mut ops, e.session(), vec![t], false); + assert_eq!(ops.rtp_velocity, -12); + e.execute("edit.undo", &json!({})).unwrap(); + sync_rtp_form(&mut ops, e.session(), vec![t], false); + assert_eq!(ops.rtp_velocity, 0, "the form kept the undone value"); + } } From e884d6eb3738ff94c4c456628672e4ebacceab6a Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 24 Oct 2026 09:16:19 +0000 Subject: [PATCH 52/52] Integration: VST3 host: keep room for note releases after a reset --- crates/vst3-host/src/plugin.rs | 53 ++++++++++++++++++++++++++++------ 1 file changed, 44 insertions(+), 9 deletions(-) diff --git a/crates/vst3-host/src/plugin.rs b/crates/vst3-host/src/plugin.rs index 0248c077..89435747 100644 --- a/crates/vst3-host/src/plugin.rs +++ b/crates/vst3-host/src/plugin.rs @@ -169,11 +169,28 @@ impl Vst3Plugin { /// Inserts keeping the queue time-sorted; drops the event when the queue is full (never /// allocates on the audio thread). fn push_note(&mut self, e: NoteEvent) { - if self.notes.len() >= self.notes.capacity() { - return; - } - let pos = self.notes.iter().rposition(|q| q.time() <= e.time()).map_or(0, |i| i + 1); - self.notes.insert(pos, e); + push_sorted(&mut self.notes, e); + } +} + +fn push_sorted(notes: &mut Vec, e: NoteEvent) { + if notes.len() >= notes.capacity() { + return; + } + let pos = notes.iter().rposition(|q| q.time() <= e.time()).map_or(0, |i| i + 1); + notes.insert(pos, e); +} + +/// Keeps only the pending releases, one per key and moved to the start of the next block, so at +/// most 128 remain and `all_notes_off` always has room in the queue. +fn keep_releases(notes: &mut Vec) { + let mut seen = [false; 128]; + notes.retain(|e| match *e { + NoteEvent::Off { key, .. } => seen.get_mut(usize::from(key)).is_some_and(|s| !std::mem::replace(s, true)), + _ => false, + }); + for e in notes.iter_mut() { + e.set_time(0); } } @@ -216,10 +233,7 @@ impl Plugin for Vst3Plugin { fn reset(&mut self) { // Keep pending releases and release whatever is still held, so the processor's voices stop // on the next block instead of sounding on while the host forgets them. - self.notes.retain(|e| matches!(e, NoteEvent::Off { .. })); - for e in &mut self.notes { - e.set_time(0); - } + keep_releases(&mut self.notes); self.controls.clear(); self.all_notes_off(); self.held = [false; 128]; @@ -523,3 +537,24 @@ impl PluginEditor for Vst3Editor { if units.is_empty() || text.trim_end().to_lowercase().ends_with(&units.to_lowercase()) { Some(text) } else { Some(format!("{text} {units}")) } } } + +#[cfg(test)] +mod tests { + use super::*; + + /// A queue full of releases still has room to release every held key after a reset. + #[test] + fn reset_keeps_room_to_release_every_held_key() { + let mut notes = Vec::with_capacity(EVENT_CAP); + for i in 0..EVENT_CAP { + push_sorted(&mut notes, NoteEvent::Off { time: i as u32, key: (i % 4) as u8 }); + } + keep_releases(&mut notes); + for key in 0..128u8 { + push_sorted(&mut notes, NoteEvent::Off { time: 0, key }); + } + for key in 0..128u8 { + assert!(notes.iter().any(|e| matches!(*e, NoteEvent::Off { key: k, .. } if k == key)), "key {key} was never released"); + } + } +}