FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust
NEST15: nested sequences in AAF and OMF, the way Premiere Pro writes them
justjohn123459b31f4eb8447
diff --git a/crates/engine/src/aaf_omf.rs b/crates/engine/src/aaf_omf.rsindex a25821126..fd0d01965 100644--- a/crates/engine/src/aaf_omf.rs+++ b/crates/engine/src/aaf_omf.rs@@ -19,8 +19,8 @@ use std::sync::{Arc, Mutex};use serde_json::{Value, json};-use filmcraft_interchange::essence::{AudioEssence, AudioNeed, EssenceData, EssenceKey, MediaOptions, MixdownVideo, NeedOptions, audio_needs};-use filmcraft_project::{ItemId, Project, SequenceSettings, TrackKind};+use filmcraft_interchange::essence::{AudioEssence, AudioNeed, EssenceData, EssenceKey, MediaOptions, MixdownVideo, NeedOptions, NestNeeds, audio_needs};+use filmcraft_project::{ClipId, ItemId, Project, Sequence, SequenceSettings, Track, TrackItem, TrackKind};use filmcraft_time::{Tick, TimeRange};use crate::commands::{bad, bool_p, str_p, u64_p};@@ -50,6 +50,10 @@ pub struct AudioPlan {pub handles: Tick,pub render_effects: bool,pub breakout: bool,+ /// Nested sequences on the audio tracks. OMF: their sound is rendered into the export, as+ /// Premiere Pro does. AAF: they are written as compositions, so the media of the clips inside+ /// them is prepared like the rest.+ pub nests: NestNeeds,}fn plan_from(s: &Session, p: &Value, seq: ItemId, cmd: &str, omf: bool) -> Result<AudioPlan> {@@ -85,6 +89,7 @@ fn plan_from(s: &Session, p: &Value, seq: ItemId, cmd: &str, omf: bool) -> Resulhandles: q.settings.frame_rate.tick_of(frames),render_effects: bool_p(p, "renderAudioEffects").unwrap_or(false),breakout: bool_p(p, "breakoutToMono").unwrap_or(false),+ nests: if omf { NestNeeds::Render } else { NestNeeds::Inside },})}@@ -154,12 +159,8 @@ fn decode(s: &Session, need: &AudioNeed, sample_rate: u32) -> Result<Vec<Vec<f32/// pipeline's audio mixer.fn render_clip(s: &Session, seq: ItemId, need: &AudioNeed, sample_rate: u32, bits: u16) -> Result<Vec<Vec<f32>>> {let EssenceKey::Clip(clip_id) = need.key else { return decode(s, need, sample_rate) };- let q = s.project.sequence(seq).ok_or(EngineError::NoSequence)?;- let (track, c) = q- .tracks(TrackKind::Audio)- .iter()- .find_map(|t| t.items.iter().find(|c| c.id == clip_id).map(|c| (t, c.clone())))- .ok_or_else(|| EngineError::Other("clip not found".into()))?;+ let (q, track, c) = audio_clip(&s.project, seq, clip_id).ok_or_else(|| EngineError::Other("clip not found".into()))?;+ let c = c.clone();let mut p: Project = (*s.project).clone();let settings = SequenceSettings { sample_rate, ..q.settings.clone() };let rs = p.new_sequence("AAF audio render", settings, 0, 1, None);@@ -204,6 +205,19 @@ fn render_clip(s: &Session, seq: ItemId, need: &AudioNeed, sample_rate: u32, bitOk(dequantize(&pcm, ch as usize, b))}+/// The audio clip `clip` with its track and sequence: in `seq`, or in a sequence nested in it+/// (clip ids are unique in a project).+fn audio_clip(p: &Project, seq: ItemId, clip: ClipId) -> Option<(&Sequence, &Track, &TrackItem)> {+ let first = p.sequence(seq).into_iter();+ let others = p.sequences().filter(|i| i.id != seq).filter_map(|i| p.sequence(i.id));+ for q in first.chain(others) {+ if let Some((t, c)) = q.tracks(TrackKind::Audio).iter().find_map(|t| t.items.iter().find(|c| c.id == clip).map(|c| (t, c))) {+ return Some((q, t, c));+ }+ }+ None+}+fn safe_name(s: &str) -> String {let n: String = s.chars().map(|c| if c.is_alphanumeric() || " -_.".contains(c) { c } else { '_' }).collect();let n = n.trim().trim_matches('.').to_string();@@ -221,19 +235,24 @@ pub fn prepare_audio(s: &Session, seq: ItemId, plan: &AudioPlan, media_dir: &strif plan.mode == AudioMode::Linked && !plan.trim && !plan.render_effects {return Ok((Vec::new(), Vec::new()));}- let needs =- audio_needs(&s.project, seq, &NeedOptions { handles: plan.handles, per_clip: plan.render_effects, whole_media: !plan.trim && !plan.render_effects });+ let needs = audio_needs(+ &s.project,+ seq,+ &NeedOptions { handles: plan.handles, per_clip: plan.render_effects, whole_media: !plan.trim && !plan.render_effects, nests: plan.nests },+ );let mut essence = Vec::new();let mut files = Vec::new();let mut used = std::collections::HashSet::new();for need in &needs {- let planar = if plan.render_effects { render_clip(s, seq, need, plan.sample_rate, plan.bits)? } else { decode(s, need, plan.sample_rate)? };+ // a nested sequence has no file to read: its sound is mixed, with what is on the clip+ let nest = s.project.sequence(need.item).is_some();+ let planar = if plan.render_effects || nest { render_clip(s, seq, need, plan.sample_rate, plan.bits)? } else { decode(s, need, plan.sample_rate)? };let frames = planar.first().map_or(0, Vec::len) as u64;let groups: Vec<(Option<u32>, Vec<&Vec<f32>>)> =if plan.breakout { planar.iter().enumerate().map(|(c, x)| (Some(c as u32), vec![x])).collect() } else { vec![(None, planar.iter().collect())] };let base = match need.key {EssenceKey::Clip(c) => {- let name = s.project.sequence(seq).and_then(|q| q.find_item(c)).map(|(_, ti)| ti.name.clone()).unwrap_or_default();+ let name = audio_clip(&s.project, seq, c).map(|(_, _, ti)| ti.name.clone()).unwrap_or_default();format!("{} {}", safe_name(&name), c.0)}EssenceKey::Media(_) => safe_name(@@ -302,7 +321,7 @@ pub fn prepare_audio(s: &Session, seq: ItemId, plan: &AudioPlan, media_dir: &strbits: plan.bits,channels: n,data,- effects_rendered: plan.render_effects,+ effects_rendered: plan.render_effects || nest,});}}diff --git a/crates/engine/src/aaf_omf_tests.rs b/crates/engine/src/aaf_omf_tests.rsindex d0a6d82c5..1bd52a8c6 100644--- a/crates/engine/src/aaf_omf_tests.rs+++ b/crates/engine/src/aaf_omf_tests.rs@@ -208,6 +208,95 @@ fn omf_renders_clip_effects_into_embedded_audio() {let _ = std::fs::remove_dir_all(dir);}+/// `setup`, with both clips nested into "Inner" (one linked picture + sound nest on V1 / A1) and+/// −6.0206 dB (half amplitude) on the nest's sound clip.+fn setup_nested(name: &str) -> (Session, Vec<ItemId>, ItemId, ItemId, std::path::PathBuf) {+ let (mut s, items, seq, dir) = setup(name);+ s.execute("sequence.open", json!({"item": seq.0})).unwrap();+ let clips: Vec<u64> = s.project.sequence(seq).unwrap().all_tracks().flat_map(|t| t.items.iter().map(|c| c.id.0)).collect();+ s.execute("timeline.select", json!({"clips": clips})).unwrap();+ let inner = ItemId(s.execute("clip.nest", json!({"name": "Inner"})).unwrap()["sequence"].as_u64().unwrap());+ let mut p = (*s.project).clone();+ let q = p.sequence_mut(seq).unwrap();+ assert_eq!((q.video_tracks[0].items.len(), q.audio_tracks[0].items.len()), (1, 1), "one linked nest");+ q.audio_tracks[0].items[0].effect_mut("volume").unwrap().params.insert("level".into(), Param::new(ParamValue::Float(-6.020_599_913)));+ s.project = Arc::new(p);+ (s, items, seq, inner, dir)+}++/// Premiere Pro renders the sound of a nested sequence into an OMF as one clip named after the+/// sequence (seen in an OMF it exported). So do we: the nest is mixed, with what is on its clip.+#[test]+fn omf_renders_the_sound_of_a_nested_sequence() {+ let (mut s, items, seq, inner, dir) = setup_nested("omf-nest");+ let nest = s.project.sequence(seq).unwrap().audio_tracks[0].items[0].clone();+ let path = dir.join("nest.omf").to_string_lossy().into_owned();+ let r = s.execute("file.exportOmf", json!({"path": path, "handles": 0, "sequence": seq.0})).unwrap();+ assert!(!r["report"].to_string().contains("nested"), "{r}");+ let r = s.execute("file.importAaf", json!({"path": path})).unwrap();+ let q = s.project.sequence(imported_seq(&r)).unwrap().clone();+ let a = &q.audio_tracks[0].items;+ assert_eq!(a.len(), 1, "the nest is one clip");+ assert_eq!((a[0].name.as_str(), a[0].start, a[0].duration), ("Inner", nest.start, nest.duration));+ assert!(s.project.sequence(a[0].item).is_none(), "media in the document, not a sequence");+ // what it plays: the nested sequence's two clips one after the other, at half amplitude+ let inside = s.project.sequence(inner).unwrap().audio_tracks[0].items.clone();+ assert_eq!(inside.len(), 2);+ let got = audio_of(&s, a[0].item, a[0].source_in.to_units_floor(48_000), 96_000);+ for (k, oc) in inside.iter().enumerate() {+ let want = audio_of(&s, oc.item, oc.source_in.to_units_floor(48_000), 48_000);+ assert_eq!(oc.item, items[k]);+ let peak = want[0].iter().fold(0f32, |m, x| m.max(x.abs()));+ assert!(peak > 0.01, "the demo scene has audio");+ // (away from the cut between the two clips)+ for i in 480..47_520 {+ let g = got[0][k * 48_000 + i];+ assert!((g - want[0][i] * 0.5).abs() < 2e-3, "clip {k} sample {i}: {g} vs {}", want[0][i] * 0.5);+ }+ }+ let _ = std::fs::remove_dir_all(dir);+}++/// An AAF holds a nested sequence as a composition of its own (as Premiere Pro's does): it comes+/// back as a sequence that the nest clips use, with its own clips, and with embedded audio the+/// media inside it is in the document too.+#[test]+fn aaf_keeps_a_nested_sequence_as_a_sequence() {+ let (mut s, items, seq, inner, dir) = setup_nested("aaf-nest");+ let path = dir.join("nest.aaf").to_string_lossy().into_owned();+ let r = s.execute("file.exportAaf", json!({"path": path, "audio": "embedded", "trimAudio": true, "handles": 6, "sequence": seq.0})).unwrap();+ assert!(!r["report"].to_string().contains("gap"), "{r}");+ let r = s.execute("file.import", json!({"paths": [path]})).unwrap();+ let q = s.project.sequence(imported_seq(&r)).unwrap().clone();+ let (v, a) = (&q.video_tracks[0].items, &q.audio_tracks[0].items);+ assert_eq!((v.len(), a.len()), (1, 1));+ let nested = v[0].item;+ assert_ne!(nested, inner, "a sequence of the imported document");+ assert_eq!((a[0].item, s.project.item(nested).unwrap().name.as_str()), (nested, "Inner"));+ assert!(v[0].link.is_some() && v[0].link == a[0].link, "picture and sound of the nest are linked");+ let level = a[0].effect("volume").and_then(|e| e.param("level")).and_then(|p| p.value.as_f64()).unwrap();+ assert!((level + 6.0206).abs() < 1e-2, "the level stays on the nest's clip: {level}");+ // inside: the two clips, their picture linked to the movies, their sound in the document+ let n = s.project.sequence(nested).unwrap().clone();+ let orig = s.project.sequence(inner).unwrap().clone();+ for kind in [TrackKind::Video, TrackKind::Audio] {+ let got: Vec<_> = n.tracks(kind)[0].items.iter().map(|c| (c.start, c.duration)).collect();+ let want: Vec<_> = orig.tracks(kind)[0].items.iter().map(|c| (c.start, c.duration)).collect();+ assert_eq!(got, want, "{kind:?}");+ }+ assert_eq!(path_of(&s, n.video_tracks[0].items[0].item), path_of(&s, items[0]));+ for (c, oc) in n.audio_tracks[0].items.iter().zip(&orig.audio_tracks[0].items) {+ let p = path_of(&s, c.item);+ assert!(p.ends_with(".wav") && std::path::Path::new(&p).exists(), "{p}");+ let got = audio_of(&s, c.item, c.source_in.to_units_floor(48_000), 4800);+ let want = audio_of(&s, oc.item, oc.source_in.to_units_floor(48_000), 4800);+ for i in 0..4800 {+ assert!((got[0][i] - want[0][i]).abs() <= 1.0 / 32_768.0 + 1e-6, "sample {i}");+ }+ }+ let _ = std::fs::remove_dir_all(dir);+}+#[test]fn commands_are_registered_with_menus_and_validate_params() {for (id, menu) in [("file.exportAaf", &["File", "Export"][..]), ("file.exportOmf", &["File", "Export"][..]), ("file.importAaf", &[][..])] {diff --git a/crates/interchange/README.md b/crates/interchange/README.mdindex f8dbd84c1..5570500a3 100644--- a/crates/interchange/README.md+++ b/crates/interchange/README.md@@ -7,7 +7,9 @@ references are strings and audio essence is supplied by the caller (the engine).## SpecificationsClean-room: written from public specifications only. The AAF SDK, pyaaf2, the OMF Toolkit and-other implementations were not consulted.+other implementations were not consulted. Where a specification leaves a layout open (how a+nested sequence is written, how several video tracks share a slot), what Premiere Pro does was+read off files it exports, never from the application itself.| Format | Document | Edition | Used for ||---|---|---|---|@@ -35,10 +37,32 @@ Embedded / consolidated audio (`essence`): `audio_needs` lists the media rangesreferences (per media item or per clip, with handles); the engine decodes or renders them andpasses `AudioEssence` (embedded PCM or a written file) back in `MediaOptions`.-Not represented: speed changes and frame holds (exported at 100 % with a report entry), nested-sequences, graphics and synthetic media (gaps), video effects other than transitions, clip+Not represented: speed changes and frame holds (exported at 100 % with a report entry),+graphics and synthetic media (gaps), video effects other than transitions, clipmarkers (written to the master mob, so they come back as media markers), OMF video and markers.+## Nested sequences++For the formats Premiere Pro exports (FCP7 XML, OTIO, EDL, AAF, OMF) a nested sequence is written+the way Premiere Pro 26.5.2 writes it, as seen in the files it exports for a sequence with a nest.+Premiere Pro does not write FCPXML.++| Format | Written as | On import into FilmCraft |+|---|---|---|+| FCP7 XML | a clip item holding the nested `<sequence>` (by id after the first use) | a sequence the clips use |+| FCPXML | a `ref-clip` to a `media` resource holding the sequence | a sequence the clips use |+| OTIO | a `Stack` inside the track | a sequence the clips use |+| EDL | one event: reel `AX` in every reel mode, the nested sequence's name as the clip name, its own time as source timecode (the report says the nest's edit is not in the EDL) | an ordinary clip of that name |+| AAF | a composition mob of its own (not tagged top-level); the nest's clips are source clips that point at it, at its first track of their kind. With embedded or consolidated audio the media inside the nest is prepared too (`NestNeeds::Inside`) | a sequence the clips use, read once however many clips use it |+| OMF | the nested sequence's sound, mixed by the engine with what is on the clip (`NestNeeds::Render`), as one clip named after the sequence. Without that essence: a gap, and the report names the sequence | media in the document |++A sequence that claims to be inside itself (a damaged project or file) is a gap with a report+entry in both directions; nothing recurses without a bound.++The AAF reader also accepts Premiere Pro's layout of a composition: all video tracks in ONE slot+(a nested scope with a segment per track, lowest first), and "top-level" tagged on nested+compositions too (the top-level ones are those no other composition uses).+## Graphics and adjustment layersNo format here has an equivalent of a FilmCraft graphic (title) clip or an adjustment layer, and@@ -62,7 +86,9 @@ OMF carries no video at all.gain, media markers and timecode); 512-byte sectors; breakout to mono; embedded trimmed audio(sample data and source offsets); separate consolidated files with a video mixdown; OMF roundtrips with embedded audio, separate AIFF files and breakout; empty sequences; truncation and- random corruption never panic.+ random corruption never panic. Nested sequences: AAF round trips as compositions (nests in+ nests, a nest used twice, another frame and sample rate, breakout to mono), OMF with the+ rendered sound, the audio needs of nests, a sequence inside itself.- `tests/uncarried_clips.rs`: every format's export report names each graphic clip and adjustmentlayer once, as a warning; a sequence without them reports nothing; what a re-import gives backmatches the report; the FCP7 XML import names a clip item whose file is not defined.@@ -70,6 +96,7 @@ OMF carries no video at all.written (Header, Identification, Mobs, slots, components, descriptors), weak referencesresolving into the dictionary, source clips resolving to mobs and slots, the Edit Protocoltransition rules and sequence length arithmetic; every stored form round-trips through the- container.+ container; a file rewritten into Premiere Pro's layout (video tracks as layers of one slot,+ nested compositions tagged top-level) reads back as the same edit.- `src/omf/tests.rs`: the Bento label and TOC, the required properties of every OMF classwritten, reference resolution, embedded WAVE data, sequence lengths in samples.diff --git a/crates/interchange/src/aaf/ids.rs b/crates/interchange/src/aaf/ids.rsindex 2b9c76ee9..c010f5a75 100644--- a/crates/interchange/src/aaf/ids.rs+++ b/crates/interchange/src/aaf/ids.rs@@ -37,6 +37,7 @@ pub(crate) mod cls {pub const FILLER: Auid = class(0x09);pub const OPERATION_GROUP: Auid = class(0x0A);pub const NESTED_SCOPE: Auid = class(0x0B);+ pub const SCOPE_REFERENCE: Auid = class(0x0D);pub const SELECTOR: Auid = class(0x0E);pub const SEQUENCE: Auid = class(0x0F);pub const SOURCE_CLIP: Auid = class(0x11);diff --git a/crates/interchange/src/aaf/mod.rs b/crates/interchange/src/aaf/mod.rsindex 5f5630720..707c6a435 100644--- a/crates/interchange/src/aaf/mod.rs+++ b/crates/interchange/src/aaf/mod.rs@@ -16,14 +16,20 @@//! `Amplitude` **ConstantValue** or **VaryingValue** (keyframes as control points),//! - sequence markers as **CommentMarker**s in an event slot;//!+//! a **CompositionMob** without a usage code for every nested sequence, built the same way (a+//! clip of the nested sequence is a **SourceClip** that points at that mob, at its first slot of+//! the clip's kind, with its start in that slot's edit units; Premiere Pro writes nested sequences+//! this way);+//!//! and for every media item a **MasterMob**, a file **SourceMob** per essence (a CDCI or PCM//! descriptor with a network locator to the file, or `EssenceData` holding embedded PCM) and a//! tape **SourceMob** carrying the media's start timecode. Clip and media markers become comment//! markers on the master mob.//!-//! Import reads the same structures (and the common variations: nested sequences, selectors,-//! operation groups around clips, legacy data definitions, essence groups) into FilmCraft-//! sequences, media items (linked by path; embedded audio is returned as WAV files for the+//! Import reads the same structures (and the common variations: sequences inside sequences,+//! selectors, operation groups around clips, legacy data definitions, essence groups, and Premiere+//! Pro's one video slot holding a nested scope with a segment per video track) into FilmCraft+//! sequences (a composition that others use becomes a nested sequence), media items (linked by path; embedded audio is returned as WAV files for the//! caller to write) and markers.mod ids;@@ -53,7 +59,7 @@ pub struct AafOptions {pub fn export(project: &Project, sequence: ItemId, opts: &AafOptions) -> Result<(Vec<u8>, Report)> {let mut report = Report::default();let name = opts.name.clone().or_else(|| project.item(sequence).map(|i| i.name.clone())).unwrap_or_else(|| "Sequence".into());- let doc = comp::from_project(project, sequence, &name, &opts.media, &mut report)?;+ let doc = comp::from_project(project, sequence, &name, &opts.media, comp::Nests::Compositions, &mut report)?;let version = if opts.small_sectors { filmcraft_cfb::Version::V3 } else { filmcraft_cfb::Version::V4 };let bytes = write::write(&doc, version, &mut report)?;Ok((bytes, report))diff --git a/crates/interchange/src/aaf/read.rs b/crates/interchange/src/aaf/read.rsindex 92b20e607..201a58058 100644--- a/crates/interchange/src/aaf/read.rs+++ b/crates/interchange/src/aaf/read.rs@@ -72,8 +72,15 @@ struct R<'a> {doc: Document,/// (file mob id, slot id, master key) → source indexsources: HashMap<(MobId, u32, String), usize>,+ /// Composition mobs read as nested compositions: their index in `doc.nested`.+ nests: HashMap<MobId, usize>,+ /// The compositions being read, outermost first.+ open: Vec<MobId>,}+/// Compositions nested deeper than this are read as gaps.+const MAX_NESTING: usize = 16;+pub(crate) fn read(bytes: &[u8], report: &mut Report) -> Result<Document> {let root = store::read(bytes).map_err(|e| Error::Parse { format: "AAF", message: e })?;let header = root.strong(pid::ROOT_HEADER).ok_or_else(|| Error::Parse { format: "AAF", message: "no header object".into() })?;@@ -90,21 +97,23 @@ pub(crate) fn read(bytes: &[u8], report: &mut Report) -> Result<Document> {essence.insert(id, d);}}- let mut r = R { report, mobs, essence, doc: Document::default(), sources: HashMap::new() };- // top-level compositions: not referenced by another composition (usage code wins when present)+ let mut r = R { report, mobs, essence, doc: Document::default(), sources: HashMap::new(), nests: HashMap::new(), open: Vec::new() };+ // Top-level compositions: those no other composition uses, among the ones tagged top-level+ // when any are. (Premiere Pro tags a nested sequence's composition top-level too; it is still+ // only a nested sequence.) Compositions that only use each other in a circle all count.let comps: Vec<&Obj> = content.objs(pid::MOBS).iter().filter(|m| m.class == cls::COMPOSITION_MOB).collect();let mut referenced = HashSet::new();for c in &comps {collect_refs(c, &mut referenced);}let tagged_top: Vec<&Obj> = comps.iter().copied().filter(|c| c.auid(pid::USAGE_CODE) == Some(def::USAGE_TOP_LEVEL)).collect();- let top: Vec<&Obj> = if !tagged_top.is_empty() {- tagged_top- } else {- comps.iter().copied().filter(|c| c.mob_id(pid::MOB_ID).is_none_or(|id| !referenced.contains(&id))).collect()- };+ let pool = if tagged_top.is_empty() { comps } else { tagged_top };+ let unused: Vec<&Obj> = pool.iter().copied().filter(|c| c.mob_id(pid::MOB_ID).is_none_or(|id| !referenced.contains(&id))).collect();+ let top = if unused.is_empty() { pool } else { unused };for c in top {+ r.open.extend(c.mob_id(pid::MOB_ID));let comp = r.composition(c);+ r.open.clear();r.doc.compositions.push(comp);}if r.doc.compositions.is_empty() {@@ -174,40 +183,60 @@ impl R<'_> {if ckind == CKind::Sound && sample_rate == 0 && er.1 == 1 && er.0 >= 8000 {sample_rate = er.0 as u32;}- let mut items = self.segment(seg, er, ckind, 0);- if origin > 0 {- // material before the origin is not shown- trim_front(&mut items, units_to_ticks(origin, er.0, er.1));- }- let number = s.u32(pid::PHYSICAL_TRACK_NUMBER).unwrap_or(0);- let name = s.string(pid::SLOT_NAME).unwrap_or_default();- let channels = if ckind == CKind::Sound {- items- .iter()- .filter_map(|i| match i {- CItem::Clip(c) => Some(self.doc.sources[c.source].channels),- _ => None,- })- .max()- .unwrap_or(1)- .min(6)- } else {- 0- };- let n = if ckind == CKind::Picture {- nv += 1;- nv+ // Premiere Pro writes every video track into one slot: a nested scope with a+ // segment per track, the lowest track first. (A scope whose last segment+ // refers to the others is an effect over layers: one track, as before.)+ let layers: Vec<&Obj> = if ckind == CKind::Picture && seg.class == cls::NESTED_SCOPE && !refers_to_scope(seg, 0) {+ seg.objs(pid::NESTED_SLOTS).iter().collect()} else {- na += 1;- na+ Vec::new()};- comp.tracks.push(CTrack { kind: ckind, name, number: if number > 0 { number } else { n }, channels, items });+ let layered = !layers.is_empty();+ let whole = units_to_ticks(len_of(seg), er.0, er.1);+ for layer in if layered { layers } else { vec![seg] } {+ let mut items = self.segment(layer, er, ckind, 0);+ if layered {+ fit(&mut items, whole);+ }+ if origin > 0 {+ // material before the origin is not shown+ trim_front(&mut items, units_to_ticks(origin, er.0, er.1));+ }+ let number = s.u32(pid::PHYSICAL_TRACK_NUMBER).unwrap_or(0);+ let name = s.string(pid::SLOT_NAME).unwrap_or_default();+ let channels = if ckind == CKind::Sound {+ items+ .iter()+ .filter_map(|i| match i {+ CItem::Clip(c) => self.doc.sources.get(c.source).map(|s| s.channels),+ _ => None,+ })+ .max()+ .unwrap_or(1)+ .min(6)+ } else {+ 0+ };+ let n = if ckind == CKind::Picture {+ nv += 1;+ nv+ } else {+ na += 1;+ na+ };+ comp.tracks.push(CTrack { kind: ckind, name, number: if number > 0 && !layered { number } else { n }, channels, items });+ }}DataKind::Other => self.report.info("a slot of an unsupported data kind was skipped"),}}if width == 0 {- let pic = self.doc.sources.iter().find(|s| s.kind == CKind::Picture && s.width > 0);+ // no size in the file: that of the first picture this composition shows, else of any+ let own = comp.tracks.iter().filter(|t| t.kind == CKind::Picture).flat_map(|t| &t.items).find_map(|i| match i {+ CItem::Clip(c) => self.doc.sources.get(c.source).filter(|s| s.kind == CKind::Picture && s.width > 0 && s.nested.is_none()),+ _ => None,+ });+ let pic = own.or_else(|| self.doc.sources.iter().find(|s| s.kind == CKind::Picture && s.width > 0));(width, height) = pic.map_or((1920, 1080), |p| (p.width, p.height));}comp.width = width;@@ -336,12 +365,85 @@ impl R<'_> {if id == [0; 32] {return CItem::Filler(len);}+ if let Some(mob) = self.mobs.get(&id).copied().filter(|m| m.class == cls::COMPOSITION_MOB) {+ return self.nest_clip(c, mob, id, slot, rate, kind, name);+ }match self.resolve(id, slot, start, kind, master_key, 0) {Some((source, t)) => CItem::Clip(CClip { len, source, start: t, gain: None, name }),None => CItem::Filler(len),}}+ /// A source clip that points at a composition: a nested sequence (Premiere Pro writes its+ /// nested sequences this way). The composition is read once, however many clips use it.+ fn nest_clip(&mut self, c: &Obj, mob: &Obj, id: MobId, slot_id: u32, rate: (i64, i64), kind: CKind, name: String) -> CItem {+ let len = units_to_ticks(len_of(c), rate.0, rate.1);+ let index = match self.nests.get(&id) {+ Some(&i) => i,+ None => {+ if self.open.contains(&id) || self.open.len() >= MAX_NESTING {+ self.report.warn("a composition nested in itself or nested too deeply was imported as a gap");+ return CItem::Filler(len);+ }+ self.open.push(id);+ let comp = self.composition(mob);+ self.open.pop();+ let i = self.doc.nested.len();+ self.doc.nested.push(comp);+ self.nests.insert(id, i);+ i+ }+ };+ // the start counts edit units of the slot the clip points at+ let slot_rate = mob.objs(pid::SLOTS).iter().find(|s| s.u32(pid::SLOT_ID) == Some(slot_id)).and_then(|s| rate_of(s, pid::EDIT_RATE)).unwrap_or(rate);+ let start = units_to_ticks(c.i64(pid::START_TIME).unwrap_or(0), slot_rate.0, slot_rate.1);+ let skey = (id, if kind == CKind::Picture { 0 } else { 1 }, "composition".to_string());+ let source =+ match self.sources.get(&skey) {+ Some(&i) => i,+ None => {+ let Some(comp) = self.doc.nested.get(index) else { return CItem::Filler(len) };+ let length =+ comp.tracks+ .iter()+ .map(|t| {+ Tick(t.items.iter().fold(0i64, |a, i| {+ if matches!(i, CItem::Transition(_)) { a.saturating_sub(i.len().0) } else { a.saturating_add(i.len().0) }+ }))+ })+ .max()+ .unwrap_or(Tick::ZERO);+ let channels = if kind == CKind::Sound { 2 } else { 0 };+ let s = Source {+ key: format!("composition:{}", hex(&id)),+ name: comp.name.clone(),+ kind,+ path: None,+ channel: None,+ channels,+ file_channels: channels,+ width: comp.width,+ height: comp.height,+ frame_rate: comp.rate,+ sample_rate: comp.sample_rate,+ bits: 16,+ length,+ offset: Tick::ZERO,+ start_tc: None,+ tc_rate: comp.rate,+ embedded: None,+ markers: Vec::new(),+ nested: Some(index),+ };+ let i = self.doc.sources.len();+ self.doc.sources.push(s);+ self.sources.insert(skey, i);+ i+ }+ };+ CItem::Clip(CClip { len, source, start, gain: None, name })+ }+/// Follow a source reference to a file source mob: (source index, file time).fn resolve(&mut self, id: MobId, slot_id: u32, start: Tick, kind: CKind, master_key: Option<String>, depth: usize) -> Option<(usize, Tick)> {if depth > 16 {@@ -448,6 +550,7 @@ impl R<'_> {tc_rate: tc.map(|t| t.1).unwrap_or(fr),embedded: None,markers: Vec::new(),+ nested: None,};if s.kind == CKind::Sound {s.frame_rate = FrameRate::FPS_25;@@ -531,6 +634,21 @@ fn fit(items: &mut Vec<CItem>, len: Tick) {}}+/// Whether anything inside `o` is a scope reference (a nested scope used as an effect's layers).+fn refers_to_scope(o: &Obj, depth: usize) -> bool {+ if o.class == cls::SCOPE_REFERENCE {+ return true;+ }+ if depth > 32 {+ return false;+ }+ o.props.iter().any(|(_, v)| match v {+ Value::Strong(c) => refers_to_scope(c, depth + 1),+ Value::StrongVec(v) | Value::StrongSet(v, _) => v.iter().any(|c| refers_to_scope(c, depth + 1)),+ _ => false,+ })+}+fn first_clip(seg: &Obj) -> Option<&Obj> {if seg.class == cls::SOURCE_CLIP {return Some(seg);diff --git a/crates/interchange/src/aaf/tests.rs b/crates/interchange/src/aaf/tests.rsindex 84933fc04..4cfbf62ee 100644--- a/crates/interchange/src/aaf/tests.rs+++ b/crates/interchange/src/aaf/tests.rs@@ -4,7 +4,7 @@use std::collections::HashSet;use filmcraft_project::{Project, SequenceSettings, TrackKind, TransitionAlign, TransitionId, find_effect};-use filmcraft_time::{FrameRate, TimeRange};+use filmcraft_time::{FrameRate, Tick, TimeRange};use super::ids::{self, cls, ddef, def, path, pid};use super::store::{self, Obj, Value};@@ -265,3 +265,107 @@ fn store_round_trips_every_stored_form() {// a data value longer than a property can hold is an error, not a panicassert!(store::write(&Obj::new(ids::ROOT).data_prop(1, vec![0; 70_000]), filmcraft_cfb::Version::V4).is_err());}++/// The property `p` of `o` as a list of objects, to change.+fn objs_mut(o: &mut Obj, p: u16) -> &mut Vec<Obj> {+ match o.props.iter_mut().find(|(k, _)| *k == p).map(|(_, v)| v) {+ Some(Value::StrongVec(v)) | Some(Value::StrongSet(v, _)) => v,+ _ => panic!("no object list {p:#06x}"),+ }+}++fn strong_mut(o: &mut Obj, p: u16) -> &mut Obj {+ match o.props.iter_mut().find(|(k, _)| *k == p).map(|(_, v)| v) {+ Some(Value::Strong(v)) => v,+ _ => panic!("no object {p:#06x}"),+ }+}++fn is_picture(o: &Obj) -> bool {+ o.weak_key(pid::DATA_DEFINITION) == Some(&ddef::PICTURE[..])+}++/// How Premiere Pro 26.5.2 lays a sequence with a nested sequence out in AAF (seen in a file it+/// exported): every composition is tagged top-level, the nested one too; all video tracks of a+/// composition are in ONE slot, a nested scope with a segment per track, lowest first; a clip of+/// the nested sequence is a source clip that points at its composition. Our own file is rewritten+/// into that layout and must read back as the same edit.+#[test]+fn premiere_style_layers_and_nested_compositions_are_read() {+ let (mut p, inner) = project();+ let r = FrameRate::FPS_24;+ let outer = p.new_sequence("Outer", SequenceSettings { frame_rate: r, ..Default::default() }, 3, 1, None);+ let media = p.sequence(inner).unwrap().video_tracks[0].items[0].item;+ for (kind, track, item, start, dur, src) in [+ (TrackKind::Video, 0, media, 0, 30, 5),+ (TrackKind::Video, 1, inner, 10, 40, 12),+ (TrackKind::Audio, 0, inner, 10, 40, 12),+ (TrackKind::Video, 2, media, 60, 20, 100),+ ] {+ let ti = p.make_track_item(item, kind, r.tick_of(start), TimeRange::new(r.tick_of(src), r.tick_of(dur)), r).unwrap();+ p.sequence_mut(outer).unwrap().tracks_mut(kind)[track].items.push(ti);+ }+ let (ours, report) = export(&p, outer, &AafOptions::default()).unwrap();+ assert!(!report.has_warnings(), "{report}");++ let mut root = store::read(&ours).unwrap();+ let content = strong_mut(strong_mut(&mut root, pid::ROOT_HEADER), pid::CONTENT);+ let mut compositions = 0;+ for mob in objs_mut(content, pid::MOBS).iter_mut().filter(|m| m.class == cls::COMPOSITION_MOB) {+ compositions += 1;+ mob.set(pid::USAGE_CODE, Value::Data(def::USAGE_TOP_LEVEL.to_vec()));+ let slots = objs_mut(mob, pid::SLOTS);+ let picture: Vec<usize> = slots.iter().enumerate().filter(|(_, s)| s.strong(pid::SEGMENT).is_some_and(is_picture)).map(|(i, _)| i).collect();+ let layers: Vec<Obj> = picture.iter().map(|&i| slots[i].strong(pid::SEGMENT).unwrap().clone()).collect();+ let length = layers.iter().filter_map(|l| l.i64(pid::LENGTH)).max().unwrap_or(0);+ let scope = Obj::new(cls::NESTED_SCOPE)+ .with(pid::DATA_DEFINITION, Value::Weak(path::DATA_DEFS.to_vec(), pid::IDENTIFICATION, ddef::PICTURE.to_vec()))+ .data_prop(pid::LENGTH, length.to_le_bytes().to_vec())+ .with(pid::NESTED_SLOTS, Value::StrongVec(layers));+ // the first video slot keeps its id (clips of the nested sequence point at it) and holds+ // every layer; the other video slots go+ slots[picture[0]].set(pid::SEGMENT, Value::Strong(Box::new(scope)));+ for &i in picture[1..].iter().rev() {+ slots.remove(i);+ }+ }+ assert_eq!(compositions, 2);+ let theirs = store::write(&root, filmcraft_cfb::Version::V4).unwrap();+ assert_ne!(theirs, ours);++ let opts = ImportOptions::default();+ let (want, _, _) = import(&ours, &opts).unwrap();+ let (got, _, report) = import(&theirs, &opts).unwrap();+ assert!(!report.has_warnings(), "{report}");+ // one edit; the nested composition is a sequence it uses, not a second edit+ assert_eq!(got.sequences.len(), 1);+ let shape =+ |imp: &Imported| {+ let mut out = Vec::new();+ for item in imp.project.items.values() {+ let Some(q) = imp.project.sequence(item.id) else { continue };+ for (kind, tracks) in [("V", &q.video_tracks), ("A", &q.audio_tracks)] {+ for (n, t) in tracks.iter().enumerate() {+ for c in &t.items {+ let source = imp.project.item(c.item).map(|i| i.name.clone()).unwrap_or_default();+ out.push((item.name.clone(), format!("{kind}{}", n + 1), source, c.start, c.duration, c.source_in, c.link.is_some()));+ }+ out.extend(t.transitions.iter().map(|x| {+ (item.name.clone(), format!("{kind}{} transition", n + 1), x.effect.effect.clone(), x.start, x.duration, Tick::ZERO, false)+ }));+ }+ }+ }+ out.sort();+ out+ };+ assert_eq!(shape(&got), shape(&want));+ // and that edit is the one that was exported: three video tracks, the nest on the second+ let q = got.project.sequence(got.sequences[0]).unwrap();+ assert_eq!(q.video_tracks.iter().map(|t| t.items.len()).collect::<Vec<_>>(), [1, 1, 1]);+ let nest = &q.video_tracks[1].items[0];+ assert_eq!(got.project.item(nest.item).unwrap().name, "S");+ assert_eq!((nest.start, nest.duration, nest.source_in), (r.tick_of(10), r.tick_of(40), r.tick_of(12)));+ assert_eq!(nest.link, q.audio_tracks[0].items[0].link);+ assert!(nest.link.is_some());+}diff --git a/crates/interchange/src/aaf/write.rs b/crates/interchange/src/aaf/write.rsindex 970678004..f0876cfeb 100644--- a/crates/interchange/src/aaf/write.rs+++ b/crates/interchange/src/aaf/write.rs@@ -6,7 +6,7 @@ use filmcraft_time::Tick;use super::ids::{META_DICTIONARY, ROOT, cls, ddef, def, path, pid};use super::store::{self, Auid, Obj, Value, rational, utf16z};-use crate::comp::{CItem, CKind, CMarker, Document, Gain, Source, ticks_to_units};+use crate::comp::{CItem, CKind, CMarker, Composition, Document, Gain, Source, ticks_to_units};use crate::{Error, Report, Result};/// UMID-style mob id (SMPTE 330 basic UMID): label, length 0x13, instance 0, material number.@@ -117,6 +117,9 @@ pub(crate) fn write(doc: &Document, version: filmcraft_cfb::Version, report: &mu// ---- media: master mobs (one per source key), file mobs (one per file and kind), tape mobslet mut groups: Vec<(String, Vec<usize>)> = Vec::new();for (i, s) in doc.sources.iter().enumerate() {+ if s.nested.is_some() {+ continue; // a nested composition: it has a composition mob, not media mobs (below)+ }match groups.iter_mut().find(|(k, _)| *k == s.key) {Some((_, v)) => v.push(i),None => groups.push((s.key.clone(), vec![i])),@@ -240,7 +243,138 @@ pub(crate) fn write(doc: &Document, version: filmcraft_cfb::Version, report: &mu}}- // ---- the composition+ // ---- nested compositions: a clip refers to one as it does to a master mob, through the+ // composition's first track of the clip's kind (a broken-out channel: that channel's track)+ let mut refs = Refs { mobs: master_ref, rates: HashMap::new() };+ let nested_ids: Vec<[u8; 32]> = doc.nested.iter().map(|_| new_id()).collect();+ for (si, s) in doc.sources.iter().enumerate() {+ let Some((comp, id)) = s.nested.and_then(|n| Some((doc.nested.get(n)?, nested_ids.get(n)?))) else { continue };+ let of_kind: Vec<usize> = comp.tracks.iter().enumerate().filter(|(_, t)| t.kind == s.kind).map(|(i, _)| i).collect();+ let Some(&track) = s.channel.and_then(|c| of_kind.get(c as usize)).or(of_kind.first()) else { continue };+ let rate = match s.kind {+ CKind::Picture => (comp.rate.num, comp.rate.den),+ CKind::Sound => (comp.sample_rate.max(1) as i64, 1),+ };+ refs.mobs.insert(si, (*id, track as u32 + 2));+ refs.rates.insert(si, rate);+ }++ // ---- the compositions: the exported sequence first+ let comp_id = new_id();+ let top = composition_mob(&mut w, doc, comp, comp_id, true, &refs, &mut used_ops, &mut uses_varying);+ mobs.insert(0, top);+ for (k, (nested, id)) in doc.nested.iter().zip(&nested_ids).enumerate() {+ let mob = composition_mob(&mut w, doc, nested, *id, false, &refs, &mut used_ops, &mut uses_varying);+ mobs.insert(1 + k, mob);+ }+ if w.inexact {+ w.report.info("some times are not on whole edit units and were rounded");+ }++ // ---- dictionary+ let mut ddefs = Vec::new();+ for (id, name) in [(ddef::PICTURE, "Picture"), (ddef::SOUND, "Sound"), (ddef::TIMECODE, "Timecode"), (ddef::DESCRIPTIVE_METADATA, "DescriptiveMetadata")] {+ ddefs.push(definition(cls::DATA_DEFINITION, id, name));+ }+ let mut opdefs = Vec::new();+ for op in &used_ops {+ let (name, dd, inputs) = match *op {+ x if x == def::VIDEO_DISSOLVE => ("Video Dissolve", ddef::PICTURE, 2),+ x if x == def::VIDEO_FADE_TO_BLACK => ("Video Fade To Black", ddef::PICTURE, 1),+ x if x == def::SMPTE_VIDEO_WIPE => ("SMPTE Video Wipe", ddef::PICTURE, 2),+ x if x == def::MONO_AUDIO_DISSOLVE => ("Mono Audio Dissolve", ddef::SOUND, 2),+ _ => ("Mono Audio Gain", ddef::SOUND, 1i32),+ };+ let params: Vec<Vec<u8>> = if *op == def::MONO_AUDIO_GAIN {+ vec![def::PARAM_AMPLITUDE.to_vec()]+ } else if *op == def::VIDEO_DISSOLVE {+ vec![def::PARAM_LEVEL.to_vec()]+ } else {+ Vec::new()+ };+ let mut o = definition(cls::OPERATION_DEFINITION, *op, name)+ .with(pid::OPDEF_DATA_DEFINITION, weak(path::DATA_DEFS, dd))+ .data_prop(pid::OPDEF_IS_TIME_WARP, vec![0])+ .data_prop(pid::OPDEF_NUMBER_INPUTS, inputs.to_le_bytes().to_vec());+ if !params.is_empty() {+ o.set(pid::OPDEF_PARAMETERS_DEFINED, Value::WeakVec(path::PARAMETER_DEFS.to_vec(), pid::IDENTIFICATION, params));+ }+ opdefs.push(o);+ }+ let pdefs = vec![+ definition(cls::PARAMETER_DEFINITION, def::PARAM_LEVEL, "Level").data_prop(pid::PARAMDEF_DISPLAY_UNITS, utf16z("")),+ definition(cls::PARAMETER_DEFINITION, def::PARAM_AMPLITUDE, "Amplitude").data_prop(pid::PARAMDEF_DISPLAY_UNITS, utf16z("")),+ ];+ let idefs = if uses_varying || !used_ops.is_empty() {+ vec![+ definition(cls::INTERPOLATION_DEFINITION, def::INTERP_LINEAR, "Linear"),+ definition(cls::INTERPOLATION_DEFINITION, def::INTERP_CONSTANT, "Constant"),+ ]+ } else {+ Vec::new()+ };+ let cdefs = vec![+ definition(cls::CONTAINER_DEFINITION, def::CONTAINER_EXTERNAL, "External Container"),+ definition(cls::CONTAINER_DEFINITION, def::CONTAINER_AAF, "AAF Container"),+ ];+ let mut dict = Obj::new(cls::DICTIONARY)+ .with(pid::DATA_DEFINITIONS, Value::StrongSet(ddefs, pid::IDENTIFICATION))+ .with(pid::PARAMETER_DEFINITIONS, Value::StrongSet(pdefs, pid::IDENTIFICATION))+ .with(pid::CONTAINER_DEFINITIONS, Value::StrongSet(cdefs, pid::IDENTIFICATION));+ if !opdefs.is_empty() {+ dict.set(pid::OPERATION_DEFINITIONS, Value::StrongSet(opdefs, pid::IDENTIFICATION));+ }+ if !idefs.is_empty() {+ dict.set(pid::INTERPOLATION_DEFINITIONS, Value::StrongSet(idefs, pid::IDENTIFICATION));+ }++ let mut content = Obj::new(cls::CONTENT_STORAGE).with(pid::MOBS, Value::StrongSet(mobs, pid::MOB_ID));+ if !essence.is_empty() {+ content.set(pid::ESSENCE_DATA, Value::StrongSet(essence, pid::ESSENCE_MOB_ID));+ }+ let ident = Obj::new(cls::IDENTIFICATION)+ .data_prop(pid::COMPANY_NAME, utf16z("FilmCraft"))+ .data_prop(pid::PRODUCT_NAME, utf16z("FilmCraft"))+ .data_prop(pid::PRODUCT_VERSION_STRING, utf16z(env!("CARGO_PKG_VERSION")))+ .data_prop(pid::PRODUCT_ID, super::ids::guid(0x46494C4D, 0x4352, 0x4146, *b"T-AAF-EP").to_vec())+ .data_prop(pid::DATE, timestamp())+ .data_prop(pid::PLATFORM, utf16z("FilmCraft"))+ .data_prop(pid::GENERATION_AUID, mob_id(seed, 0)[16..].to_vec());+ let header = Obj::new(cls::HEADER)+ .data_prop(pid::BYTE_ORDER, 0x4949i16.to_le_bytes().to_vec())+ .data_prop(pid::LAST_MODIFIED, timestamp())+ .data_prop(pid::VERSION, vec![1, 1])+ .data_prop(pid::OBJECT_MODEL_VERSION, 1u32.to_le_bytes().to_vec())+ .data_prop(pid::OPERATIONAL_PATTERN, def::OP_EDIT_PROTOCOL.to_vec())+ .with(pid::CONTENT, Value::Strong(Box::new(content)))+ .with(pid::DICTIONARY, Value::Strong(Box::new(dict)))+ .with(pid::IDENTIFICATION_LIST, Value::StrongVec(vec![ident]));+ let root = Obj::new(ROOT)+ .with(pid::ROOT_META_DICTIONARY, Value::Strong(Box::new(Obj::new(META_DICTIONARY))))+ .with(pid::ROOT_HEADER, Value::Strong(Box::new(header)));+ store::write(&root, version).map_err(Error::Other)+}++/// Where clips find their sources: source index → (mob id, slot id), and for nested compositions+/// the edit rate of that slot.+#[derive(Default)]+struct Refs {+ mobs: HashMap<usize, ([u8; 32], u32)>,+ rates: HashMap<usize, (i64, i64)>,+}++/// The composition mob of `comp`. Slot 1 is its timecode; its tracks follow from slot 2 in order.+#[allow(clippy::too_many_arguments)]+fn composition_mob(+ w: &mut W,+ doc: &Document,+ comp: &Composition,+ id: [u8; 32],+ top: bool,+ refs: &Refs,+ used_ops: &mut Vec<Auid>,+ uses_varying: &mut bool,+) -> Obj {let crate_rate = (comp.rate.num, comp.rate.den);let mut slots = Vec::new();let total = comp@@ -290,8 +424,9 @@ pub(crate) fn write(doc: &Document, version: filmcraft_cfb::Version, report: &muCItem::Clip(c) => {let n = w.u(cursor + c.len, rate) - w.u(cursor, rate);let s = &doc.sources[c.source];- let (mid, mslot) = master_ref.get(&c.source).copied().unwrap_or(([0; 32], 0));- let start = w.u(c.start, rate);+ let (mid, mslot) = refs.mobs.get(&c.source).copied().unwrap_or(([0; 32], 0));+ // (a nested composition counts the start in its own slot's edit units)+ let start = w.u(c.start, refs.rates.get(&c.source).copied().unwrap_or(rate));let mut sc = source_clip(t.kind, n, mid, mslot, start);if !c.name.is_empty() && c.name != s.name {sc.set(pid::COMPONENT_USER_COMMENTS, Value::StrongVec(vec![tagged("Clip Name", &c.name)]));@@ -306,7 +441,7 @@ pub(crate) fn write(doc: &Document, version: filmcraft_cfb::Version, report: &mu.data_prop(pid::PARAMETER_DEFINITION, def::PARAM_AMPLITUDE.to_vec()).data_prop(pid::CONSTANT_VALUE, indirect(def::TYPE_RATIONAL, &gain_rational(*a))),Gain::Varying { linear, points } => {- uses_varying = true;+ *uses_varying = true;let pts = points.iter().map(|(off, a)| {@@ -353,7 +488,7 @@ pub(crate) fn write(doc: &Document, version: filmcraft_cfb::Version, report: &mu.with(pid::OPERATION, weak(path::OPERATION_DEFS, op)).with(pid::COMPONENT_USER_COMMENTS, Value::StrongVec(vec![tagged("FilmCraft Effect", &x.effect)]));if op == def::VIDEO_DISSOLVE {- uses_varying = true;+ *uses_varying = true;let pts = [(0, 0), (1, 1)].iter().map(|&(t, v)| {@@ -398,112 +533,25 @@ pub(crate) fn write(doc: &Document, version: filmcraft_cfb::Version, report: &muslot_id += 1;}if !comp.markers.is_empty() {- slots.push(event_slot(&mut w, slot_id, crate_rate, &comp.markers));- }- let comp_id = new_id();- mobs.insert(- 0,- Obj::new(cls::COMPOSITION_MOB)- .data_prop(pid::MOB_ID, comp_id.to_vec())- .data_prop(pid::MOB_NAME, utf16z(&comp.name))- .data_prop(pid::MOB_LAST_MODIFIED, timestamp())- .data_prop(pid::MOB_CREATION_TIME, timestamp())- .data_prop(pid::USAGE_CODE, def::USAGE_TOP_LEVEL.to_vec())- .with(pid::SLOTS, Value::StrongVec(slots))- .with(- pid::MOB_USER_COMMENTS,- Value::StrongVec(vec![- tagged("FilmCraft Frame Size", &format!("{}x{}", comp.width, comp.height)),- tagged("FilmCraft Audio Sample Rate", &comp.sample_rate.to_string()),- ]),- ),- );- if w.inexact {- w.report.info("some times are not on whole edit units and were rounded");- }-- // ---- dictionary- let mut ddefs = Vec::new();- for (id, name) in [(ddef::PICTURE, "Picture"), (ddef::SOUND, "Sound"), (ddef::TIMECODE, "Timecode"), (ddef::DESCRIPTIVE_METADATA, "DescriptiveMetadata")] {- ddefs.push(definition(cls::DATA_DEFINITION, id, name));- }- let mut opdefs = Vec::new();- for op in &used_ops {- let (name, dd, inputs) = match *op {- x if x == def::VIDEO_DISSOLVE => ("Video Dissolve", ddef::PICTURE, 2),- x if x == def::VIDEO_FADE_TO_BLACK => ("Video Fade To Black", ddef::PICTURE, 1),- x if x == def::SMPTE_VIDEO_WIPE => ("SMPTE Video Wipe", ddef::PICTURE, 2),- x if x == def::MONO_AUDIO_DISSOLVE => ("Mono Audio Dissolve", ddef::SOUND, 2),- _ => ("Mono Audio Gain", ddef::SOUND, 1i32),- };- let params: Vec<Vec<u8>> = if *op == def::MONO_AUDIO_GAIN {- vec![def::PARAM_AMPLITUDE.to_vec()]- } else if *op == def::VIDEO_DISSOLVE {- vec![def::PARAM_LEVEL.to_vec()]- } else {- Vec::new()- };- let mut o = definition(cls::OPERATION_DEFINITION, *op, name)- .with(pid::OPDEF_DATA_DEFINITION, weak(path::DATA_DEFS, dd))- .data_prop(pid::OPDEF_IS_TIME_WARP, vec![0])- .data_prop(pid::OPDEF_NUMBER_INPUTS, inputs.to_le_bytes().to_vec());- if !params.is_empty() {- o.set(pid::OPDEF_PARAMETERS_DEFINED, Value::WeakVec(path::PARAMETER_DEFS.to_vec(), pid::IDENTIFICATION, params));- }- opdefs.push(o);- }- let pdefs = vec![- definition(cls::PARAMETER_DEFINITION, def::PARAM_LEVEL, "Level").data_prop(pid::PARAMDEF_DISPLAY_UNITS, utf16z("")),- definition(cls::PARAMETER_DEFINITION, def::PARAM_AMPLITUDE, "Amplitude").data_prop(pid::PARAMDEF_DISPLAY_UNITS, utf16z("")),- ];- let idefs = if uses_varying || !used_ops.is_empty() {- vec![- definition(cls::INTERPOLATION_DEFINITION, def::INTERP_LINEAR, "Linear"),- definition(cls::INTERPOLATION_DEFINITION, def::INTERP_CONSTANT, "Constant"),- ]- } else {- Vec::new()- };- let cdefs = vec![- definition(cls::CONTAINER_DEFINITION, def::CONTAINER_EXTERNAL, "External Container"),- definition(cls::CONTAINER_DEFINITION, def::CONTAINER_AAF, "AAF Container"),- ];- let mut dict = Obj::new(cls::DICTIONARY)- .with(pid::DATA_DEFINITIONS, Value::StrongSet(ddefs, pid::IDENTIFICATION))- .with(pid::PARAMETER_DEFINITIONS, Value::StrongSet(pdefs, pid::IDENTIFICATION))- .with(pid::CONTAINER_DEFINITIONS, Value::StrongSet(cdefs, pid::IDENTIFICATION));- if !opdefs.is_empty() {- dict.set(pid::OPERATION_DEFINITIONS, Value::StrongSet(opdefs, pid::IDENTIFICATION));+ slots.push(event_slot(w, slot_id, crate_rate, &comp.markers));}- if !idefs.is_empty() {- dict.set(pid::INTERPOLATION_DEFINITIONS, Value::StrongSet(idefs, pid::IDENTIFICATION));- }-- let mut content = Obj::new(cls::CONTENT_STORAGE).with(pid::MOBS, Value::StrongSet(mobs, pid::MOB_ID));- if !essence.is_empty() {- content.set(pid::ESSENCE_DATA, Value::StrongSet(essence, pid::ESSENCE_MOB_ID));+ let mut mob = Obj::new(cls::COMPOSITION_MOB)+ .data_prop(pid::MOB_ID, id.to_vec())+ .data_prop(pid::MOB_NAME, utf16z(&comp.name))+ .data_prop(pid::MOB_LAST_MODIFIED, timestamp())+ .data_prop(pid::MOB_CREATION_TIME, timestamp());+ // only the exported sequence is a top-level composition; a nested sequence is found through+ // the clips that use it+ if top {+ mob.set(pid::USAGE_CODE, Value::Data(def::USAGE_TOP_LEVEL.to_vec()));}- let ident = Obj::new(cls::IDENTIFICATION)- .data_prop(pid::COMPANY_NAME, utf16z("FilmCraft"))- .data_prop(pid::PRODUCT_NAME, utf16z("FilmCraft"))- .data_prop(pid::PRODUCT_VERSION_STRING, utf16z(env!("CARGO_PKG_VERSION")))- .data_prop(pid::PRODUCT_ID, super::ids::guid(0x46494C4D, 0x4352, 0x4146, *b"T-AAF-EP").to_vec())- .data_prop(pid::DATE, timestamp())- .data_prop(pid::PLATFORM, utf16z("FilmCraft"))- .data_prop(pid::GENERATION_AUID, mob_id(seed, 0)[16..].to_vec());- let header = Obj::new(cls::HEADER)- .data_prop(pid::BYTE_ORDER, 0x4949i16.to_le_bytes().to_vec())- .data_prop(pid::LAST_MODIFIED, timestamp())- .data_prop(pid::VERSION, vec![1, 1])- .data_prop(pid::OBJECT_MODEL_VERSION, 1u32.to_le_bytes().to_vec())- .data_prop(pid::OPERATIONAL_PATTERN, def::OP_EDIT_PROTOCOL.to_vec())- .with(pid::CONTENT, Value::Strong(Box::new(content)))- .with(pid::DICTIONARY, Value::Strong(Box::new(dict)))- .with(pid::IDENTIFICATION_LIST, Value::StrongVec(vec![ident]));- let root = Obj::new(ROOT)- .with(pid::ROOT_META_DICTIONARY, Value::Strong(Box::new(Obj::new(META_DICTIONARY))))- .with(pid::ROOT_HEADER, Value::Strong(Box::new(header)));- store::write(&root, version).map_err(Error::Other)+ mob.with(pid::SLOTS, Value::StrongVec(slots)).with(+ pid::MOB_USER_COMMENTS,+ Value::StrongVec(vec![+ tagged("FilmCraft Frame Size", &format!("{}x{}", comp.width, comp.height)),+ tagged("FilmCraft Audio Sample Rate", &comp.sample_rate.to_string()),+ ]),+ )}fn slot_name(kind: CKind, n: u32) -> String {diff --git a/crates/interchange/src/comp.rs b/crates/interchange/src/comp.rsindex 6efb58e62..839e43424 100644--- a/crates/interchange/src/comp.rs+++ b/crates/interchange/src/comp.rs@@ -31,10 +31,27 @@ pub(crate) enum CKind {/// A whole document: compositions and the media they reference.#[derive(Clone, Debug, Default, PartialEq)]pub(crate) struct Document {+ /// The top-level compositions.pub compositions: Vec<Composition>,pub sources: Vec<Source>,+ /// Compositions that are only used inside others (nested sequences); a [`Source`] refers to+ /// one by its index here. They may nest further.+ pub nested: Vec<Composition>,}+/// How a nested sequence is written. Premiere Pro writes one as a composition of its own in AAF+/// (clips refer to it the way they refer to media) and renders its sound in OMF, which has no+/// picture and whose readers do not follow compositions.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub(crate) enum Nests {+ Compositions,+ Rendered,+}++/// Nested sequences deeper than this are left as gaps (a sequence cannot be inside itself, but a+/// damaged project may claim so).+const MAX_NESTING: usize = 16;+#[derive(Clone, Debug, PartialEq)]pub(crate) struct Composition {pub name: String,@@ -146,6 +163,9 @@ pub(crate) struct Source {pub tc_rate: FrameRate,pub embedded: Option<Vec<u8>>,pub markers: Vec<CMarker>,+ /// Not media but a nested composition: its index in [`Document::nested`]. `start` of a clip+ /// that uses it is a time in that composition.+ pub nested: Option<usize>,}impl Source {@@ -174,102 +194,221 @@ struct Exporter<'a> {memo: HashMap<(String, CKind, Option<u32>), usize>,report: &'a mut Report,seq_rate: FrameRate,+ nests: Nests,+ /// Nested sequences already written: their index in `doc.nested`.+ nested: HashMap<ItemId, usize>,+ /// The sequences being written, outermost first.+ open: Vec<ItemId>,}-pub(crate) fn from_project(p: &Project, seq_id: ItemId, name: &str, media: &MediaOptions, report: &mut Report) -> crate::Result<Document> {+pub(crate) fn from_project(p: &Project, seq_id: ItemId, name: &str, media: &MediaOptions, nests: Nests, report: &mut Report) -> crate::Result<Document> {let seq = p.sequence(seq_id).ok_or(crate::Error::NoSequence(seq_id))?;let rate = seq.settings.frame_rate;- let mut ex = Exporter { p, media, doc: Document::default(), memo: HashMap::new(), report, seq_rate: rate };- let mut comp = Composition {- name: name.to_string(),- rate,- sample_rate: seq.settings.sample_rate.max(1),- width: seq.settings.width,- height: seq.settings.height,- start_tc: seq.start_timecode,- drop: seq.settings.drop_frame,- tracks: Vec::new(),- markers: seq- .markers- .iter()- .map(|m| CMarker {- start: m.start,- duration: m.duration,- name: m.name.clone(),- comment: m.comment.clone(),- color: Some(m.color.name().to_string()),- })- .collect(),- };- if !media.audio_only {- if let Some(mix) = &media.mixdown_video {- let src = ex.doc.sources.len();- ex.doc.sources.push(Source {- key: "mixdown".into(),- name: format!("{name} (video mixdown)"),- kind: CKind::Picture,- path: Some(mix.path.clone()),- channel: None,- channels: 0,- file_channels: 0,- width: mix.width,- height: mix.height,- frame_rate: rate,- sample_rate: 0,- bits: 0,- length: mix.duration,- offset: Tick::ZERO,- start_tc: Some(seq.start_timecode + rate.frame_at(mix.start)),- tc_rate: rate,- embedded: None,- markers: Vec::new(),- });- let mut items = Vec::new();- if mix.start > Tick::ZERO {- items.push(CItem::Filler(mix.start));+ let mut ex =+ Exporter { p, media, doc: Document::default(), memo: HashMap::new(), report, seq_rate: rate, nests, nested: HashMap::new(), open: vec![seq_id] };+ let comp = ex.composition(seq, name, true);+ ex.doc.compositions.push(comp);+ Ok(ex.doc)+}++impl Exporter<'_> {+ /// `seq` as a composition. `top`: the exported sequence itself (a video mixdown replaces its+ /// video tracks; a nested sequence under a mixdown has no video tracks left to show).+ fn composition(&mut self, seq: &Sequence, name: &str, top: bool) -> Composition {+ let rate = seq.settings.frame_rate;+ let outer_rate = std::mem::replace(&mut self.seq_rate, rate);+ let media = self.media;+ let mut comp = Composition {+ name: name.to_string(),+ rate,+ sample_rate: seq.settings.sample_rate.max(1),+ width: seq.settings.width,+ height: seq.settings.height,+ start_tc: seq.start_timecode,+ drop: seq.settings.drop_frame,+ tracks: Vec::new(),+ markers: seq+ .markers+ .iter()+ .map(|m| CMarker {+ start: m.start,+ duration: m.duration,+ name: m.name.clone(),+ comment: m.comment.clone(),+ color: Some(m.color.name().to_string()),+ })+ .collect(),+ };+ if !media.audio_only {+ if let Some(mix) = media.mixdown_video.as_ref().filter(|_| top) {+ let src = self.doc.sources.len();+ self.doc.sources.push(Source {+ key: "mixdown".into(),+ name: format!("{name} (video mixdown)"),+ kind: CKind::Picture,+ path: Some(mix.path.clone()),+ channel: None,+ channels: 0,+ file_channels: 0,+ width: mix.width,+ height: mix.height,+ frame_rate: rate,+ sample_rate: 0,+ bits: 0,+ length: mix.duration,+ offset: Tick::ZERO,+ start_tc: Some(seq.start_timecode + rate.frame_at(mix.start)),+ tc_rate: rate,+ embedded: None,+ markers: Vec::new(),+ nested: None,+ });+ let mut items = Vec::new();+ if mix.start > Tick::ZERO {+ items.push(CItem::Filler(mix.start));+ }+ items.push(CItem::Clip(CClip { len: mix.duration, source: src, start: Tick::ZERO, gain: None, name: format!("{name} (video mixdown)") }));+ comp.tracks.push(CTrack { kind: CKind::Picture, name: "V1".into(), number: 1, channels: 0, items });+ } else if media.mixdown_video.is_none() {+ for (i, t) in seq.video_tracks.iter().enumerate() {+ let items = self.track(t, TrackKind::Video, None);+ comp.tracks.push(CTrack { kind: CKind::Picture, name: format!("V{}", i + 1), number: i as u32 + 1, channels: 0, items });+ }}- items.push(CItem::Clip(CClip { len: mix.duration, source: src, start: Tick::ZERO, gain: None, name: format!("{name} (video mixdown)") }));- comp.tracks.push(CTrack { kind: CKind::Picture, name: "V1".into(), number: 1, channels: 0, items });- } else {- for (i, t) in seq.video_tracks.iter().enumerate() {- let items = ex.track(t, TrackKind::Video, None);- comp.tracks.push(CTrack { kind: CKind::Picture, name: format!("V{}", i + 1), number: i as u32 + 1, channels: 0, items });+ }+ let mut n = 0;+ for t in &seq.audio_tracks {+ let ch = match t.channels {+ AudioChannels::Mono => 1,+ AudioChannels::Surround51 => 6,+ AudioChannels::Stereo | AudioChannels::Adaptive => 2,+ };+ if media.breakout_to_mono {+ for c in 0..ch {+ n += 1;+ let items = self.track(t, TrackKind::Audio, Some(c));+ comp.tracks.push(CTrack { kind: CKind::Sound, name: format!("A{n}"), number: n, channels: 1, items });+ }+ } else {+ n += 1;+ let items = self.track(t, TrackKind::Audio, None);+ comp.tracks.push(CTrack { kind: CKind::Sound, name: format!("A{n}"), number: n, channels: ch, items });}}+ self.seq_rate = outer_rate;+ comp}- let mut n = 0;- for t in &seq.audio_tracks {- let ch = match t.channels {- AudioChannels::Mono => 1,- AudioChannels::Surround51 => 6,- AudioChannels::Stereo | AudioChannels::Adaptive => 2,- };- if media.breakout_to_mono {- for c in 0..ch {- n += 1;- let items = ex.track(t, TrackKind::Audio, Some(c));- comp.tracks.push(CTrack { kind: CKind::Sound, name: format!("A{n}"), number: n, channels: 1, items });++ /// The source behind a clip of the nested sequence `nested` (project item `item`): the+ /// sequence's sound as the caller rendered it for this clip, or the sequence as a composition+ /// of its own.+ fn nest_source(&mut self, c: &TrackItem, item: ItemId, name: &str, nested: &Sequence, ckind: CKind, channel: Option<u32>) -> Option<usize> {+ let clip_key = EssenceKey::Clip(c.id);+ if ckind == CKind::Sound+ && let Some(e) = self.media.essence_for(clip_key, channel).cloned()+ {+ let memo_key = (format!("clip:{}", c.id.0), ckind, channel);+ if let Some(&i) = self.memo.get(&memo_key) {+ return Some(i);}- } else {- n += 1;- let items = ex.track(t, TrackKind::Audio, None);- comp.tracks.push(CTrack { kind: CKind::Sound, name: format!("A{n}"), number: n, channels: ch, items });+ let (path, embedded) = match e.data {+ EssenceData::Embedded(d) => (None, Some(d)),+ EssenceData::File { path } => (Some(path), None),+ };+ let s = Source {+ key: memo_key.0.clone(),+ // (Premiere names the rendered clip after the nested sequence)+ name: name.to_string(),+ kind: ckind,+ path,+ channel: None,+ channels: e.channels.max(1),+ file_channels: e.channels.max(1),+ width: 0,+ height: 0,+ frame_rate: self.seq_rate,+ sample_rate: e.sample_rate.max(1),+ bits: e.bits,+ length: Tick::from_units(e.frames as i64, e.sample_rate.max(1) as i64),+ offset: e.start,+ start_tc: None,+ tc_rate: self.seq_rate,+ embedded,+ markers: c.markers.iter().map(marker_out).collect(),+ nested: None,+ };+ let i = self.doc.sources.len();+ self.doc.sources.push(s);+ self.memo.insert(memo_key, i);+ return Some(i);}+ if self.nests == Nests::Rendered {+ self.report.warn(format!("the sound of the nested sequence \"{name}\" was not rendered (left as a gap)"));+ return None;+ }+ let memo_key = (format!("seq:{}", item.0), ckind, channel);+ if let Some(&i) = self.memo.get(&memo_key) {+ return Some(i);+ }+ let index = match self.nested.get(&item) {+ Some(&i) => i,+ None => {+ if self.open.contains(&item) || self.open.len() >= MAX_NESTING {+ self.report.warn(format!("the nested sequence \"{name}\" is inside itself or nested too deeply (left as a gap)"));+ return None;+ }+ self.open.push(item);+ let comp = self.composition(nested, name, false);+ self.open.pop();+ let i = self.doc.nested.len();+ self.doc.nested.push(comp);+ self.nested.insert(item, i);+ i+ }+ };+ // nothing to show or play on this kind of track: a gap (as in the sequence itself)+ let comp = self.doc.nested.get(index)?;+ if !comp.tracks.iter().any(|t| t.kind == ckind) {+ return None;+ }+ let channels = if ckind == CKind::Sound { 2 } else { 0 };+ let s = Source {+ key: memo_key.0.clone(),+ name: name.to_string(),+ kind: ckind,+ path: None,+ channel: if ckind == CKind::Sound { channel } else { None },+ channels: if channel.is_some() { 1 } else { channels },+ file_channels: channels,+ width: comp.width,+ height: comp.height,+ frame_rate: comp.rate,+ sample_rate: comp.sample_rate.max(1),+ bits: 16,+ length: nested.duration(),+ offset: Tick::ZERO,+ start_tc: None,+ tc_rate: comp.rate,+ embedded: None,+ markers: Vec::new(),+ nested: Some(index),+ };+ let i = self.doc.sources.len();+ self.doc.sources.push(s);+ self.memo.insert(memo_key, i);+ Some(i)}- ex.doc.compositions.push(comp);- Ok(ex.doc)-}-impl Exporter<'_> {/// The source behind `c` on a track of `kind` (`sub`: broken-out channel slot), if exportable.fn source_of(&mut self, c: &TrackItem, kind: TrackKind, sub: Option<u32>) -> Option<usize> {let item = base_item(self.p, c.item);let it = self.p.item(item)?;let m = match &it.kind {ItemKind::Media(m) => m,- ItemKind::Sequence(_) => {- self.report.warn("nested sequences are not exported (left as gaps); render and replace them first");- return None;+ ItemKind::Sequence(nested) => {+ let ckind = if kind == TrackKind::Video { CKind::Picture } else { CKind::Sound };+ let channel = sub.map(|s| c.source_channels.get(s as usize).map(|&x| x as u32).unwrap_or(s));+ return self.nest_source(c, item, &it.name, nested, ckind, channel);}_ => {match crate::common::uncarried_clip(self.p, c, self.seq_rate) {@@ -334,6 +473,7 @@ impl Exporter<'_> {tc_rate: frame_rate,embedded: None,markers,+ nested: None,};if ckind == CKind::Sound {s.file_channels = audio.map_or(2, |a| a.channels.max(1));@@ -541,6 +681,9 @@ pub(crate) fn to_project(doc: Document, opts: &ImportOptions, report: &mut Reporlet mut item_of: HashMap<usize, ItemId> = HashMap::new();let mut groups: Vec<((String, Option<String>), Vec<usize>)> = Vec::new();for (i, s) in doc.sources.iter().enumerate() {+ if s.nested.is_some() {+ continue; // a nested composition, not media: a sequence (below)+ }let k = (s.key.clone(), s.path.clone().or_else(|| s.embedded.is_some().then(|| format!("embedded:{i}"))));match groups.iter_mut().find(|(g, _)| *g == k) {Some((_, v)) => v.push(i),@@ -611,42 +754,69 @@ pub(crate) fn to_project(doc: Document, opts: &ImportOptions, report: &mut Reporitem_of.insert(i, id);}}- for comp in &doc.compositions {+ // nested compositions are sequences that clips use as their source: reserve them all first+ // (they may use each other), then build them+ let settings_of = |comp: &Composition| {let mut settings = settings_for(comp.rate, comp.width.max(16), comp.height.max(16), comp.drop);settings.sample_rate = comp.sample_rate.max(1);- let seq_id = b.reserve_sequence(&comp.name, settings.clone(), None);- let mut seq = crate::common::empty_sequence(settings);- seq.start_timecode = comp.start_tc;- seq.markers = comp.markers.iter().map(|m| marker_in(&mut b, m)).collect();- for t in &comp.tracks {- let kind = if t.kind == CKind::Picture { TrackKind::Video } else { TrackKind::Audio };- let idx = seq.tracks(kind).len();- let mut track = b.track(kind, idx);- if kind == TrackKind::Audio {- track.channels = match t.channels {- 1 => AudioChannels::Mono,- 6 => AudioChannels::Surround51,- _ => AudioChannels::Stereo,- };- }- build_track(&mut b, &mut track, kind, t, &doc.sources, &item_of, report);- seq.tracks_mut(kind).push(track);- }- if seq.video_tracks.is_empty() {- let t = b.track(TrackKind::Video, 0);- seq.video_tracks.push(t);- }- if seq.audio_tracks.is_empty() {- let t = b.track(TrackKind::Audio, 0);- seq.audio_tracks.push(t);+ settings+ };+ let nested_ids: Vec<ItemId> = doc.nested.iter().map(|comp| b.reserve_sequence(&comp.name, settings_of(comp), None)).collect();+ for (i, s) in doc.sources.iter().enumerate() {+ if let Some(&id) = s.nested.and_then(|n| nested_ids.get(n)) {+ item_of.insert(i, id);}- link_clips(&mut b, &mut seq);+ }+ for (comp, &seq_id) in doc.nested.iter().zip(&nested_ids) {+ let seq = build_sequence(&mut b, comp, settings_of(comp), &doc.sources, &item_of, report);+ b.put_sequence(seq_id, seq);+ }+ for comp in &doc.compositions {+ let seq_id = b.reserve_sequence(&comp.name, settings_of(comp), None);+ let seq = build_sequence(&mut b, comp, settings_of(comp), &doc.sources, &item_of, report);b.put_sequence(seq_id, seq);b.top.push(seq_id);}Ok((b.finish(), extracted))}+fn build_sequence(+ b: &mut Builder,+ comp: &Composition,+ settings: filmcraft_project::SequenceSettings,+ sources: &[Source],+ item_of: &HashMap<usize, ItemId>,+ report: &mut Report,+) -> Sequence {+ let mut seq = crate::common::empty_sequence(settings);+ seq.start_timecode = comp.start_tc;+ seq.markers = comp.markers.iter().map(|m| marker_in(b, m)).collect();+ for t in &comp.tracks {+ let kind = if t.kind == CKind::Picture { TrackKind::Video } else { TrackKind::Audio };+ let idx = seq.tracks(kind).len();+ let mut track = b.track(kind, idx);+ if kind == TrackKind::Audio {+ track.channels = match t.channels {+ 1 => AudioChannels::Mono,+ 6 => AudioChannels::Surround51,+ _ => AudioChannels::Stereo,+ };+ }+ build_track(b, &mut track, kind, t, sources, item_of, report);+ seq.tracks_mut(kind).push(track);+ }+ if seq.video_tracks.is_empty() {+ let t = b.track(TrackKind::Video, 0);+ seq.video_tracks.push(t);+ }+ if seq.audio_tracks.is_empty() {+ let t = b.track(TrackKind::Audio, 0);+ seq.audio_tracks.push(t);+ }+ link_clips(b, &mut seq);+ seq+}+enum Placed {Gap,Clip(usize),@@ -680,7 +850,7 @@ fn build_track(b: &mut Builder, track: &mut Track, kind: TrackKind, t: &CTrack,let mut ti = b.clip(item, kind, if c.name.is_empty() { &sources[c.source].name } else { &c.name }, pos, c.len, c.start);if kind == TrackKind::Audio {let src = &sources[c.source];- if t.channels == 1 {+ if t.channels == 1 && src.nested.is_none() {ti.source_channels = vec![src.channel.unwrap_or(0) as u16];}if let Some(g) = &c.gain {diff --git a/crates/interchange/src/essence.rs b/crates/interchange/src/essence.rsindex 739eb7509..863bf10a3 100644--- a/crates/interchange/src/essence.rs+++ b/crates/interchange/src/essence.rs@@ -99,6 +99,21 @@ impl MediaOptions {}}+/// What [`audio_needs`] lists for a nested sequence on an audio track.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]+pub enum NestNeeds {+ /// Nothing.+ #[default]+ Skip,+ /// The nested sequence's own sound over the range the clip uses, as one [`EssenceKey::Clip`]+ /// range per clip (its `item` is the nested sequence) for the caller to mix. OMF: Premiere Pro+ /// renders the sound of a nested sequence into the document.+ Render,+ /// What the clips inside the nested sequence need, like those of the sequence itself. AAF: a+ /// nested sequence is written as a composition of its own.+ Inside,+}+/// How [`audio_needs`] groups ranges.#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]pub struct NeedOptions {@@ -109,42 +124,75 @@ pub struct NeedOptions {pub per_clip: bool,/// Whole media instead of the used range (embedding / copying without trimming).pub whole_media: bool,+ /// Nested sequences on the audio tracks.+ #[serde(default)]+ pub nests: NestNeeds,}+/// Nested sequences deeper than this are not followed.+const MAX_NESTING: usize = 16;+/// The audio ranges the audio tracks of `sequence` reference, in a stable order.pub fn audio_needs(project: &Project, sequence: ItemId, opts: &NeedOptions) -> Vec<AudioNeed> {- let Some(seq) = project.sequence(sequence) else { return Vec::new() };let mut by_item: BTreeMap<EssenceKey, AudioNeed> = BTreeMap::new();+ collect_needs(project, sequence, opts, &mut Vec::new(), &mut by_item);+ by_item.into_values().collect()+}++fn collect_needs(project: &Project, sequence: ItemId, opts: &NeedOptions, open: &mut Vec<ItemId>, by_item: &mut BTreeMap<EssenceKey, AudioNeed>) {+ let Some(seq) = project.sequence(sequence) else { return };+ // (a sequence cannot be inside itself, but a damaged project may claim so)+ if open.contains(&sequence) || open.len() >= MAX_NESTING {+ return;+ }+ open.push(sequence);for t in seq.tracks(TrackKind::Audio) {for c in &t.items {let item = crate::common::base_item(project, c.item);- let Some(m) = project.item(item).and_then(|i| match &i.kind {- ItemKind::Media(m) => Some(m),- _ => None,- }) else {- continue;- };- let Some(a) = m.info.audio.as_ref() else { continue };- let path = match &m.media {- MediaRef::File { path } => Some(path.clone()),- MediaRef::Generator(_) => None,- };- let dur = m.info.duration;let (lo, hi) = if c.speed < 0.0 || c.reverse { (c.source_out(), c.source_in) } else { (c.source_in, c.source_out()) };let (lo, hi) = (lo.min(hi), lo.max(hi));let (mut start, mut end) = ((lo - opts.handles).max(Tick::ZERO), hi + opts.handles);- if dur > Tick::ZERO {- end = end.min(dur);+ match project.item(item).map(|i| &i.kind) {+ Some(ItemKind::Media(m)) => {+ let Some(a) = m.info.audio.as_ref() else { continue };+ let path = match &m.media {+ MediaRef::File { path } => Some(path.clone()),+ MediaRef::Generator(_) => None,+ };+ let dur = m.info.duration;+ if dur > Tick::ZERO {+ end = end.min(dur);+ }+ if opts.whole_media {+ start = Tick::ZERO;+ end = dur.max(end);+ }+ let key = if opts.per_clip { EssenceKey::Clip(c.id) } else { EssenceKey::Media(item) };+ let e = by_item.entry(key).or_insert_with(|| AudioNeed { key, item, path, start, end, channels: a.channels, sample_rate: a.sample_rate });+ e.start = e.start.min(start);+ e.end = e.end.max(end);+ }+ Some(ItemKind::Sequence(nested)) => match opts.nests {+ NestNeeds::Skip => {}+ NestNeeds::Inside => collect_needs(project, item, opts, open, by_item),+ NestNeeds::Render => {+ // a clip longer than its sequence plays silence past the end: nothing to supply+ end = end.min(nested.duration());+ if end <= start {+ continue;+ }+ let channels = match t.channels {+ filmcraft_project::AudioChannels::Mono => 1,+ filmcraft_project::AudioChannels::Surround51 => 6,+ _ => 2,+ };+ let key = EssenceKey::Clip(c.id);+ by_item.insert(key, AudioNeed { key, item, path: None, start, end, channels, sample_rate: nested.settings.sample_rate.max(1) });+ }+ },+ _ => {}}- if opts.whole_media {- start = Tick::ZERO;- end = dur.max(end);- }- let key = if opts.per_clip { EssenceKey::Clip(c.id) } else { EssenceKey::Media(item) };- let e = by_item.entry(key).or_insert_with(|| AudioNeed { key, item, path, start, end, channels: a.channels, sample_rate: a.sample_rate });- e.start = e.start.min(start);- e.end = e.end.max(end);}}- by_item.into_values().collect()+ open.pop();}diff --git a/crates/interchange/src/omf/mod.rs b/crates/interchange/src/omf/mod.rsindex e04b72caf..f0ae1c5e2 100644--- a/crates/interchange/src/omf/mod.rs+++ b/crates/interchange/src/omf/mod.rs@@ -11,6 +11,10 @@//! mob (`SMOB` with a `WAVD` / `AIFD` descriptor: embedded essence in a `WAVE` media data object,//! or a locator to a separate file) and a tape source mob carrying its timecode. Times are in//! samples (sound slots use the sample rate as edit rate) so edits are sample-exact.+//!+//! A nested sequence is not written as a composition: its sound, mixed by the caller for the clip+//! ([`crate::essence::NestNeeds::Render`]), is media like any other, in a clip named after the+//! sequence. Premiere Pro's OMF export does the same.pub(crate) mod bento;mod read;@@ -40,7 +44,7 @@ pub fn export(project: &Project, sequence: ItemId, opts: &OmfOptions) -> Result<let mut media = opts.media.clone();media.audio_only = true;media.mixdown_video = None;- let doc = comp::from_project(project, sequence, &name, &media, &mut report)?;+ let doc = comp::from_project(project, sequence, &name, &media, comp::Nests::Rendered, &mut report)?;if !doc.compositions[0].markers.is_empty() {report.info("sequence markers are not written to OMF");}diff --git a/crates/interchange/src/omf/read.rs b/crates/interchange/src/omf/read.rsindex f07cb4fb4..3b2d1b369 100644--- a/crates/interchange/src/omf/read.rs+++ b/crates/interchange/src/omf/read.rs@@ -395,6 +395,7 @@ impl R<'_, '_> {tc_rate: tc.map(|t| t.1).unwrap_or(FrameRate::FPS_25),embedded: None,markers: Vec::new(),+ nested: None,};if let Some(d) = self.media.get(&id) {if let Some((pcm, ch, sr, b)) = crate::wav::parse_wav(d).or_else(|| crate::wav::parse_aiff(d)) {diff --git a/crates/interchange/tests/aaf_omf.rs b/crates/interchange/tests/aaf_omf.rsindex 4753fb308..6b6ac8680 100644--- a/crates/interchange/tests/aaf_omf.rs+++ b/crates/interchange/tests/aaf_omf.rs@@ -3,7 +3,7 @@mod support;use filmcraft_interchange::aaf::{self, AafOptions};-use filmcraft_interchange::essence::{AudioEssence, EssenceData, MediaOptions, MixdownVideo, NeedOptions, audio_needs};+use filmcraft_interchange::essence::{AudioEssence, EssenceData, EssenceKey, MediaOptions, MixdownVideo, NeedOptions, NestNeeds, audio_needs};use filmcraft_interchange::omf::{self, OmfOptions};use filmcraft_interchange::{Format, ImportOptions, Imported, detect};use filmcraft_project::{@@ -191,7 +191,7 @@ fn pcm_ramp(frames: usize, channels: usize, seed: i32) -> Vec<u8> {fn aaf_embedded_trimmed_audio() {let (p, s) = sample(FrameRate::FPS_25, false);let handles = FrameRate::FPS_25.tick_of(5);- let needs = audio_needs(&p, s, &NeedOptions { handles, per_clip: false, whole_media: false });+ let needs = audio_needs(&p, s, &NeedOptions { handles, ..Default::default() });assert_eq!(needs.len(), 3);let a = needs.iter().find(|n| n.path.as_deref() == Some("/media/A001.mov")).unwrap();// A001 is used at source 20..120 and 300..360 (+ 5 frame handles, plus the crossfade's 5 frames)@@ -448,3 +448,231 @@ fn unsupported_clips_become_gaps_with_a_report() {assert_eq!(v.items.len(), 1);assert_eq!(v.items[0].start, FrameRate::FPS_25.tick_of(25));}++// ---- nested sequences+//+// Premiere Pro 26.5.2 (observed in the files it exports): in AAF a nested sequence is a composition+// of its own that clips point at; in OMF its sound is rendered into the document as one clip named+// after the nested sequence.++/// "Outer": a media clip, then a nest ("Inner", picture and linked sound, trimmed in, -4 dB on+/// its sound clip), then the same nest again. "Inner": two clips with a dissolve, a second audio+/// track, and a nest of its own ("Deep").+fn nested(rate: FrameRate) -> (Project, [ItemId; 3]) {+ let mut p = Project::new("n");+ let a = media(&mut p, "/media/A001.mov", true, true, rate);+ let b = media(&mut p, "/media/B002.mov", true, true, rate);+ let m = media(&mut p, "/media/music.wav", false, true, rate);+ let deep = sequence(&mut p, "Deep", rate, false);+ clip(&mut p, deep, TrackKind::Video, 0, b, 0, 50, 200);+ let inner = sequence(&mut p, "Inner", rate, false);+ let i1 = clip(&mut p, inner, TrackKind::Video, 0, a, 0, 60, 10);+ let i2 = clip(&mut p, inner, TrackKind::Video, 0, b, 60, 60, 100);+ transition(&mut p, inner, TrackKind::Video, 0, "cross_dissolve", Some(i1), Some(i2), 54, 12, TransitionAlign::CenterAtCut);+ clip(&mut p, inner, TrackKind::Video, 1, deep, 20, 30, 5);+ let ia = clip(&mut p, inner, TrackKind::Audio, 0, a, 0, 60, 10);+ clip(&mut p, inner, TrackKind::Audio, 1, m, 0, 120, 0);+ link(&mut p, inner, &[i1, ia]);+ let outer = sequence(&mut p, "Outer", rate, false);+ let v0 = clip(&mut p, outer, TrackKind::Video, 0, a, 0, 40, 0);+ let a0 = clip(&mut p, outer, TrackKind::Audio, 0, a, 0, 40, 0);+ let v1 = clip(&mut p, outer, TrackKind::Video, 0, inner, 40, 70, 15);+ let a1 = clip(&mut p, outer, TrackKind::Audio, 0, inner, 40, 70, 15);+ let v2 = clip(&mut p, outer, TrackKind::Video, 1, inner, 150, 30, 0);+ link(&mut p, outer, &[v0, a0]);+ link(&mut p, outer, &[v1, a1]);+ let (_, c) = p.sequence_mut(outer).unwrap().find_item_mut(a1).unwrap();+ c.effect_mut("volume").unwrap().params.insert("level".into(), Param::new(ParamValue::Float(-4.0)));+ let _ = v2;+ (p, [outer, inner, deep])+}++fn sequence_named(p: &Project, name: &str) -> ItemId {+ let mut found = p.items.values().filter(|i| i.name == name && matches!(i.kind, ItemKind::Sequence(_)));+ let id = found.next().unwrap_or_else(|| panic!("no sequence {name}")).id;+ assert!(found.next().is_none(), "{name} was imported more than once");+ id+}++#[test]+fn aaf_nested_sequences_round_trip_as_compositions() {+ for rate in [FrameRate::FPS_25, FrameRate::FPS_23_976] {+ let (p, [outer, inner, deep]) = nested(rate);+ let (bytes, rep) = aaf::export(&p, outer, &AafOptions::default()).unwrap();+ assert!(!rep.has_warnings(), "{rep}");+ let (imp, _, rep) = aaf::import(&bytes, &ImportOptions { base_dir: Some("/proj".into()), ..Default::default() }).unwrap();+ assert!(!rep.has_warnings(), "{rep}");+ // one sequence is imported as the edit; the nested ones are sequences in the project that+ // it uses (each once, however many clips use it)+ let q = &imp.project;+ let n = only_seq(&imp);+ assert_eq!(q.item(n).unwrap().name, "Outer");+ let (ni, nd) = (sequence_named(q, "Inner"), sequence_named(q, "Deep"));+ for kind in [TrackKind::Video, TrackKind::Audio] {+ assert_eq!(structure(q, n, kind), structure(&p, outer, kind), "{rate:?} Outer {kind:?}");+ assert_eq!(structure(q, ni, kind), structure(&p, inner, kind), "{rate:?} Inner {kind:?}");+ assert_eq!(structure(q, nd, kind), structure(&p, deep, kind), "{rate:?} Deep {kind:?}");+ }+ let top = q.sequence(n).unwrap();+ assert_eq!((top.video_tracks[0].items[1].item, top.video_tracks[1].items[0].item, top.audio_tracks[0].items[1].item), (ni, ni, ni));+ assert_eq!(q.sequence(ni).unwrap().video_tracks[1].items[0].item, nd);+ // the nest's picture and sound are linked again, and the level on its sound clip is kept+ assert_eq!(links(q, n), links(&p, outer));+ assert!(close(level(q, n, 0, 1).value.as_f64().unwrap(), -4.0));+ // the nested sequences keep their own settings+ assert_eq!(q.sequence(ni).unwrap().settings.frame_rate, rate);+ // reproducible+ assert_eq!(bytes, aaf::export(&p, outer, &AafOptions::default()).unwrap().0);+ }+}++#[test]+fn aaf_nested_sequence_of_another_rate_and_broken_out_to_mono() {+ // the nest runs at 25 fps and 44.1 kHz inside a 23.976 fps, 48 kHz sequence: a clip's start in+ // it counts the nested composition's edit units+ let (mut p, [outer, inner, _]) = nested(FrameRate::FPS_23_976);+ {+ let q = p.sequence_mut(inner).unwrap();+ q.settings.frame_rate = FrameRate::FPS_25;+ q.settings.sample_rate = 44_100;+ }+ let before = (structure(&p, outer, TrackKind::Video), structure(&p, outer, TrackKind::Audio));+ for breakout in [false, true] {+ let opts = AafOptions { media: MediaOptions { breakout_to_mono: breakout, ..Default::default() }, ..Default::default() };+ let (bytes, _) = aaf::export(&p, outer, &opts).unwrap();+ let (imp, _, rep) = aaf::import(&bytes, &ImportOptions::default()).unwrap();+ let (q, n) = (&imp.project, only_seq(&imp));+ // picture starts are stored in frames of the nested composition: within half of one+ let picture = structure(q, n, TrackKind::Video);+ assert_eq!(picture.len(), before.0.len(), "{rep}");+ for (t, o) in picture.iter().zip(&before.0) {+ assert_eq!(t.clips.len(), o.clips.len());+ for (c, o) in t.clips.iter().zip(&o.clips) {+ assert_eq!((c.start, c.dur, &c.media), (o.start, o.dur, &o.media));+ let grid = if c.media == "seq:Inner" { FrameRate::FPS_25.frame_duration() } else { Tick(1) };+ assert!((c.src - o.src).abs() <= Tick(grid.0 / 2), "{c:?} {o:?}");+ }+ }+ let ni = sequence_named(q, "Inner");+ assert_eq!((q.sequence(ni).unwrap().settings.frame_rate, q.sequence(ni).unwrap().settings.sample_rate), (FrameRate::FPS_25, 44_100));+ let sound = structure(q, n, TrackKind::Audio);+ if breakout {+ // each stereo track became two mono tracks; the nest is on both, at the same place+ assert_eq!(sound.len(), 2);+ assert_eq!(sound[0], sound[1]);+ assert_eq!(+ sound[0].clips.iter().map(|c| (c.start, c.dur, c.media.as_str())).collect::<Vec<_>>(),+ before.1[0].clips.iter().map(|c| (c.start, c.dur, c.media.as_str())).collect::<Vec<_>>()+ );+ } else {+ // sound starts are stored in samples of the nested composition: within one sample+ assert_eq!(sound.len(), before.1.len());+ for (c, o) in sound[0].clips.iter().zip(&before.1[0].clips) {+ assert_eq!((c.start, c.dur, &c.media), (o.start, o.dur, &o.media));+ assert!((c.src - o.src).abs() <= Tick(filmcraft_time::TICKS_PER_SECOND / 44_100), "{c:?} {o:?}");+ }+ }+ }+}++/// A project that claims a sequence is inside itself (FilmCraft refuses to make one, a damaged+/// file may hold one) exports without looping: the clip is left as a gap and named in the report.+#[test]+fn a_sequence_inside_itself_exports_as_a_gap() {+ let rate = FrameRate::FPS_25;+ let (mut p, [outer, inner, deep]) = nested(rate);+ clip(&mut p, deep, TrackKind::Video, 1, outer, 0, 20, 0);+ clip(&mut p, deep, TrackKind::Audio, 0, outer, 0, 20, 0);+ clip(&mut p, inner, TrackKind::Audio, 2, inner, 0, 20, 0);+ let (bytes, rep) = aaf::export(&p, outer, &AafOptions::default()).unwrap();+ assert!(rep.mentions("inside itself"), "{rep}");+ let (imp, _, _) = aaf::import(&bytes, &ImportOptions::default()).unwrap();+ let q = &imp.project;+ assert!(q.sequence(sequence_named(q, "Deep")).unwrap().video_tracks[1].items.is_empty());+ // the lists of what to prepare end too+ for nests in [NestNeeds::Skip, NestNeeds::Inside, NestNeeds::Render] {+ let needs = audio_needs(&p, outer, &NeedOptions { nests, ..Default::default() });+ assert!(needs.len() < 16, "{nests:?}: {}", needs.len());+ }+ let (_, rep) = omf::export(&p, outer, &OmfOptions::default()).unwrap();+ assert!(rep.mentions("was not rendered"), "{rep}");+}++#[test]+fn audio_needs_of_nested_sequences() {+ let rate = FrameRate::FPS_25;+ let (p, [outer, inner, _]) = nested(rate);+ let media_named = |name: &str| p.items.values().find(|i| i.name == name).unwrap().id;+ let (a, m) = (media_named("A001.mov"), media_named("music.wav"));+ let nest_clip = p.sequence(outer).unwrap().audio_tracks[0].items[1].clone();+ // by default a nest needs nothing (as before)+ let plain = audio_needs(&p, outer, &NeedOptions::default());+ assert_eq!(plain.iter().map(|n| n.key).collect::<Vec<_>>(), [EssenceKey::Media(a)]);+ // inside: the media of the clips in the nested sequence, each item once over all its uses+ let inside = audio_needs(&p, outer, &NeedOptions { nests: NestNeeds::Inside, ..Default::default() });+ assert_eq!(inside.iter().map(|n| n.key).collect::<Vec<_>>(), [EssenceKey::Media(a), EssenceKey::Media(m)]);+ assert_eq!((inside[0].start, inside[0].end), (Tick::ZERO, rate.tick_of(70)), "0..40 in Outer and 10..70 in Inner");+ // render: one range of the nested sequence per clip, with handles, not past the sequence's end+ let handles = rate.tick_of(10);+ let render = audio_needs(&p, outer, &NeedOptions { nests: NestNeeds::Render, handles, ..Default::default() });+ let need = render.iter().find(|n| n.key == EssenceKey::Clip(nest_clip.id)).expect("the nest clip");+ assert_eq!((need.item, need.path.as_deref()), (inner, None));+ assert_eq!((need.start, need.end), (rate.tick_of(5), rate.tick_of(95)));+ assert_eq!((need.channels, need.sample_rate), (2, 48_000));+ let whole = audio_needs(&p, outer, &NeedOptions { nests: NestNeeds::Render, handles: rate.tick_of(100), ..Default::default() });+ let need = whole.iter().find(|n| n.key == EssenceKey::Clip(nest_clip.id)).unwrap();+ assert_eq!((need.start, need.end), (Tick::ZERO, p.sequence(inner).unwrap().duration()));+}++#[test]+fn omf_carries_the_rendered_sound_of_a_nested_sequence() {+ let rate = FrameRate::FPS_25;+ let (p, [outer, _, _]) = nested(rate);+ let nest_clip = p.sequence(outer).unwrap().audio_tracks[0].items[1].clone();+ let needs = audio_needs(&p, outer, &NeedOptions { handles: rate.tick_of(5), nests: NestNeeds::Render, ..Default::default() });+ assert_eq!(needs.len(), 2);+ let essence: Vec<AudioEssence> = needs+ .iter()+ .enumerate()+ .map(|(k, n)| {+ let frames = ((n.end - n.start).0 / (filmcraft_time::TICKS_PER_SECOND / 48_000)) as u64;+ AudioEssence {+ key: n.key,+ channel: None,+ start: n.start,+ frames,+ sample_rate: 48_000,+ bits: 16,+ channels: 2,+ data: EssenceData::Embedded(pcm_ramp(frames as usize, 2, k as i32 * 11)),+ effects_rendered: matches!(n.key, EssenceKey::Clip(_)),+ }+ })+ .collect();+ let opts = OmfOptions { media: MediaOptions { essence: essence.clone(), ..Default::default() }, ..Default::default() };+ let (bytes, rep) = omf::export(&p, outer, &opts).unwrap();+ assert!(!rep.mentions("nested") && !rep.mentions("gap"), "{rep}");+ let (imp, extracted, rep) = omf::import(&bytes, &ImportOptions { base_dir: Some("/x".into()), name: Some("o".into()), ..Default::default() }).unwrap();+ let q = imp.project.sequence(only_seq(&imp)).unwrap();+ let t = &q.audio_tracks[0];+ assert_eq!(t.items.len(), 2, "{rep}");+ // the nest is one clip named after the nested sequence, playing the rendered sound from where+ // the clip starts in it (the render begins 5 frames earlier: the handle)+ let c = &t.items[1];+ assert_eq!((c.name.as_str(), imp.project.item(c.item).unwrap().name.as_str()), ("Inner", "Inner"));+ assert_eq!((c.start, c.duration, c.source_in), (nest_clip.start, nest_clip.duration, rate.tick_of(5)));+ assert!(matches!(imp.project.item(c.item).unwrap().kind, ItemKind::Media(_)), "media in the document, not a sequence");+ // the clip's level is in the rendered sound, not written again+ assert!(close(level(&imp.project, only_seq(&imp), 0, 1).value.as_f64().unwrap(), 0.0));+ let nest_pcm = essence.iter().find(|e| e.key == EssenceKey::Clip(nest_clip.id)).map(|e| match &e.data {+ EssenceData::Embedded(d) => d.clone(),+ EssenceData::File { .. } => unreachable!(),+ });+ assert!(extracted.iter().any(|e| filmcraft_interchange::wav::parse_wav(&e.wav).map(|w| w.0) == nest_pcm));++ // without the rendered sound the nest is a gap, and the report says which sequence+ let (bytes, rep) = omf::export(&p, outer, &OmfOptions::default()).unwrap();+ assert!(rep.mentions("\"Inner\" was not rendered"), "{rep}");+ let (imp, _, _) = omf::import(&bytes, &ImportOptions::default()).unwrap();+ assert_eq!(imp.project.sequence(only_seq(&imp)).unwrap().audio_tracks[0].items.len(), 1);+}diff --git a/docs/architecture.md b/docs/architecture.mdindex 3c06cc2ea..6278ccc80 100644--- a/docs/architecture.md+++ b/docs/architecture.md@@ -635,7 +635,10 @@ any other value is a parameter error and nothing is written. For AAF andOMF the engine (`engine::aaf_omf`) first prepares the audio the document references: it lists theused ranges (`interchange::essence::audio_needs`), decodes or renders them (clip effects through theexport audio pipeline), embeds them or writes WAV / AIFF files, and optionally renders a video-mixdown.+mixdown. A nested sequence is exported the way Premiere Pro does it: a composition of its own in+AAF (the media of the clips inside it is prepared with the rest), its sound mixed into the document+in OMF, a nested sequence in FCP7 XML, FCPXML and OTIO, and one `AX` event in an EDL (table in the+[interchange README](../crates/interchange/README.md)).## 7. Automation surfaces