diff --git a/Cargo.lock b/Cargo.lock index 6ce244fb9..fb0a5309c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -850,6 +850,17 @@ dependencies = [ "nom 7.1.3", ] +[[package]] +name = "cfb" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f13298d9178622b7916ec5d01d470425c04273c8ed07e87b1c38b34c4f4612b" +dependencies = [ + "fnv", + "uuid", + "web-time", +] + [[package]] name = "cfg-if" version = "1.0.5" @@ -4994,6 +5005,7 @@ dependencies = [ name = "soundcraft-engine" version = "0.20.1" dependencies = [ + "cfb", "craft-audio", "craft-docpath", "craft-score", @@ -5006,6 +5018,7 @@ dependencies = [ "soundcraft-au-host", "soundcraft-clap-host", "soundcraft-dsp", + "soundcraft-interchange", "soundcraft-midi", "soundcraft-mix", "soundcraft-model", @@ -5017,6 +5030,18 @@ dependencies = [ "zip", ] +[[package]] +name = "soundcraft-interchange" +version = "0.20.1" +dependencies = [ + "cfb", + "serde", + "serde_json", + "soundcraft-model", + "soundcraft-time", + "thiserror 2.0.21", +] + [[package]] name = "soundcraft-midi" version = "0.20.1" diff --git a/Cargo.toml b/Cargo.toml index 0311bf6b1..ded0fe265 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -15,6 +15,7 @@ craft-score = { git = "https://github.com/storytold/craft-libs", rev = "3a1a627d craft-xml = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "ea24422ae9859dc5da398d0462bc87f8e02e0d10" } craft-mime = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "ea24422ae9859dc5da398d0462bc87f8e02e0d10" } # internal +soundcraft-interchange = { path = "crates/interchange" } soundcraft-time = { path = "crates/time" } soundcraft-midi = { path = "crates/midi" } soundcraft-video = { path = "crates/video" } @@ -46,6 +47,8 @@ proptest = "1" # audio rustfft = "6" +# AAF interchange: Compound File Binary (structured storage) container reader. +cfb = "0.15" # Session bundles (one file holding a session and its audio, for the browser): stored entries only. zip = { version = "9", default-features = false } cpal = "0.18" diff --git a/ROADMAP.md b/ROADMAP.md index 7d474df9d..42d16f0a4 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-24 · **Last updated:** 2026-11-18 · **Change:** minor (MIDI input in the progress log; previously trivial: Frequency Shifter plugin, Command-click target priority and cursor, Command-click automation points, plugin editors on Linux/X11, Cancel Zoom Toggle, side panels in dock columns, Auto Pan stereo balance, Alt-click returns a plugin parameter to its default, Clip List Auto Rename, Strip Silence rectangles, Strip Silence Rename, Strip Silence Extract and Separate, Clip Looping dialog, AudioSuite Vari-Fi speed ramps, Auto Pan plugin, Subharmonic plugin, Ring Modulator plugin, Float32 file headroom) · **Target:** Avid Pro Tools Ultimate 2026.4.1 +> **Last reviewed:** 2026-11-14 · **Last updated:** 2026-11-18 · **Change:** minor (strict external-WAV AAF import and MIDI input in the progress log; previously trivial: Frequency Shifter plugin, Command-click target priority and cursor, Command-click automation points, plugin editors on Linux/X11, Cancel Zoom Toggle, side panels in dock columns, Auto Pan stereo balance, Alt-click returns a plugin parameter to its default, Clip List Auto Rename, Strip Silence rectangles, Strip Silence Rename, Strip Silence Extract and Separate, Clip Looping dialog, AudioSuite Vari-Fi speed ramps, Auto Pan plugin, Subharmonic plugin, Ring Modulator plugin, 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 @@ -38,8 +38,8 @@ Editing, mixing, bouncing, and saving and reopening work end to end. But a Pro T record from a chosen audio interface at a chosen buffer size (only the default devices, a fixed 512-sample block, and takes held in RAM). Recording MIDI from a keyboard is built but checked on Linux only: macOS and Windows are type-checked and have not been tried with a device, and there -is no MIDI input on FreeBSD or the web. And they can't bring a session in or hand one back (no -AAF/OMF/`.ptx`). +is no MIDI input on FreeBSD or the web. Session interchange is still incomplete: a strict +external-WAV AAF import subset works, but AAF export, OMF and `.ptx` do not. Readiness (~40 %) sits right at the alpha bar, but a gate failure keeps the app pre-alpha. The 2026-10-07 estimate ("~65 % overall, 110–150 h to 100 %") counted feature presence. This one measures readiness and adds hardware, localization and field bug reports. @@ -106,7 +106,7 @@ Ranked; the alpha gate, the alpha checklist and the beta plan are in [docs/roadm 1. **Alpha blocker:** audio interfaces: device and buffer-size choice, duplex stream, ASIO; record to disk (G-01, G-06). 35–55 h. 2. **Alpha blocker:** MIDI devices: keyboard input, live play and recording are in (checked on Linux only; macOS and Windows type-checked, none on FreeBSD or the web); output, clock and loop/merge recording remain (G-02). 12–22 h. -3. **Alpha blocker:** AAF/OMF import and export (G-03). 50–90 h. +3. **Alpha blocker:** complete AAF/OMF interchange (G-03): strict external-WAV AAF import works; AAF export and OMF import/export remain. 50–90 h. 4. macOS plugin entitlement (#153), then AU editors and embedded CLAP editors on macOS (G-05). 1 h for the entitlement (needed for the mix row), then 10–15 h. 5. Land the open bug-fix PRs and clear the correctness backlog (G-04). 15–25 h. 6. PR CI running `cargo xtask ci` on three OSes (G-14). 5–10 h. @@ -125,6 +125,7 @@ mutated and truncated movies. Field reports from the first public week are track ## Progress log - **2026-11-18 (MIDI input):** MIDI input devices: keyboards play record-enabled and input-monitored MIDI and instrument tracks live and are recorded into MIDI clips, with a device and channel choice per track. The device switches are in the MIDI inputs section of Setup › Playback Engine (Setup › MIDI › MIDI Input Devices opens the same window) and are kept in the app preferences, per computer, not in the session. Controllers, pitch bend and aftertouch reach the instrument live; a pitch held on two devices or channels sounds until both release it; a full input queue releases the notes of its device and marks the take incomplete. On Linux, live play was checked with a hardware keyboard (Akai MPK mini 3) and recording with a virtual one; macOS and Windows are type-checked only, and there is no MIDI input on FreeBSD or the web. Guide: `docs/midi-input.md`. No readiness percentage change until that is measured. +- **2026-11-14:** AAF import supports a strict CompositionMob SourceClip/Filler subset with external mono/stereo PCM WAV media, editable clips and handles, relink and absolute or relative timecode mapping. The reader shares cached object properties, caps retained property data at 128 MiB and rejects duplicate local references before expansion. AAF export, OMF and `.ptx` remain missing. No readiness percentage change. - **2026-11-09:** A built-in Frequency Shifter (`freq_shifter`) moves every frequency in the signal by the same number of hertz, from 0.01 Hz to 5 kHz: up, down, both ways at once, or down on the left and up on the right of a stereo track. The unwanted sideband stays at least 100 dB down from 20 Hz to 20 Hz below Nyquist at 44.1 to 96 kHz. Feedback sends the output round again for a trail of further shifts, Mix blends in the dry signal, and every change glides without a click. No readiness percentage change. - **2026-11-08:** Command-click near an existing automation breakpoint keeps that point as the click target with every active tool, and existing fade and clip-gain controls retain their normal priority. Empty automation space shows a crosshair and an insertion hint while Command is held. The active tool's drag gestures stay unchanged. No readiness percentage change. - **2026-11-05:** Command-click in an automation lane adds a point at the clicked time and value with the current editing tool (#1394), using the existing Pencil mapping. Command-click preserves the existing selection and also works on the fallback volume lanes of Master, Aux and VCA tracks. Plain clicks and clip contents stay unchanged, and one Undo removes the new point. No readiness percentage change. @@ -187,6 +188,7 @@ mutated and truncated movies. Field reports from the first public week are track | Date | Change | Summary | |---|---|---| +| 2026-11-14 | minor | Strict external-WAV AAF import with bounded property caching; remaining interchange work and readiness estimates unchanged | | 2026-11-09 | trivial | Progress log: Frequency Shifter plugin; readiness estimates unchanged | | 2026-11-08 | trivial | Command-click breakpoint/control priority and insertion affordance; active-tool drags retained; readiness estimates unchanged | | 2026-11-05 | trivial | Progress log: Command-click adds an undoable automation point (#1394); readiness estimates unchanged | diff --git a/apps/soundcraft/src/main.rs b/apps/soundcraft/src/main.rs index ac2b988bb..46410a040 100644 --- a/apps/soundcraft/src/main.rs +++ b/apps/soundcraft/src/main.rs @@ -151,6 +151,7 @@ fn services() -> Services { let d = rfd::FileDialog::new(); let d = match purpose { "session.open" => d.add_filter("SoundCraft Session", &["scraft"]), + "file.import_aaf" => d.add_filter("AAF session data", &["aaf"]), "file.import_midi" => d.add_filter("MIDI", &["mid", "midi", "smf"]), _ => d.add_filter("Audio", craft_audio::DECODE_EXTENSIONS), }; diff --git a/contributors/people.toml b/contributors/people.toml index 06ae81ce5..3205f1598 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -69,3 +69,7 @@ sync_github_name = true [people.kk376] real_name = "Kushagra Kumar" sync_github_name = true + +# Display name explicitly chosen by the contributor on 2026-10-19. +[people.vhhr7] +display_name = "Vic Herrera (@vhhr)" diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 083ed614b..a25685e74 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -8,6 +8,7 @@ rust-version.workspace = true repository.workspace = true [dependencies] +soundcraft-interchange.workspace = true craft-score.workspace = true craft-xml.workspace = true soundcraft-time.workspace = true @@ -31,6 +32,7 @@ craft-docpath.workspace = true winsafe = { version = "0.0.29", features = ["kernel"] } [dev-dependencies] +cfb.workspace = true proptest.workspace = true zip.workspace = true diff --git a/crates/engine/src/aaf.rs b/crates/engine/src/aaf.rs new file mode 100644 index 000000000..5432ebd11 --- /dev/null +++ b/crates/engine/src/aaf.rs @@ -0,0 +1,156 @@ +//! AAF boundary: the reusable interchange crate constructs the source document, then this module +//! verifies and decodes media and maps new tracks into the destination as one undoable edit. +use crate::{EngineError, Result}; +use serde_json::{Value, json}; +use soundcraft_interchange::{Plan, build_session}; +use soundcraft_model::{ClipContent, ClipId, Session, SourceAudio, SourceId, TrackId}; +use soundcraft_time::MAX_POSITION; +use std::{ + collections::{HashMap, HashSet}, + path::Path, + sync::Arc, +}; + +fn bad(message: impl Into) -> EngineError { + EngineError::Io(message.into()) +} + +pub fn preview(path: &str, media_dir: &str, composition: Option<&str>) -> Result { + let plan = crate::io::read_aaf_plan(path, media_dir, composition)?; + let parsed: Plan = serde_json::from_value(plan.clone()).map_err(|e| bad(e.to_string()))?; + let built = build_session(parsed).map_err(|e| bad(e.to_string()))?; + let s = built.session; + let tracks: Vec<_> = s + .tracks + .iter() + .enumerate() + .map(|(index, t)| json!({"index": index, "name": t.name, "channels": t.channels(), "clips": t.clips().len()})) + .collect(); + Ok(json!({"plan": plan, "name": s.name, "sample_rate": s.sample_rate.hz(), "frame_rate": s.frame_rate.label(), + "timecode_start": s.timecode_start, "start_timecode": s.format_position(0, soundcraft_time::TimeFormat::Timecode), + "sources": s.sources.len(), "tracks": tracks, "warnings": built.report.warnings})) +} + +/// No destination mutation until all options, times and decoded source files have been checked. +/// Every source must be a file directly inside `media_dir`, the folder given to the analysis. +pub fn import_into(destination: &Session, params: &Value) -> Result<(Session, Value)> { + let plan_value = params.get("plan").ok_or_else(|| bad("`plan` from file.preview_aaf is required"))?; + let mut plan: Plan = serde_json::from_value(plan_value.clone()).map_err(|e| bad(e.to_string()))?; + // The plan comes from the caller, so its media is confined again here, not only at analysis. + let media_dir = params.get("media_dir").and_then(Value::as_str).ok_or_else(|| bad("`media_dir` used for file.preview_aaf is required"))?; + crate::file_access::check_read(media_dir).map_err(EngineError::Io)?; + let indices = params.get("selected").and_then(Value::as_array).ok_or_else(|| bad("`selected` track indices required"))?; + let mut selected = HashSet::new(); + for v in indices { + let n = + v.as_u64().and_then(|n| usize::try_from(n).ok()).filter(|n| *n < plan.tracks.len()).ok_or_else(|| bad("invalid source track index"))?; + if !selected.insert(n) { + return Err(bad("duplicate source track selection")); + } + } + if selected.is_empty() { + return Err(bad("select at least one source track")); + } + let mut i = 0; + plan.tracks.retain(|_| { + let keep = selected.contains(&i); + i += 1; + keep + }); + let used: HashSet = plan.tracks.iter().flat_map(|t| t.clips.iter().map(|c| c.source.clone())).collect(); + plan.sources.retain(|s| used.contains(&s.key)); + let built = build_session(plan).map_err(|e| bad(e.to_string()))?; + let mut incoming = built.session; + let media = params.get("media").and_then(Value::as_str).unwrap_or("copy"); + if media != "copy" { + return Err(bad("only full-source copy is supported; external linking is not preserved by Save Session")); + } + let mapping = params.get("mapping").and_then(Value::as_str).unwrap_or("absolute"); + if !matches!(mapping, "absolute" | "relative") { + return Err(bad("mapping must be absolute or relative")); + } + let offset = match params.get("offset_samples") { + None => 0, + Some(v) => v.as_i64().filter(|n| n.abs_diff(0) <= MAX_POSITION as u64).ok_or_else(|| bad("invalid track offset in samples"))?, + }; + let empty = destination.tracks.is_empty() && destination.sources.is_empty(); + if !empty && incoming.sample_rate != destination.sample_rate { + return Err(bad("sample rates differ; sample-rate conversion is not implemented")); + } + let origin = if empty { incoming.timecode_start } else { destination.timecode_start }; + let shift = if mapping == "absolute" { incoming.timecode_start.checked_sub(origin) } else { Some(0) } + .and_then(|n| n.checked_add(offset)) + .ok_or_else(|| bad("time mapping overflow"))?; + for t in &mut incoming.tracks { + for c in &mut t.playlist_mut().ok_or_else(|| bad("source playlist missing"))?.clips { + c.start = c + .start + .checked_add(shift) + .filter(|n| *n >= 0 && *n <= MAX_POSITION) + .ok_or_else(|| bad("mapped clip precedes session start or exceeds time limit; choose relative mapping or another offset"))?; + if c.start.checked_add(c.length).is_none_or(|n| n > MAX_POSITION) { + return Err(bad("mapped end exceeds time limit")); + } + } + } + let mut total_samples = 0u64; + for src in &incoming.sources { + if !Path::new(&src.path).is_absolute() { + return Err(bad("source paths must be absolute")); + } + total_samples = total_samples + .checked_add(src.frames.saturating_mul(u64::from(src.channels))) + .filter(|n| *n <= 1 << 27) + .ok_or_else(|| bad("selected media exceeds the decoded import memory limit (512 MiB)"))?; + crate::io::check_in_media_dir(Path::new(&src.path), Path::new(media_dir))?; + let bytes = crate::io::read_interchange_file(Path::new(&src.path), 512 * 1024 * 1024)?; + let info = craft_audio::probe(&bytes, Some("wav")).map_err(|e| bad(e.to_string()))?; + if (info.sample_rate, info.channels, info.frames) != (src.sample_rate, src.channels, src.frames) + || soundcraft_model::FileFormat::of(&info) != soundcraft_model::FileFormat::Wav + { + return Err(bad(format!("media changed since analysis: {}", src.path))); + } + let (_, buffer) = craft_audio::decode(&bytes, Some("wav")).map_err(|e| bad(e.to_string()))?; + incoming.pool.insert(src.id, Arc::new(SourceAudio::new(buffer))); + } + let mut target = destination.clone(); + if empty { + target.sample_rate = incoming.sample_rate; + target.frame_rate = incoming.frame_rate; + target.timecode_start = incoming.timecode_start; + if target.name == "Untitled" { + target.name = incoming.name.clone(); + } + } + let mut source_ids = HashMap::new(); + for mut src in incoming.sources { + let old = src.id; + src.id = SourceId(target.alloc()); + let audio = incoming.pool.get(old).ok_or_else(|| bad("decoded media missing"))?.clone(); + target.pool.insert(src.id, audio); + source_ids.insert(old, src.id); + // Save writes the whole decoded source into the destination Audio Files folder. + src.unsaved = true; + target.sources.push(src); + } + let mut track_ids = Vec::new(); + for mut track in incoming.tracks { + track.id = TrackId(target.alloc()); + track.name = target.unique_track_name(&track.name); + let name = track.name.clone(); + for playlist in &mut track.playlists { + playlist.name = name.clone(); + for clip in &mut playlist.clips { + clip.id = ClipId(target.alloc()); + if let ClipContent::Audio { source, .. } = &mut clip.content { + *source = *source_ids.get(source).ok_or_else(|| bad("source mapping missing"))?; + } + } + } + track_ids.push(track.id); + target.tracks.push(track); + } + let first_clip = target.tracks.iter().filter(|t| track_ids.contains(&t.id)).flat_map(|t| t.clips()).map(|c| c.start).min(); + let report = json!({"first_clip_sample":first_clip,"tracks":track_ids,"sources":source_ids.len(),"warnings":built.report.warnings,"handles":built.report.handles,"mapping":mapping,"shift_samples":shift,"media":media}); + Ok((target, report)) +} diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 05a4469e1..28861d02b 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -6,6 +6,7 @@ use soundcraft_model::{ClipId, TrackId}; use soundcraft_time::{Range, Samples}; use std::sync::OnceLock; +mod aaf; mod audio_midi; mod audiosuite; mod auto_rename; @@ -131,6 +132,7 @@ pub fn command_specs() -> &'static [CommandSpec] { SPECS.get_or_init(|| { let mut v = Vec::new(); v.extend(file::specs()); + v.extend(aaf::specs()); v.extend(edit::specs()); v.extend(edit_more::specs()); v.extend(view::specs()); diff --git a/crates/engine/src/cmd/aaf.rs b/crates/engine/src/cmd/aaf.rs new file mode 100644 index 000000000..e758d38bc --- /dev/null +++ b/crates/engine/src/cmd/aaf.rs @@ -0,0 +1,30 @@ +use super::{CommandSpec, always, bad, str_param}; +use crate::Engine; +use crate::cmd; + +pub fn specs() -> Vec { + vec![ + cmd!(query "file.preview_aaf", "Analyze AAF", [], None, "{path, media_dir, composition?} — read-only plan and source properties", always, |_,p| { + let path = str_param(p,"path").ok_or_else(|| bad("file.preview_aaf","path required"))?; + let media = str_param(p,"media_dir").ok_or_else(|| bad("file.preview_aaf","media_dir required"))?; + crate::aaf::preview(path,media,str_param(p,"composition")) + }), + cmd!( + "file.import_aaf", + "Session Data (AAF)...", + ["File", "Import"], + None, + "{plan, media_dir, selected:[track indices], media?: copy, mapping?: absolute|relative, offset_samples?: 0} — new tracks, full source handles, undoable", + stopped, + |e, p| { + stopped(e).map_err(|why| bad("file.import_aaf", why))?; + let (session, report) = crate::aaf::import_into(e.session(), p)?; + *e.session_mut() = session; + Ok(report) + } + ), + ] +} +fn stopped(e: &Engine) -> std::result::Result<(), String> { + if e.transport.playing || e.transport.recording { Err("Stop playback and recording before importing session data".into()) } else { Ok(()) } +} diff --git a/crates/engine/src/io.rs b/crates/engine/src/io.rs index e5a904622..2c921192a 100644 --- a/crates/engine/src/io.rs +++ b/crates/engine/src/io.rs @@ -1121,6 +1121,126 @@ pub fn plan_takes(e: &Engine, unsaved_dir: &Path, input_channels: usize) -> Vec< .collect() } +/// Checks that `path` is a file directly inside the media folder `media_dir` once both are +/// canonical (symlinks resolved), so a plan handed to an import cannot name media elsewhere. +pub(crate) fn check_in_media_dir(path: &Path, media_dir: &Path) -> Result<()> { + let dir = std::fs::canonicalize(media_dir).map_err(|e| EngineError::Io(format!("media folder {}: {e}", media_dir.display())))?; + let file = std::fs::canonicalize(path).map_err(|e| EngineError::Io(format!("{}: {e}", path.display())))?; + if file.parent() != Some(dir.as_path()) { + return Err(EngineError::Io(format!("{} is outside the media folder {}", path.display(), dir.display()))); + } + Ok(()) +} + +/// Bounded, root-checked media read for interchange imports. +pub(crate) fn read_interchange_file(path: &Path, limit: u64) -> Result> { + use std::io::Read; + crate::file_access::check_read(path).map_err(EngineError::Io)?; + let meta = std::fs::metadata(path).map_err(|e| EngineError::Io(e.to_string()))?; + if !meta.is_file() || meta.len() > limit { + return Err(EngineError::Io(format!("{}: not a regular file or exceeds import byte limit", path.display()))); + } + let mut bytes = Vec::new(); + std::fs::File::open(path).and_then(|f| f.take(limit.saturating_add(1)).read_to_end(&mut bytes)).map_err(|e| EngineError::Io(e.to_string()))?; + if bytes.len() as u64 > limit { + return Err(EngineError::Io("media exceeds import byte limit".into())); + } + Ok(bytes) +} + +/// Reads an AAF with the pure-Rust interchange reader. Only the user-chosen AAF and media folder +/// are opened; every referenced WAV must be named in that folder (exact name, no search). +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn read_aaf_plan(path: &str, media_dir: &str, composition: Option<&str>) -> Result { + use soundcraft_interchange::aaf::{AafOptions, read_aaf}; + crate::file_access::check_read(path).map_err(EngineError::Io)?; + crate::file_access::check_read(media_dir).map_err(EngineError::Io)?; + let meta = std::fs::metadata(path).map_err(|e| EngineError::Io(e.to_string()))?; + if !meta.is_file() || meta.len() > 512 * 1024 * 1024 || !Path::new(media_dir).is_dir() { + return Err(EngineError::Io("choose an AAF file (at most 512 MiB) and its media folder".into())); + } + let aaf = std::fs::canonicalize(path).map_err(|e| EngineError::Io(e.to_string()))?; + let media_dir = std::fs::canonicalize(media_dir).map_err(|e| EngineError::Io(e.to_string()))?; + let base = aaf.parent().map(Path::to_path_buf).unwrap_or_default(); + let stem = aaf.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default(); + let file = std::fs::File::open(&aaf).map_err(|e| EngineError::Io(e.to_string()))?; + let options = AafOptions { composition, base_dir: &base, default_name: &stem }; + let plan = read_aaf(std::io::BufReader::new(file), &options, &mut LocalMedia { media_dir: Some(media_dir) }) + .map_err(|e| EngineError::Io(e.to_string()))?; + serde_json::to_value(plan).map_err(|e| EngineError::Io(e.to_string())) +} + +/// Resolves AAF locators to local WAV files, optionally relinking by exact file name. +#[cfg(not(target_arch = "wasm32"))] +pub struct LocalMedia { + /// Canonical relink folder. `None` keeps the locator's own path. + pub media_dir: Option, +} + +#[cfg(not(target_arch = "wasm32"))] +impl soundcraft_interchange::aaf::MediaResolver for LocalMedia { + fn resolve(&mut self, locator: &Path) -> std::result::Result { + use soundcraft_interchange::aaf::{MediaError, MediaInfo, wav_info}; + let source = lenient_canonical(locator); + let (path, relinked_from) = match &self.media_dir { + None => (source, None), + Some(dir) => { + let name = source.file_name().ok_or_else(|| MediaError::Invalid(format!("Locator has no file name: {}", source.display())))?; + let chosen = dir.join(name); + let resolved = lenient_canonical(&chosen); + if resolved.parent() != Some(dir.as_path()) { + return Err(MediaError::Invalid(format!("Relink escapes media directory: {}", chosen.display()))); + } + let from = (chosen != source).then(|| source.display().to_string()); + (resolved, from) + } + }; + if !path.is_file() { + return Err(MediaError::Missing(path.display().to_string())); + } + crate::file_access::check_read(&path).map_err(MediaError::Invalid)?; + let file = std::fs::File::open(&path).map_err(|e| MediaError::Invalid(format!("{}: {e}", path.display())))?; + let info = wav_info(std::io::BufReader::new(file)).map_err(|e| MediaError::Invalid(format!("{}: {e}", path.display())))?; + Ok(MediaInfo { path: path.display().to_string(), relinked_from, channels: info.channels, frames: info.frames, sample_rate: info.sample_rate }) + } +} + +/// `realpath` without requiring the path to exist: the longest existing prefix is canonical +/// (symlinks resolved) and the remaining components are appended after lexical `.`/`..` handling. +#[cfg(not(target_arch = "wasm32"))] +fn lenient_canonical(path: &Path) -> PathBuf { + use std::path::Component; + let mut lexical = PathBuf::new(); + for c in path.components() { + match c { + Component::CurDir => {} + Component::ParentDir => { + lexical.pop(); + } + other => lexical.push(other), + } + } + let mut tail = Vec::new(); + let mut prefix = lexical.as_path(); + loop { + if let Ok(real) = std::fs::canonicalize(prefix) { + return tail.iter().rev().fold(real, |acc: PathBuf, part| acc.join(part)); + } + match (prefix.parent(), prefix.file_name()) { + (Some(parent), Some(name)) => { + tail.push(name.to_os_string()); + prefix = parent; + } + _ => return lexical, + } + } +} + +#[cfg(target_arch = "wasm32")] +pub(crate) fn read_aaf_plan(_: &str, _: &str, _: Option<&str>) -> Result { + Err(EngineError::Io("AAF import needs the desktop app: its media files are read from a local folder".into())) +} + #[cfg(test)] mod exclusive_tests { use super::*; diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index a3ab1243b..c3707df1b 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -5,6 +5,7 @@ //! The engine owns the [`Session`] behind an `Arc` (copy-on-write), so undo snapshots are cheap. #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +pub mod aaf; pub mod autosave; pub mod catalog; pub mod catalog_more; diff --git a/crates/engine/tests/aaf_import.rs b/crates/engine/tests/aaf_import.rs new file mode 100644 index 000000000..1b39b60a9 --- /dev/null +++ b/crates/engine/tests/aaf_import.rs @@ -0,0 +1,414 @@ +use craft_audio::{AudioBuffer, BitDepth, EncodeOptions}; +use serde_json::{Value, json}; +use soundcraft_engine::{Engine, file_access}; +use soundcraft_model::{ChannelFormat, Session, TrackKind}; +use soundcraft_time::SampleRate; +use std::{ + io::{Cursor, Read}, + path::PathBuf, + sync::atomic::{AtomicU64, Ordering}, +}; + +struct Fixture { + dir: PathBuf, + params: Value, +} +impl Fixture { + fn new() -> Self { + static NEXT: AtomicU64 = AtomicU64::new(0); + let dir = std::env::temp_dir().join(format!("soundcraft-aaf-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed))); + std::fs::create_dir(&dir).unwrap(); + let path = dir.join("Source á with spaces.wav"); + let mut ch = vec![0.0; 480000]; + ch[96000] = 0.5; + let bytes = craft_audio::encode( + &AudioBuffer { sample_rate: 48000, channels: vec![ch] }, + &EncodeOptions::new(craft_audio::EncodeFormat::Wav).with_bit_depth(BitDepth::Int16), + ) + .unwrap(); + std::fs::write(&path, bytes).unwrap(); + let params = json!({"plan":{"schema_version":1,"name":"AAF test","sample_rate":48000,"timecode_start":[3600,1],"frame_rate":{"rate":[25,1],"drop":false},"warnings":["Test warning"], + "sources":[{"key":"source","name":"Original source","path":std::fs::canonicalize(&path).unwrap(),"channels":1,"frames":480000,"sample_rate":48000}], + "tracks":[{"name":"DX","channels":1,"clips":[{"name":"Cut","source":"source","start":[1,1],"end":[3,1],"offset":[2,1]}]}, + {"name":"Empty","channels":1,"clips":[]}]},"media_dir":dir,"selected":[0],"mapping":"absolute","media":"copy","offset_samples":0}); + Self { dir, params } + } +} +impl Drop for Fixture { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.dir); + } +} +fn existing() -> Engine { + let mut s = Session::new("Existing", SampleRate::HZ_48000); + s.add_track(TrackKind::Audio, ChannelFormat::Mono, Some("Keep")); + Engine::new(s) +} +#[test] +fn absolute_mapping_preserves_source_window_and_is_one_undo_step() { + let f = Fixture::new(); + let mut e = existing(); + let before = e.session().to_json().unwrap(); + let report = e.execute("file.import_aaf", &f.params).unwrap(); + assert_eq!(report["tracks"].as_array().unwrap().len(), 1); + assert_eq!(e.session().tracks.len(), 2); + let c = &e.session().tracks[1].clips()[0]; + assert_eq!((c.start, c.length, c.source_offset()), (172848000, 96000, 96000)); + assert_eq!(e.session().sources[0].frames, 480000); + assert!(e.session().sources[0].unsaved); + let source = c.source().unwrap(); + assert_eq!(e.session().pool.get(source).unwrap().channel(0).unwrap()[96000], 0.5); + assert_eq!(e.undo_label(), Some("Session Data (AAF)...")); + e.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(e.session().to_json().unwrap(), before); +} +#[test] +fn relative_mapping_and_track_selection_do_not_replace_existing_tracks() { + let mut f = Fixture::new(); + let mut e = existing(); + f.params["mapping"] = json!("relative"); + f.params["offset_samples"] = json!(96000); + e.execute("file.import_aaf", &f.params).unwrap(); + assert_eq!(e.session().tracks[0].name, "Keep"); + assert_eq!(e.session().tracks[1].name, "DX"); + assert_eq!(e.session().tracks[1].clips()[0].start, 144000); + assert!(e.session().sources[0].unsaved); +} +#[test] +fn empty_session_adopts_source_clock_and_save_collects_the_whole_source() { + let f = Fixture::new(); + let mut e = Engine::default(); + e.execute("file.import_aaf", &f.params).unwrap(); + assert_eq!(e.session().timecode_start, 172800000); + assert_eq!(e.session().tracks[0].clips()[0].start, 48000); + let dest = f.dir.join("Saved/session.scraft"); + soundcraft_engine::io::save_session(&mut e, &dest.to_string_lossy()).unwrap(); + let file = f.dir.join("Saved").join(&e.session().sources[0].path); + let info = craft_audio::probe(&std::fs::read(file).unwrap(), Some("wav")).unwrap(); + assert_eq!(info.frames, 480000); + assert_eq!(e.session().tracks[0].clips()[0].source_offset(), 96000); +} +#[test] +fn invalid_inputs_fail_without_mutation() { + let f = Fixture::new(); + let mut e = existing(); + let before = e.session().to_json().unwrap(); + for update in [ + json!({"selected":[]}), + json!({"selected":[99]}), + json!({"selected":[0,0]}), + json!({"mapping":"unknown"}), + json!({"media":"link"}), + json!({"offset_samples":-172900000}), + ] { + let mut p = f.params.clone(); + for (k, v) in update.as_object().unwrap() { + p[k] = v.clone(); + } + assert!(e.execute("file.import_aaf", &p).is_err()); + assert_eq!(e.session().to_json().unwrap(), before); + assert!(e.undo_label().is_none()); + } + std::fs::remove_file(f.dir.join("Source á with spaces.wav")).unwrap(); + assert!(e.execute("file.import_aaf", &f.params).is_err()); + assert_eq!(e.session().to_json().unwrap(), before); +} +#[test] +fn sample_rate_changes_and_confined_media_are_rejected() { + let f = Fixture::new(); + let mut s = Session::new("44.1", SampleRate::HZ_44100); + s.add_track(TrackKind::Audio, ChannelFormat::Mono, Some("Existing")); + let mut e = Engine::new(s); + assert!(e.execute("file.import_aaf", &f.params).unwrap_err().to_string().contains("sample rates differ")); + let restricted = f.dir.join("allowed"); + std::fs::create_dir(&restricted).unwrap(); + let roots = file_access::AutomationRoots::new(&[restricted.as_path()], &[]).unwrap(); + let mut e = existing(); + assert!(file_access::confine(roots.as_ref(), || e.execute("file.import_aaf", &f.params)).is_err()); + assert_eq!(e.session().tracks.len(), 1); +} +#[test] +fn import_confines_the_plans_media_to_the_media_folder_again() { + // A plan is caller-supplied (MCP, automation): editing its paths must not reach other files. + let f = Fixture::new(); + let mut e = existing(); + let before = e.session().to_json().unwrap(); + let elsewhere = f.dir.join("elsewhere"); + std::fs::create_dir(&elsewhere).unwrap(); + std::fs::copy(f.dir.join("Source á with spaces.wav"), elsewhere.join("Source á with spaces.wav")).unwrap(); + let outside = std::fs::canonicalize(elsewhere.join("Source á with spaces.wav")).unwrap(); + let traversal = elsewhere.join("..").join("elsewhere").join("Source á with spaces.wav"); + for path in [json!(outside), json!(traversal)] { + let mut p = f.params.clone(); + p["plan"]["sources"][0]["path"] = path.clone(); + let err = e.execute("file.import_aaf", &p).unwrap_err().to_string(); + assert!(err.contains("outside the media folder"), "{path}: {err}"); + } + #[cfg(unix)] + { + let link = f.dir.join("link.wav"); + std::os::unix::fs::symlink(&outside, &link).unwrap(); + let mut p = f.params.clone(); + p["plan"]["sources"][0]["path"] = json!(link); + assert!(e.execute("file.import_aaf", &p).unwrap_err().to_string().contains("outside the media folder")); + } + let mut p = f.params.clone(); + p.as_object_mut().unwrap().remove("media_dir"); + assert!(e.execute("file.import_aaf", &p).unwrap_err().to_string().contains("media_dir")); + assert_eq!(e.session().to_json().unwrap(), before); + assert!(e.undo_label().is_none()); +} +#[test] +fn playing_import_cannot_bypass_the_transport_guard_with_target_params() { + let f = Fixture::new(); + let mut e = existing(); + e.transport.playing = true; + let mut p = f.params.clone(); + p["tracks"] = json!([1]); + assert!(e.execute("file.import_aaf", &p).is_err()); + assert_eq!(e.session().tracks.len(), 1); +} + +/// A synthetic AAF (two tracks, three edits, chained source offsets) written by pyaaf2. Its +/// external WAVs are regenerated here with the same names, layouts and lengths. +struct AafFolder { + dir: PathBuf, +} +impl AafFolder { + fn new() -> Self { + let dir = Fixture::new().dir.with_extension("aaf"); + std::fs::create_dir(&dir).unwrap(); + std::fs::copy(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fixtures/synthetic-two-tracks.aaf"), dir.join("Montaje sintético.aaf")).unwrap(); + for (name, channels) in [("Diálogo á #1.wav", 1), ("Ambiente estéreo.wav", 2)] { + let audio = AudioBuffer { sample_rate: 48000, channels: vec![vec![0.25; 384000]; channels] }; + let options = EncodeOptions::new(craft_audio::EncodeFormat::Wav).with_bit_depth(BitDepth::Int16); + std::fs::write(dir.join(name), craft_audio::encode(&audio, &options).unwrap()).unwrap(); + } + Self { dir } + } + fn preview(&self) -> soundcraft_engine::Result { + let aaf = self.dir.join("Montaje sintético.aaf"); + Engine::default().execute("file.preview_aaf", &json!({"path": aaf, "media_dir": self.dir})) + } +} +impl Drop for AafFolder { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.dir); + } +} + +#[test] +fn rust_reader_turns_an_aaf_file_into_editable_tracks() { + let f = AafFolder::new(); + let preview = f.preview().unwrap(); + let plan = &preview["plan"]; + assert_eq!(plan["name"], "Clase AAF — cortes y handles"); + assert_eq!(plan["timecode_start"], json!([3600, 1])); + assert_eq!(plan["frame_rate"], json!({"rate": [25, 1], "drop": false})); + let names: Vec<_> = plan["tracks"].as_array().unwrap().iter().map(|t| t["name"].as_str().unwrap()).collect(); + assert_eq!(names, ["01 Diálogo", "02 Ambiente estéreo"]); + assert_eq!(plan["tracks"][0]["clips"][1]["offset"], json!([7, 2])); + let channels: Vec<_> = plan["sources"].as_array().unwrap().iter().map(|s| s["channels"].as_u64().unwrap()).collect(); + assert_eq!(channels, [1, 2]); + assert!(plan["sources"][0]["path"].as_str().unwrap().ends_with("Diálogo á #1.wav")); + + let mut e = Engine::default(); + e.execute("file.import_aaf", &json!({"plan": plan, "media_dir": f.dir, "selected": [0, 1]})).unwrap(); + let edits: Vec<_> = e.session().tracks.iter().flat_map(|t| t.clips()).map(|c| (c.start, c.length, c.source_offset())).collect(); + assert_eq!(edits, [(48000, 96000, 48000), (192000, 48000, 168000), (0, 240000, 72000)]); + assert_eq!(e.session().timecode_start, 3600 * 48000); + assert_eq!(e.session().tracks[1].channels(), 2); +} + +#[test] +fn missing_media_is_reported_and_its_edits_skipped_without_failing_the_import() { + let f = AafFolder::new(); + std::fs::remove_file(f.dir.join("Diálogo á #1.wav")).unwrap(); + let preview = f.preview().unwrap(); + let plan = &preview["plan"]; + let missing: Vec<_> = plan["warnings"].as_array().unwrap().iter().filter_map(|w| w.as_str()).filter(|w| w.starts_with("Missing media")).collect(); + assert_eq!(missing.len(), 1, "{missing:?}"); + assert!(missing[0].contains("Diálogo á #1.wav") && missing[0].contains("2 edit(s) skipped"), "{}", missing[0]); + // The dialogue track keeps its name but loses its two edits; the ambience edit is intact. + assert_eq!(plan["tracks"][0]["clips"].as_array().unwrap().len(), 0); + assert_eq!(plan["tracks"][1]["clips"].as_array().unwrap().len(), 1); + assert_eq!(plan["sources"].as_array().unwrap().len(), 1); + let mut e = Engine::default(); + e.execute("file.import_aaf", &json!({"plan": plan, "media_dir": f.dir, "selected": [0, 1]})).unwrap(); + let edits: Vec<_> = e.session().tracks.iter().flat_map(|t| t.clips()).map(|c| (c.start, c.length, c.source_offset())).collect(); + assert_eq!(edits, [(0, 240000, 72000)]); + + // With no media at all there is nothing to import. + std::fs::remove_file(f.dir.join("Ambiente estéreo.wav")).unwrap(); + let err = f.preview().unwrap_err().to_string(); + assert!(err.contains("none of the referenced files were found"), "{err}"); +} + +#[test] +fn media_that_is_present_but_not_a_wav_still_fails() { + let f = AafFolder::new(); + std::fs::write(f.dir.join("Diálogo á #1.wav"), b"RIFF\0\0\0\0WAVEnot audio").unwrap(); + assert!(f.preview().is_err()); +} + +/// The fixture with its first WAV locator (`Di%C3%A1logo%20%C3%A1%20%231.wav`, 32 UTF-16 units) +/// replaced by `url`, padded to the same length so the property stream stays well formed. +fn with_locator(f: &AafFolder, url: &str) -> soundcraft_engine::Result { + let original = "Di%C3%A1logo%20%C3%A1%20%231.wav"; + assert_eq!(url.encode_utf16().count(), original.encode_utf16().count(), "{url}"); + let aaf = f.dir.join("Montaje sintético.aaf"); + let mut bytes = std::fs::read(&aaf).unwrap(); + let from: Vec = original.encode_utf16().flat_map(u16::to_le_bytes).collect(); + let to: Vec = url.encode_utf16().flat_map(u16::to_le_bytes).collect(); + let at = bytes.windows(from.len()).position(|w| w == from.as_slice()).unwrap(); + bytes[at..at + to.len()].copy_from_slice(&to); + std::fs::write(&aaf, bytes).unwrap(); + f.preview() +} + +#[test] +fn locators_that_try_to_leave_the_aaf_folder_are_refused() { + for url in [ + "../../../../../../etc/passwd.wav", + "%2E%2E/%2E%2E/%2E%2E/secret1.wav", + "file:///tmp/../etc/shadow000.wav", + "http://evil.example/payload0.wav", + "file://server/share/payload0.wav", + "Di%C3%A1logo%20%C3%A1%20%231.wa/", + "Di%C3%A1logo%20%C3%A1%20%001.wav", + ] { + let f = AafFolder::new(); + let err = with_locator(&f, url).unwrap_err().to_string(); + assert!(err.contains("ocator"), "{url}: {err}"); + } +} + +#[test] +fn an_absolute_locator_only_names_a_file_in_the_chosen_media_folder() { + // A locator pointing anywhere on disk is reduced to its file name and looked up only in the + // media folder the user chose: the real file elsewhere is never opened. + let f = AafFolder::new(); + let preview = with_locator(&f, "file:///etc/Dlogo%20%C3%A1_1.wav").unwrap(); + let w: Vec<_> = preview["plan"]["warnings"].as_array().unwrap().iter().filter_map(|w| w.as_str()).collect(); + assert!( + w.iter().any( + |w| w.starts_with("Missing media") && w.contains(&std::fs::canonicalize(&f.dir).unwrap().join("Dlogo á_1.wav").display().to_string()) + ), + "{w:?}" + ); +} + +/// Offsets into a structured-storage (CFB) file, enough to rewrite one FAT entry. +struct Cfb { + bytes: Vec, + sector: usize, +} +impl Cfb { + fn new(bytes: Vec) -> Self { + let sector = 1 << u16::from_le_bytes([bytes[0x1E], bytes[0x1F]]); + Self { bytes, sector } + } + fn u32_at(&self, at: usize) -> u32 { + u32::from_le_bytes(self.bytes[at..at + 4].try_into().unwrap()) + } + fn fat_entry(&self, i: u32) -> usize { + let per = self.sector / 4; + let fat_sector = self.u32_at(0x4C + 4 * (i as usize / per)); + (fat_sector as usize + 1) * self.sector + 4 * (i as usize % per) + } + fn chain(&self, start: u32) -> Vec { + let mut out = vec![start]; + while let next @ 0..=0xFFFF_FFF9 = self.u32_at(self.fat_entry(*out.last().unwrap())) { + out.push(next); + } + out + } + fn point(&mut self, from: u32, to: u32) { + let at = self.fat_entry(from); + self.bytes[at..at + 4].copy_from_slice(&to.to_le_bytes()); + } +} + +#[test] +fn looped_sector_chains_fail_instead_of_hanging() { + let fixture = std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fixtures/synthetic-two-tracks.aaf")).unwrap(); + let base = Cfb::new(fixture); + let root_start = base.u32_at(base.sector + 0x74); + // (chain, start sector): directory, mini FAT, mini stream (root entry). + let chains = [("directory", base.u32_at(0x30)), ("mini FAT", base.u32_at(0x3C)), ("mini stream", root_start)]; + for (name, start) in chains { + let chain = base.chain(start); + assert!(chain.len() >= 2, "{name}: fixture chain too short to loop"); + let last = *chain.last().unwrap(); + // Back to the start, and onto itself in the middle (a sector reached twice). + for (from, to) in [(last, start), (chain[1], chain[1])] { + let mut cfb = Cfb::new(base.bytes.clone()); + cfb.point(from, to); + let f = AafFolder::new(); + let aaf = f.dir.join("Montaje sintético.aaf"); + std::fs::write(&aaf, &cfb.bytes).unwrap(); + let (tx, rx) = std::sync::mpsc::channel(); + let media = f.dir.clone(); + std::thread::spawn(move || { + let _ = tx.send(Engine::default().execute("file.preview_aaf", &json!({"path": aaf, "media_dir": media})).map(|_| ())); + }); + let result = + rx.recv_timeout(std::time::Duration::from_secs(30)).unwrap_or_else(|_| panic!("{name} {from}->{to}: reader did not terminate")); + assert!(result.is_err(), "{name} {from}->{to}: a looped chain was accepted"); + } + } +} + +#[test] +fn relinked_sources_are_reported_once_however_many_edits_use_them() { + let f = AafFolder::new(); + let moved = f.dir.join("moved media"); + std::fs::create_dir(&moved).unwrap(); + for name in ["Diálogo á #1.wav", "Ambiente estéreo.wav"] { + std::fs::rename(f.dir.join(name), moved.join(name)).unwrap(); + } + let aaf = f.dir.join("Montaje sintético.aaf"); + let preview = Engine::default().execute("file.preview_aaf", &json!({"path": aaf, "media_dir": moved})).unwrap(); + let relinks = preview["plan"]["warnings"].as_array().unwrap().iter().filter(|w| w.as_str().unwrap().starts_with("Relinked ")).count(); + // Three edits, two source files: the dialogue source is used twice. + assert_eq!(relinks, 2); + assert_eq!(preview["plan"]["sources"].as_array().unwrap().len(), 2); +} + +#[test] +fn an_unknown_composition_id_is_refused() { + let f = AafFolder::new(); + let aaf = f.dir.join("Montaje sintético.aaf"); + let err = Engine::default() + .execute("file.preview_aaf", &json!({"path": aaf, "media_dir": f.dir, "composition": "urn:smpte:umid:00"})) + .unwrap_err() + .to_string(); + assert!(err.contains("Choose exactly one composition"), "{err}"); +} + +#[test] +fn repeated_local_mob_references_fail_before_property_expansion() { + // A small index can otherwise expand one storage's properties once per repeated reference. + let mut bytes = std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fixtures/synthetic-two-tracks.aaf")).unwrap(); + let mut index = Vec::new(); + { + let mut cfb = cfb::CompoundFile::open(Cursor::new(bytes.as_slice())).unwrap(); + cfb.open_stream("/Header-2/Content-3b03/Mobs-1901 index").unwrap().read_to_end(&mut index).unwrap(); + } + let count = u32::from_le_bytes(index[0..4].try_into().unwrap()) as usize; + let key_size = usize::from(index[14]); + assert!(count >= 2 && matches!(key_size, 16 | 32)); + let entry = 8 + key_size; + let original_index = index.clone(); + let first_local = index[15..19].to_vec(); + index[15 + entry..19 + entry].copy_from_slice(&first_local); + + // This small stream is contiguous in the fixture's mini stream; replace only its index bytes. + let at = bytes.windows(original_index.len()).position(|window| window == original_index.as_slice()).unwrap(); + bytes[at..at + index.len()].copy_from_slice(&index); + + let f = AafFolder::new(); + std::fs::write(f.dir.join("Montaje sintético.aaf"), bytes).unwrap(); + let err = f.preview().unwrap_err().to_string(); + assert!(err.contains("duplicate local reference in mobs"), "{err}"); +} diff --git a/crates/engine/tests/fixtures/synthetic-two-tracks.aaf b/crates/engine/tests/fixtures/synthetic-two-tracks.aaf new file mode 100644 index 000000000..848bdfdb2 Binary files /dev/null and b/crates/engine/tests/fixtures/synthetic-two-tracks.aaf differ diff --git a/crates/interchange/Cargo.toml b/crates/interchange/Cargo.toml new file mode 100644 index 000000000..a70193d00 --- /dev/null +++ b/crates/interchange/Cargo.toml @@ -0,0 +1,19 @@ +[package] +name = "soundcraft-interchange" +description = "Rational-time interchange plans and editable session construction" +version.workspace = true +edition.workspace = true +license = "MIT" +rust-version.workspace = true +repository.workspace = true + +[dependencies] +soundcraft-model.workspace = true +soundcraft-time.workspace = true +serde.workspace = true +serde_json.workspace = true +thiserror.workspace = true +cfb.workspace = true + +[lints] +workspace = true diff --git a/crates/interchange/README.md b/crates/interchange/README.md new file mode 100644 index 000000000..0b6642563 --- /dev/null +++ b/crates/interchange/README.md @@ -0,0 +1,28 @@ +# Interchange core + +Pure Rust Plan → Session constructor, originally developed in vhhr7/soundcraft_helper. +Rational endpoints are converted to samples independently; sources retain complete media +bounds and clips retain source offsets. No processes, UI or filesystem access. + +`aaf` reads a strict subset of AAF (structured storage, via the `cfb` crate) into a Plan: +timeline slots of SourceClip/Filler, resolved through MasterMobs to SourceMobs with a +WAVEDescriptor and one external file locator. Gain, fades, transitions, selectors, nested +sequences, embedded essence and split channels fail explicitly. The caller supplies the +opened AAF and a `MediaResolver` that confines, relinks and probes each WAV; the engine's +resolver accepts only files named exactly in the media folder the user chose. + +The reader's plans were checked byte-for-byte against the earlier pyaaf2 prototype on the +synthetic fixture, twelve edited variants of it and a 22-track/124-edit real-world AAF. + +## Untrusted input and provenance + +AAF files are treated as hostile input; the bounds (sector chains, directory size, stream +size, collection counts, source-chain depth) and the locator rules (local paths only, no +`..`, relative locators stay under the AAF's folder, missing media reported per file rather +than aborting) are listed in the `aaf` module documentation and covered by tests in +`crates/engine/tests/aaf_import.rs`. + +The storage layout, class and property identifiers and MobID text form were learned by +reading pyaaf2 (MIT, Mark Reid); no pyaaf2 code was copied, and pyaaf2 also wrote the +synthetic test fixture. No code from the AAF SDK or from any GPL/LGPL/MPL project was read or +used. diff --git a/crates/interchange/src/aaf.rs b/crates/interchange/src/aaf.rs new file mode 100644 index 000000000..c300e5804 --- /dev/null +++ b/crates/interchange/src/aaf.rs @@ -0,0 +1,1068 @@ +//! Strict, read-only AAF reader that emits an interchange [`Plan`]. Pure Rust over `cfb`. +//! +//! Reads the AAF structured-storage object model directly (properties streams, strong +//! reference vectors/sets and dictionary weak references) for a deliberately small subset: +//! one CompositionMob whose timeline slots hold Sequences of SourceClip and Filler, resolved +//! through MasterMobs to SourceMobs with a WAVEDescriptor and one external NetworkLocator. +//! Anything else in an audio slot aborts instead of producing a misleading montage. +//! +//! No filesystem access happens here: the caller passes the opened AAF and a [`MediaResolver`] +//! that turns a decoded locator path into checked media properties. +//! +//! # Provenance +//! Written for SoundCraft. The storage layout (properties streams, reference indexes, the +//! referenced-properties table), the class and property identifiers and the MobID text form +//! were learned by reading pyaaf2 (MIT, Mark Reid); no pyaaf2 code was copied. The reader was +//! checked against plans from a pyaaf2 prototype on the synthetic fixture, edited variants of +//! it and a real session export. No code from the AAF SDK (AAF SDK Public Source License) or +//! any GPL/LGPL/MPL project was read or copied. +//! +//! # Untrusted input +//! The AAF is hostile input. Every walk is bounded: +//! - structured storage (FAT, mini FAT, DIFAT and directory chains, directory tree) is parsed by +//! `cfb`, which rejects a sector pointed to twice, a chain that returns to its start and a +//! loop in the directory tree; we additionally cap the directory at [`MAX_DIRECTORY_ENTRIES`]; +//! - each stream we read is capped at 32 MiB, so no property or index can exceed it; the object +//! cache retains at most 128 MiB of property streams and shares payloads when objects are cloned; +//! - collections (mobs, slots, components, set/vector entries) are capped at [`MAX_ITEMS`], reject +//! duplicate local references, and retain at most `4 * MAX_ITEMS` distinct objects. Repeated +//! traversal uses the cache. Mob-to-mob source chains are capped at 32 links with cycle detection. +//! Object lookups are iterative except that source chain, so recursion depth is bounded by it; +//! - locator URLs are data: only local `file:` or scheme-less paths, never `..`, and a relative +//! locator resolves under the AAF's folder (see `locator_path`). A file that cannot be found +//! is reported and its edits skipped; it does not abort the import. +use crate::{ImportClip, ImportError, ImportTrack, Media, Plan, Rational, TimecodeRate}; +use std::{ + collections::{HashMap, HashSet}, + io::{Read, Seek, SeekFrom}, + path::{Path, PathBuf}, + rc::Rc, +}; + +type Result = std::result::Result; +fn fail(s: impl Into) -> ImportError { + ImportError(s.into()) +} + +/// Upper bound on mobs, slots, components and collection entries. +pub const MAX_ITEMS: usize = 100_000; +/// Upper bound on structured-storage directory entries (storages and streams). +pub const MAX_DIRECTORY_ENTRIES: usize = 4 * MAX_ITEMS; +const MAX_STREAM_BYTES: u64 = 32 * 1024 * 1024; +/// Aggregate bound on property streams retained by the object cache. +const MAX_PROPERTY_BYTES: usize = 128 * 1024 * 1024; +const MAX_SOURCE_DEPTH: usize = 32; + +const CLASS_COMPOSITION_MOB: &str = "0d010101-0101-3500-060e-2b3402060101"; +const CLASS_MASTER_MOB: &str = "0d010101-0101-3600-060e-2b3402060101"; +const CLASS_SOURCE_MOB: &str = "0d010101-0101-3700-060e-2b3402060101"; +const CLASS_TIMELINE_SLOT: &str = "0d010101-0101-3b00-060e-2b3402060101"; +const CLASS_SEQUENCE: &str = "0d010101-0101-0f00-060e-2b3402060101"; +const CLASS_SOURCE_CLIP: &str = "0d010101-0101-1100-060e-2b3402060101"; +const CLASS_FILLER: &str = "0d010101-0101-0900-060e-2b3402060101"; +const CLASS_TIMECODE: &str = "0d010101-0101-1400-060e-2b3402060101"; +const CLASS_TRANSITION: &str = "0d010101-0101-1700-060e-2b3402060101"; +const CLASS_WAVE_DESCRIPTOR: &str = "0d010101-0101-2c00-060e-2b3402060101"; + +const PID_HEADER: u16 = 0x0002; +const PID_COMPONENT_DATADEF: u16 = 0x0201; +const PID_COMPONENT_LENGTH: u16 = 0x0202; +const PID_SEQUENCE_COMPONENTS: u16 = 0x1001; +const PID_SOURCE_ID: u16 = 0x1101; +const PID_SOURCE_SLOT_ID: u16 = 0x1102; +const PID_START_TIME: u16 = 0x1201; +const PID_TIMECODE_START: u16 = 0x1501; +const PID_TIMECODE_FPS: u16 = 0x1502; +const PID_TIMECODE_DROP: u16 = 0x1503; +const PID_CONTENT_MOBS: u16 = 0x1901; +const PID_CONTENT_ESSENCE: u16 = 0x1902; +const PID_DEF_NAME: u16 = 0x1B02; +const PID_ESSENCE_MOB_ID: u16 = 0x2701; +const PID_DESCRIPTOR_LOCATORS: u16 = 0x2F01; +const PID_FILE_SAMPLE_RATE: u16 = 0x3001; +const PID_FILE_LENGTH: u16 = 0x3002; +const PID_HEADER_CONTENT: u16 = 0x3B03; +const PID_URL_STRING: u16 = 0x4001; +const PID_MOB_ID: u16 = 0x4401; +const PID_MOB_NAME: u16 = 0x4402; +const PID_MOB_SLOTS: u16 = 0x4403; +const PID_SOURCE_MOB_DESCRIPTOR: u16 = 0x4701; +const PID_SLOT_ID: u16 = 0x4801; +const PID_SLOT_NAME: u16 = 0x4802; +const PID_SLOT_SEGMENT: u16 = 0x4803; +const PID_SLOT_PHYSICAL: u16 = 0x4804; +const PID_SLOT_EDIT_RATE: u16 = 0x4B01; +const PID_SLOT_ORIGIN: u16 = 0x4B02; + +const SF_DATA: u16 = 0x82; +const SF_STRONG_REF: u16 = 0x22; +const SF_STRONG_VECTOR: u16 = 0x32; +const SF_STRONG_SET: u16 = 0x3A; +const SF_WEAK_REF: u16 = 0x02; + +/// Media properties of one external source, checked by the caller. +#[derive(Debug, Clone)] +pub struct MediaInfo { + /// Absolute, resolved path of the file that will be imported. + pub path: String, + /// The resolved locator path when the caller substituted another file (explicit relink). + pub relinked_from: Option, + pub channels: u16, + pub frames: u64, + pub sample_rate: u32, +} + +#[derive(Debug)] +pub enum MediaError { + /// The (possibly relinked) file does not exist. + Missing(String), + Invalid(String), +} + +/// Supplies checked properties for a locator. `locator` is the percent-decoded local path, +/// already joined to the AAF's folder when the URL was relative. Implementations decide how +/// to resolve, confine and relink it. +pub trait MediaResolver { + fn resolve(&mut self, locator: &Path) -> std::result::Result; +} + +pub struct AafOptions<'a> { + /// Explicit CompositionMob MobID (`urn:smpte:umid:...`) when the file holds several. + pub composition: Option<&'a str>, + /// Folder of the AAF file, used for relative locators. + pub base_dir: &'a Path, + /// Session name when the composition has none (usually the AAF file stem). + pub default_name: &'a str, +} + +/// Readable names for classes that commonly appear in rejected structures. +const CLASS_NAMES: &[(&str, &str)] = &[ + (CLASS_COMPOSITION_MOB, "CompositionMob"), + (CLASS_MASTER_MOB, "MasterMob"), + (CLASS_SOURCE_MOB, "SourceMob"), + (CLASS_TIMELINE_SLOT, "TimelineMobSlot"), + (CLASS_SEQUENCE, "Sequence"), + (CLASS_SOURCE_CLIP, "SourceClip"), + (CLASS_FILLER, "Filler"), + (CLASS_TIMECODE, "Timecode"), + (CLASS_TRANSITION, "Transition"), + (CLASS_WAVE_DESCRIPTOR, "WAVEDescriptor"), + ("0d010101-0101-0a00-060e-2b3402060101", "OperationGroup"), + ("0d010101-0101-0e00-060e-2b3402060101", "Selector"), + ("0d010101-0101-0b00-060e-2b3402060101", "NestedScope"), + ("0d010101-0101-0d00-060e-2b3402060101", "ScopeReference"), + ("0d010101-0101-0500-060e-2b3402060101", "EssenceGroup"), + ("0d010101-0101-0c00-060e-2b3402060101", "Pulldown"), + ("0d010101-0101-0400-060e-2b3402060101", "EdgeCode"), + ("0d010101-0101-0600-060e-2b3402060101", "Event"), + ("0d010101-0101-0800-060e-2b3402060101", "CommentMarker"), + ("0d010101-0101-2e00-060e-2b3402060101", "TapeDescriptor"), + ("0d010101-0101-4800-060e-2b3402060101", "PCMDescriptor"), + ("0d010101-0101-2600-060e-2b3402060101", "AIFCDescriptor"), + ("0d010101-0101-4400-060e-2b3402060101", "MultipleDescriptor"), + ("0d010101-0101-4a00-060e-2b3402060101", "ImportDescriptor"), + ("0d010101-0101-3900-060e-2b3402060101", "EventMobSlot"), + ("0d010101-0101-3a00-060e-2b3402060101", "StaticMobSlot"), +]; + +// --------------------------------------------------------------------------------------------- +// Exact rational arithmetic (Python Fraction semantics within i128). + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +struct Q { + n: i128, + d: i128, +} +fn gcd(mut a: i128, mut b: i128) -> i128 { + a = a.abs(); + b = b.abs(); + while b != 0 { + (a, b) = (b, a % b); + } + a +} +impl Q { + fn new(n: i128, d: i128) -> Result { + if d == 0 { + return Err(fail("zero denominator")); + } + let (n, d) = if d < 0 { (n.checked_neg(), d.checked_neg()) } else { (Some(n), Some(d)) }; + let (n, d) = n.zip(d).ok_or_else(|| fail("rational overflow"))?; + let g = gcd(n, d).max(1); + Ok(Q { n: n / g, d: d / g }) + } + fn int(n: i64) -> Q { + Q { n: i128::from(n), d: 1 } + } + fn add(self, o: Q) -> Result { + let n = self.n.checked_mul(o.d).zip(o.n.checked_mul(self.d)).and_then(|(a, b)| a.checked_add(b)); + let d = self.d.checked_mul(o.d); + Q::new(n.ok_or_else(|| fail("rational overflow"))?, d.ok_or_else(|| fail("rational overflow"))?) + } + fn div(self, o: Q) -> Result { + let n = self.n.checked_mul(o.d); + let d = self.d.checked_mul(o.n); + Q::new(n.ok_or_else(|| fail("rational overflow"))?, d.ok_or_else(|| fail("rational overflow"))?) + } + fn lt(self, o: Q) -> bool { + // Denominators are positive after normalisation; overflow compares as "not less". + match (self.n.checked_mul(o.d), o.n.checked_mul(self.d)) { + (Some(a), Some(b)) => a < b, + _ => false, + } + } + /// Python `round()`: nearest integer, ties to even. + fn round_half_even(self) -> i128 { + let floor = self.n.div_euclid(self.d); + let twice = (self.n - floor * self.d) * 2; + if twice < self.d || (twice == self.d && floor % 2 == 0) { floor } else { floor + 1 } + } + fn plan(self) -> Result { + Ok(Rational(i64::try_from(self.n).map_err(|_| fail("time overflow"))?, i64::try_from(self.d).map_err(|_| fail("time overflow"))?)) + } +} + +// --------------------------------------------------------------------------------------------- +// Structured storage object model. + +#[derive(Debug, Clone)] +struct Obj { + path: String, + class: String, + // Cached objects are cloned along source and dictionary walks; share their property payload. + props: Rc)>>, +} + +impl Obj { + fn data(&self, pid: u16) -> Option<&[u8]> { + self.props.get(&pid).filter(|(form, _)| *form == SF_DATA).map(|(_, d)| d.as_slice()) + } + fn has(&self, pid: u16) -> bool { + self.props.contains_key(&pid) + } + fn bytes(&self, pid: u16, what: &str) -> Result<[u8; N]> { + self.data(pid).and_then(|d| d.get(..N)).and_then(|d| d.try_into().ok()).ok_or_else(|| fail(format!("missing or short {what}"))) + } + fn u32(&self, pid: u16, what: &str) -> Result { + self.bytes::<4>(pid, what).map(u32::from_le_bytes) + } + fn i64(&self, pid: u16, what: &str) -> Result { + self.bytes::<8>(pid, what).map(i64::from_le_bytes) + } + fn opt_u32(&self, pid: u16, what: &str) -> Result> { + if self.has(pid) { self.u32(pid, what).map(Some) } else { Ok(None) } + } + fn rational(&self, pid: u16, what: &str) -> Result { + let b = self.bytes::<8>(pid, what)?; + let n = i32::from_le_bytes([b[0], b[1], b[2], b[3]]); + let d = i32::from_le_bytes([b[4], b[5], b[6], b[7]]); + Q::new(i128::from(n), i128::from(d)) + } + /// Optional string; absent or empty reads as `None` like a falsy Python name. + fn string(&self, pid: u16) -> Option { + self.data(pid).map(utf16).filter(|s| !s.is_empty()) + } + fn length(&self) -> Result { + self.i64(PID_COMPONENT_LENGTH, "component Length") + } + fn is(&self, class: &str) -> bool { + self.class == class + } + /// Class name for messages; unknown (extension) classes print their AUID. + fn kind(&self) -> &str { + CLASS_NAMES.iter().find(|(id, _)| *id == self.class).map_or(self.class.as_str(), |(_, n)| n) + } +} + +fn utf16(d: &[u8]) -> String { + let units: Vec = d.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c)).take_while(|u| *u != 0).collect(); + String::from_utf16_lossy(&units) +} + +fn read_u16(d: &[u8], at: usize) -> Result { + d.get(at..at + 2).and_then(|b| b.try_into().ok()).map(u16::from_le_bytes).ok_or_else(|| fail("truncated AAF structure")) +} +fn read_u32(d: &[u8], at: usize) -> Result { + d.get(at..at + 4).and_then(|b| b.try_into().ok()).map(u32::from_le_bytes).ok_or_else(|| fail("truncated AAF structure")) +} + +fn property_total(current: usize, additional: usize) -> Result { + current.checked_add(additional).filter(|total| *total <= MAX_PROPERTY_BYTES).ok_or_else(|| fail("AAF retained property data exceeds 128 MiB")) +} + +/// `urn:smpte:umid:` text identical to pyaaf2 and Pro Tools' MobID notation. +fn mob_urn(b: &[u8; 32]) -> String { + let label: String = b[..12].chunks(4).map(|c| c.iter().map(|x| format!("{x:02x}")).collect::()).collect::>().join("."); + let head = format!("urn:smpte:umid:{label}.{:02x}{:02x}{:02x}{:02x}", b[12], b[13], b[14], b[15]); + let data1 = u32::from_le_bytes([b[16], b[17], b[18], b[19]]); + let data2 = u16::from_le_bytes([b[20], b[21]]); + let data3 = u16::from_le_bytes([b[22], b[23]]); + let d4 = &b[24..32]; + let d4a = format!("{:02x}{:02x}{:02x}{:02x}", d4[0], d4[1], d4[2], d4[3]); + let d4b = format!("{:02x}{:02x}{:02x}{:02x}", d4[4], d4[5], d4[6], d4[7]); + // Material numbers stored half swapped (an SMPTE label in Data4) print label-first. + if b[11] == 0 && d4[..6] == [0x06, 0x0e, 0x2b, 0x34, 0x7f, 0x7f] { + format!("{head}.{d4a}.{d4b}.{data1:08x}.{data2:04x}{data3:04x}") + } else { + format!("{head}.{data1:08x}.{data2:04x}{data3:04x}.{d4a}.{d4b}") + } +} + +struct Store { + cfb: cfb::CompoundFile, + objects: HashMap, + property_bytes: usize, + weakrefs: Vec>, + datadefs: HashMap, Option>, +} + +impl Store { + fn open(file: F) -> Result { + let cfb = cfb::CompoundFile::open(file).map_err(|e| fail(format!("not an AAF structured-storage file: {e}")))?; + if cfb.walk().take(MAX_DIRECTORY_ENTRIES + 1).count() > MAX_DIRECTORY_ENTRIES { + return Err(fail("AAF directory has too many entries")); + } + let mut s = Store { cfb, objects: HashMap::new(), property_bytes: 0, weakrefs: Vec::new(), datadefs: HashMap::new() }; + s.weakrefs = s.read_weakref_table()?; + Ok(s) + } + + fn stream(&mut self, path: &str) -> Result>> { + if !self.cfb.is_stream(path) { + return Ok(None); + } + let s = self.cfb.open_stream(path).map_err(|e| fail(format!("{path}: {e}")))?; + let mut out = Vec::new(); + s.take(MAX_STREAM_BYTES + 1).read_to_end(&mut out).map_err(|e| fail(format!("{path}: {e}")))?; + if out.len() as u64 > MAX_STREAM_BYTES { + return Err(fail(format!("{path}: AAF stream exceeds 32 MiB"))); + } + Ok(Some(out)) + } + + fn read_weakref_table(&mut self) -> Result>> { + let Some(d) = self.stream("/referenced properties")? else { return Ok(Vec::new()) }; + if d.first() != Some(&0x4c) { + return Err(fail("unsupported AAF byte order")); + } + let paths = usize::from(read_u16(&d, 1)?); + let pids = read_u32(&d, 3)? as usize; + if pids > MAX_ITEMS { + return Err(fail("referenced property table too large")); + } + let mut table = Vec::new(); + let mut path = Vec::new(); + for i in 0..pids { + match read_u16(&d, 7 + 2 * i)? { + 0 => table.push(std::mem::take(&mut path)), + pid => path.push(pid), + } + } + if table.len() != paths { + return Err(fail("inconsistent referenced property table")); + } + Ok(table) + } + + fn charge_properties(&mut self, additional: usize) -> Result<()> { + self.property_bytes = property_total(self.property_bytes, additional)?; + Ok(()) + } + + fn object(&mut self, path: &str) -> Result { + // Repeated traversal must not read or copy the same property payload again. + if let Some(object) = self.objects.get(path) { + return Ok(object.clone()); + } + if self.objects.len() >= 4 * MAX_ITEMS { + return Err(fail("too many AAF objects")); + } + let entry = self.cfb.entry(path).map_err(|e| fail(format!("{path}: {e}")))?; + if !entry.is_storage() { + return Err(fail(format!("{path}: not an AAF object"))); + } + let class = entry.clsid().to_string(); + let props_path = if path == "/" { "/properties".to_string() } else { format!("{path}/properties") }; + let d = self.stream(&props_path)?.ok_or_else(|| fail(format!("{path}: missing properties")))?; + if d.first() != Some(&0x4c) { + return Err(fail("unsupported AAF byte order")); + } + let count = usize::from(read_u16(&d, 2)?); + let headers_end = 4 + 6 * count; + let mut at = headers_end; + // Validate and charge the complete object before copying any property values. + for i in 0..count { + let size = usize::from(read_u16(&d, 8 + 6 * i)?); + at = at.checked_add(size).filter(|end| *end <= d.len()).ok_or_else(|| fail(format!("{path}: truncated properties")))?; + } + let additional = + d.len().checked_add(path.len()).and_then(|n| n.checked_add(class.len())).ok_or_else(|| fail("AAF property size overflow"))?; + self.charge_properties(additional)?; + + let mut props = HashMap::new(); + at = headers_end; + for i in 0..count { + let pid = read_u16(&d, 4 + 6 * i)?; + let form = read_u16(&d, 6 + 6 * i)?; + let size = usize::from(read_u16(&d, 8 + 6 * i)?); + let value = d.get(at..at + size).ok_or_else(|| fail(format!("{path}: truncated properties")))?.to_vec(); + at += size; + props.insert(pid, (form, value)); + } + let object = Obj { path: path.to_string(), class, props: Rc::new(props) }; + self.objects.insert(path.to_string(), object.clone()); + Ok(object) + } + + fn child_path(parent: &Obj, name: &str) -> String { + if parent.path == "/" { format!("/{name}") } else { format!("{}/{name}", parent.path) } + } + + fn reference(parent: &Obj, pid: u16, form: u16) -> Option { + parent.props.get(&pid).filter(|(f, _)| *f == form).map(|(_, d)| utf16(d)) + } + + fn strong(&mut self, parent: &Obj, pid: u16, what: &str) -> Result { + let name = Self::reference(parent, pid, SF_STRONG_REF).ok_or_else(|| fail(format!("missing {what}")))?; + self.object(&Self::child_path(parent, &name)) + } + + fn opt_strong(&mut self, parent: &Obj, pid: u16, what: &str) -> Result> { + if parent.has(pid) { self.strong(parent, pid, what).map(Some) } else { Ok(None) } + } + + /// Strong reference vector, in stored order. Absent optional vectors read as empty. + fn vector(&mut self, parent: &Obj, pid: u16, what: &str, required: bool) -> Result> { + let Some(name) = Self::reference(parent, pid, SF_STRONG_VECTOR) else { + return if required { Err(fail(format!("missing {what}"))) } else { Ok(Vec::new()) }; + }; + let index = self.stream(&Self::child_path(parent, &format!("{name} index")))?.ok_or_else(|| fail(format!("missing {what} index")))?; + let count = read_u32(&index, 0)? as usize; + if count > MAX_ITEMS { + return Err(fail(format!("too many {what}"))); + } + let mut seen = HashSet::new(); + let mut objects = Vec::new(); + for i in 0..count { + let key = read_u32(&index, 12 + 4 * i)?; + if !seen.insert(key) { + return Err(fail(format!("duplicate local reference in {what}"))); + } + objects.push(self.object(&Self::child_path(parent, &format!("{name}{{{key:x}}}")))?); + } + Ok(objects) + } + + /// Strong reference set: (key bytes, child storage path) in stored order. + fn set_entries(&mut self, parent: &Obj, pid: u16, what: &str) -> Result, String)>> { + let Some(name) = Self::reference(parent, pid, SF_STRONG_SET) else { return Ok(Vec::new()) }; + let index = self.stream(&Self::child_path(parent, &format!("{name} index")))?.ok_or_else(|| fail(format!("missing {what} index")))?; + let count = read_u32(&index, 0)? as usize; + let key_size = usize::from(*index.get(14).ok_or_else(|| fail(format!("truncated {what} index")))?); + if count > MAX_ITEMS || !matches!(key_size, 16 | 32) { + return Err(fail(format!("unsupported {what} index"))); + } + let entry = 8 + key_size; + let mut seen = HashSet::new(); + let mut entries = Vec::new(); + for i in 0..count { + let at = 15 + entry * i; + let local = read_u32(&index, at)?; + if !seen.insert(local) { + return Err(fail(format!("duplicate local reference in {what}"))); + } + let key = index.get(at + 8..at + 8 + key_size).ok_or_else(|| fail(format!("truncated {what} index")))?.to_vec(); + entries.push((key, Self::child_path(parent, &format!("{name}{{{local:x}}}")))); + } + Ok(entries) + } + + fn set(&mut self, parent: &Obj, pid: u16, what: &str) -> Result> { + let entries = self.set_entries(parent, pid, what)?; + entries.into_iter().map(|(_, path)| self.object(&path)).collect() + } + + /// Short name of a component's data definition (`DataDef_` prefix removed), as pyaaf2's + /// `media_kind`. Resolved through the file's referenced-property table, not built-ins. + fn media_kind(&mut self, root: &Obj, component: &Obj) -> Result> { + let Some((form, d)) = component.props.get(&PID_COMPONENT_DATADEF) else { return Ok(None) }; + if *form != SF_WEAK_REF { + return Err(fail("unsupported DataDefinition reference")); + } + let index = usize::from(read_u16(d, 0)?); + let size = usize::from(*d.get(4).ok_or_else(|| fail("truncated DataDefinition reference"))?); + let key = d.get(5..5 + size).ok_or_else(|| fail("truncated DataDefinition reference"))?.to_vec(); + if let Some(name) = self.datadefs.get(&key) { + return Ok(name.clone()); + } + let path = self.weakrefs.get(index).cloned().ok_or_else(|| fail("unknown DataDefinition reference"))?; + let (last, walk) = path.split_last().ok_or_else(|| fail("empty weak reference path"))?; + let mut owner = root.clone(); + for pid in walk { + owner = self.strong(&owner, *pid, "weak reference owner")?; + } + let target = self.set_entries(&owner, *last, "data definitions")?.into_iter().find(|(k, _)| *k == key).map(|(_, p)| p); + let path = target.ok_or_else(|| fail("DataDefinition not found in dictionary"))?; + let name = self.object(&path)?.string(PID_DEF_NAME).map(|n| n.replace("DataDef_", "").replace("ContainerDef_", "")); + self.datadefs.insert(key, name.clone()); + Ok(name) + } +} + +// --------------------------------------------------------------------------------------------- +// Plan construction (same rules and messages as the original pyaaf2 adapter). + +fn rate(slot: &Obj) -> Result { + if !slot.is(CLASS_TIMELINE_SLOT) || slot.i64(PID_SLOT_ORIGIN, "slot Origin")? != 0 { + let id = slot.u32(PID_SLOT_ID, "SlotID").map(|i| i.to_string()).unwrap_or_default(); + return Err(fail(format!("Unsupported slot/origin: {} {id}", slot.kind()))); + } + let r = slot.rational(PID_SLOT_EDIT_RATE, "slot EditRate")?; + if r.n <= 0 { + return Err(fail("Edit rate must be positive")); + } + Ok(r) +} + +/// Local path from a NetworkLocator URL (`file:` or scheme-less), percent-decoded. +fn locator_path(url: &str, base: &Path) -> Result { + let mut rest = url; + let mut scheme = String::new(); + if let Some(i) = url.find(':') { + let s = &url[..i]; + if s.chars().next().is_some_and(|c| c.is_ascii_alphabetic()) && s.chars().all(|c| c.is_ascii_alphanumeric() || "+-.".contains(c)) { + scheme = s.to_ascii_lowercase(); + rest = &url[i + 1..]; + } + } + let mut netloc = ""; + if let Some(after) = rest.strip_prefix("//") { + let end = after.find(['/', '?', '#']).unwrap_or(after.len()); + netloc = &after[..end]; + rest = &after[end..]; + } + let (rest, fragment) = rest.split_once('#').unwrap_or((rest, "")); + let (path, query) = rest.split_once('?').unwrap_or((rest, "")); + if !matches!(scheme.as_str(), "" | "file") || !matches!(netloc, "" | "localhost") { + return Err(fail(format!("Unsupported non-local locator: {url}"))); + } + if !query.is_empty() || !fragment.is_empty() { + return Err(fail(format!("Locator must escape special characters: {url}"))); + } + let decoded = percent_decode(path); + if decoded.ends_with(['/', '\\']) { + return Err(fail(format!("Locator does not name a file: {url}"))); + } + if decoded.contains('\0') { + return Err(fail(format!("Locator contains a NUL byte: {url}"))); + } + let p = PathBuf::from(decoded); + // The locator is data: it may name a file, never walk the filesystem. `..` is refused + // anywhere (also inside absolute paths), so a relative locator stays under `base`. + use std::path::Component; + if p.components().any(|c| matches!(c, Component::ParentDir)) { + return Err(fail(format!("Locator must not contain `..`: {url}"))); + } + if !matches!(p.components().next_back(), Some(Component::Normal(_))) { + return Err(fail(format!("Locator does not name a file: {url}"))); + } + if p.is_absolute() { + return Ok(p); + } + // A relative locator may only hold plain names (no drive prefix or root on Windows). + if !p.components().all(|c| matches!(c, Component::Normal(_) | Component::CurDir)) { + return Err(fail(format!("Relative locator escapes the AAF folder: {url}"))); + } + Ok(base.join(p)) +} + +fn percent_decode(s: &str) -> String { + let b = s.as_bytes(); + let mut out = Vec::with_capacity(b.len()); + let mut i = 0; + while i < b.len() { + let hex = b.get(i + 1..i + 3).and_then(|h| std::str::from_utf8(h).ok()).and_then(|h| u8::from_str_radix(h, 16).ok()); + match (b[i], hex) { + (b'%', Some(v)) => { + out.push(v); + i += 3; + } + (c, _) => { + out.push(c); + i += 1; + } + } + } + String::from_utf8_lossy(&out).into_owned() +} + +struct Builder<'a, F> { + store: Store, + root: Obj, + mobs: HashMap, + embedded: Vec, + options: &'a AafOptions<'a>, + media: &'a mut dyn MediaResolver, + sources: Vec, + /// Sources whose file could not be found, with the number of edits left out because of them. + missing: Vec, + warnings: Vec, +} + +struct MissingMedia { + key: String, + path: String, + url: String, + edits: usize, +} + +impl Builder<'_, F> { + fn slot_of(&mut self, mob: &Obj, slot_id: u32) -> Result> { + for slot in self.store.vector(mob, PID_MOB_SLOTS, "mob slots", true)? { + if slot.u32(PID_SLOT_ID, "SlotID")? == slot_id { + return Ok(Some(slot)); + } + } + Ok(None) + } + + fn slot_length(&mut self, slot: &Obj) -> Result { + let seg = self.store.strong(slot, PID_SLOT_SEGMENT, "slot Segment")?; + if !seg.is(CLASS_SEQUENCE) { + return seg.length(); + } + let mut total = 0i64; + for c in self.store.vector(&seg, PID_SEQUENCE_COMPONENTS, "sequence components", true)? { + let l = c.length()?; + total = if c.is(CLASS_TRANSITION) { total.checked_sub(l) } else { total.checked_add(l) }.ok_or_else(|| fail("length overflow"))?; + } + Ok(total) + } + + /// Follows a SourceClip to its file SourceMob. Returns (source key, mob, offset seconds). + fn resolve(&mut self, clip: &Obj, incoming: Q, mut offset: Q, seen: &mut Vec<(String, u32)>) -> Result<(String, Q)> { + if !clip.is(CLASS_SOURCE_CLIP) { + return Err(fail(format!("Unsupported source chain component: {}", clip.kind()))); + } + let id = clip.bytes::<32>(PID_SOURCE_ID, "SourceID").ok(); + let slot_id = clip.u32(PID_SOURCE_SLOT_ID, "SourceMobSlotID")?; + let urn = id.filter(|b| b.iter().any(|x| *x != 0)).map(|b| mob_urn(&b)); + let mob = urn.as_ref().and_then(|u| self.mobs.get(u)).cloned(); + let Some(mob) = mob else { + return Err(fail(format!("Unresolved SourceClip MobID/slot: {}/{slot_id}", urn.unwrap_or_default()))); + }; + let key_urn = urn.unwrap_or_default(); + let slot = self.slot_of(&mob, slot_id)?.ok_or_else(|| fail(format!("Unresolved SourceClip MobID/slot: {key_urn}/{slot_id}")))?; + if seen.contains(&(key_urn.clone(), slot_id)) || seen.len() >= MAX_SOURCE_DEPTH { + return Err(fail("Cyclic or too deep source chain")); + } + let rr = rate(&slot)?; + let start = clip.i64(PID_START_TIME, "SourceClip StartTime")?; + offset = offset.add(Q::int(start).div(rr)?)?; + let name = mob.string(PID_MOB_NAME); + if mob.is(CLASS_SOURCE_MOB) && self.embedded.contains(&key_urn) { + return Err(fail(format!("Embedded essence unsupported: {}", name.unwrap_or_default()))); + } + if mob.is(CLASS_SOURCE_MOB) { + let desc = self.store.opt_strong(&mob, PID_SOURCE_MOB_DESCRIPTOR, "EssenceDescription")?; + if let Some(desc) = desc.filter(|d| d.is(CLASS_WAVE_DESCRIPTOR)) { + return self.file_source(&mob, &slot, &desc, key_urn, offset); + } + } + if !mob.is(CLASS_MASTER_MOB) { + return Err(fail(format!("Unsupported referenced mob/descriptor: {}", name.unwrap_or_default()))); + } + let window_end = offset.add(Q::int(clip.length()?).div(incoming)?)?; + let slot_end = Q::int(self.slot_length(&slot)?).div(rr)?; + if offset.lt(Q::int(0)) || slot_end.lt(window_end) { + return Err(fail(format!("SourceClip exceeds master slot: {}", name.unwrap_or_default()))); + } + let segment = self.store.strong(&slot, PID_SLOT_SEGMENT, "slot Segment")?; + if !segment.is(CLASS_SOURCE_CLIP) { + return Err(fail(format!("Unsupported master segment: {}", segment.kind()))); + } + seen.push((key_urn, slot_id)); + self.resolve(&segment, rr, offset, seen) + } + + fn file_source(&mut self, mob: &Obj, slot: &Obj, desc: &Obj, key: String, offset: Q) -> Result<(String, Q)> { + // Full interleaved WAV only: selecting one physical channel needs a channel map. + if !matches!(slot.opt_u32(PID_SLOT_PHYSICAL, "PhysicalTrackNumber")?, None | Some(0)) { + return Err(fail("Physical channel selection / split stereo unsupported")); + } + // Each source file is located, probed and reported once, however many edits use it. + if self.sources.iter().any(|s| s.key == key) || self.missing.iter().any(|m| m.key == key) { + return Ok((key, offset)); + } + let name = mob.string(PID_MOB_NAME); + let locators = self.store.vector(desc, PID_DESCRIPTOR_LOCATORS, "locators", false)?; + let urls: Vec = locators.iter().map(|l| l.data(PID_URL_STRING).map(utf16).unwrap_or_default()).collect(); + let [url] = urls.as_slice() else { + return Err(fail(format!("Expected one unambiguous WAV locator: {}", name.unwrap_or_default()))); + }; + let locator = locator_path(url, self.options.base_dir)?; + let info = match self.media.resolve(&locator) { + Ok(info) => info, + // Reported with the edits that need it; the rest of the composition still imports. + Err(MediaError::Missing(path)) => { + self.missing.push(MissingMedia { key: key.clone(), path, url: url.clone(), edits: 0 }); + return Ok((key, offset)); + } + Err(MediaError::Invalid(m)) => return Err(fail(m)), + }; + if let Some(from) = &info.relinked_from { + self.warnings.push(format!("Relinked {from} -> {}", info.path)); + } + if !matches!(info.channels, 1 | 2) { + return Err(fail("Only mono/stereo PCM WAV supported")); + } + if desc.rational(PID_FILE_SAMPLE_RATE, "descriptor SampleRate")? != Q::int(i64::from(info.sample_rate)) { + return Err(fail(format!("Descriptor/file sample rates differ: {}", name.unwrap_or_default()))); + } + if u64::try_from(desc.i64(PID_FILE_LENGTH, "descriptor Length")?).ok() != Some(info.frames) { + return Err(fail(format!("Descriptor/file lengths differ: {}", name.unwrap_or_default()))); + } + let stem = Path::new(&info.path).file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default(); + self.sources.push(Media { + key: key.clone(), + name: name.unwrap_or(stem), + path: info.path, + channels: info.channels, + frames: info.frames, + sample_rate: info.sample_rate, + }); + Ok((key, offset)) + } +} + +/// Reads one composition of an AAF as an interchange plan. Fails on anything outside the +/// supported subset; no partial plan is returned. The one exception is media that cannot be +/// found: each missing file is listed in the plan's warnings and its edits are left out (the +/// timeline positions of the other edits are unchanged). It fails only if no file is found. +pub fn read_aaf(file: F, options: &AafOptions, media: &mut dyn MediaResolver) -> Result { + let mut store = Store::open(file)?; + let root = store.object("/")?; + let header = store.strong(&root, PID_HEADER, "Header")?; + let content = store.strong(&header, PID_HEADER_CONTENT, "ContentStorage")?; + let all = store.set(&content, PID_CONTENT_MOBS, "mobs")?; + if all.len() > MAX_ITEMS { + return Err(fail("Too many mobs")); + } + let mut mobs = HashMap::new(); + let mut compositions = Vec::new(); + for mob in all { + let urn = mob_urn(&mob.bytes::<32>(PID_MOB_ID, "MobID")?); + if mob.is(CLASS_COMPOSITION_MOB) { + compositions.push((urn.clone(), mob.clone())); + } + mobs.insert(urn, mob); + } + let mut embedded = Vec::new(); + for e in store.set(&content, PID_CONTENT_ESSENCE, "essence data")? { + embedded.push(mob_urn(&e.bytes::<32>(PID_ESSENCE_MOB_ID, "EssenceData MobID")?)); + } + if let Some(id) = options.composition { + compositions.retain(|(urn, _)| urn == id); + } + let [(_, comp)] = compositions.as_slice() else { + let listed: Vec = compositions.iter().map(|(u, m)| format!("({:?}, {u:?})", m.string(PID_MOB_NAME).unwrap_or_default())).collect(); + return Err(fail(format!("Choose exactly one composition by MobID: [{}]", listed.join(", ")))); + }; + let comp = comp.clone(); + let mut b = Builder { + store, + root, + mobs, + embedded, + options, + media, + sources: Vec::new(), + missing: Vec::new(), + warnings: vec![ + "AAF subset: plugins, routing, automation and metadata are not transferred.".into(), + "Clip gain, fades, transitions, selectors, nested sequences and embedded media are unsupported; encountered editorial structures fail." + .into(), + ], + }; + let mut plan_tracks = Vec::new(); + let mut frame_rate = None; + let mut timecode_start = Rational(0, 1); + let mut count = 0usize; + let slots = b.store.vector(&comp, PID_MOB_SLOTS, "composition slots", true)?; + for slot in slots { + if plan_tracks.len() >= MAX_ITEMS { + return Err(fail("Too many tracks")); + } + let rr = rate(&slot)?; + let seg = b.store.strong(&slot, PID_SLOT_SEGMENT, "slot Segment")?; + let slot_id = slot.u32(PID_SLOT_ID, "SlotID")?; + if seg.is(CLASS_TIMECODE) { + if frame_rate.is_some() { + return Err(fail("Multiple timecode slots unsupported")); + } + let fps = u16::from_le_bytes(seg.bytes::<2>(PID_TIMECODE_FPS, "Timecode FPS")?); + let drop = seg.bytes::<1>(PID_TIMECODE_DROP, "Timecode Drop")?[0] != 0; + if rr.round_half_even() != i128::from(fps) { + return Err(fail("Timecode FPS disagrees with edit rate")); + } + frame_rate = Some(TimecodeRate { rate: rr.plan()?, drop }); + timecode_start = Q::int(seg.i64(PID_TIMECODE_START, "Timecode Start")?).div(rr)?.plan()?; + continue; + } + let kind = b.store.media_kind(&b.root, &seg)?; + if kind.as_deref() != Some("Sound") { + b.warnings.push(format!("Skipped non-audio slot {slot_id}: {}", kind.as_deref().unwrap_or("None"))); + continue; + } + let physical = slot.opt_u32(PID_SLOT_PHYSICAL, "PhysicalTrackNumber")?; + let fallback = format!("Audio {}", physical.unwrap_or(slot_id)); + let name = match slot.string(PID_SLOT_NAME) { + Some(n) => n, + None => { + b.warnings.push(format!("Unnamed AAF slot {slot_id}: assigned {fallback}")); + fallback + } + }; + let items = + if seg.is(CLASS_SEQUENCE) { b.store.vector(&seg, PID_SEQUENCE_COMPONENTS, "sequence components", true)? } else { vec![seg.clone()] }; + let mut cursor = 0i64; + let mut formats = Vec::new(); + let mut clips = Vec::new(); + for item in items { + count += 1; + if count > MAX_ITEMS { + return Err(fail("Too many components")); + } + let len = item.length()?; + if len < 0 { + return Err(fail("Negative component length")); + } + if item.is(CLASS_FILLER) { + cursor = cursor.checked_add(len).ok_or_else(|| fail("length overflow"))?; + continue; + } + if !item.is(CLASS_SOURCE_CLIP) { + return Err(fail(format!("Unsupported component in {name}: {}", item.kind()))); + } + let (sid, offset) = b.resolve(&item, rr, Q::int(0), &mut Vec::new())?; + if let Some(m) = b.missing.iter_mut().find(|m| m.key == sid) { + m.edits += 1; + cursor = cursor.checked_add(len).ok_or_else(|| fail("length overflow"))?; + continue; + } + let source = b.sources.iter().find(|s| s.key == sid).ok_or_else(|| fail("source missing"))?; + if !formats.contains(&source.channels) { + formats.push(source.channels); + } + let source_name = source.name.clone(); + let clip_name = item + .bytes::<32>(PID_SOURCE_ID, "SourceID") + .ok() + .and_then(|id| b.mobs.get(&mob_urn(&id))) + .and_then(|m| m.string(PID_MOB_NAME)) + .unwrap_or(source_name); + let end = cursor.checked_add(len).ok_or_else(|| fail("length overflow"))?; + clips.push(ImportClip { + name: clip_name, + source: sid, + start: Q::int(cursor).div(rr)?.plan()?, + end: Q::int(end).div(rr)?.plan()?, + offset: offset.plan()?, + }); + cursor = end; + } + if seg.is(CLASS_SEQUENCE) && seg.length()? != cursor { + return Err(fail("Sequence declared length differs from components")); + } + if formats.len() > 1 { + return Err(fail(format!("Mixed channel layouts in track: {name}"))); + } + let channels = match formats.first() { + Some(c) => *c, + None => { + b.warnings.push(format!("Empty track {name}: mono layout assumed")); + 1 + } + }; + plan_tracks.push(ImportTrack { name, channels, clips }); + } + for m in &b.missing { + b.warnings.push(format!("Missing media: {}; locator={}; {} edit(s) skipped", m.path, m.url, m.edits)); + } + if b.sources.is_empty() && !b.missing.is_empty() { + let names: Vec<&str> = b.missing.iter().map(|m| m.path.as_str()).collect(); + return Err(fail(format!("Missing media: none of the referenced files were found: {}", names.join(", ")))); + } + let mut rates: Vec = b.sources.iter().map(|s| s.sample_rate).collect(); + rates.sort_unstable(); + rates.dedup(); + let [sample_rate] = rates.as_slice() else { + return Err(fail("Require at least one source and a single source sample rate; no resampling yet")); + }; + if frame_rate.is_none() { + b.warnings.push("No composition timecode: start=0, frame rate defaults to 30".into()); + } + Ok(Plan { + schema_version: 1, + name: comp.string(PID_MOB_NAME).unwrap_or_else(|| options.default_name.to_string()), + sample_rate: *sample_rate, + timecode_start, + frame_rate, + sources: b.sources, + tracks: plan_tracks, + warnings: b.warnings, + }) +} + +/// PCM WAV header properties. Reads chunk headers only; sample data is not loaded. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct WavInfo { + pub channels: u16, + pub sample_rate: u32, + pub frames: u64, +} + +const KSDATAFORMAT_SUBTYPE_PCM: [u8; 16] = [1, 0, 0, 0, 0, 0, 0x10, 0, 0x80, 0, 0, 0xaa, 0, 0x38, 0x9b, 0x71]; + +/// Integer PCM RIFF/WAVE only (format 1, or WAVE_FORMAT_EXTENSIBLE with the PCM subtype). +pub fn wav_info(mut r: R) -> std::result::Result { + let mut head = [0u8; 12]; + r.read_exact(&mut head).map_err(|_| "not a RIFF/WAVE file".to_string())?; + if &head[..4] != b"RIFF" || &head[8..] != b"WAVE" { + return Err("Only mono/stereo PCM WAV supported (not RIFF/WAVE)".into()); + } + let mut fmt: Option<(u16, u32, u16, u16)> = None; + for _ in 0..4096 { + let mut ch = [0u8; 8]; + if r.read_exact(&mut ch).is_err() { + break; + } + let size = u32::from_le_bytes([ch[4], ch[5], ch[6], ch[7]]); + let padded = u64::from(size) + u64::from(size & 1); + match &ch[..4] { + b"fmt " => { + let mut f = vec![0u8; usize::try_from(size.min(64)).unwrap_or(64)]; + r.read_exact(&mut f).map_err(|_| "truncated WAV fmt chunk".to_string())?; + let u16_at = |i: usize| f.get(i..i + 2).map(|b| u16::from_le_bytes([b[0], b[1]])); + let tag = u16_at(0).ok_or("truncated WAV fmt chunk")?; + let channels = u16_at(2).ok_or("truncated WAV fmt chunk")?; + let rate = f.get(4..8).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])).ok_or("truncated WAV fmt chunk")?; + let bits = u16_at(14).ok_or("truncated WAV fmt chunk")?; + let pcm = tag == 1 || (tag == 0xfffe && f.get(24..40) == Some(&KSDATAFORMAT_SUBTYPE_PCM[..])); + if !pcm { + return Err("Only mono/stereo PCM WAV supported".into()); + } + fmt = Some((tag, rate, channels, bits)); + r.seek(SeekFrom::Current(i64::try_from(padded).unwrap_or(i64::MAX) - f.len() as i64)).map_err(|e| e.to_string())?; + } + b"data" => { + let (_, sample_rate, channels, bits) = fmt.ok_or("WAV data before fmt chunk")?; + let frame = u64::from(channels) * u64::from(bits.div_ceil(8)); + if frame == 0 || sample_rate == 0 { + return Err("invalid WAV format".into()); + } + return Ok(WavInfo { channels, sample_rate, frames: u64::from(size) / frame }); + } + _ => { + r.seek(SeekFrom::Current(i64::try_from(padded).map_err(|e| e.to_string())?)).map_err(|e| e.to_string())?; + } + } + } + Err("WAV data chunk not found".into()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn rationals_reduce_and_round_like_python() { + let r = Q::new(24000, 1001).unwrap(); + assert_eq!(r.round_half_even(), 24); + assert_eq!(Q::new(5, 2).unwrap().round_half_even(), 2); + assert_eq!(Q::new(7, 2).unwrap().round_half_even(), 4); + assert_eq!(Q::int(48).div(Q::int(96)).unwrap(), Q { n: 1, d: 2 }); + assert!(Q::new(1, 0).is_err()); + } + + #[test] + fn aggregate_property_budget_is_checked_before_allocation() { + assert_eq!(property_total(0, MAX_PROPERTY_BYTES).unwrap(), MAX_PROPERTY_BYTES); + assert!(property_total(0, MAX_PROPERTY_BYTES + 1).is_err()); + assert!(property_total(MAX_PROPERTY_BYTES, 1).is_err()); + assert!(property_total(usize::MAX, 1).is_err()); + } + + #[test] + fn locators_accept_only_local_files() { + let base = Path::new("/base"); + assert_eq!(locator_path("file:///Macintosh%20HD/a%23b.wav", base).unwrap(), PathBuf::from("/Macintosh HD/a#b.wav")); + assert_eq!(locator_path("file://localhost/x.wav", base).unwrap(), PathBuf::from("/x.wav")); + assert_eq!(locator_path("rel%C3%A1.wav", base).unwrap(), PathBuf::from("/base/relá.wav")); + assert!(locator_path("http://host/x.wav", base).is_err()); + assert!(locator_path("file://server/x.wav", base).is_err()); + assert!(locator_path("file:///x.wav?y", base).is_err()); + assert!(locator_path("file:///x.wav#y", base).is_err()); + } + + #[test] + fn locators_never_walk_out_of_the_aaf_folder() { + let base = Path::new("/base"); + assert_eq!(locator_path("Audio%20Files/a.wav", base).unwrap(), PathBuf::from("/base/Audio Files/a.wav")); + assert_eq!(locator_path("./a.wav", base).unwrap(), PathBuf::from("/base/a.wav")); + for url in [ + "../a.wav", + "Audio Files/../../a.wav", + "%2E%2E/a.wav", + "%2e%2e%2Fsecret.wav", + "file:///base/../etc/a.wav", + "file:///base/Audio%20Files/%2E%2E/%2E%2E/a.wav", + "a.wav%00.txt", + "file:///base/folder/", + "", + "smb://server/share/a.wav", + "file://evil.example/a.wav", + "javascript:alert(1)", + ] { + assert!(locator_path(url, base).is_err(), "{url}"); + } + } + + #[test] + fn mob_ids_print_as_smpte_urns() { + let mut b = [0u8; 32]; + b[..12].copy_from_slice(&[0x06, 0x0a, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x0f, 0x00]); + b[12] = 0x13; + b[16..20].copy_from_slice(&0x4fa5c20fu32.to_le_bytes()); + b[20..22].copy_from_slice(&0x4e30u16.to_le_bytes()); + b[22..24].copy_from_slice(&0x1e50u16.to_le_bytes()); + b[24..32].copy_from_slice(&[0x06, 0x0e, 0x2b, 0x34, 0x7f, 0x7f, 0x2a, 0x80]); + assert_eq!(mob_urn(&b), "urn:smpte:umid:060a2b34.01010101.01010f00.13000000.060e2b34.7f7f2a80.4fa5c20f.4e301e50"); + } + + fn wav(tag: u16, channels: u16, bits: u16, data: u32, junk: u32) -> Vec { + let mut v = b"RIFF\0\0\0\0WAVE".to_vec(); + v.extend(b"JUNK"); + v.extend(junk.to_le_bytes()); + v.extend(vec![0; (junk + (junk & 1)) as usize]); + v.extend(b"fmt "); + v.extend(16u32.to_le_bytes()); + v.extend(tag.to_le_bytes()); + v.extend(channels.to_le_bytes()); + v.extend(48000u32.to_le_bytes()); + v.extend((48000 * u32::from(channels) * u32::from(bits / 8)).to_le_bytes()); + v.extend((channels * bits / 8).to_le_bytes()); + v.extend(bits.to_le_bytes()); + v.extend(b"data"); + v.extend(data.to_le_bytes()); + v + } + + #[test] + fn wav_headers_are_read_without_sample_data() { + let info = wav_info(std::io::Cursor::new(wav(1, 2, 24, 6 * 1000, 3))).unwrap(); + assert_eq!(info, WavInfo { channels: 2, sample_rate: 48000, frames: 1000 }); + assert!(wav_info(std::io::Cursor::new(wav(3, 1, 32, 400, 0))).is_err()); + assert!(wav_info(std::io::Cursor::new(b"RIFX\0\0\0\0WAVE".to_vec())).is_err()); + } +} diff --git a/crates/interchange/src/lib.rs b/crates/interchange/src/lib.rs new file mode 100644 index 000000000..2d96fabd3 --- /dev/null +++ b/crates/interchange/src/lib.rs @@ -0,0 +1,287 @@ +//! Reusable interchange plan -> SoundCraft session. No processes, UI, or filesystem access. +//! Readers supply rational seconds. Endpoints are rounded independently (nearest, ties away +//! from zero), so adjacent edits share exactly the same boundary without cumulative drift. +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +pub mod aaf; + +use serde::{Deserialize, Serialize}; +use soundcraft_model::{ChannelFormat, Clip, ClipId, Session, Source, SourceId, Track, TrackId, TrackKind}; +use soundcraft_time::{FrameRate, MAX_POSITION, SampleRate}; +use std::collections::HashMap; + +#[derive(Debug, thiserror::Error)] +#[error("interchange: {0}")] +pub struct ImportError(pub String); +type Result = std::result::Result; +fn invalid(s: &str) -> ImportError { + ImportError(s.into()) +} + +/// Rational seconds [numerator, denominator]. Both must be nonnegative, denominator > 0. +#[derive(Debug, Clone, Copy, Serialize, Deserialize)] +pub struct Rational(pub i64, pub i64); +impl Rational { + pub fn samples(self, hz: u32) -> Result { + if self.0 < 0 || self.1 <= 0 { + return Err(invalid("negative time or invalid denominator")); + } + let n = i128::from(self.0) * i128::from(hz); + let d = i128::from(self.1); + let v = (n + d / 2) / d; + if v > i128::from(MAX_POSITION) { + return Err(invalid("time exceeds SoundCraft limit")); + } + i64::try_from(v).map_err(|_| invalid("time overflow")) + } +} +#[derive(Debug, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Plan { + pub schema_version: u32, + pub name: String, + pub sample_rate: u32, + pub timecode_start: Rational, + pub frame_rate: Option, + pub sources: Vec, + pub tracks: Vec, + pub warnings: Vec, +} +#[derive(Debug, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct TimecodeRate { + pub rate: Rational, + pub drop: bool, +} +#[derive(Debug, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Media { + pub key: String, + pub name: String, + pub path: String, + pub channels: u16, + pub frames: u64, + pub sample_rate: u32, +} +#[derive(Debug, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ImportTrack { + pub name: String, + pub channels: u16, + pub clips: Vec, +} +#[derive(Debug, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ImportClip { + pub name: String, + pub source: String, + pub start: Rational, + pub end: Rational, + pub offset: Rational, +} +#[derive(Debug, Serialize)] +pub struct HandleReport { + pub clip: String, + pub before: i64, + pub after: i64, +} +#[derive(Debug, Serialize)] +pub struct Report { + pub warnings: Vec, + pub handles: Vec, +} +pub struct Imported { + pub session: Session, + pub report: Report, +} + +fn layout(channels: u16) -> Result { + match channels { + 1 => Ok(ChannelFormat::Mono), + 2 => Ok(ChannelFormat::Stereo), + _ => Err(invalid("only mono/stereo supported")), + } +} +fn name(s: &str) -> Result<()> { + if s.chars().count() > soundcraft_model::MAX_NAME_CHARS || s.is_empty() { + return Err(invalid("name empty or too long for SoundCraft")); + } + Ok(()) +} +fn frame_rate(tc: &TimecodeRate) -> Result { + let Rational(n, d) = tc.rate; + if n <= 0 || d <= 0 { + return Err(invalid("invalid frame rate")); + } + FrameRate::ALL + .into_iter() + .find(|r| { + let (rn, rd) = r.rational(); + i128::from(n) * i128::from(rd) == i128::from(rn) * i128::from(d) && r.is_drop() == tc.drop + }) + .ok_or_else(|| invalid("unsupported frame rate/drop combination")) +} +/// Build transactionally. On any error no partial session is returned. The caller must verify +/// media bytes against the metadata before using the plan; see the CLI for a bounded probe. +pub fn build_session(plan: Plan) -> Result { + if plan.schema_version != 1 { + return Err(invalid("unsupported interchange schema")); + } + if plan.sources.len() > 100_000 || plan.tracks.len() > 100_000 || plan.tracks.iter().map(|t| t.clips.len()).sum::() > 100_000 { + return Err(invalid("too many sources/tracks/clips")); + } + name(&plan.name)?; + let sr = SampleRate::new(plan.sample_rate).map_err(|e| ImportError(e.to_string()))?; + let mut s = Session::new(&plan.name, sr); + s.timecode_start = plan.timecode_start.samples(sr.hz())?; + if let Some(tc) = &plan.frame_rate { + s.frame_rate = frame_rate(tc)?; + } + let mut ids = HashMap::new(); + for m in &plan.sources { + name(&m.name)?; + layout(m.channels)?; + if m.sample_rate != sr.hz() || m.frames == 0 || m.frames > MAX_POSITION as u64 || m.path.is_empty() { + return Err(invalid("invalid media metadata or mixed sample rates (resampling unsupported)")); + } + let id = SourceId(s.alloc()); + if ids.insert(m.key.as_str(), (id, m.frames, m.channels)).is_some() { + return Err(invalid("duplicate source key")); + } + s.sources.push(Source { + id, + name: m.name.clone(), + path: m.path.clone(), + channels: m.channels, + frames: m.frames, + sample_rate: m.sample_rate, + format: soundcraft_model::FileFormat::Wav, + time_reference: 0, + unsaved: false, + }); + } + let mut report = Report { warnings: plan.warnings.clone(), handles: Vec::new() }; + for t in &plan.tracks { + name(&t.name)?; + let track_id = TrackId(s.alloc()); + // Construct directly: add_track intentionally renames duplicates, interchange must not. + let mut track = Track::new(track_id, &t.name, TrackKind::Audio, layout(t.channels)?, s.next_track_color()); + let mut previous_end = 0; + for c in &t.clips { + name(&c.name)?; + let (source, frames, channels) = ids.get(c.source.as_str()).ok_or_else(|| invalid("unknown source key"))?; + if *channels != t.channels { + return Err(invalid("clip/track layout mismatch")); + } + let start = c.start.samples(sr.hz())?; + let end = c.end.samples(sr.hz())?; + let offset = c.offset.samples(sr.hz())?; + if end <= start || start < previous_end { + return Err(invalid("zero/negative duration or overlapping/out-of-order clips")); + } + let length = end - start; + let source_end = offset.checked_add(length).ok_or_else(|| invalid("source window overflow"))?; + if source_end > *frames as i64 { + return Err(invalid("clip extends beyond source; refusing truncated handles")); + } + let clip = Clip::audio(ClipId(s.alloc()), &c.name, *source, offset, start, length); + track.playlist_mut().ok_or_else(|| invalid("missing playlist"))?.clips.push(clip); + report.handles.push(HandleReport { clip: c.name.clone(), before: offset, after: *frames as i64 - source_end }); + previous_end = end; + } + s.tracks.push(track); + } + s.comments = "Imported by soundcraft-interchange schema v1; see accompanying import report for limitations.".into(); + Ok(Imported { session: s, report }) +} + +#[cfg(test)] +#[allow(clippy::unwrap_used)] +mod tests { + use super::*; + fn plan() -> Plan { + Plan { + schema_version: 1, + name: "Test".into(), + sample_rate: 48000, + timecode_start: Rational(3600, 1), + frame_rate: Some(TimecodeRate { rate: Rational(25, 1), drop: false }), + warnings: vec![], + sources: vec![Media { key: "s".into(), name: "src".into(), path: "a.wav".into(), channels: 1, frames: 480000, sample_rate: 48000 }], + tracks: vec![ImportTrack { + name: "DX".into(), + channels: 1, + clips: vec![ImportClip { + name: "cut".into(), + source: "s".into(), + start: Rational(1, 1), + end: Rational(3, 1), + offset: Rational(2, 1), + }], + }], + } + } + #[test] + fn positions_offsets_handles_and_roundtrip() { + let result = build_session(plan()).unwrap(); + let c = &result.session.tracks[0].clips()[0]; + assert_eq!((c.start, c.length, c.source_offset()), (48000, 96000, 96000)); + assert_eq!((result.report.handles[0].before, result.report.handles[0].after), (96000, 288000)); + assert_eq!(result.session.timecode_start, 172800000); + let back = Session::from_json(&result.session.to_json().unwrap()).unwrap(); + assert_eq!(back.tracks[0].clips()[0], *c); + } + #[test] + fn adjacent_fractional_frame_boundaries_never_drift() { + for n in 1..10000 { + let a = Rational(n * 1001, 24000).samples(48000).unwrap(); + let b = Rational((n + 1) * 1001, 24000).samples(48000).unwrap(); + assert_eq!(b - a, 2002); + } + assert_eq!(Rational(1, 96000).samples(48000).unwrap(), 1); + } + #[test] + fn fractional_sample_boundaries_use_absolute_endpoints() { + let mut p = plan(); + p.sample_rate = 44100; + p.sources[0].sample_rate = 44100; + p.sources[0].frames = 4410000; + p.tracks[0].clips = (0..1000) + .map(|n| ImportClip { + name: "frame".into(), + source: "s".into(), + start: Rational(n * 1001, 24000), + end: Rational((n + 1) * 1001, 24000), + offset: Rational(n * 1001, 24000), + }) + .collect(); + let s = build_session(p).unwrap().session; + let clips = s.tracks[0].clips(); + for pair in clips.windows(2) { + assert_eq!(pair[0].end(), pair[1].start); + } + assert_eq!(clips[999].end(), 1839338); + assert_eq!(clips.iter().map(|c| c.length).sum::(), 1839338); + } + #[test] + fn invalid_windows_and_metadata_are_rejected() { + let mut p = plan(); + p.tracks[0].clips[0].offset = Rational(9, 1); + assert!(build_session(p).is_err()); + let mut p = plan(); + p.sources[0].sample_rate = 44100; + assert!(build_session(p).is_err()); + assert!(Rational(1, 0).samples(48000).is_err()); + assert!(Rational(i64::MAX, 1).samples(48000).is_err()); + assert!(Rational(-1, 1).samples(48000).is_err()); + } + #[test] + fn stereo_names_and_order_are_preserved() { + let mut p = plan(); + p.sources[0].channels = 2; + p.tracks[0].channels = 2; + p.tracks.push(ImportTrack { name: "DX".into(), channels: 1, clips: vec![] }); + let s = build_session(p).unwrap().session; + assert_eq!(s.tracks.iter().map(|t| t.name.as_str()).collect::>(), vec!["DX", "DX"]); + assert_eq!(s.tracks[0].channels(), 2); + } +} diff --git a/crates/ui-egui/src/aaf_import.rs b/crates/ui-egui/src/aaf_import.rs new file mode 100644 index 000000000..2b7306056 --- /dev/null +++ b/crates/ui-egui/src/aaf_import.rs @@ -0,0 +1,368 @@ +//! Session-data import UI. File parsing goes through engine commands; successful insertion is +//! a single undoable command. Nothing in this window replaces or saves the active document. +use crate::SoundApp; +use egui::{RichText, ScrollArea}; +use serde_json::{Value, json}; +use std::sync::mpsc::{self, Receiver}; + +pub struct ImportState { + pub open: bool, + pub path: String, + pub media_dir: String, + /// CompositionMob to read when the AAF holds several; empty lets the reader require one. + composition: String, + /// (name, MobID) choices reported by the reader for a multi-composition AAF. + compositions: Vec<(String, String)>, + preview: Option, + selected: Vec, + filter: String, + absolute: bool, + offset: String, + error: Option, + busy: Option>>, + pending: bool, + report: Option, +} +impl Default for ImportState { + fn default() -> Self { + Self { + open: false, + path: String::new(), + media_dir: String::new(), + composition: String::new(), + compositions: Vec::new(), + preview: None, + selected: Vec::new(), + filter: String::new(), + absolute: true, + offset: "0".into(), + error: None, + busy: None, + pending: false, + report: None, + } + } +} +impl ImportState { + pub fn set_path(&mut self, path: String) { + self.media_dir = std::path::Path::new(&path).parent().map_or(String::new(), |p| p.display().to_string()); + self.path = path; + self.composition.clear(); + self.compositions.clear(); + self.invalidate(); + } + /// A typed path is a different file: forget its compositions, and follow it with the media + /// folder unless the user pointed that folder somewhere other than the previous AAF's folder. + fn path_edited(&mut self, previous: &str) { + let parent = |p: &str| std::path::Path::new(p).parent().map_or(String::new(), |d| d.display().to_string()); + if self.media_dir == parent(previous) { + self.media_dir = parent(&self.path); + } + self.composition.clear(); + self.compositions.clear(); + self.invalidate(); + } + /// Drops the current preview and any analysis still running, whose plan would belong to the + /// previous file or folder. The worker's late result goes to a closed channel. + fn invalidate(&mut self) { + self.preview = None; + self.busy = None; + self.error = None; + } + pub fn inspect(&self) -> Value { + json!({"open":self.open,"path":self.path,"media_dir":self.media_dir,"busy":self.busy.is_some(),"preview":self.preview,"selected":self.selected,"error":self.error,"report":self.report}) + } + #[cfg(not(target_arch = "wasm32"))] + fn analyze(&mut self, ctx: &egui::Context) { + if self.busy.is_some() { + return; + } + self.error = None; + self.preview = None; + let path = self.path.clone(); + let media = self.media_dir.clone(); + let mut params = json!({"path":path,"media_dir":media}); + if !self.composition.is_empty() { + params["composition"] = json!(self.composition); + } + let roots = soundcraft_engine::file_access::current(); + let ctx = ctx.clone(); + let (tx, rx) = mpsc::channel(); + self.busy = Some(rx); + std::thread::spawn(move || { + let result = soundcraft_engine::file_access::confine(roots.as_ref(), || { + soundcraft_engine::Engine::default().execute("file.preview_aaf", ¶ms).map_err(|e| e.to_string()) + }); + let _ = tx.send(result); + ctx.request_repaint(); + }); + } + #[cfg(target_arch = "wasm32")] + fn analyze(&mut self, _: &egui::Context) { + self.error = Some("AAF import needs the desktop app: its media files are read from a local folder".into()); + } +} + +pub fn command(app: &mut SoundApp, p: &Value) -> Result { + if let Some(path) = p.get("path").and_then(Value::as_str) { + app.aaf_import.set_path(path.to_string()); + } + if let Some(dir) = p.get("media_dir").and_then(Value::as_str) { + app.aaf_import.media_dir = dir.to_string(); + app.aaf_import.invalidate(); + } + app.aaf_import.open = true; + Ok(app.aaf_import.inspect()) +} + +pub fn show(app: &mut SoundApp, ctx: &egui::Context) { + let mut state = std::mem::take(&mut app.aaf_import); + if let Some(rx) = &state.busy { + let result = rx.try_recv(); + match result { + Ok(Ok(preview)) => { + state.selected = vec![true; preview.get("tracks").and_then(Value::as_array).map_or(0, Vec::len)]; + state.preview = Some(preview); + state.busy = None; + } + Ok(Err(e)) => { + let choices = composition_choices(&e); + if !choices.is_empty() { + state.compositions = choices; + } + state.error = Some(e); + state.busy = None; + } + Err(mpsc::TryRecvError::Disconnected) => { + state.error = Some("AAF reader stopped unexpectedly".into()); + state.busy = None; + } + Err(mpsc::TryRecvError::Empty) => { + ctx.request_repaint_after(std::time::Duration::from_millis(50)); + } + } + } + if state.pending { + state.pending = false; + let indices: Vec<_> = state.selected.iter().enumerate().filter_map(|(i, on)| on.then_some(i)).collect(); + let params = json!({"plan":state.preview.as_ref().and_then(|v|v.get("plan")),"media_dir":state.media_dir,"selected":indices,"media":"copy","mapping":if state.absolute{"absolute"}else{"relative"},"offset_samples":state.offset.parse::().ok()}); + match app.run("file.import_aaf", params) { + Ok(v) => { + state.report = Some(v); + state.open = false; + app.ui.status = "AAF imported as new editable tracks. Save the session to collect copied media.".into(); + } + Err(e) => state.error = Some(e), + } + } + if state.open { + let mut open = true; + egui::Window::new("Import Session Data — AAF").id(egui::Id::unique("import_aaf")).open(&mut open).default_size([1080.0,690.0]).min_size([850.0,560.0]).show(ctx,|ui| { + ui.horizontal(|ui| { + ui.label("AAF file"); + let before=state.path.clone(); + let edited=ui.add_enabled(state.busy.is_none(),egui::TextEdit::singleline(&mut state.path).desired_width((ui.available_width()-200.0).max(200.0))).changed(); + if edited { state.path_edited(&before); } + if ui.add_enabled(state.busy.is_none(),egui::Button::new("Browse…")).clicked() + && let Some(path)=app.services.pick_open.as_ref().and_then(|pick|pick("file.import_aaf",&["aaf"])) { + match crate::dialogs::unicode(&path) { Ok(p)=>state.set_path(p.to_string()), Err(e)=>state.error=Some(e.to_string()) } + } + if ui.add_enabled(state.busy.is_none()&&!state.path.is_empty()&&!state.media_dir.is_empty(),egui::Button::new("Analyze AAF")).clicked() { state.analyze(ctx); } + }); + if state.busy.is_some() { ui.horizontal(|ui|{ui.spinner();ui.label("Reading source properties and locating media…");}); } + if !state.compositions.is_empty() { + ui.horizontal(|ui| { + ui.label("Composition"); + let current=state.compositions.iter().find(|(_,id)|*id==state.composition).map_or("Choose one…".to_string(),|(n,_)|n.clone()); + // Locked while analyzing, so a finished analysis always matches the selection. + ui.add_enabled_ui(state.busy.is_none(),|ui|{ + craft_ui::ComboBox::from_id_salt("aaf_composition").selected_text(current).show_ui(ui,|ui|{ + for (name,id) in &state.compositions { + if ui.selectable_label(state.composition==*id,format!("{name} ({id})")).clicked() { state.composition=id.clone(); state.preview=None; } + } + }); + }); + }); + } + if let Some(error)=&state.error { ui.colored_label(ui.visuals().error_fg_color,error); } + ui.separator(); + let preview=state.preview.clone(); + ui.horizontal_top(|ui| { + ui.vertical(|ui| { + ui.set_width(300.0); + ui.group(|ui| { + ui.label(RichText::new("Source Properties").strong()); + if let Some(p)=&preview { + ui.label(format!("Name: {}",p["name"].as_str().unwrap_or(""))); + ui.label("Type: AAF • external PCM WAV"); + ui.label(format!("Start: {}",p["start_timecode"].as_str().unwrap_or(""))); + ui.label(format!("Frame rate: {} fps",p["frame_rate"].as_str().unwrap_or(""))); + ui.label(format!("Sample rate: {} Hz",p["sample_rate"])); + ui.label(format!("Source files: {}",p["sources"])); + } else { ui.label("Choose an AAF and analyze it to preview the montage."); } + }); + ui.add_space(8.0); + ui.group(|ui| { + ui.label(RichText::new("Media Options").strong()); + ui.label("Locate source WAV files in:"); + if ui.add_enabled(state.busy.is_none(),egui::TextEdit::singleline(&mut state.media_dir).desired_width(275.0)).changed(){state.preview=None;} + if ui.add_enabled(state.busy.is_none(),egui::Button::new("Choose media folder…")).clicked() + && let Some(dir)=app.services.pick_folder.as_ref().and_then(|pick|pick(std::path::Path::new(&state.media_dir))){ + match crate::dialogs::unicode(&dir) { Ok(d)=>{state.media_dir=d.to_string();state.invalidate();} Err(e)=>state.error=Some(e.to_string()) } + } + ui.label("Copy full sources when saving"); + ui.small("Save the session before moving or removing original files."); + ui.small("All available handles are retained. Sources are not consolidated or trimmed."); + }); + ui.add_space(8.0); + ui.group(|ui| { + ui.label(RichText::new("Timecode Mapping").strong()); + ui.radio_value(&mut state.absolute,true,"Maintain absolute timecode"); + ui.radio_value(&mut state.absolute,false,"Relative to session start"); + ui.horizontal(|ui|{ui.label("Offset (samples)");ui.add(egui::TextEdit::singleline(&mut state.offset).desired_width(110.0));}); + ui.small(format!("Destination: {} Hz • {} fps",app.engine.session().sample_rate.hz(),app.engine.session().frame_rate.label())); + ui.small("An empty destination adopts the source rate and timecode. No sample-rate conversion."); + }); + ui.add_space(8.0); + ui.label(RichText::new("Initial import scope").strong()); + ui.small("New tracks and editable clips. Clip gain, automation, parametric fades, video, plugins and routing are not transferred. Existing playlists are not replaced."); + }); + ui.add_space(12.0); + ui.vertical(|ui| { + ui.set_min_width(450.0); + ui.horizontal(|ui|{ + ui.label("Tracks");ui.text_edit_singleline(&mut state.filter); + if ui.button("All").clicked(){state.selected.fill(true);} + if ui.button("Clear").clicked(){state.selected.fill(false);} + }); + ui.separator(); + ScrollArea::vertical().id_salt("aaf_tracks").max_height(400.0).show(ui,|ui| { + egui::Grid::new("aaf_track_table").striped(true).min_col_width(120.0).show(ui,|ui|{ + ui.strong("Import / Source");ui.strong("Clips");ui.strong("Destination");ui.end_row(); + if let Some(tracks)=preview.as_ref().and_then(|p|p["tracks"].as_array()) { + for (i,t) in tracks.iter().enumerate() { + let name=t["name"].as_str().unwrap_or(""); + if !name.to_lowercase().contains(&state.filter.to_lowercase()){continue;} + let label=format!("{} ({})",name,if t["channels"].as_u64()==Some(2){"Stereo"}else{"Mono"}); + if let Some(on)=state.selected.get_mut(i){ui.checkbox(on,label);}else{ui.label(label);} + ui.label(t["clips"].to_string());ui.label("New Track");ui.end_row(); + } + } + }); + }); + ui.separator(); + let warnings=preview.as_ref().and_then(|p|p["warnings"].as_array()); + ui.collapsing(format!("Compatibility and media report ({} notices)",warnings.map_or(0,Vec::len)),|ui|{ + ScrollArea::vertical().id_salt("aaf_warnings").max_height(130.0).show(ui,|ui|{ + if let Some(warnings)=warnings {for w in warnings{ui.small(w.as_str().unwrap_or(""));}} + }); + }); + ui.label(format!("{} tracks selected",state.selected.iter().filter(|x|**x).count())); + }); + }); + ui.separator(); + ui.horizontal(|ui| { + if ui.button("Cancel").clicked(){state.open=false;} + let ready=state.preview.is_some() && state.busy.is_none() && state.selected.iter().any(|x|*x) && state.offset.parse::().is_ok() && !app.engine.transport.playing && !app.engine.transport.recording; + if ui.add_enabled(ready,egui::Button::new("Import")).clicked(){state.pending=true;ctx.request_repaint();} + if app.engine.transport.playing || app.engine.transport.recording {ui.label("Stop transport before importing.");} + if state.pending {ui.spinner();ui.label("Preparing media and new tracks…");} + }); + }); + if !open { + state.open = false; + } + } + if let Some(report) = &state.report { + let mut open = true; + egui::Window::new("AAF Import Report").id(egui::Id::unique("aaf_import_report")).open(&mut open).default_size([640.0, 400.0]).show( + ctx, + |ui| { + ui.heading("Session data imported"); + ui.label(format!("{} new tracks • {} complete sources", report["tracks"].as_array().map_or(0, Vec::len), report["sources"])); + ui.label("Clips remain editable. Use Save Session to collect copied media."); + if ui.button("Go to first imported clip").clicked() + && let Some(at) = report["first_clip_sample"].as_i64() + { + let _ = app.run("transport.locate", json!({"at":at})); + } + if ui.button("Copy complete report").clicked() { + ctx.copy_text(serde_json::to_string_pretty(report).unwrap_or_default()); + } + ScrollArea::vertical().max_height(300.0).show(ui, |ui| { + if let Some(warnings) = report["warnings"].as_array() { + for w in warnings { + ui.label(w.as_str().unwrap_or("")); + } + } + }); + }, + ); + if !open { + state.report = None; + } + } + app.aaf_import = state; +} + +/// (name, MobID) pairs from the reader's "Choose exactly one composition" error, so the window +/// can offer a choice instead of asking for an ID it gives no way to enter. +fn composition_choices(error: &str) -> Vec<(String, String)> { + let Some(list) = error.split_once("Choose exactly one composition by MobID: ").map(|(_, l)| l) else { return Vec::new() }; + list.split("(\"") + .filter_map(|entry| { + let (name, rest) = entry.split_once("\", \"")?; + let id = rest.split('"').next()?; + id.starts_with("urn:smpte:umid:").then(|| (name.to_string(), id.to_string())) + }) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn several_compositions_become_choices() { + let e = r#"io: interchange: Choose exactly one composition by MobID: [("Reel 1", "urn:smpte:umid:060a2b34.01"), ("Alt cut", "urn:smpte:umid:060a2b34.02")]"#; + assert_eq!( + composition_choices(e), + [("Reel 1".to_string(), "urn:smpte:umid:060a2b34.01".to_string()), ("Alt cut".to_string(), "urn:smpte:umid:060a2b34.02".to_string())] + ); + assert!(composition_choices("Missing media: x.wav").is_empty()); + } + #[test] + fn a_new_file_discards_the_analysis_still_running_for_the_previous_one() { + let mut state = ImportState::default(); + let (tx, rx) = mpsc::channel(); + state.set_path("/a/first.aaf".into()); + state.busy = Some(rx); + state.set_path("/b/second.aaf".into()); + assert!(state.busy.is_none()); + assert!(tx.send(Ok(json!({"plan": {}}))).is_err()); + assert!(state.preview.is_none()); + assert_eq!(state.media_dir, "/b"); + } + #[test] + fn a_typed_path_moves_the_derived_media_folder_but_keeps_a_chosen_one() { + let mut state = ImportState::default(); + state.set_path("/a/first.aaf".into()); + state.composition = "urn:smpte:umid:01".into(); + state.path = "/b/second.aaf".into(); + state.path_edited("/a/first.aaf"); + assert_eq!(state.media_dir, "/b"); + assert!(state.composition.is_empty()); + state.media_dir = "/media/elsewhere".into(); + state.path = "/c/third.aaf".into(); + state.path_edited("/b/second.aaf"); + assert_eq!(state.media_dir, "/media/elsewhere"); + } + #[test] + fn menu_opens_preview_but_programmatic_import_does_not_open_a_dialog() { + let mut app = SoundApp::new(soundcraft_engine::Engine::default(), None, crate::Services::default()); + assert!(app.run("file.import_aaf", json!({})).is_err()); + assert!(!app.aaf_import.open); + crate::menus::invoke_menu(&mut app, "file.import_aaf", "File > Import > Session Data..."); + assert!(app.aaf_import.open); + assert!(app.engine.session().tracks.is_empty()); + } +} diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 882cd1353..fe6feed08 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -2,8 +2,9 @@ use super::services::Services; use super::state::MainWindow; use super::{ ControlRequest, Engine, Gesture, HashMap, MeterDisplay, OutputTrouble, Player, Range, Receiver, Samples, SoundApp, TrackId, TransportRequest, - Trouble, UiState, Value, VecDeque, bounce, dialogs, edit_window, extra_windows, fonts, import, json, menus, midi_editor, mix_window, ops_windows, - palette, panels, preferences, recovery, sampler_window, score_editor, shortcuts, theme, updates_ui, video_track, video_window, windows, + Trouble, UiState, Value, VecDeque, aaf_import, bounce, dialogs, edit_window, extra_windows, fonts, import, json, menus, midi_editor, mix_window, + ops_windows, palette, panels, preferences, recovery, sampler_window, score_editor, shortcuts, theme, updates_ui, video_track, video_window, + windows, }; mod audio; @@ -61,6 +62,7 @@ impl SoundApp { preset_dir: None, last_autosave: None, dialogs: dialogs::Dialogs::default(), + aaf_import: aaf_import::ImportState::default(), updates_rt: updates_ui::Runtime::default(), meters: HashMap::new(), main_meter: MeterDisplay::default(), @@ -352,6 +354,7 @@ impl SoundApp { score_editor::show(self, &ctx); palette::show(self, &ctx); dialogs::show(self, &ctx); + aaf_import::show(self, &ctx); updates_ui::show(self, &ctx); // The sampler's drop rects are current now, so route any captured drop in this pass. self.route_dropped_files(); diff --git a/crates/ui-egui/src/dialogs/files.rs b/crates/ui-egui/src/dialogs/files.rs index c029f3300..1e56fa544 100644 --- a/crates/ui-egui/src/dialogs/files.rs +++ b/crates/ui-egui/src/dialogs/files.rs @@ -45,7 +45,7 @@ pub fn unicode(path: &std::path::Path) -> Result<&str, NotUnicode> { } /// Opens a dropped, picked or command-line file by its extension: a session opens (asking to save -/// first), MIDI imports, and anything else imports as audio, decoded in the background so a long +/// first), an AAF opens the Session Data window, MIDI imports, and anything else imports as audio, decoded in the background so a long /// file doesn't freeze the window (#597). A name that is not valid Unicode goes on the status line. pub fn open_path(app: &mut SoundApp, path: &std::path::Path) { let p = match unicode(path) { @@ -59,6 +59,8 @@ pub fn open_path(app: &mut SoundApp, path: &std::path::Path) { let lower = p.to_ascii_lowercase(); let r = if lower.ends_with(".scraft") { run_or_ask(app, "session.open", json!({"path": p})) + } else if lower.ends_with(".aaf") { + app.run("window.import_aaf", json!({"path": p})) } else if lower.ends_with(".mid") || lower.ends_with(".midi") || lower.ends_with(".smf") { app.run("file.import_midi", json!({"path": p})) } else { diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 753ecda95..a93bd0842 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -13,6 +13,7 @@ pub const UPDATE_APP: craft_update::app::App = craft_update::app::App { ..craft_update::suite::SOUNDCRAFT }; +pub mod aaf_import; pub mod appearance; pub mod bounce; pub mod control; @@ -329,6 +330,7 @@ pub struct SoundApp { pub preset_dir: Option, last_autosave: Option, pub dialogs: dialogs::Dialogs, + pub aaf_import: aaf_import::ImportState, pub(crate) updates_rt: updates_ui::Runtime, pub meters: HashMap, pub main_meter: MeterDisplay, diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index c23068990..3a1d4b4d8 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -68,6 +68,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, Option<&str>)] = &[ ("window.time_ops", "Time Operations", "", None), ("window.midi_ops", "MIDI Operations", "", None), ("window.rtp", "MIDI Real-Time Properties", "", None), + ("window.import_aaf", "Import Session Data (AAF)", "", None), ("window.playback_engine", "Playback Engine", "", None), ("ui.audio_device", "Audio Device", "", None), ("window.io_setup", "I/O Setup", "", None), @@ -524,6 +525,7 @@ fn params_for(path: &str, id: &str) -> Value { /// Menu items that open a SoundCraft window when clicked (programmatic calls still run the command). const MENU_WINDOWS: &[(&str, &str)] = &[ ("Setup > Appearance", "window.ui_customization"), + ("File > Import > Session Data...", "file.import_aaf"), ("Setup > Hardware...", "window.playback_engine"), ("Setup > Playback Engine...", "window.playback_engine"), ("Setup > MIDI > MIDI Input Devices...", "window.playback_engine"), @@ -560,6 +562,10 @@ pub fn live_label(app: &SoundApp, id: Option<&str>) -> Option { /// Menu-style invocation: may open a dialog. pub fn invoke_menu(app: &mut SoundApp, id: &str, path: &str) { + if id == "file.import_aaf" || path == "File > Import > Session Data..." { + let _ = crate::aaf_import::command(app, &json!({})); + return; + } if id == "setup.preferences" { let _ = app.run(id, json!({"value": true})); return; @@ -594,6 +600,10 @@ pub fn invoke_menu(app: &mut SoundApp, id: &str, path: &str) { /// Keyboard shortcut for a dialog command, or one that would close a modified session: open its /// dialog. Returns true when handled. pub fn invoke_shortcut_dialog(app: &mut SoundApp, id: &str) -> bool { + if id == "file.import_aaf" { + let _ = crate::aaf_import::command(app, &json!({})); + return true; + } (wants_dialog(id) && app.dialogs.open_for_command(&app.engine, id)) || crate::dialogs::ask_to_save(app, id, &json!({})) } @@ -604,6 +614,9 @@ fn wants_dialog(id: &str) -> bool { /// Handle UI-layer commands. Returns None when `id` is not a UI command. pub fn run_ui_command(app: &mut SoundApp, id: &str, p: &Value) -> Option> { + if id == "window.import_aaf" { + return Some(crate::aaf_import::command(app, p)); + } if matches!(id, "ui.dock" | "ui.dock.reset") { return Some(crate::docking::command(app, id, p)); } diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 3b5f437a8..7a1c6f6ff 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File-format parity -> **Last reviewed:** 2026-10-19 · **Last updated:** 2026-11-11 · **Change:** minor (audio formats come from craft-audio; previously trivial: bounces carry a BWF time reference, #1296) · **Target:** Avid Pro Tools Ultimate 2026.4.1 +> **Last reviewed:** 2026-11-14 · **Last updated:** 2026-11-14 · **Change:** minor (strict external-WAV AAF import; previously minor: audio formats come from craft-audio) · **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 @@ -9,7 +9,7 @@ documented import/bounce options. Ours comes from `craft-audio` in craft-libs (` `crates/engine/src/score.rs`, `crates/engine/src/clip_group_file.rs` and `crates/video`. **File formats: ~40 % ready** (estimated: weighted by how often a Pro Tools user hits each row; -session interchange carries a third of the weight and is at 0 %). Remaining ≈ 70–120 h. +session interchange carries a third of the weight and has only a strict AAF import subset). Remaining ≈ 70–120 h. Legend: ✅ supported and tested · 🟡 partial · ❌ missing · — not applicable. @@ -19,7 +19,7 @@ Legend: ✅ supported and tested · 🟡 partial · ❌ missing · — not appli |---|---|---|---|---| | Pro Tools session `.ptx` (and `.ptf` from 7–9) | native | ❌ | ❌ | Proprietary, undocumented. Owner decision needed on black-box format study (G-03) | | Session templates `.ptxt` | read/write | ❌ | ❌ | We have no templates at all (G-16) | -| AAF (Advanced Authoring Format) | import/export | ❌ | ❌ | #40. The post-production handoff from picture editors (G-03) | +| AAF (Advanced Authoring Format) | import/export | 🟡 | ❌ | #40. Strict subset: CompositionMob SourceClip/Filler edits with external mono/stereo PCM WAV; editable clips, handles, relink and timecode mapping. Gain, fades, transitions, embedded essence, split channels, mixed rates and export are unsupported (G-03) | | OMF | import/export | ❌ | ❌ | Legacy, still delivered by some editors | | Media Composer–compatible session | export | ❌ | ❌ | AAF variant | | ADM BWF (Dolby Atmos master) | import/export | ❌ | ❌ | G-12 | @@ -81,6 +81,7 @@ Legend: ✅ supported and tested · 🟡 partial · ❌ missing · — not appli | Date | Change | Summary | |---|---|---| +| 2026-11-14 | minor | Strict external-WAV AAF import with editable clips, relink and timecode mapping; export and the wider AAF/OMF feature set remain unsupported; readiness estimate unchanged | | 2026-11-11 | minor | Audio formats come from `craft-audio` (craft-libs); `crates/audio-io` is gone. New on import: Opus, AC-3/E-AC-3, `.mov`/`.mka` audio; AAC, ALAC and MP2 no longer go through symphonia; `.aifc` is a writable name | | 2026-11-02 | trivial | WAV bounces (mix and stems) write a `bext` TimeReference: session timecode start plus bounce start (#1296) | | 2026-10-19 | trivial | WAV and AIFF-C Float32 encoders retain finite headroom (#791); whole-file, streaming and bounce regression tests | diff --git a/docs/gaps.md b/docs/gaps.md index f7a706e19..1d1fec2b7 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Where SoundCraft falls short of Pro Tools -> **Last reviewed:** 2026-10-25 · **Last updated:** 2026-11-18 · **Change:** minor (G-02 shrunk: MIDI input devices work; previously minor: G-05: plugin editors on Linux/X11; previously trivial: G-09: the pt-BR catalog now covers helper-passed tooltips, the status bar, the remove-session prompt and engine error text; G-08: Frequency Shifter, 28 processors; G-04: volume automation read at every sample, #1354; G-01: `setup.playback_engine` applies the device buffer in the desktop app; G-04: Clip Looping crossfade and loop count) · **Target:** Avid Pro Tools Ultimate 2026.4.1 +> **Last reviewed:** 2026-11-14 · **Last updated:** 2026-11-18 · **Change:** minor (G-02 shrunk: MIDI input devices work; G-03: strict external-WAV AAF import; previously minor: G-05: plugin editors on Linux/X11; previously trivial: G-09: the pt-BR catalog now covers helper-passed tooltips, the status bar, the remove-session prompt and engine error text; G-08: Frequency Shifter, 28 processors; G-04: volume automation read at every sample, #1354; G-01: `setup.playback_engine` applies the device buffer in the desktop app; G-04: Clip Looping crossfade and loop count) · **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** @@ -17,7 +17,7 @@ When you close a gap, delete its entry (or shrink it) in the same PR, and bump t |---|---|---|---|---:| | G-01 | **Alpha blocker.** No channel routing or duplex low-latency path (device, rate and buffer choice done; ASIO opt-in) | Hardware | [hardware-parity.md](hardware-parity.md) | 15–25 | | G-02 | **Alpha blocker.** MIDI devices: input works (checked on Linux only); no output, clock or loop/merge recording | Hardware / MIDI | [hardware-parity.md](hardware-parity.md) | 12–22 | -| G-03 | **Alpha blocker.** Cannot exchange sessions with Pro Tools (no AAF/OMF, no `.ptx`) | File formats | [file-format-parity.md](file-format-parity.md) | 50–90 | +| G-03 | **Alpha blocker.** Session exchange remains incomplete (strict external-WAV AAF import only; no AAF/OMF export, OMF import or `.ptx`) | File formats | [file-format-parity.md](file-format-parity.md) | 50–90 | | G-04 | Open correctness bugs in features counted as done (~25 issues) | Stability | this file | 25–40 | | G-05 | (Entitlement part: alpha blocker for the mix row) Third-party VST3s blocked in the signed macOS build; AU editors missing | Ecosystem | [plugin-parity.md](plugin-parity.md) | 10–15 | | G-06 | (Record-to-disk part: alpha blocker for the tracking row) Sources decoded whole into RAM; recording into RAM | Performance | [hardware-parity.md](hardware-parity.md) | 15–25 | @@ -84,10 +84,15 @@ When you close a gap, delete its entry (or shrink it) in the same PR, and bump t ### G-03. Session interchange with Pro Tools -- **Missing:** opening or saving `.ptx`/`.ptf`, AAF and OMF import and export (#40), Media - Composer–compatible sessions. Our session format is `.scraft` JSON. -- **Impact:** a main-format requirement for beta. A Pro Tools user cannot bring a project in - or hand one back; post-production (picture editors deliver AAF) is blocked. +- **Done (2026-11-14):** strict AAF import for CompositionMob SourceClip/Filler edits with external + mono/stereo PCM WAV media. It creates editable clips with source handles, relink and absolute or + relative timecode mapping. The reader bounds cached property data to 128 MiB and rejects duplicate + local references before expanding objects. +- **Missing:** gain, fades, transitions, embedded essence, split channels and mixed sample rates in + AAF; AAF export; OMF import and export; opening or saving `.ptx`/`.ptf`; Media + Composer–compatible sessions (#40). Our session format is `.scraft` JSON. +- **Impact:** a main-format requirement for beta. Only the strict AAF subset can come in; other AAFs + and handing a session back remain blocked for post-production interchange. - **Estimate:** AAF/OMF import + export ≈ 50–90 h (FilmCraft already writes AAF/OMF; we can learn from it but not share code). `.ptx` is proprietary and undocumented: owner decision on whether black-box format study is in the clean-room rules; not included in the estimate. @@ -247,6 +252,7 @@ missing. Out of scope unless the owner decides otherwise. | Date | Change | Summary | |---|---|---| +| 2026-11-14 | minor | G-03: strict external-WAV AAF import with bounded property caching; AAF/OMF export, OMF import and `.ptx` remain; estimates unchanged | | 2026-11-13 | trivial | G-09: the pt-BR catalog now covers tooltips localized inside buttons and toggles, the Edit-window status bar, the remove-session question, the send help text and engine errors shown in the status line; estimates unchanged | | 2026-11-09 | trivial | G-08: 28 processors + 3 instruments with the Frequency Shifter | | 2026-11-04 | trivial | G-04: track and master volume automation read at every sample, so breakpoints act on their own sample in any block size (#1354); estimates unchanged | diff --git a/docs/roadmap.md b/docs/roadmap.md index 81a26b1ba..441f94ca5 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,6 +1,6 @@ # SoundCraft roadmap: milestones and what's next -> **Last reviewed:** 2026-11-05 · **Last updated:** 2026-11-18 · **Change:** minor (MIDI input landed, the gate row needs checking on macOS and Windows; previously trivial: 28 built-in processors with the Frequency Shifter; previously trivial: G-05 estimate after Linux/X11 plugin editors; previously trivial: M15: partial pt-BR catalog in PR #1346) · **Target:** Avid Pro Tools Ultimate 2026.4.1 +> **Last reviewed:** 2026-11-14 · **Last updated:** 2026-11-18 · **Change:** minor (MIDI input landed, the gate row needs checking on macOS and Windows; strict external-WAV AAF import; previously trivial: 28 built-in processors with the Frequency Shifter; G-05 estimate after Linux/X11 plugin editors; M15: partial pt-BR catalog; readiness estimates unchanged) · **Target:** Avid Pro Tools Ultimate 2026.4.1 Forward-looking plan. Status and numbers: [`../ROADMAP.md`](../ROADMAP.md) and [`target-app-parity.md`](target-app-parity.md); the ranked work list: [`gaps.md`](gaps.md). @@ -27,7 +27,7 @@ main platform). Any **no** keeps SoundCraft **pre-alpha**, and those rows are th | Edit: select, trim, fade, comp playlists, Slip/Shuffle/Grid | yes (rough) | Every Edit menu command; property-tested with undo; open bugs #3, #5, #140 don't block the workflow | — | | Mix with built-in and third-party plugins, sends, busses, automation | partial (passes on CLAP/AU) | 28 built-in processors; CLAP and AU host on the signed macOS build, but its missing entitlement blocks third-party VST3 (#153). No AU plugin windows yet; VST3 windows on macOS, Windows and Linux/X11 | 1–2 (entitlement) | | Bounce mix and stems; save and reopen the session | yes (rough) | WAV/BWF/AIFF/FLAC bounce, stems, `.scraft` save/reopen with plugin state; bugs #59, #103 in bus bounce and aux latency (PRs open) | — | -| Exchange a session with Pro Tools or a picture editor | **no** | No `.ptx`, AAF or OMF import or export (#40, G-03) | 50–90 | +| Exchange a session with Pro Tools or a picture editor | **no** | Strict external-WAV AAF import works, but AAF export, OMF and `.ptx` do not (#40, G-03) | 50–90 | **Result: pre-alpha.** Three workflows fail. Passing them is ~110–180 h, about 70 % of it parallelizable (interfaces, MIDI and AAF are independent crates). @@ -47,7 +47,7 @@ Status: ✅ done · 🟡 in progress · ⬜ not started. | M10 | Public releases on all platforms | ✅ v0.3.0 (2026-10-08) and v0.4.0 (2026-10-10) released for every platform | — | | M11 | Third-party plugin hosting (CLAP, VST3, AU), video, surround | 🟡 mostly done | 40–60 | | M12 | **Hardware**: audio interfaces, MIDI devices, sync, control surfaces | ⬜ | 110–180 | -| M13 | **Interchange**: AAF/OMF import/export, disk streaming, record to disk | ⬜ | 65–115 | +| M13 | **Interchange**: AAF/OMF import/export, disk streaming, record to disk | 🟡 strict external-WAV AAF import; export, OMF and disk streaming missing | 65–115 | | M14 | **Fidelity harness** against Pro Tools (null tests, plugin responses) | ⬜ | 20–30 | | M15 | **Localization**: catalog, fonts/RTL, the 8 Pro Tools languages first | 🟡 partial (pt-BR catalog; needs native review; PRs #141, #143 open) | 45–80 | | M16 | Built-in plugin depth, sidechain, ARA | ⬜ | 110–170 | @@ -89,6 +89,7 @@ There is no `cargo xtask scorecard` in this repo; the measured number is `cargo | Date | Change | Summary | |---|---|---| | 2026-11-18 | minor | MIDI input devices landed (G-02 shrunk); the MIDI gate row is unverified until checked on macOS and Windows | +| 2026-11-14 | minor | M13 is in progress with strict external-WAV AAF import; the exchange gate still fails without AAF export, OMF or `.ptx`; estimates unchanged | | 2026-11-09 | trivial | 28 built-in processors with the Frequency Shifter | | 2026-11-05 | trivial | M15: a pt-BR catalog covers menus and `text`/`localized_format!` strings; remains native review, CJK/RTL and the other languages. Estimates unchanged | | 2026-10-30 | trivial | G-05 down to 10–15 h and the mix row's VST3 windows updated: VST3 and embedded CLAP editors are hosted on Linux/X11 (#527) | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index b7f4fcd11..6346760cd 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Target-app parity: SoundCraft vs Avid Pro Tools -> **Last reviewed:** 2026-11-05 · **Last updated:** 2026-11-09 · **Change:** trivial (Frequency Shifter: 28 built-in processors; previously trivial: G-09/localization: pt-BR catalog; percentages unchanged) · **Target:** Avid Pro Tools Ultimate 2026.4.1 (bundle 26.4.1.179, macOS) +> **Last reviewed:** 2026-11-14 · **Last updated:** 2026-11-14 · **Change:** minor (strict external-WAV AAF import; previously trivial: Frequency Shifter: 28 built-in processors; G-09/localization: pt-BR catalog; readiness estimates unchanged) · **Target:** Avid Pro Tools Ultimate 2026.4.1 (bundle 26.4.1.179, macOS) The authoritative assessment of how close SoundCraft is to Pro Tools. [`ROADMAP.md`](../ROADMAP.md) summarizes it, [`gaps.md`](gaps.md) itemizes every shortfall, and the per-dimension docs go deeper: @@ -81,7 +81,7 @@ post-production, tracking) can switch. "Ready" is depth, correctness and fidelit |---|---:|---:|---|---:|---|---| | Features | 45 % | **~45 %** | estimated | 520–810 | [area table](#feature-areas) | Menu breadth 94 % measured, but depth is thin: see the area table | | UI/UX fidelity | 10 % | **~55 %** | estimated | 60–100 | [ui-parity.md](ui-parity.md) | Edit/Mix windows, every menu, floating windows; open UX bugs #3 #5 #6 #7 #140 #144; shortcuts only recently right on Windows/Linux (#15, #41); generic plugin UIs | -| File formats | 10 % | **~40 %** | estimated | 70–120 | [file-format-parity.md](file-format-parity.md) | WAV/BWF/RF64/AIFF/FLAC read+write, compressed formats read; no `.ptx`, AAF, OMF, ADM BWF, MP3/AAC export, video export | +| File formats | 10 % | **~40 %** | estimated | 70–120 | [file-format-parity.md](file-format-parity.md) | WAV/BWF/RF64/AIFF/FLAC read+write, compressed formats read; strict external-WAV AAF import; no `.ptx`, AAF/OMF export, OMF import, ADM BWF, MP3/AAC export, video export | | Hardware | 10 % | **~12 %** | estimated | 110–180 | [hardware-parity.md](hardware-parity.md) | Default output and default input device only, fixed 512-sample block, no ASIO, no MIDI devices, no control surfaces, no sync | | Stability | 10 % | **~45 %** | estimated | 50–80 | [gaps.md](gaps.md) | Never-crash rules and proptests (random edits, mutated sessions, hostile params); but ~25 open correctness bugs, a launch failure (#142), an X11 llvmpipe failure (#107) | | Performance | 5 % | **~35 %** | estimated (unmeasured) | 40–70 | [hardware-parity.md](hardware-parity.md) | Parallel strip rendering and PDC exist; whole files decoded into RAM, recording into RAM (#84 open), no track-count or latency benchmarks | @@ -122,7 +122,7 @@ immersive delivery, video, notation, and languages other than English. |---|---:|---| | Interaction fidelity | ×0.90 | Shortcut collisions and dead shortcuts (#140 Heal, #144 Mix/Edit vs zoom, #7 Export); Multitool handles don't adjust audio (#5); generic plugin parameter panels (#138, #139); clip deletion inconsistencies (#3, #4) | | Stability on real machines | ×0.92 | 26 open core-path bugs, e.g. bounce and latency (#59, #103), playback speed (#101), session saves (#86, #91), plus a launch failure (#142). Never-crash rules and property tests hold up: no crash reports on macOS since #16 | -| File exchange with Pro Tools users | ×0.85 | Engineers trade sessions, not stems. No `.ptx`, AAF or OMF (#40); WAV/BWF stems and MIDI files do work, so the factor isn't lower | +| File exchange with Pro Tools users | ×0.85 | Engineers trade sessions, not stems. Only a strict external-WAV AAF import subset works; `.ptx`, AAF export and OMF do not (#40). WAV/BWF stems and MIDI files work, so the factor isn't lower | | **Result** | 50.6 × 0.90 × 0.92 × 0.85 = **35.6 % ≈ 36 %** | | This comes out *below* the full number (~40 %), which is unusual. The @@ -188,7 +188,7 @@ Weights by what Pro Tools users actually spend time on. **Breadth** = the featur | Elastic Audio, TCE, Beat Detective, pitch | 5 % | 70 % | **35 %** | 40–60 | Pitch-preserving warp on Elastic tracks, TCE, conform to tempo, Beat Detective and Identify Beat, audio-to-MIDI. Missing: per-algorithm choice (polyphonic/rhythmic/monophonic/varispeed/X-Form), warp markers UI depth, Elastic Pitch, quality vs Pro Tools unmeasured | | Surround and immersive | 5 % | 55 % | **35 %** | 50–80 | Formats stereo → 9.1.6 and Ambisonics, surround panner, fold-down, multichannel bounce, object/bed routing. Missing: Dolby Atmos renderer integration and ADM BWF, MPEG-H (new in 2026.4), binaural/headphone monitoring, surround automation; bug #89 | | Video and post | 5 % | 60 % | **40 %** | 40–60 | Video track, H.264/ProRes/MJPEG decoders, sync offset, relinking, timecode rulers. Missing: HEVC/DNx/AV1, video bounce/export, timecode sync to external machines, speech-to-text transcript, field-recorder/iXML conform | -| Session, file management, interchange | 10 % | 55 % | **35 %** | 60–100 | `.scraft` + Audio Files, Save Copy In, Import Session Data, clip groups, session text export, audio-health report. Missing: `.ptx` read/write, AAF/OMF (#40), session templates, track presets, workspace/Soundbase browser, disk streaming of long sources, batch rename; bugs #86, #91, #136 | +| Session, file management, interchange | 10 % | 55 % | **35 %** | 60–100 | `.scraft` + Audio Files, Save Copy In, Import Session Data, clip groups, session text export, audio-health report, strict external-WAV AAF import. Missing: `.ptx` read/write, AAF export, OMF import/export (#40), session templates, track presets, workspace/Soundbase browser, disk streaming of long sources, batch rename; bugs #86, #91, #136 | | Collaboration, cloud, Sketch, Splice | 2 % | 0 % | **0 %** | not estimated | Avid services; out of scope unless the owner decides otherwise | | Agent control (CLI, control channel, MCP) | 1 % | 100 % | **100 %** | 3 | Ahead of Pro Tools' scripting SDK; one open bug (#145) | | **Weighted** | 100 % | **~70 %** | **~45 %** | **~520–810** | | @@ -203,7 +203,7 @@ platform: used, the mix runs in fixed 512-sample blocks, input and output are separate streams, and takes are held in RAM. - MIDI recording: **no**. There is no MIDI device layer. -- Session interchange with Pro Tools or picture editors: **no**. No AAF/OMF/`.ptx`. +- Session interchange with Pro Tools or picture editors: **no**. Strict external-WAV AAF import works, but AAF export, OMF and `.ptx` do not. Editing, mixing with plugins, bouncing, and saving and reopening pass (with known bugs). @@ -245,6 +245,7 @@ serializes more, because it needs hands-on testing. | Date | Change | Summary | |---|---|---| +| 2026-11-14 | minor | Strict external-WAV AAF import added to format, interchange and alpha-gate evidence; readiness estimates unchanged | | 2026-11-09 | trivial | Built-in plugin counts: 28 processors + 3 instruments with the Frequency Shifter. Percentages unchanged | | 2026-11-05 | trivial | Localization row: English plus a near-complete pt-BR catalog for fixed UI strings (PR #1346), not native-reviewed. Percentages and hours unchanged | | 2026-10-24 | trivial | Built-in plugin counts: 27 processors + 3 instruments on `main`, and 24 + 2 in the 3bc2d92 code snapshot; the sampler (#108) is no longer listed as missing. Percentages unchanged | diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 7c5c193c2..d98b3e926 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -31,6 +31,7 @@ const LAYERS: &[(&str, u8)] = &[ ("au-host", 1), ("model", 2), ("mix", 3), + ("interchange", 3), ("engine", 4), ("playback", 4), ("automation", 5),