Skip to content

FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust

M11.3: EDL — filmcraft-interchange crate with CMX 3600 import/export

Brandon Thomasc14a7d44a4c0
diff --git a/Cargo.lock b/Cargo.lock
index 090956989..293045595 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1488,6 +1488,22 @@ dependencies = [
"thiserror 2.0.21",
]
+[[package]]
+name = "filmcraft-interchange"
+version = "0.1.0"
+dependencies = [
+ "filmcraft-color",
+ "filmcraft-geom",
+ "filmcraft-media",
+ "filmcraft-project",
+ "filmcraft-time",
+ "proptest",
+ "roxmltree",
+ "serde",
+ "serde_json",
+ "thiserror 2.0.21",
+]
+
[[package]]
name = "filmcraft-isobmff"
version = "0.1.0"
@@ -3688,6 +3704,15 @@ dependencies = [
"syn 3.0.6",
]
+[[package]]
+name = "roxmltree"
+version = "0.21.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f1964b10c76125c36f8afe190065a4bf9a87bf324842c05701330bba9f1cacbb"
+dependencies = [
+ "memchr",
+]
+
[[package]]
name = "rustc-hash"
version = "1.1.0"
diff --git a/Cargo.toml b/Cargo.toml
index 0093b3675..ee4bf1a35 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -29,6 +29,7 @@ filmcraft-media = { path = "crates/media" }
filmcraft-codecs = { path = "crates/codecs" }
filmcraft-project = { path = "crates/project" }
filmcraft-edit = { path = "crates/edit" }
+filmcraft-interchange = { path = "crates/interchange" }
filmcraft-render = { path = "crates/render" }
filmcraft-gpu = { path = "crates/gpu" }
filmcraft-export = { path = "crates/export" }
@@ -43,6 +44,7 @@ serde_json = "1"
log = "0.4"
rayon = "1"
proptest = "1"
+roxmltree = "0.21"
# ui
egui = "0.36"
diff --git a/crates/interchange/Cargo.toml b/crates/interchange/Cargo.toml
new file mode 100644
index 000000000..4d6599afe
--- /dev/null
+++ b/crates/interchange/Cargo.toml
@@ -0,0 +1,24 @@
+[package]
+name = "filmcraft-interchange"
+description = "FilmCraft interchange: CMX 3600 EDL, Final Cut Pro 7 XML (xmeml), FCPXML and OpenTimelineIO import/export"
+version.workspace = true
+edition.workspace = true
+license.workspace = true
+rust-version.workspace = true
+
+[lints]
+workspace = true
+
+[dependencies]
+filmcraft-time = { workspace = true }
+filmcraft-geom = { workspace = true }
+filmcraft-color = { workspace = true }
+filmcraft-media = { workspace = true }
+filmcraft-project = { workspace = true }
+serde = { workspace = true }
+serde_json = { workspace = true }
+thiserror = { workspace = true }
+roxmltree = { workspace = true }
+
+[dev-dependencies]
+proptest = { workspace = true }
diff --git a/crates/interchange/src/common.rs b/crates/interchange/src/common.rs
new file mode 100644
index 000000000..94a524b82
--- /dev/null
+++ b/crates/interchange/src/common.rs
@@ -0,0 +1,661 @@
+//! Shared helpers: fragment builder, track placement, media paths/URLs, effect and transition
+//! mapping, frame/tick conversion.
+
+use std::collections::HashMap;
+
+use filmcraft_color::ColorInfo;
+use filmcraft_media::{AudioStreamInfo, Generator, MediaInfo, MediaKind, VideoStreamInfo};
+use filmcraft_project::{
+ BinId, ClipId, EffectInstance, EffectKind, Interpretation, ItemId, ItemKind, Label, MediaClip, MediaRef, Param, Project, Sequence, SequenceSettings, Track,
+ TrackId, TrackItem, TrackKind, effect, effect::find_effect_by_name, find_effect,
+};
+use filmcraft_time::{FrameRate, Tick};
+
+use crate::{Imported, Report};
+
+// ---------------------------------------------------------------------------------------------
+// Paths and URLs
+// ---------------------------------------------------------------------------------------------
+
+fn is_windows_abs(p: &str) -> bool {
+ let b = p.as_bytes();
+ b.len() >= 3 && b[0].is_ascii_alphabetic() && b[1] == b':' && (b[2] == b'/' || b[2] == b'\\')
+}
+
+pub(crate) fn is_absolute(p: &str) -> bool {
+ p.starts_with('/') || p.starts_with("\\\\") || is_windows_abs(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() {
+ if b[i] == b'%' && i + 2 < b.len() {
+ let h = std::str::from_utf8(&b[i + 1..i + 3]).ok().and_then(|h| u8::from_str_radix(h, 16).ok());
+ if let Some(v) = h {
+ out.push(v);
+ i += 3;
+ continue;
+ }
+ }
+ out.push(b[i]);
+ i += 1;
+ }
+ String::from_utf8(out).unwrap_or_else(|e| String::from_utf8_lossy(e.as_bytes()).into_owned())
+}
+
+fn percent_encode_path(s: &str) -> String {
+ let mut out = String::with_capacity(s.len());
+ for &c in s.as_bytes() {
+ if c.is_ascii_alphanumeric() || b"/-._~!$&'()*+,;=:@".contains(&c) {
+ out.push(c as char);
+ } else {
+ out.push_str(&format!("%{c:02X}"));
+ }
+ }
+ out
+}
+
+/// Convert a `file://` URL (`file:///a/b`, `file://localhost/a/b`, `file:///C:/x`) to a path.
+/// Strings that are not file URLs are returned unchanged.
+pub fn file_url_to_path(url: &str) -> String {
+ let lower = url.get(..7).map(|s| s.to_ascii_lowercase());
+ if lower.as_deref() != Some("file://") {
+ return url.to_string();
+ }
+ let rest = &url[7..];
+ let rest = if rest.len() >= 9 && rest[..9].eq_ignore_ascii_case("localhost") { &rest[9..] } else { rest };
+ let decoded = percent_decode(rest);
+ // file:///C:/x -> C:/x
+ if decoded.len() >= 3 && decoded.starts_with('/') && is_windows_abs(&decoded[1..]) {
+ return decoded[1..].to_string();
+ }
+ if !decoded.starts_with('/') {
+ // file://server/share -> UNC
+ return format!("//{decoded}");
+ }
+ decoded
+}
+
+/// Convert an absolute path to a `file://` URL (`localhost` form for FCP7 XML).
+pub fn path_to_file_url(path: &str, localhost: bool) -> String {
+ let p = path.replace('\\', "/");
+ let host = if localhost { "localhost" } else { "" };
+ if is_windows_abs(&p) {
+ format!("file://{host}/{}", percent_encode_path(&p))
+ } else if let Some(unc) = p.strip_prefix("//") {
+ format!("file://{}", percent_encode_path(unc))
+ } else {
+ format!("file://{host}{}", percent_encode_path(&p))
+ }
+}
+
+fn join(base: &str, rel: &str) -> String {
+ let sep = if base.contains('\\') && !base.contains('/') { '\\' } else { '/' };
+ let mut parts: Vec<&str> = base.split(['/', '\\']).collect();
+ if parts.last() == Some(&"") && parts.len() > 1 {
+ parts.pop();
+ }
+ for seg in rel.split(['/', '\\']) {
+ match seg {
+ "" | "." => {}
+ ".." => {
+ if parts.len() > 1 {
+ parts.pop();
+ }
+ }
+ s => parts.push(s),
+ }
+ }
+ parts.join(&sep.to_string())
+}
+
+/// Resolve a media reference from a document: file URLs become paths, relative paths are joined to
+/// `base_dir` (when given).
+pub fn resolve_path(reference: &str, base_dir: Option<&str>) -> String {
+ let p = file_url_to_path(reference.trim());
+ if is_absolute(&p) {
+ return p;
+ }
+ match base_dir {
+ Some(b) if !b.is_empty() => join(b, &p),
+ _ => p,
+ }
+}
+
+/// `path` relative to directory `base`, if `path` lies under it (or shares a prefix).
+pub(crate) fn relative_path(path: &str, base: &str) -> Option<String> {
+ if !is_absolute(path) || !is_absolute(base) {
+ return None;
+ }
+ let a: Vec<&str> = path.split(['/', '\\']).filter(|s| !s.is_empty()).collect();
+ let b: Vec<&str> = base.split(['/', '\\']).filter(|s| !s.is_empty()).collect();
+ let common = a.iter().zip(&b).take_while(|(x, y)| x == y).count();
+ if common == 0 {
+ return None;
+ }
+ let mut out: Vec<&str> = std::iter::repeat_n("..", b.len() - common).collect();
+ out.extend(&a[common..]);
+ Some(out.join("/"))
+}
+
+/// Final path component.
+pub(crate) fn file_name(path: &str) -> &str {
+ path.rsplit(['/', '\\']).next().unwrap_or(path)
+}
+
+/// File name without extension.
+pub(crate) fn file_stem(path: &str) -> &str {
+ let n = file_name(path);
+ match n.rfind('.') {
+ Some(i) if i > 0 => &n[..i],
+ _ => n,
+ }
+}
+
+pub(crate) fn extension(path: &str) -> String {
+ let n = file_name(path);
+ n.rfind('.').map(|i| n[i + 1..].to_ascii_lowercase()).unwrap_or_default()
+}
+
+/// Media kind guess from a file extension.
+pub(crate) fn kind_from_ext(path: &str) -> MediaKind {
+ match extension(path).as_str() {
+ "wav" | "aif" | "aiff" | "mp3" | "aac" | "m4a" | "flac" | "ogg" | "opus" | "bwf" => MediaKind::AudioOnly,
+ "png" | "jpg" | "jpeg" | "tif" | "tiff" | "psd" | "bmp" | "gif" | "webp" | "exr" | "dpx" | "tga" => MediaKind::Still,
+ _ => MediaKind::Movie,
+ }
+}
+
+// ---------------------------------------------------------------------------------------------
+// Frames and rates
+// ---------------------------------------------------------------------------------------------
+
+/// Frame count nearest to `t` at `rate`.
+pub(crate) fn frames_round(rate: FrameRate, t: Tick) -> i64 {
+ let f = rate.frame_at(t);
+ if rate.tick_of(f + 1) - t < t - rate.tick_of(f) { f + 1 } else { f }
+}
+
+/// Whether `t` is exactly on a frame boundary of `rate`.
+pub(crate) fn on_frame(rate: FrameRate, t: Tick) -> bool {
+ rate.tick_of(rate.frame_at(t)) == t
+}
+
+/// FCP7-style `(timebase, ntsc)` for a rate.
+pub(crate) fn timebase(rate: FrameRate) -> (i64, bool) {
+ (rate.timecode_base(), rate.is_ntsc())
+}
+
+/// Rate from FCP7-style `(timebase, ntsc)`.
+pub(crate) fn rate_from_timebase(timebase: i64, ntsc: bool) -> FrameRate {
+ let tb = timebase.max(1);
+ if ntsc { FrameRate::new(tb * 1000, 1001) } else { FrameRate::new(tb, 1) }
+}
+
+/// Snap a floating rate (OTIO) to an exact rate.
+pub(crate) fn rate_from_f64(r: f64) -> FrameRate {
+ if r <= 0.0 || !r.is_finite() {
+ return FrameRate::FPS_24;
+ }
+ for c in FrameRate::COMMON {
+ if (c.as_f64() - r).abs() < 1e-3 {
+ return c;
+ }
+ }
+ let n = (r * 1001.0).round();
+ if ((n / 1001.0) - r).abs() < 1e-9 && (n as i64) % 1000 == 0 {
+ return FrameRate::new(n as i64, 1001);
+ }
+ if (r - r.round()).abs() < 1e-9 {
+ return FrameRate::new(r.round() as i64, 1);
+ }
+ FrameRate::new((r * 1_000_000.0).round() as i64, 1_000_000)
+}
+
+// ---------------------------------------------------------------------------------------------
+// Media descriptions
+// ---------------------------------------------------------------------------------------------
+
+/// What a document says about a media file.
+#[derive(Clone, Debug, Default)]
+pub(crate) struct MediaSpec {
+ pub duration: Option<Tick>,
+ /// (width, height, rate).
+ pub video: Option<(u32, u32, FrameRate)>,
+ /// (sample rate, channels).
+ pub audio: Option<(u32, u32)>,
+ pub start_tc: Option<i64>,
+ pub kind: Option<MediaKind>,
+}
+
+pub(crate) fn media_info(name: &str, spec: &MediaSpec) -> MediaInfo {
+ let kind = spec.kind.unwrap_or(match (spec.video.is_some(), spec.audio.is_some()) {
+ (false, true) => MediaKind::AudioOnly,
+ _ => MediaKind::Movie,
+ });
+ MediaInfo {
+ name: name.to_string(),
+ kind,
+ duration: spec.duration.unwrap_or(Tick::ZERO),
+ video: spec.video.map(|(w, h, r)| VideoStreamInfo {
+ width: w,
+ height: h,
+ frame_rate: r,
+ par: (1, 1),
+ codec: String::new(),
+ pixel_format: String::new(),
+ color: ColorInfo::REC709,
+ has_alpha: false,
+ bitrate: None,
+ }),
+ audio: spec.audio.map(|(sr, ch)| AudioStreamInfo { sample_rate: sr, channels: ch, codec: String::new(), bits_per_sample: None }),
+ container: String::new(),
+ start_timecode: spec.start_tc,
+ file_size: None,
+ }
+}
+
+pub(crate) fn media_clip(media: MediaRef, info: MediaInfo) -> MediaClip {
+ MediaClip { media, info, interpret: Interpretation::default(), mark_in: None, mark_out: None, markers: Vec::new(), offline: false, proxy: None }
+}
+
+/// The file path behind an item (following subclips), if it is file media.
+pub(crate) fn item_path(p: &Project, id: ItemId) -> Option<&str> {
+ match &p.item(id)?.kind {
+ ItemKind::Media(m) => match &m.media {
+ MediaRef::File { path } => Some(path),
+ MediaRef::Generator(_) => None,
+ },
+ ItemKind::Subclip { parent, .. } => item_path(p, *parent),
+ _ => None,
+ }
+}
+
+/// The media clip behind an item (following subclips).
+pub(crate) fn item_media(p: &Project, id: ItemId) -> Option<&MediaClip> {
+ match &p.item(id)?.kind {
+ ItemKind::Media(m) => Some(m),
+ ItemKind::Subclip { parent, .. } => item_media(p, *parent),
+ _ => None,
+ }
+}
+
+/// The underlying item for exports (subclip → parent media).
+pub(crate) fn base_item(p: &Project, id: ItemId) -> ItemId {
+ match p.item(id).map(|i| &i.kind) {
+ Some(ItemKind::Subclip { parent, .. }) => base_item(p, *parent),
+ _ => id,
+ }
+}
+
+pub(crate) fn generator_of(p: &Project, id: ItemId) -> Option<&Generator> {
+ match &item_media(p, id)?.media {
+ MediaRef::Generator(g) => Some(g),
+ MediaRef::File { .. } => None,
+ }
+}
+
+// ---------------------------------------------------------------------------------------------
+// Fragment builder
+// ---------------------------------------------------------------------------------------------
+
+pub(crate) struct Builder {
+ pub p: Project,
+ media: HashMap<String, ItemId>,
+ pub top: Vec<ItemId>,
+ next_link: u64,
+}
+
+impl Builder {
+ pub fn new(name: &str) -> Self {
+ Self { p: Project::new(name), media: HashMap::new(), top: Vec::new(), next_link: 1 }
+ }
+
+ pub fn bin(&mut self, name: &str, parent: Option<BinId>) -> BinId {
+ self.p.add_bin(name, parent)
+ }
+
+ pub fn find_media(&self, key: &str) -> Option<ItemId> {
+ self.media.get(key).copied()
+ }
+
+ pub fn register_media(&mut self, key: &str, id: ItemId) {
+ self.media.insert(key.to_string(), id);
+ }
+
+ /// File media deduplicated by `key` (normally the resolved path).
+ pub fn file_media(&mut self, key: &str, name: &str, path: &str, spec: &MediaSpec, bin: Option<BinId>) -> ItemId {
+ if let Some(id) = self.media.get(key) {
+ return *id;
+ }
+ let info = media_info(name, spec);
+ let id = self.p.add_item(name, Label::Iris, ItemKind::Media(media_clip(MediaRef::File { path: path.to_string() }, info)), bin);
+ self.media.insert(key.to_string(), id);
+ id
+ }
+
+ pub fn generator_media(&mut self, key: &str, name: &str, g: Generator, spec: &MediaSpec, bin: Option<BinId>) -> ItemId {
+ if let Some(id) = self.media.get(key) {
+ return *id;
+ }
+ let mut spec = spec.clone();
+ spec.kind = Some(MediaKind::Synthetic);
+ let info = media_info(name, &spec);
+ let id = self.p.add_item(name, Label::Lavender, ItemKind::Media(media_clip(MediaRef::Generator(g), info)), bin);
+ self.media.insert(key.to_string(), id);
+ id
+ }
+
+ /// Add an empty sequence item (filled later with [`Builder::put_sequence`]).
+ pub fn reserve_sequence(&mut self, name: &str, settings: SequenceSettings, bin: Option<BinId>) -> ItemId {
+ let seq = empty_sequence(settings);
+ self.p.add_item(name, Label::Forest, ItemKind::Sequence(Box::new(seq)), bin)
+ }
+
+ pub fn put_sequence(&mut self, id: ItemId, mut seq: Sequence) {
+ for t in seq.all_tracks_mut() {
+ t.sort();
+ }
+ if let Some(s) = self.p.sequence_mut(id) {
+ *s = seq;
+ }
+ }
+
+ pub fn track(&mut self, kind: TrackKind, index: usize) -> Track {
+ let id = TrackId(self.p.alloc_id());
+ let name = match kind {
+ TrackKind::Video => format!("Video {}", index + 1),
+ TrackKind::Audio => format!("Audio {}", index + 1),
+ };
+ Track::new(id, kind, name)
+ }
+
+ pub fn ensure_tracks(&mut self, seq: &mut Sequence, kind: TrackKind, n: usize) {
+ while seq.tracks(kind).len() < n {
+ let i = seq.tracks(kind).len();
+ let t = self.track(kind, i);
+ seq.tracks_mut(kind).push(t);
+ }
+ }
+
+ pub fn link_id(&mut self) -> u64 {
+ let l = self.next_link;
+ self.next_link += 1;
+ l
+ }
+
+ pub fn alloc(&mut self) -> u64 {
+ self.p.alloc_id()
+ }
+
+ /// A track item with the intrinsic effects of its track kind.
+ pub fn clip(&mut self, item: ItemId, kind: TrackKind, name: &str, start: Tick, duration: Tick, source_in: Tick) -> TrackItem {
+ let label = self.p.item(item).map(|i| i.label).unwrap_or(Label::Iris);
+ TrackItem {
+ id: ClipId(self.p.alloc_id()),
+ item,
+ name: name.to_string(),
+ label,
+ start,
+ duration,
+ source_in,
+ speed: 1.0,
+ reverse: false,
+ enabled: true,
+ link: None,
+ group: None,
+ effects: match kind {
+ TrackKind::Video => effect::intrinsic_video(),
+ TrackKind::Audio => effect::intrinsic_audio(),
+ },
+ markers: Vec::new(),
+ gain_db: 0.0,
+ frame_hold: None,
+ scale_to_frame: false,
+ }
+ }
+
+ /// Place `item` on the first track at or after `preferred` where it does not overlap anything,
+ /// creating tracks as needed. Returns the track index.
+ pub fn place(&mut self, seq: &mut Sequence, kind: TrackKind, preferred: usize, item: TrackItem) -> usize {
+ let mut i = preferred;
+ loop {
+ self.ensure_tracks(seq, kind, i + 1);
+ let t = &mut seq.tracks_mut(kind)[i];
+ if !t.items.iter().any(|o| o.start < item.end() && item.start < o.end()) {
+ t.items.push(item);
+ t.sort();
+ return i;
+ }
+ i += 1;
+ }
+ }
+
+ /// Finish: grow media durations to cover every use, return the fragment.
+ pub fn finish(mut self) -> Imported {
+ let mut need: HashMap<ItemId, Tick> = HashMap::new();
+ for it in self.p.items.values() {
+ if let Some(seq) = it.as_sequence() {
+ for t in seq.all_tracks() {
+ for ti in &t.items {
+ let e = need.entry(ti.item).or_insert(Tick::ZERO);
+ *e = (*e).max(ti.source_out()).max(ti.source_in + Tick(1));
+ }
+ }
+ }
+ }
+ for (id, end) in need {
+ if let Some(m) = self.p.item_mut(id).and_then(|i| i.as_media_mut())
+ && m.info.duration < end
+ {
+ m.info.duration = end;
+ }
+ }
+ Imported { project: self.p, sequences: self.top }
+ }
+}
+
+pub(crate) fn empty_sequence(settings: SequenceSettings) -> Sequence {
+ Sequence {
+ settings,
+ video_tracks: Vec::new(),
+ audio_tracks: Vec::new(),
+ markers: Vec::new(),
+ mark_in: None,
+ mark_out: None,
+ work_area: None,
+ start_timecode: 0,
+ master_volume_db: 0.0,
+ master_effects: Vec::new(),
+ }
+}
+
+pub(crate) fn settings_for(rate: FrameRate, width: u32, height: u32, drop_frame: bool) -> SequenceSettings {
+ SequenceSettings {
+ width,
+ height,
+ frame_rate: rate,
+ drop_frame: drop_frame && rate.supports_drop_frame(),
+ preset: format!("Custom {width}x{height} {}", rate.label()),
+ ..SequenceSettings::default()
+ }
+}
+
+/// Source time advanced by a timeline duration at `speed` (exact for integral speeds).
+pub(crate) fn scaled(d: Tick, speed: f64) -> Tick {
+ let s = speed.abs();
+ if s == s.round() && s < 1e6 { Tick(d.0 * s as i64) } else { Tick((d.0 as f64 * s).round() as i64) }
+}
+
+/// Timeline duration of a source duration at `speed`.
+pub(crate) fn unscaled(d: Tick, speed: f64) -> Tick {
+ let s = speed.abs();
+ if s == 0.0 {
+ return d;
+ }
+ if s == 1.0 { d } else { Tick((d.0 as f64 / s).round() as i64) }
+}
+
+/// Overwrite `item` onto `track` (EDL record semantics): whatever was under it is trimmed/split.
+pub(crate) fn overwrite(track: &mut Track, item: TrackItem, alloc: &mut dyn FnMut() -> u64) {
+ let (s, e) = (item.start, item.end());
+ let mut out = Vec::with_capacity(track.items.len() + 2);
+ for o in track.items.drain(..) {
+ if o.end() <= s || o.start >= e {
+ out.push(o);
+ continue;
+ }
+ if o.start < s {
+ let mut l = o.clone();
+ l.duration = s - o.start;
+ out.push(l);
+ }
+ if o.end() > e {
+ let mut r = o.clone();
+ r.id = ClipId(alloc());
+ r.source_in = o.source_in + scaled(e - o.start, o.speed);
+ r.start = e;
+ r.duration = o.end() - e;
+ out.push(r);
+ }
+ }
+ out.push(item);
+ track.items = out;
+ track.sort();
+}
+
+// ---------------------------------------------------------------------------------------------
+// Effects
+// ---------------------------------------------------------------------------------------------
+
+pub(crate) fn param<'a>(ti: &'a TrackItem, effect: &str, param: &str) -> Option<&'a Param> {
+ ti.effect(effect).and_then(|e| e.param(param))
+}
+
+/// Set a parameter, adding the effect instance (defaults) if the item lacks it.
+pub(crate) fn set_param(ti: &mut TrackItem, effect: &str, param: &str, value: Param) {
+ if ti.effect(effect).is_none()
+ && let Some(d) = find_effect(effect)
+ {
+ ti.effects.push(d.instance());
+ }
+ if let Some(e) = ti.effect_mut(effect) {
+ e.params.insert(param.to_string(), value);
+ }
+}
+
+/// Whether a parameter differs from its definition default or is animated.
+pub(crate) fn param_modified(ti: &TrackItem, effect: &str, param_id: &str) -> bool {
+ let Some(p) = param(ti, effect, param_id) else { return false };
+ if p.is_animated() {
+ return true;
+ }
+ let def = find_effect(effect).and_then(|d| d.param(param_id)).map(|d| d.default.clone());
+ match (&p.value, def) {
+ (filmcraft_project::ParamValue::Vec2(v), Some(filmcraft_project::ParamValue::Vec2(_))) => !(v.x.is_nan() && v.y.is_nan()),
+ (v, Some(d)) => *v != d,
+ _ => false,
+ }
+}
+
+/// Non-intrinsic effects on an item.
+pub(crate) fn standard_effects(ti: &TrackItem) -> impl Iterator<Item = &EffectInstance> {
+ ti.effects.iter().filter(|e| !e.def().is_some_and(|d| d.intrinsic))
+}
+
+/// A transition effect for a document's transition name. Unknown names become Cross Dissolve
+/// (Constant Power on audio) with a warning.
+pub(crate) fn transition_effect(name: &str, audio: bool, report: &mut Report) -> EffectInstance {
+ let n = name.trim().to_ascii_lowercase();
+ let alias = match n.as_str() {
+ "dissolve" | "cross dissolve" | "smpte_dissolve" | "d" | "crossdissolve" => Some(if audio { "constant_power" } else { "cross_dissolve" }),
+ "cross fade (+3db)" | "cross fade +3db" | "crossfade (+3db)" | "cross fade" => Some("constant_power"),
+ "cross fade (0db)" | "cross fade 0db" | "crossfade (0db)" => Some("constant_gain"),
+ "dip to color dissolve" | "fade in fade out dissolve" | "fade to color" => Some("dip_to_black"),
+ "edge wipe" | "wipe" | "smpte_wipe" => Some("wipe"),
+ _ => None,
+ };
+ if let Some(id) = alias
+ && let Some(d) = find_effect(id)
+ {
+ return d.instance();
+ }
+ let want = if audio { EffectKind::AudioTransition } else { EffectKind::VideoTransition };
+ if let Some(d) = find_effect_by_name(name.trim()).filter(|d| d.kind == want) {
+ return d.instance();
+ }
+ let fallback = if audio { "constant_power" } else { "cross_dissolve" };
+ report.warn(format!("transition \"{name}\" is not supported; imported as {}", find_effect(fallback).map(|d| d.name).unwrap_or(fallback)));
+ find_effect(fallback).map(|d| d.instance()).unwrap_or_else(|| EffectInstance {
+ effect: fallback.into(),
+ enabled: true,
+ params: Default::default(),
+ masks: vec![],
+ })
+}
+
+/// Display name of a transition (for documents).
+pub(crate) fn transition_name(e: &EffectInstance) -> String {
+ e.def().map(|d| d.name.to_string()).unwrap_or_else(|| e.effect.clone())
+}
+
+/// Label from a document label name (Premiere label names; FCP7 names like "Good Take" ignored).
+pub(crate) fn label_from(s: &str) -> Option<Label> {
+ Label::from_name(s.trim())
+}
+
+/// dB ↔ linear gain.
+pub(crate) fn db_to_gain(db: f64) -> f64 {
+ if db <= -287.0 { 0.0 } else { 10f64.powf(db / 20.0) }
+}
+pub(crate) fn gain_to_db(g: f64) -> f64 {
+ if g <= 1e-15 { -287.5 } else { 20.0 * g.log10() }
+}
+
+/// Sanitise a name for fixed-width EDL fields.
+pub(crate) fn sanitize_reel(s: &str, max: usize) -> String {
+ let r: String = s.chars().map(|c| if c.is_ascii_alphanumeric() || c == '_' || c == '-' { c.to_ascii_uppercase() } else { '_' }).take(max).collect();
+ if r.is_empty() { "AX".into() } else { r }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn urls() {
+ assert_eq!(file_url_to_path("file://localhost/Users/me/My%20Clip.mov"), "/Users/me/My Clip.mov");
+ assert_eq!(file_url_to_path("file:///C:/Media/a.mxf"), "C:/Media/a.mxf");
+ assert_eq!(file_url_to_path("/plain/path.mov"), "/plain/path.mov");
+ assert_eq!(path_to_file_url("/Users/me/My Clip.mov", true), "file://localhost/Users/me/My%20Clip.mov");
+ assert_eq!(path_to_file_url("C:\\Media\\a b.mxf", false), "file:///C:/Media/a%20b.mxf");
+ for p in ["/a/b c/ü.mov", "C:/x/y.mp4", "/r/%/#?.mov"] {
+ assert_eq!(file_url_to_path(&path_to_file_url(p, true)), p);
+ assert_eq!(file_url_to_path(&path_to_file_url(p, false)), p);
+ }
+ }
+
+ #[test]
+ fn paths() {
+ assert_eq!(resolve_path("media/a.mov", Some("/proj")), "/proj/media/a.mov");
+ assert_eq!(resolve_path("../a.mov", Some("/proj/x/")), "/proj/a.mov");
+ assert_eq!(resolve_path("/abs/a.mov", Some("/proj")), "/abs/a.mov");
+ assert_eq!(relative_path("/proj/media/a.mov", "/proj").as_deref(), Some("media/a.mov"));
+ assert_eq!(relative_path("/proj/a.mov", "/proj/edl").as_deref(), Some("../a.mov"));
+ assert_eq!(file_stem("/x/y/Clip 01.final.mov"), "Clip 01.final");
+ }
+
+ #[test]
+ fn rates() {
+ assert_eq!(rate_from_timebase(24, true), FrameRate::FPS_23_976);
+ assert_eq!(rate_from_timebase(30, true), FrameRate::FPS_29_97);
+ assert_eq!(rate_from_timebase(60, true), FrameRate::FPS_59_94);
+ assert_eq!(rate_from_timebase(25, false), FrameRate::FPS_25);
+ assert_eq!(rate_from_f64(24000.0 / 1001.0), FrameRate::FPS_23_976);
+ assert_eq!(rate_from_f64(23.976), FrameRate::FPS_23_976);
+ assert_eq!(rate_from_f64(48000.0), FrameRate::new(48000, 1));
+ assert_eq!(frames_round(FrameRate::FPS_24, FrameRate::FPS_24.tick_of(5) + Tick(10)), 5);
+ }
+}
diff --git a/crates/interchange/src/edl.rs b/crates/interchange/src/edl.rs
new file mode 100644
index 000000000..756dcce1a
--- /dev/null
+++ b/crates/interchange/src/edl.rs
@@ -0,0 +1,1023 @@
+//! CMX 3600 edit decision lists.
+//!
+//! Supported: `TITLE:`, `FCM:` (drop/non-drop, may change mid-list), cut / dissolve (`D nnn`) /
+//! wipe (`Wnnn nnn`) / key (`K B`, `K`, `K O`) events, audio channels (`V`, `A`, `A2`, `AA`, `B`,
+//! `AA/V`, `A2/V`, `A3`, `A4`, `AUD 3 4` lines), `M2` motion (speed, reverse, freeze) lines, `BL`
+//! black, reel names up to 8 (strict) or 32+ (extended) characters, and the comment extensions
+//! `* FROM CLIP NAME:`, `* TO CLIP NAME:`, `* SOURCE FILE:`, `* EFFECT NAME:` and `* LOC:` markers.
+//!
+//! EDLs carry no frame rate and no media identity beyond reels/comments; see [`ImportOptions`].
+//! Source timecodes are imported as media time (a file starting at 01:00:00:00 would need
+//! [`crate::rebase_source_timecode`] after probing).
+
+use std::collections::{BTreeSet, HashMap};
+
+use filmcraft_media::Generator;
+use filmcraft_project::{
+ ItemId, ItemKind, Label, Marker, MarkerId, MarkerKind, ParamValue, Project, Sequence, TrackKind, Transition, TransitionAlign, TransitionId, find_effect,
+};
+use filmcraft_time::{FrameRate, Tick, fields_to_frames, format_timecode_frames};
+
+use crate::common::{
+ Builder, MediaSpec, empty_sequence, file_name, file_stem, frames_round, generator_of, item_path, on_frame, overwrite, relative_path, resolve_path,
+ sanitize_reel, scaled, settings_for, transition_effect, transition_name,
+};
+use crate::{ExportOptions, Format, ImportOptions, Imported, ReelMode, Report, Result};
+
+/// Heuristic: does this text look like an EDL?
+pub(crate) fn looks_like_edl(text: &str) -> bool {
+ text.lines().take(40).any(|l| {
+ let l = l.trim_start();
+ l.starts_with("TITLE:") || l.starts_with("FCM:") || parse_event_line(l).is_some()
+ })
+}
+
+// ---------------------------------------------------------------------------------------------
+// Parsing
+// ---------------------------------------------------------------------------------------------
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+struct Tc {
+ h: i64,
+ m: i64,
+ s: i64,
+ f: i64,
+ df: bool,
+}
+
+fn parse_tc(s: &str) -> Option<Tc> {
+ let parts: Vec<&str> = s.split([':', ';', '.', ',']).collect();
+ if parts.len() != 4 || parts.iter().any(|p| p.is_empty() || !p.bytes().all(|b| b.is_ascii_digit())) {
+ return None;
+ }
+ let n: Vec<i64> = parts.iter().map(|p| p.parse().unwrap_or(0)).collect();
+ Some(Tc { h: n[0], m: n[1], s: n[2], f: n[3], df: s.contains(';') || s.contains(',') })
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+enum Trans {
+ Cut,
+ Dissolve,
+ Wipe(u32),
+ KeyBackground,
+ Key,
+ KeyOut,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
+enum Ch {
+ V,
+ A(usize),
+}
+
+fn parse_channels(s: &str) -> Option<Vec<Ch>> {
+ let u = s.to_ascii_uppercase();
+ match u.as_str() {
+ "B" => return Some(vec![Ch::V, Ch::A(1)]),
+ "NONE" => return Some(vec![]),
+ _ => {}
+ }
+ let mut out = Vec::new();
+ for part in u.split('/') {
+ match part {
+ "V" => out.push(Ch::V),
+ "A" | "A1" => out.push(Ch::A(1)),
+ "AA" => out.extend([Ch::A(1), Ch::A(2)]),
+ p if p.starts_with('A') && p[1..].parse::<usize>().is_ok_and(|n| (1..=99).contains(&n)) => out.push(Ch::A(p[1..].parse().ok()?)),
+ _ => return None,
+ }
+ }
+ (!out.is_empty()).then_some(out)
+}
+
+#[derive(Clone, Debug)]
+struct Line {
+ num: String,
+ reel: String,
+ chans: Vec<Ch>,
+ trans: Trans,
+ dur: i64,
+ tcs: [Tc; 4],
+}
+
+fn parse_event_line(l: &str) -> Option<Line> {
+ let toks: Vec<&str> = l.split_whitespace().collect();
+ if toks.len() < 8 || !toks[0].bytes().all(|b| b.is_ascii_digit()) {
+ return None;
+ }
+ let n = toks.len();
+ let tcs = [parse_tc(toks[n - 4])?, parse_tc(toks[n - 3])?, parse_tc(toks[n - 2])?, parse_tc(toks[n - 1])?];
+ let reel = toks[1].to_string();
+ let chans = parse_channels(toks[2])?;
+ let mid = &toks[3..n - 4];
+ let first = mid.first()?.to_ascii_uppercase();
+ let num_at = |i: usize| mid.get(i).and_then(|t| t.parse::<i64>().ok());
+ let (trans, dur) = match first.as_str() {
+ "C" => (Trans::Cut, 0),
+ "D" => (Trans::Dissolve, num_at(1).unwrap_or(0)),
+ "K" => match mid.get(1).map(|s| s.to_ascii_uppercase()) {
+ Some(ref s) if s == "B" => (Trans::KeyBackground, 0),
+ Some(ref s) if s == "O" => (Trans::KeyOut, num_at(2).unwrap_or(0)),
+ _ => (Trans::Key, num_at(1).unwrap_or(0)),
+ },
+ "KB" => (Trans::KeyBackground, 0),
+ "KO" => (Trans::KeyOut, num_at(1).unwrap_or(0)),
+ w if w.starts_with('W') => (Trans::Wipe(w[1..].parse().unwrap_or(1)), num_at(1).unwrap_or(0)),
+ _ => return None,
+ };
+ Some(Line { num: toks[0].to_string(), reel, chans, trans, dur, tcs })
+}
+
+#[derive(Clone, Debug, Default)]
+struct Event {
+ lines: Vec<Line>,
+ from_clip: Option<String>,
+ to_clip: Option<String>,
+ files: Vec<String>,
+ effect: Option<String>,
+ /// (reel, fps, entry tc)
+ m2: Vec<(String, f64)>,
+ locs: Vec<(Tc, String, String)>,
+ /// FCM in force for this event.
+ df: bool,
+}
+
+struct Parsed {
+ title: Option<String>,
+ events: Vec<Event>,
+ any_df: bool,
+ max_ff: i64,
+}
+
+fn parse(text: &str, report: &mut Report) -> Parsed {
+ let mut p = Parsed { title: None, events: Vec::new(), any_df: false, max_ff: 0 };
+ let mut df = false;
+ for raw in text.lines() {
+ let l = raw.trim();
+ if l.is_empty() {
+ continue;
+ }
+ let upper = l.to_ascii_uppercase();
+ if let Some(t) = l.strip_prefix("TITLE:") {
+ p.title = Some(t.trim().to_string());
+ continue;
+ }
+ if upper.starts_with("FCM:") {
+ df = upper.contains("DROP") && !upper.contains("NON");
+ p.any_df |= df;
+ continue;
+ }
+ if let Some(c) = l.strip_prefix('*') {
+ let c = c.trim();
+ let Some(ev) = p.events.last_mut() else { continue };
+ let cu = c.to_ascii_uppercase();
+ let value = |prefix: &str| c[prefix.len()..].trim().to_string();
+ if cu.starts_with("FROM CLIP NAME:") {
+ ev.from_clip = Some(value("FROM CLIP NAME:"));
+ } else if cu.starts_with("TO CLIP NAME:") {
+ ev.to_clip = Some(value("TO CLIP NAME:"));
+ } else if cu.starts_with("SOURCE FILE:") {
+ ev.files.push(value("SOURCE FILE:"));
+ } else if cu.starts_with("EFFECT NAME:") {
+ ev.effect = Some(value("EFFECT NAME:"));
+ } else if cu.starts_with("LOC:") {
+ let rest = value("LOC:");
+ let mut it = rest.splitn(3, char::is_whitespace).filter(|s| !s.is_empty());
+ if let Some(tc) = it.next().and_then(parse_tc) {
+ let rest2: Vec<&str> = rest.split_whitespace().skip(1).collect();
+ let (color, name) = match rest2.split_first() {
+ Some((c, n)) if marker_color(c).is_some() => (c.to_string(), n.join(" ")),
+ _ => (String::new(), rest2.join(" ")),
+ };
+ ev.locs.push((tc, color, name));
+ }
+ }
+ continue;
+ }
+ if upper.starts_with("M2") {
+ let toks: Vec<&str> = l.split_whitespace().collect();
+ if toks.len() >= 3 {
+ // `M2 REEL fps tc`; reels with spaces are joined back.
+ let fps_i = toks.iter().rposition(|t| t.parse::<f64>().is_ok() && parse_tc(t).is_none()).unwrap_or(2);
+ let reel = toks[1..fps_i.max(2)].join(" ");
+ if let Ok(fps) = toks[fps_i].parse::<f64>()
+ && let Some(ev) = p.events.last_mut()
+ {
+ ev.m2.push((reel, fps));
+ }
+ }
+ continue;
+ }
+ if upper.starts_with("AUD") {
+ let extra: Vec<Ch> = l.split_whitespace().skip(1).filter_map(|t| t.parse::<usize>().ok()).map(Ch::A).collect();
+ if let Some(line) = p.events.last_mut().and_then(|e| e.lines.last_mut()) {
+ line.chans.extend(extra);
+ }
+ continue;
+ }
+ if upper.starts_with("SPLIT:") {
+ report.warn("EDL split (L-cut/J-cut) lines are not supported; the split was ignored");
+ continue;
+ }
+ if let Some(line) = parse_event_line(l) {
+ for tc in &line.tcs {
+ p.max_ff = p.max_ff.max(tc.f);
+ p.any_df |= tc.df;
+ }
+ let same = p.events.last().and_then(|e| e.lines.last()).is_some_and(|last| last.num == line.num);
+ if same {
+ p.events.last_mut().unwrap().lines.push(line);
+ } else {
+ p.events.push(Event { lines: vec![line], df, ..Default::default() });
+ }
+ continue;
+ }
+ if upper.starts_with(">>>") || upper.starts_with("REM") {
+ continue;
+ }
+ report.warn(format!("unrecognised EDL line ignored: {}", l.chars().take(60).collect::<String>()));
+ }
+ p
+}
+
+fn guess_rate(p: &Parsed) -> FrameRate {
+ if p.any_df {
+ if p.max_ff >= 30 { FrameRate::FPS_59_94 } else { FrameRate::FPS_29_97 }
+ } else if p.max_ff >= 30 {
+ FrameRate::FPS_60
+ } else if p.max_ff >= 25 {
+ FrameRate::FPS_30
+ } else if p.max_ff >= 24 {
+ FrameRate::FPS_25
+ } else {
+ FrameRate::FPS_24
+ }
+}
+
+fn marker_color(s: &str) -> Option<Label> {
+ Some(match s.to_ascii_uppercase().as_str() {
+ "RED" => Label::Rose,
+ "GREEN" => Label::Green,
+ "BLUE" => Label::Blue,
+ "CYAN" => Label::Teal,
+ "MAGENTA" => Label::Magenta,
+ "YELLOW" => Label::Yellow,
+ "WHITE" => Label::Lavender,
+ "BLACK" => Label::Brown,
+ _ => return None,
+ })
+}
+
+fn color_word(l: Label) -> &'static str {
+ match l {
+ Label::Rose => "RED",
+ Label::Green | Label::Forest => "GREEN",
+ Label::Blue | Label::Iris | Label::Cerulean => "BLUE",
+ Label::Teal | Label::Caribbean => "CYAN",
+ Label::Magenta | Label::Purple | Label::Violet => "MAGENTA",
+ Label::Lavender => "WHITE",
+ Label::Brown => "BLACK",
+ Label::Yellow | Label::Mango | Label::Tan => "YELLOW",
+ }
+}
+
+// ---------------------------------------------------------------------------------------------
+// Import
+// ---------------------------------------------------------------------------------------------
+
+struct Ctx<'a> {
+ b: Builder,
+ seq: Sequence,
+ rate: FrameRate,
+ start_tc: i64,
+ opts: &'a ImportOptions,
+ has_video: bool,
+ has_audio: bool,
+}
+
+impl Ctx<'_> {
+ fn frames(&self, tc: Tc, df: bool) -> i64 {
+ fields_to_frames(tc.h, tc.m, tc.s, tc.f, self.rate, tc.df || df)
+ }
+
+ fn rec(&self, tc: Tc, df: bool) -> Tick {
+ self.rate.tick_of(self.frames(tc, df) - self.start_tc)
+ }
+
+ fn src(&self, tc: Tc, df: bool) -> Tick {
+ self.rate.tick_of(self.frames(tc, df))
+ }
+
+ /// Media item for a line.
+ fn media(&mut self, reel: &str, clip: Option<&str>, file: Option<&str>, chans: &[Ch]) -> ItemId {
+ let (w, h) = (self.seq.settings.width, self.seq.settings.height);
+ let spec = MediaSpec {
+ duration: None,
+ video: chans.contains(&Ch::V).then_some((w, h, self.rate)).or(self.has_video.then_some((w, h, self.rate))),
+ audio: chans.iter().any(|c| matches!(c, Ch::A(_))).then_some((48_000, 2)).or(self.has_audio.then_some((48_000, 2))),
+ ..Default::default()
+ };
+ if let Some(f) = file {
+ let path = resolve_path(f, self.opts.base_dir.as_deref());
+ let name = file_name(&path).to_string();
+ return self.b.file_media(&format!("file:{path}"), &name, &path, &spec, None);
+ }
+ let name = clip.filter(|c| !c.is_empty()).unwrap_or(reel).to_string();
+ let key = format!("reel:{reel}|{name}");
+ if let Some(id) = self.b.find_media(&key) {
+ return id;
+ }
+ // Without a file, the clip name (or reel) is the best path guess; relinking resolves it.
+ let path = resolve_path(&name, self.opts.base_dir.as_deref());
+ let id = self.b.file_media(&key, &name, &path, &spec, None);
+ if let Some(m) = self.b.p.item_mut(id) {
+ m.metadata.insert("Tape Name".into(), reel.to_string());
+ if let Some(mc) = m.as_media_mut() {
+ mc.offline = true;
+ }
+ }
+ id
+ }
+
+ fn track_index(&mut self, ch: Ch, video_base: usize) -> (TrackKind, usize) {
+ match ch {
+ Ch::V => (TrackKind::Video, video_base),
+ Ch::A(n) => (TrackKind::Audio, n.saturating_sub(1)),
+ }
+ }
+
+ /// Put an item for `line` on each of its channels (overwrite). Returns (track, clip) per channel.
+ #[allow(clippy::too_many_arguments)]
+ fn lay(
+ &mut self,
+ line: &Line,
+ item: ItemId,
+ name: &str,
+ start: Tick,
+ dur: Tick,
+ src_in: Tick,
+ m2: Option<f64>,
+ video_base: usize,
+ ) -> Vec<(TrackKind, usize, filmcraft_project::ClipId)> {
+ let mut out = Vec::new();
+ let link = if line.chans.len() > 1 { Some(self.b.link_id()) } else { None };
+ let base = self.rate.timecode_base() as f64;
+ let chans: BTreeSet<Ch> = line.chans.iter().copied().collect();
+ for ch in chans {
+ let (kind, idx) = self.track_index(ch, video_base);
+ let mut ti = self.b.clip(item, kind, name, start, dur, src_in);
+ ti.link = link;
+ if let Some(fps) = m2 {
+ if fps == 0.0 {
+ ti.frame_hold = Some(src_in);
+ } else {
+ ti.speed = (fps.abs() / base * 10_000.0).round() / 10_000.0;
+ ti.reverse = fps < 0.0;
+ }
+ }
+ let id = ti.id;
+ self.b.ensure_tracks(&mut self.seq, kind, idx + 1);
+ let mut next = self.b.p.next_id;
+ let track = &mut self.seq.tracks_mut(kind)[idx];
+ overwrite(track, ti, &mut || {
+ let v = next;
+ next += 1;
+ v
+ });
+ self.b.p.next_id = next;
+ out.push((kind, idx, id));
+ }
+ out
+ }
+}
+
+pub(crate) fn import(text: &str, opts: &ImportOptions, report: &mut Report) -> Result<Imported> {
+ let parsed = parse(text, report);
+ if parsed.events.is_empty() {
+ return Err(crate::Error::parse(Format::Edl, "no events found"));
+ }
+ let rate = match opts.edl_frame_rate {
+ Some(r) => r,
+ None => {
+ let r = guess_rate(&parsed);
+ report.info(format!("EDL has no frame rate; assumed {r} (set ImportOptions::edl_frame_rate to override)"));
+ r
+ }
+ };
+ let title = parsed.title.clone().or_else(|| opts.name.clone()).unwrap_or_else(|| "EDL Sequence".into());
+ let mut settings = settings_for(rate, 1920, 1080, parsed.any_df);
+ settings.drop_frame = parsed.any_df && rate.supports_drop_frame();
+ let mut ctx = Ctx { b: Builder::new(&title), seq: empty_sequence(settings), rate, start_tc: 0, opts, has_video: false, has_audio: false };
+ for ev in &parsed.events {
+ for l in &ev.lines {
+ ctx.has_video |= l.chans.contains(&Ch::V);
+ ctx.has_audio |= l.chans.iter().any(|c| matches!(c, Ch::A(_)));
+ }
+ }
+ // Sequence start: the hour of the first record timecode.
+ let first_rec = {
+ let c = &ctx;
+ parsed.events.iter().flat_map(|e| e.lines.iter().map(move |l| c.frames(l.tcs[2], e.df))).min().unwrap_or(0)
+ };
+ let (_, h, _, _, _) = filmcraft_time::frames_to_fields(first_rec, rate, ctx.seq.settings.drop_frame);
+ ctx.start_tc = fields_to_frames(h, 0, 0, 0, rate, ctx.seq.settings.drop_frame).min(first_rec);
+ ctx.seq.start_timecode = ctx.start_tc;
+ if source_tc_warning(&parsed) {
+ report.info("EDL source timecodes were imported as media time; rebase after probing media that has a start timecode");
+ }
+
+ for ev in &parsed.events {
+ import_event(&mut ctx, ev, report);
+ for (tc, color, name) in &ev.locs {
+ let t = ctx.rec(*tc, ev.df);
+ let id = MarkerId(ctx.b.alloc());
+ ctx.seq.markers.push(Marker {
+ id,
+ start: t,
+ duration: Tick::ZERO,
+ name: name.clone(),
+ comment: String::new(),
+ kind: MarkerKind::Comment,
+ color: marker_color(color).unwrap_or(Label::Green),
+ });
+ }
+ }
+ ctx.seq.markers.sort_by_key(|m| m.start);
+ if ctx.seq.video_tracks.is_empty() {
+ ctx.b.ensure_tracks(&mut ctx.seq, TrackKind::Video, 1);
+ }
+ if ctx.seq.audio_tracks.is_empty() {
+ ctx.b.ensure_tracks(&mut ctx.seq, TrackKind::Audio, 1);
+ }
+ let seq_id = ctx.b.reserve_sequence(&title, ctx.seq.settings.clone(), None);
+ let seq = std::mem::replace(&mut ctx.seq, empty_sequence(Default::default()));
+ ctx.b.put_sequence(seq_id, seq);
+ ctx.b.top.push(seq_id);
+ Ok(ctx.b.finish())
+}
+
+fn source_tc_warning(p: &Parsed) -> bool {
+ p.events.iter().flat_map(|e| &e.lines).any(|l| l.reel != "BL" && l.tcs[0].h > 0)
+}
+
+fn import_event(ctx: &mut Ctx, ev: &Event, report: &mut Report) {
+ let df = ev.df;
+ let m2_for = |reel: &str| ev.m2.iter().find(|(r, _)| r == reel).map(|(_, f)| *f);
+ match ev.lines.as_slice() {
+ [l1, l2] if matches!(l2.trans, Trans::Dissolve | Trans::Wipe(_)) => {
+ let t0 = ctx.rec(l2.tcs[2], df);
+ let t1 = ctx.rec(l2.tcs[3], df);
+ let d = ctx.rate.tick_of(l2.dur);
+ let effect = transition_for(l2.trans, ev.effect.as_deref(), report);
+ let to_black = l2.reel.eq_ignore_ascii_case("BL");
+ let from_black = l1.reel.eq_ignore_ascii_case("BL");
+ // Incoming clip.
+ let mut placed = Vec::new();
+ if !to_black {
+ let file = if ev.files.len() >= 2 { ev.files.get(1) } else { ev.files.first() };
+ let clip = ev.to_clip.as_deref().or(ev.from_clip.as_deref().filter(|_| from_black));
+ let item = ctx.media(&l2.reel, clip, file.map(String::as_str), &l2.chans);
+ let name = clip.unwrap_or(&l2.reel).to_string();
+ let src = ctx.src(l2.tcs[0], df);
+ placed = ctx.lay(l2, item, &name, t0, t1 - t0, src, m2_for(&l2.reel), 0);
+ }
+ // Transition on each channel of the incoming line.
+ let chans: BTreeSet<Ch> = l2.chans.iter().copied().collect();
+ for ch in chans {
+ let (kind, idx) = ctx.track_index(ch, 0);
+ ctx.b.ensure_tracks(&mut ctx.seq, kind, idx + 1);
+ let to = placed.iter().find(|(k, i, _)| *k == kind && *i == idx).map(|p| p.2);
+ let track = &mut ctx.seq.tracks_mut(kind)[idx];
+ let from = if from_black { None } else { track.items.iter().find(|i| i.end() == t0).map(|i| i.id) };
+ let mut align = TransitionAlign::StartAtCut;
+ if to_black {
+ // Fade out: extend the outgoing clip through the transition.
+ if let Some(fid) = from {
+ let blocked = track.items.iter().any(|o| o.id != fid && o.start < t0 + d && o.end() > t0);
+ if let Some(it) = track.item_mut(fid)
+ && !blocked
+ {
+ it.duration += d;
+ }
+ }
+ align = TransitionAlign::EndAtCut;
+ }
+ if from.is_none() && to.is_none() {
+ continue;
+ }
+ let audio = kind == TrackKind::Audio;
+ let mut eff = effect.clone();
+ if audio && eff.def().is_some_and(|d| d.kind != filmcraft_project::EffectKind::AudioTransition) {
+ eff = find_effect("constant_power").map(|d| d.instance()).unwrap_or(eff);
+ }
+ let id = TransitionId(ctx.b.alloc());
+ let track = &mut ctx.seq.tracks_mut(kind)[idx];
+ track.transitions.push(Transition { id, effect: eff, start: t0, duration: d, from, to, align, reverse: false });
+ track.sort();
+ }
+ }
+ [l1, l2] if l1.trans == Trans::KeyBackground && matches!(l2.trans, Trans::Key | Trans::KeyOut) => {
+ report.info("EDL key events imported as background on V1 and foreground on V2");
+ if l2.trans == Trans::KeyOut {
+ report.warn("EDL key-out fade was imported as a plain key");
+ }
+ for (i, l) in [l1, l2].into_iter().enumerate() {
+ lay_cut(ctx, ev, l, i, df, &m2_for(&l.reel));
+ }
+ }
+ lines => {
+ if lines.len() > 1 {
+ report.warn(format!("EDL event {} has {} lines; imported as separate cuts", lines[0].num, lines.len()));
+ }
+ for l in lines {
+ match l.trans {
+ Trans::Cut | Trans::KeyBackground => {}
+ Trans::Key | Trans::KeyOut => {
+ lay_cut(ctx, ev, l, 1, df, &m2_for(&l.reel));
+ continue;
+ }
+ _ => report.warn(format!("EDL event {}: transition without an outgoing source line imported as a cut", l.num)),
+ }
+ lay_cut(ctx, ev, l, 0, df, &m2_for(&l.reel));
+ }
+ }
+ }
+}
+
+fn lay_cut(ctx: &mut Ctx, ev: &Event, l: &Line, video_base: usize, df: bool, m2: &Option<f64>) {
+ if l.reel.eq_ignore_ascii_case("BL") {
+ if video_base > 0 || !l.chans.contains(&Ch::V) {
+ return;
+ }
+ // Black filler on V1 is a gap.
+ return;
+ }
+ let t0 = ctx.rec(l.tcs[2], df);
+ let t1 = ctx.rec(l.tcs[3], df);
+ if t1 <= t0 {
+ return;
+ }
+ let clip = if video_base > 0 { ev.to_clip.as_deref().or(ev.from_clip.as_deref()) } else { ev.from_clip.as_deref() };
+ let file = if video_base > 0 && ev.files.len() > 1 { ev.files.get(1) } else { ev.files.first() };
+ let item = ctx.media(&l.reel, clip, file.map(String::as_str), &l.chans);
+ let name = clip.unwrap_or(&l.reel).to_string();
+ let src = ctx.src(l.tcs[0], df);
+ ctx.lay(l, item, &name, t0, t1 - t0, src, *m2, video_base);
+}
+
+fn transition_for(t: Trans, effect_name: Option<&str>, report: &mut Report) -> filmcraft_project::EffectInstance {
+ if let Some(n) = effect_name {
+ return transition_effect(n, false, report);
+ }
+ match t {
+ Trans::Wipe(code) => {
+ let mut e = transition_effect("wipe", false, report);
+ match code {
+ 1 => {}
+ 2 => {
+ e.params.insert("direction".into(), filmcraft_project::Param::new(ParamValue::Choice(0)));
+ }
+ c => report.warn(format!("SMPTE wipe code {c:03} imported as a plain Wipe")),
+ }
+ e
+ }
+ _ => transition_effect("Cross Dissolve", false, report),
+ }
+}
+
+// ---------------------------------------------------------------------------------------------
+// Export
+// ---------------------------------------------------------------------------------------------
+
+struct OutLine {
+ item: Option<ItemId>,
+ reel: String,
+ chan: String,
+ trans: String,
+ dur: Option<i64>,
+ src: (Tick, Tick),
+ rec: (Tick, Tick),
+}
+
+struct OutEvent {
+ lines: Vec<OutLine>,
+ comments: Vec<String>,
+ m2: Option<(String, f64, Tick)>,
+ /// Merge key for combining linked V/A cut events: (link, item, rec, src, speed bits).
+ merge: Option<(u64, ItemId, Tick, Tick, Tick, u64, bool)>,
+ channels: BTreeSet<Ch>,
+ order: (Tick, u8),
+}
+
+struct Exp<'a> {
+ p: &'a Project,
+ seq: &'a Sequence,
+ rate: FrameRate,
+ df: bool,
+ opts: &'a ExportOptions,
+ reels: HashMap<ItemId, String>,
+ used_reels: HashMap<String, ItemId>,
+}
+
+impl Exp<'_> {
+ fn reel(&mut self, item: ItemId, report: &mut Report) -> String {
+ if let Some(r) = self.reels.get(&item) {
+ return r.clone();
+ }
+ let max = self.opts.edl.reel_len.max(1);
+ let base = crate::common::base_item(self.p, item);
+ let r = if let Some(g) = generator_of(self.p, base) {
+ match g {
+ Generator::BlackVideo => "BL".to_string(),
+ Generator::ColorMatte { .. } => {
+ report.warn("colour mattes exported to EDL as black (BL)");
+ "BL".to_string()
+ }
+ _ => {
+ report.warn("synthetic media exported to EDL as reel AX");
+ "AX".to_string()
+ }
+ }
+ } else {
+ match self.opts.edl.reel_mode {
+ ReelMode::Ax => "AX".to_string(),
+ ReelMode::ClipName => sanitize_reel(&self.p.item(item).map(|i| i.name.clone()).unwrap_or_default(), max),
+ ReelMode::FileName => {
+ let tape = self.p.item(item).and_then(|i| i.metadata.get("Tape Name")).cloned();
+ let src = tape.unwrap_or_else(|| match item_path(self.p, base) {
+ Some(path) => file_stem(path).to_string(),
+ None => self.p.item(item).map(|i| i.name.clone()).unwrap_or_default(),
+ });
+ let mut r = sanitize_reel(&src, max);
+ // Distinct media must get distinct reels.
+ let mut n = 1;
+ while self.used_reels.get(&r).is_some_and(|other| *other != base) {
+ n += 1;
+ let suffix = format!("{n}");
+ let keep = max.saturating_sub(suffix.len());
+ r = format!("{}{}", &sanitize_reel(&src, max)[..keep.min(sanitize_reel(&src, max).len())], suffix);
+ }
+ self.used_reels.insert(r.clone(), base);
+ r
+ }
+ }
+ };
+ self.reels.insert(item, r.clone());
+ r
+ }
+
+ fn tc(&self, frames: i64) -> String {
+ format_timecode_frames(frames, self.rate, self.df)
+ }
+
+ fn src_frames(&self, item: ItemId, t: Tick) -> i64 {
+ let base = crate::common::base_item(self.p, item);
+ let start = self
+ .p
+ .item(base)
+ .and_then(|i| i.as_media())
+ .and_then(|m| m.info.start_timecode.map(|tc| self.rate.frame_at(m.frame_rate().tick_of(tc))))
+ .unwrap_or(0);
+ start + frames_round(self.rate, t)
+ }
+
+ fn rec_frames(&self, t: Tick) -> i64 {
+ self.seq.start_timecode + frames_round(self.rate, t)
+ }
+
+ fn file_comment(&self, item: ItemId) -> Option<String> {
+ let path = item_path(self.p, crate::common::base_item(self.p, item))?;
+ let shown = match &self.opts.relative_to {
+ Some(base) => relative_path(path, base).unwrap_or_else(|| path.to_string()),
+ None => path.to_string(),
+ };
+ Some(shown)
+ }
+}
+
+fn chan_code(set: &BTreeSet<Ch>) -> Option<&'static str> {
+ let v: Vec<Ch> = set.iter().copied().collect();
+ Some(match v.as_slice() {
+ [Ch::V] => "V",
+ [Ch::V, Ch::A(1)] => "B",
+ [Ch::V, Ch::A(1), Ch::A(2)] => "AA/V",
+ [Ch::V, Ch::A(2)] => "A2/V",
+ [Ch::A(1)] => "A",
+ [Ch::A(2)] => "A2",
+ [Ch::A(1), Ch::A(2)] => "AA",
+ [Ch::A(3)] => "A3",
+ [Ch::A(4)] => "A4",
+ _ => return None,
+ })
+}
+
+fn signed_scaled(d: Tick, speed: f64) -> Tick {
+ if d.0 < 0 { -scaled(-d, speed) } else { scaled(d, speed) }
+}
+
+pub(crate) fn export(p: &Project, seq_id: ItemId, opts: &ExportOptions, report: &mut Report) -> Result<String> {
+ let seq = p.sequence(seq_id).ok_or(crate::Error::NoSequence(seq_id))?;
+ let rate = seq.settings.frame_rate;
+ let df = seq.settings.drop_frame && rate.supports_drop_frame();
+ let mut x = Exp { p, seq, rate, df, opts, reels: HashMap::new(), used_reels: HashMap::new() };
+ let title = opts.name.clone().or_else(|| p.item(seq_id).map(|i| i.name.clone())).unwrap_or_default();
+
+ let mut events: Vec<OutEvent> = Vec::new();
+ let mut tracks: Vec<(TrackKind, usize, Ch)> = Vec::new();
+ if let Some(v) = opts.edl.video_track
+ && v < seq.video_tracks.len()
+ {
+ tracks.push((TrackKind::Video, v, Ch::V));
+ }
+ for &a in &opts.edl.audio_tracks {
+ if a < seq.audio_tracks.len() {
+ if a >= 4 {
+ report.warn("EDL export supports at most four audio channels; A5 and above were skipped");
+ continue;
+ }
+ tracks.push((TrackKind::Audio, a, Ch::A(a + 1)));
+ }
+ }
+ if seq.video_tracks.len() > 1
+ && opts.edl.video_track.is_some()
+ && seq.video_tracks.iter().enumerate().any(|(i, t)| Some(i) != opts.edl.video_track && !t.items.is_empty())
+ {
+ report.info("EDLs hold one video track; other video tracks were not exported (use export_edl_per_track)");
+ }
+
+ for (kind, idx, ch) in tracks {
+ let track = &seq.tracks(kind)[idx];
+ let chs = match ch {
+ Ch::V => "V".to_string(),
+ Ch::A(1) => "A".to_string(),
+ Ch::A(n) => format!("A{n}"),
+ };
+ for it in &track.items {
+ if !on_frame(rate, it.start) || !on_frame(rate, it.duration) {
+ report.warn("sub-frame clip positions were rounded to frames in the EDL");
+ }
+ if matches!(p.item(it.item).map(|i| &i.kind), Some(ItemKind::Sequence(_))) {
+ report.warn("nested sequences are exported to EDL as a single source (reel AX)");
+ }
+ if !it.enabled {
+ report.warn("disabled clips are exported to EDL as normal events");
+ }
+ let tr_in = track.transitions.iter().find(|t| t.to == Some(it.id));
+ let tr_out = track.transitions.iter().find(|t| t.from == Some(it.id));
+ let reel = x.reel(it.item, report);
+ let mut rec0 = it.start;
+ let mut rec1 = it.end();
+ let mut src0 = it.source_in;
+ if let Some(t) = tr_out {
+ rec1 = rec1.min(t.start).max(rec0);
+ }
+ let speed = if it.frame_hold.is_some() { 0.0 } else { it.speed };
+ let mut lines = Vec::new();
+ let mut comments = Vec::new();
+ let mut trans_name = None;
+ if let Some(t) = tr_in {
+ let s = t.start;
+ let (l1_reel, l1_src, from_name, from_item) = match t.from.and_then(|f| track.item(f)) {
+ Some(a) => {
+ let r = x.reel(a.item, report);
+ (r, a.source_in + signed_scaled(s - a.start, a.speed), Some(a.name.clone()), Some(a.item))
+ }
+ None => ("BL".to_string(), Tick::ZERO, None, None),
+ };
+ lines.push(OutLine { item: from_item, reel: l1_reel, chan: chs.clone(), trans: "C".into(), dur: None, src: (l1_src, l1_src), rec: (s, s) });
+ src0 = match it.frame_hold {
+ Some(h) => h,
+ None => it.source_in + signed_scaled(s - it.start, it.speed),
+ };
+ if src0 < Tick::ZERO {
+ report.warn("a transition needs more source media than available; its source in was clamped to 0");
+ src0 = Tick::ZERO;
+ }
+ rec0 = s;
+ let (code, name) = edl_transition(&t.effect, report);
+ trans_name = Some(name);
+ let src_end = src0 + (rec1 - rec0);
+ lines.push(OutLine {
+ item: Some(it.item),
+ reel: reel.clone(),
+ chan: chs.clone(),
+ trans: code,
+ dur: Some(frames_round(rate, t.duration)),
+ src: (src0, src_end),
+ rec: (rec0, rec1),
+ });
+ if opts.edl.clip_names {
+ if let Some(n) = from_name {
+ comments.push(format!("FROM CLIP NAME: {n}"));
+ }
+ comments.push(format!("TO CLIP NAME: {}", it.name));
+ }
+ if opts.edl.source_files {
+ if let Some(f) = from_item.and_then(|fi| x.file_comment(fi)) {
+ comments.push(format!("SOURCE FILE: {f}"));
+ }
+ if let Some(f) = x.file_comment(it.item) {
+ comments.push(format!("SOURCE FILE: {f}"));
+ }
+ }
+ } else {
+ if it.frame_hold.is_some() {
+ src0 = it.frame_hold.unwrap_or(it.source_in);
+ }
+ lines.push(OutLine {
+ item: Some(it.item),
+ reel: reel.clone(),
+ chan: chs.clone(),
+ trans: "C".into(),
+ dur: None,
+ src: (src0, src0 + (rec1 - rec0)),
+ rec: (rec0, rec1),
+ });
+ if opts.edl.clip_names {
+ comments.push(format!("FROM CLIP NAME: {}", it.name));
+ }
+ if opts.edl.source_files
+ && let Some(f) = x.file_comment(it.item)
+ {
+ comments.push(format!("SOURCE FILE: {f}"));
+ }
+ }
+ if let (true, Some(n)) = (opts.edl.effect_names, trans_name) {
+ comments.push(format!("EFFECT NAME: {n}"));
+ }
+ let m2 = if speed != 1.0 || it.reverse {
+ let fps = if it.frame_hold.is_some() { 0.0 } else { speed * rate.timecode_base() as f64 * if it.reverse { -1.0 } else { 1.0 } };
+ Some((reel.clone(), fps, src0))
+ } else {
+ None
+ };
+ if let Some(ef) = crate::common::standard_effects(it).next() {
+ report.warn(format!("effect \"{}\" cannot be represented in an EDL", ef.def().map(|d| d.name).unwrap_or(&ef.effect)));
+ }
+ let simple = tr_in.is_none() && m2.is_none();
+ events.push(OutEvent {
+ merge: if simple { it.link.map(|l| (l, it.item, rec0, rec1, src0, 0, it.enabled)) } else { None },
+ lines,
+ comments,
+ m2,
+ channels: [ch].into_iter().collect(),
+ order: (rec0, if kind == TrackKind::Video { 0 } else { 1 + idx as u8 }),
+ });
+ // Fade to black after this clip.
+ if let Some(t) = tr_out.filter(|t| t.to.is_none()) {
+ let s = t.start;
+ let a_src = it.source_in + signed_scaled(s - it.start, it.speed);
+ let (code, name) = edl_transition(&t.effect, report);
+ let d = t.duration;
+ let mut comments = Vec::new();
+ if opts.edl.clip_names {
+ comments.push(format!("FROM CLIP NAME: {}", it.name));
+ }
+ if opts.edl.effect_names {
+ comments.push(format!("EFFECT NAME: {name}"));
+ }
+ events.push(OutEvent {
+ lines: vec![
+ OutLine { item: Some(it.item), reel: reel.clone(), chan: chs.clone(), trans: "C".into(), dur: None, src: (a_src, a_src), rec: (s, s) },
+ OutLine {
+ item: None,
+ reel: "BL".into(),
+ chan: chs.clone(),
+ trans: code,
+ dur: Some(frames_round(rate, d)),
+ src: (Tick::ZERO, d),
+ rec: (s, s + d),
+ },
+ ],
+ comments,
+ m2: None,
+ merge: None,
+ channels: [ch].into_iter().collect(),
+ order: (s, if kind == TrackKind::Video { 0 } else { 1 + idx as u8 }),
+ });
+ }
+ }
+ }
+
+ // Merge identical linked cut events across channels (V + A → B, A + A2 → AA …).
+ let mut merged: Vec<OutEvent> = Vec::new();
+ for ev in events {
+ if let Some(key) = ev.merge
+ && let Some(prev) = merged.iter_mut().find(|m| m.merge == Some(key))
+ {
+ let mut set = prev.channels.clone();
+ set.extend(ev.channels.iter().copied());
+ if let Some(code) = chan_code(&set) {
+ prev.channels = set;
+ for l in &mut prev.lines {
+ l.chan = code.to_string();
+ }
+ continue;
+ }
+ }
+ merged.push(ev);
+ }
+ merged.sort_by_key(|e| e.order);
+
+ let mut out = String::new();
+ out.push_str(&format!("TITLE: {title}\n"));
+ out.push_str(if df { "FCM: DROP FRAME\n" } else { "FCM: NON-DROP FRAME\n" });
+ let w = opts.edl.reel_len.max(8);
+ let mut markers: Vec<&Marker> = if opts.edl.markers { seq.markers.iter().collect() } else { Vec::new() };
+ markers.sort_by_key(|m| m.start);
+ let mut mi = 0;
+ let n_events = merged.len();
+ for (i, ev) in merged.iter().enumerate() {
+ out.push('\n');
+ let num = i + 1;
+ for l in &ev.lines {
+ let dur = l.dur.map(|d| format!("{d:03}")).unwrap_or_default();
+ out.push_str(&format!(
+ "{num:03} {:<w$} {:<5} {:<4} {:>3} {} {} {} {}\n",
+ l.reel,
+ l.chan,
+ l.trans,
+ dur,
+ x.tc(src_tc(&x, l, l.src.0)),
+ x.tc(src_tc(&x, l, l.src.1)),
+ x.tc(x.rec_frames(l.rec.0)),
+ x.tc(x.rec_frames(l.rec.1)),
+ ));
+ }
+ if let Some((reel, fps, entry)) = &ev.m2 {
+ let l = ev.lines.last().unwrap();
+ let sign = if *fps < 0.0 { "-" } else { "" };
+ out.push_str(&format!("M2 {:<w$} {sign}{:05.1} {}\n", reel, fps.abs(), x.tc(src_tc(&x, l, *entry))));
+ }
+ for c in &ev.comments {
+ out.push_str(&format!("* {c}\n"));
+ }
+ // Markers up to the end of this event (all remaining after the last one).
+ let end = ev.lines.last().map(|l| l.rec.1).unwrap_or(Tick::ZERO);
+ while mi < markers.len() && (markers[mi].start < end || i + 1 == n_events) {
+ let m = markers[mi];
+ out.push_str(&format!("* LOC: {} {:<7} {}\n", x.tc(x.rec_frames(m.start)), color_word(m.color), m.name));
+ mi += 1;
+ }
+ }
+ Ok(out)
+}
+
+/// Source frame for a line position (BL lines are plain frame counts from 0).
+fn src_tc(x: &Exp, l: &OutLine, t: Tick) -> i64 {
+ match l.item {
+ Some(i) if l.reel != "BL" => x.src_frames(i, t),
+ _ => frames_round(x.rate, t),
+ }
+}
+
+/// EDL transition code and effect name.
+fn edl_transition(e: &filmcraft_project::EffectInstance, report: &mut Report) -> (String, String) {
+ let name = transition_name(e).to_ascii_uppercase();
+ match e.effect.as_str() {
+ "cross_dissolve" | "constant_power" | "constant_gain" | "exponential_fade" | "film_dissolve" | "additive_dissolve" | "non_additive_dissolve" => {
+ ("D".into(), name)
+ }
+ "wipe" => {
+ let dir = e.param("direction").and_then(|p| p.value.as_f64()).unwrap_or(3.0) as u32;
+ match dir {
+ 0 => ("W002".into(), name),
+ 3 => ("W001".into(), name),
+ _ => {
+ report.info("wipe direction approximated by SMPTE wipe 001 in the EDL");
+ ("W001".into(), name)
+ }
+ }
+ }
+ _ => {
+ report.info(format!("transition \"{}\" written as a dissolve with an EFFECT NAME comment", transition_name(e)));
+ ("D".into(), name)
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn channels() {
+ assert_eq!(parse_channels("B"), Some(vec![Ch::V, Ch::A(1)]));
+ assert_eq!(parse_channels("AA/V"), Some(vec![Ch::A(1), Ch::A(2), Ch::V]));
+ assert_eq!(parse_channels("A4"), Some(vec![Ch::A(4)]));
+ assert_eq!(parse_channels("X"), None);
+ }
+
+ #[test]
+ fn event_lines() {
+ let l = parse_event_line("002 REEL_B V D 030 02:00:10:00 02:00:15:00 01:00:05:00 01:00:10:00").unwrap();
+ assert_eq!(l.trans, Trans::Dissolve);
+ assert_eq!(l.dur, 30);
+ let k = parse_event_line("003 KEY V K B 00:00:00:00 00:00:01:00 01:00:00:00 01:00:01:00").unwrap();
+ assert_eq!(k.trans, Trans::KeyBackground);
+ let w = parse_event_line("004 R V W001 015 00:00:00:00 00:00:01:00 01:00:00:00 01:00:01:00").unwrap();
+ assert_eq!(w.trans, Trans::Wipe(1));
+ assert!(parse_event_line("* comment").is_none());
+ assert!(parse_tc("01;00;00;02").unwrap().df);
+ }
+}
diff --git a/crates/interchange/src/fcp7.rs b/crates/interchange/src/fcp7.rs
new file mode 100644
index 000000000..59810b9f4
--- /dev/null
+++ b/crates/interchange/src/fcp7.rs
@@ -0,0 +1,13 @@
+//! (in progress)
+
+use filmcraft_project::{ItemId, Project};
+
+use crate::{Error, ExportOptions, ImportOptions, Imported, Report, Result};
+
+pub(crate) fn import(_text: &str, _opts: &ImportOptions, _report: &mut Report) -> Result<Imported> {
+ Err(Error::Other("not implemented".into()))
+}
+
+pub(crate) fn export(_p: &Project, _seq: ItemId, _opts: &ExportOptions, _report: &mut Report) -> Result<String> {
+ Err(Error::Other("not implemented".into()))
+}
diff --git a/crates/interchange/src/fcpxml.rs b/crates/interchange/src/fcpxml.rs
new file mode 100644
index 000000000..59810b9f4
--- /dev/null
+++ b/crates/interchange/src/fcpxml.rs
@@ -0,0 +1,13 @@
+//! (in progress)
+
+use filmcraft_project::{ItemId, Project};
+
+use crate::{Error, ExportOptions, ImportOptions, Imported, Report, Result};
+
+pub(crate) fn import(_text: &str, _opts: &ImportOptions, _report: &mut Report) -> Result<Imported> {
+ Err(Error::Other("not implemented".into()))
+}
+
+pub(crate) fn export(_p: &Project, _seq: ItemId, _opts: &ExportOptions, _report: &mut Report) -> Result<String> {
+ Err(Error::Other("not implemented".into()))
+}
diff --git a/crates/interchange/src/lib.rs b/crates/interchange/src/lib.rs
new file mode 100644
index 000000000..5e6bc9c24
--- /dev/null
+++ b/crates/interchange/src/lib.rs
@@ -0,0 +1,489 @@
+//! Timeline interchange for FilmCraft: import and export of
+//!
+//! - **CMX 3600 EDL** (`.edl`) with the common comment extensions (`* FROM CLIP NAME:`,
+//! `* SOURCE FILE:`, `* LOC:`), `M2` speed lines, dissolves, wipes, key events, audio channels and
+//! drop-frame timecode ([`edl`]);
+//! - **Final Cut Pro 7 XML** (`xmeml` v4/v5, the dialect Premiere Pro reads and writes) ([`fcp7`]);
+//! - **FCPXML** 1.9–1.11 ([`fcpxml`]);
+//! - **OpenTimelineIO** JSON (`.otio`) ([`otio`]).
+//!
+//! Every importer returns a standalone [`Project`] fragment ([`Imported`]) that the caller merges into
+//! the open project with [`merge_into`], plus a [`Report`] of everything that could not be represented
+//! (unmapped effects, speed ramps, …). Exporters take a sequence of a project and never fail on
+//! unsupported features either; they record them in the report instead.
+//!
+//! All time math is exact on [`filmcraft_time::Tick`]s: document frame counts, SMPTE timecode and
+//! rational seconds (`1001/24000s`) map onto ticks without rounding for every broadcast rate.
+//!
+//! This crate is L2: it does no file I/O. Media references are strings (absolute paths, or paths
+//! resolved against the `base_dir` passed to the importer); the engine probes/relinks them.
+
+pub mod edl;
+pub mod fcp7;
+pub mod fcpxml;
+pub mod otio;
+
+#[allow(dead_code)] // helpers shared by importers still being written
+mod common;
+#[allow(dead_code)]
+mod xml;
+
+use std::collections::{BTreeMap, HashMap};
+
+use filmcraft_project::{BinEntry, BinId, ClipId, ItemId, ItemKind, MarkerId, Project, TrackId, TransitionId};
+use filmcraft_time::{FrameRate, Tick};
+use serde::{Deserialize, Serialize};
+
+pub use common::{file_url_to_path, path_to_file_url, resolve_path};
+
+/// An interchange format.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
+pub enum Format {
+ /// CMX 3600 edit decision list.
+ Edl,
+ /// Final Cut Pro 7 XML interchange (`xmeml`), as read/written by Premiere Pro.
+ Fcp7Xml,
+ /// Final Cut Pro X XML (1.9–1.11).
+ Fcpxml,
+ /// OpenTimelineIO JSON.
+ Otio,
+}
+
+impl Format {
+ pub const ALL: [Format; 4] = [Format::Edl, Format::Fcp7Xml, Format::Fcpxml, Format::Otio];
+
+ pub fn name(self) -> &'static str {
+ match self {
+ Format::Edl => "CMX 3600 EDL",
+ Format::Fcp7Xml => "Final Cut Pro XML",
+ Format::Fcpxml => "FCPXML",
+ Format::Otio => "OpenTimelineIO",
+ }
+ }
+
+ /// Default file extension (without the dot).
+ pub fn extension(self) -> &'static str {
+ match self {
+ Format::Edl => "edl",
+ Format::Fcp7Xml => "xml",
+ Format::Fcpxml => "fcpxml",
+ Format::Otio => "otio",
+ }
+ }
+
+ /// Format for a file extension (case-insensitive, with or without the dot). `.xml` is ambiguous
+ /// between xmeml and FCPXML; use [`detect`] when the bytes are available.
+ pub fn from_extension(ext: &str) -> Option<Format> {
+ match ext.trim_start_matches('.').to_ascii_lowercase().as_str() {
+ "edl" => Some(Format::Edl),
+ "xml" => Some(Format::Fcp7Xml),
+ "fcpxml" | "fcpxmld" => Some(Format::Fcpxml),
+ "otio" => Some(Format::Otio),
+ _ => None,
+ }
+ }
+}
+
+/// Sniff the format of a document from its bytes, using the file extension as a hint.
+pub fn detect(bytes: &[u8], extension: Option<&str>) -> Option<Format> {
+ let head = String::from_utf8_lossy(&bytes[..bytes.len().min(4096)]);
+ let head = head.trim_start_matches('\u{feff}').trim_start();
+ if head.starts_with('<') {
+ if head.contains("<xmeml") {
+ return Some(Format::Fcp7Xml);
+ }
+ if head.contains("<fcpxml") {
+ return Some(Format::Fcpxml);
+ }
+ return extension.and_then(Format::from_extension).filter(|f| matches!(f, Format::Fcp7Xml | Format::Fcpxml));
+ }
+ if head.starts_with('{') {
+ if head.contains("\"OTIO_SCHEMA\"") {
+ return Some(Format::Otio);
+ }
+ return extension.and_then(Format::from_extension).filter(|f| *f == Format::Otio);
+ }
+ if edl::looks_like_edl(head) {
+ return Some(Format::Edl);
+ }
+ extension.and_then(Format::from_extension).filter(|f| *f == Format::Edl)
+}
+
+/// Error from an importer or exporter. Unsupported *features* never error; they go in the [`Report`].
+#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
+pub enum Error {
+ #[error("{format} parse error: {message}")]
+ Parse { format: &'static str, message: String },
+ #[error("the document contains no timeline")]
+ Empty,
+ #[error("no sequence {0:?} in the project")]
+ NoSequence(ItemId),
+ #[error("{0}")]
+ Other(String),
+}
+
+impl Error {
+ pub(crate) fn parse(format: Format, message: impl Into<String>) -> Error {
+ Error::Parse { format: format.name(), message: message.into() }
+ }
+}
+
+pub type Result<T> = std::result::Result<T, Error>;
+
+/// Severity of a report entry.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
+pub enum Level {
+ /// Informational (an assumption the importer made).
+ Info,
+ /// Something was dropped or approximated.
+ Warning,
+}
+
+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
+pub struct ReportEntry {
+ pub level: Level,
+ pub message: String,
+ /// How many times this message occurred.
+ pub count: u32,
+}
+
+/// What an import/export could not represent exactly. Identical messages are merged with a count.
+#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+pub struct Report {
+ pub entries: Vec<ReportEntry>,
+}
+
+impl Report {
+ pub fn push(&mut self, level: Level, message: impl Into<String>) {
+ let message = message.into();
+ if let Some(e) = self.entries.iter_mut().find(|e| e.level == level && e.message == message) {
+ e.count += 1;
+ } else {
+ self.entries.push(ReportEntry { level, message, count: 1 });
+ }
+ }
+ pub fn warn(&mut self, message: impl Into<String>) {
+ self.push(Level::Warning, message);
+ }
+ pub fn info(&mut self, message: impl Into<String>) {
+ self.push(Level::Info, message);
+ }
+ pub fn is_empty(&self) -> bool {
+ self.entries.is_empty()
+ }
+ pub fn warnings(&self) -> impl Iterator<Item = &ReportEntry> {
+ self.entries.iter().filter(|e| e.level == Level::Warning)
+ }
+ pub fn has_warnings(&self) -> bool {
+ self.warnings().next().is_some()
+ }
+ /// Whether any entry contains `needle` (case-insensitive).
+ pub fn mentions(&self, needle: &str) -> bool {
+ let n = needle.to_ascii_lowercase();
+ self.entries.iter().any(|e| e.message.to_ascii_lowercase().contains(&n))
+ }
+}
+
+impl std::fmt::Display for Report {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ for e in &self.entries {
+ let lvl = match e.level {
+ Level::Info => "info",
+ Level::Warning => "warning",
+ };
+ if e.count > 1 {
+ writeln!(f, "{lvl}: {} (×{})", e.message, e.count)?;
+ } else {
+ writeln!(f, "{lvl}: {}", e.message)?;
+ }
+ }
+ Ok(())
+ }
+}
+
+/// The result of an import: a standalone project fragment.
+#[derive(Clone, Debug, PartialEq)]
+pub struct Imported {
+ /// Bins, media items and sequences read from the document (ids local to this fragment).
+ pub project: Project,
+ /// Top-level sequences, in document order (nested sequences are items too but not listed here).
+ pub sequences: Vec<ItemId>,
+}
+
+/// Import options beyond the defaults of [`import`].
+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
+pub struct ImportOptions {
+ /// Directory relative media paths are resolved against (normally the document's directory).
+ pub base_dir: Option<String>,
+ /// EDLs carry no frame rate: the rate to interpret timecode at (default: guessed, 29.97 for
+ /// drop-frame lists, else 24 unless frame fields show otherwise).
+ pub edl_frame_rate: Option<FrameRate>,
+ /// Name for documents without a title (EDL without `TITLE:`).
+ pub name: Option<String>,
+}
+
+/// Import a document. `base_dir` resolves relative media paths.
+pub fn import(bytes: &[u8], format: Format, base_dir: Option<&str>) -> Result<(Imported, Report)> {
+ import_with(bytes, format, &ImportOptions { base_dir: base_dir.map(str::to_string), ..Default::default() })
+}
+
+/// Import a document with explicit options.
+pub fn import_with(bytes: &[u8], format: Format, opts: &ImportOptions) -> Result<(Imported, Report)> {
+ let text = decode_text(bytes);
+ let mut report = Report::default();
+ let imported = match format {
+ Format::Edl => edl::import(&text, opts, &mut report)?,
+ Format::Fcp7Xml => fcp7::import(&text, opts, &mut report)?,
+ Format::Fcpxml => fcpxml::import(&text, opts, &mut report)?,
+ Format::Otio => otio::import(&text, opts, &mut report)?,
+ };
+ Ok((imported, report))
+}
+
+fn decode_text(bytes: &[u8]) -> String {
+ // UTF-8 (with or without BOM); fall back to Latin-1 for old EDLs.
+ let b = bytes.strip_prefix(&[0xef, 0xbb, 0xbf]).unwrap_or(bytes);
+ match std::str::from_utf8(b) {
+ Ok(s) => s.to_string(),
+ Err(_) => b.iter().map(|&c| c as char).collect(),
+ }
+}
+
+/// How EDL reel names are derived from media.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+pub enum ReelMode {
+ /// From the media file name (without extension), sanitised and truncated.
+ #[default]
+ FileName,
+ /// From the clip name.
+ ClipName,
+ /// Every event uses reel `AX` (clip names/source files identify the media in comments).
+ Ax,
+}
+
+/// EDL export options.
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct EdlOptions {
+ /// Video track to export (0 = V1). `None` exports audio only.
+ pub video_track: Option<usize>,
+ /// Audio tracks to include (0 = A1); at most four (A, A2, A3, A4).
+ pub audio_tracks: Vec<usize>,
+ pub reel_mode: ReelMode,
+ /// Maximum reel name length: 8 (strict CMX 3600) or 32 (extended).
+ pub reel_len: usize,
+ /// Write `* FROM CLIP NAME:` / `* TO CLIP NAME:` comments.
+ pub clip_names: bool,
+ /// Write `* SOURCE FILE:` comments.
+ pub source_files: bool,
+ /// Write `* EFFECT NAME:` comments for transitions.
+ pub effect_names: bool,
+ /// Write sequence markers as `* LOC:` comments.
+ pub markers: bool,
+}
+
+impl Default for EdlOptions {
+ fn default() -> Self {
+ Self {
+ video_track: Some(0),
+ audio_tracks: vec![0, 1, 2, 3],
+ reel_mode: ReelMode::FileName,
+ reel_len: 8,
+ clip_names: true,
+ source_files: true,
+ effect_names: true,
+ markers: true,
+ }
+ }
+}
+
+/// FCPXML document version to write.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+pub enum FcpxmlVersion {
+ V1_9,
+ #[default]
+ V1_10,
+ V1_11,
+}
+
+impl FcpxmlVersion {
+ pub fn as_str(self) -> &'static str {
+ match self {
+ FcpxmlVersion::V1_9 => "1.9",
+ FcpxmlVersion::V1_10 => "1.10",
+ FcpxmlVersion::V1_11 => "1.11",
+ }
+ }
+}
+
+/// Export options.
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct ExportOptions {
+ /// Write media paths relative to this directory where possible (EDL `SOURCE FILE`, OTIO
+ /// `target_url`). XML formats always use absolute `file://` URLs for absolute paths.
+ pub relative_to: Option<String>,
+ /// Document/title name (default: the sequence name).
+ pub name: Option<String>,
+ pub edl: EdlOptions,
+ /// `xmeml` version attribute (4 or 5).
+ pub xmeml_version: u32,
+ pub fcpxml_version: FcpxmlVersion,
+}
+
+impl Default for ExportOptions {
+ fn default() -> Self {
+ Self { relative_to: None, name: None, edl: EdlOptions::default(), xmeml_version: 4, fcpxml_version: FcpxmlVersion::default() }
+ }
+}
+
+/// Export `sequence` of `project` (and the media/nested sequences it uses).
+pub fn export(project: &Project, sequence: ItemId, format: Format, opts: &ExportOptions) -> Result<(Vec<u8>, Report)> {
+ if project.sequence(sequence).is_none() {
+ return Err(Error::NoSequence(sequence));
+ }
+ let mut report = Report::default();
+ let text = match format {
+ Format::Edl => edl::export(project, sequence, opts, &mut report)?,
+ Format::Fcp7Xml => fcp7::export(project, sequence, opts, &mut report)?,
+ Format::Fcpxml => fcpxml::export(project, sequence, opts, &mut report)?,
+ Format::Otio => otio::export(project, sequence, opts, &mut report)?,
+ };
+ Ok((text.into_bytes(), report))
+}
+
+/// Premiere's "Export ▸ EDL" with one list per video track: returns `(suggested suffix, document)`
+/// for every non-empty video track (`"V1"`, `"V2"`, …). Audio tracks go in the V1 list.
+pub fn export_edl_per_track(project: &Project, sequence: ItemId, opts: &ExportOptions) -> Result<(Vec<(String, Vec<u8>)>, Report)> {
+ let seq = project.sequence(sequence).ok_or(Error::NoSequence(sequence))?;
+ let mut report = Report::default();
+ let mut out = Vec::new();
+ for (i, t) in seq.video_tracks.iter().enumerate() {
+ if t.items.is_empty() {
+ continue;
+ }
+ let mut o = opts.clone();
+ o.edl.video_track = Some(i);
+ if !out.is_empty() {
+ o.edl.audio_tracks.clear();
+ }
+ let text = edl::export(project, sequence, &o, &mut report)?;
+ out.push((format!("V{}", i + 1), text.into_bytes()));
+ }
+ if out.is_empty() {
+ let text = edl::export(project, sequence, opts, &mut report)?;
+ out.push(("V1".into(), text.into_bytes()));
+ }
+ Ok((out, report))
+}
+
+/// Merge an imported fragment into `target`, re-allocating every id so nothing collides. The
+/// fragment's root children go into `bin` (or the root). Returns the new ids of the fragment's
+/// top-level sequences.
+pub fn merge_into(target: &mut Project, fragment: Imported, bin: Option<BinId>) -> Vec<ItemId> {
+ let Imported { project: frag, sequences } = fragment;
+ let mut items: HashMap<ItemId, ItemId> = HashMap::new();
+ for id in frag.items.keys() {
+ items.insert(*id, ItemId(target.alloc_id()));
+ }
+ let mut map_u64: HashMap<u64, u64> = HashMap::new();
+ let mut fresh = |target: &mut Project, old: u64| *map_u64.entry(old).or_insert_with(|| target.alloc_id());
+
+ let mut new_items: BTreeMap<ItemId, filmcraft_project::ProjectItem> = BTreeMap::new();
+ for (old, mut it) in frag.items {
+ it.id = items[&old];
+ it.created = it.id.0;
+ match &mut it.kind {
+ ItemKind::Sequence(seq) => {
+ for m in &mut seq.markers {
+ m.id = MarkerId(target.alloc_id());
+ }
+ for t in seq.all_tracks_mut() {
+ t.id = TrackId(target.alloc_id());
+ let mut clips: HashMap<ClipId, ClipId> = HashMap::new();
+ for ti in &mut t.items {
+ let n = ClipId(target.alloc_id());
+ clips.insert(ti.id, n);
+ ti.id = n;
+ if let Some(i) = items.get(&ti.item) {
+ ti.item = *i;
+ }
+ ti.link = ti.link.map(|l| fresh(target, l | (1 << 62)));
+ ti.group = ti.group.map(|g| fresh(target, g | (1 << 61)));
+ for m in &mut ti.markers {
+ m.id = MarkerId(target.alloc_id());
+ }
+ }
+ for tr in &mut t.transitions {
+ tr.id = TransitionId(target.alloc_id());
+ tr.from = tr.from.and_then(|c| clips.get(&c).copied());
+ tr.to = tr.to.and_then(|c| clips.get(&c).copied());
+ }
+ }
+ }
+ ItemKind::Subclip { parent, .. } => {
+ if let Some(p) = items.get(parent) {
+ *parent = *p;
+ }
+ }
+ ItemKind::Media(m) => {
+ for mk in &mut m.markers {
+ mk.id = MarkerId(target.alloc_id());
+ }
+ }
+ ItemKind::AdjustmentLayer { .. } => {}
+ }
+ new_items.insert(it.id, it);
+ }
+ fn remap_bin(b: &mut filmcraft_project::Bin, items: &HashMap<ItemId, ItemId>, target: &mut Project) {
+ for c in &mut b.children {
+ match c {
+ BinEntry::Item(i) => *i = items[i],
+ BinEntry::Bin(sub) => {
+ sub.id = BinId(target.alloc_id());
+ remap_bin(sub, items, target);
+ }
+ }
+ }
+ }
+ let mut root = frag.root;
+ remap_bin(&mut root, &items, target);
+ target.items.extend(new_items);
+ let dest = match bin.and_then(|b| target.root.find_bin_mut(b)) {
+ Some(b) => b,
+ None => &mut target.root,
+ };
+ dest.children.extend(root.children);
+ sequences.iter().filter_map(|s| items.get(s).copied()).collect()
+}
+
+/// After probing a media file imported from an EDL (whose source times are absolute timecode),
+/// shift every use of `item` so source times become media-relative: subtracts the media's start
+/// timecode (`start_tc_frames` at `rate`) from `source_in`, frame holds and keyframes.
+pub fn rebase_source_timecode(project: &mut Project, item: ItemId, start_tc_frames: i64, rate: FrameRate) {
+ let off = rate.tick_of(start_tc_frames);
+ if off == Tick::ZERO {
+ return;
+ }
+ for it in project.items.values_mut() {
+ if let ItemKind::Sequence(seq) = &mut it.kind {
+ for t in seq.all_tracks_mut() {
+ for ti in t.items.iter_mut().filter(|ti| ti.item == item) {
+ ti.source_in -= off;
+ if let Some(h) = &mut ti.frame_hold {
+ *h -= off;
+ }
+ for e in &mut ti.effects {
+ for p in e.params.values_mut() {
+ for k in &mut p.keyframes {
+ k.time -= off;
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ if let Some(m) = project.item_mut(item).and_then(|i| i.as_media_mut()) {
+ m.info.start_timecode = Some(start_tc_frames);
+ m.markers.iter_mut().for_each(|mk| mk.start -= off);
+ }
+}
diff --git a/crates/interchange/src/otio.rs b/crates/interchange/src/otio.rs
new file mode 100644
index 000000000..59810b9f4
--- /dev/null
+++ b/crates/interchange/src/otio.rs
@@ -0,0 +1,13 @@
+//! (in progress)
+
+use filmcraft_project::{ItemId, Project};
+
+use crate::{Error, ExportOptions, ImportOptions, Imported, Report, Result};
+
+pub(crate) fn import(_text: &str, _opts: &ImportOptions, _report: &mut Report) -> Result<Imported> {
+ Err(Error::Other("not implemented".into()))
+}
+
+pub(crate) fn export(_p: &Project, _seq: ItemId, _opts: &ExportOptions, _report: &mut Report) -> Result<String> {
+ Err(Error::Other("not implemented".into()))
+}
diff --git a/crates/interchange/src/xml.rs b/crates/interchange/src/xml.rs
new file mode 100644
index 000000000..9286bcb34
--- /dev/null
+++ b/crates/interchange/src/xml.rs
@@ -0,0 +1,169 @@
+//! Minimal XML writer and read helpers over `roxmltree`.
+
+use std::fmt::Write as _;
+
+use roxmltree::Node;
+
+pub(crate) fn escape(s: &str) -> String {
+ let mut o = String::with_capacity(s.len());
+ for c in s.chars() {
+ match c {
+ '&' => o.push_str("&amp;"),
+ '<' => o.push_str("&lt;"),
+ '>' => o.push_str("&gt;"),
+ '"' => o.push_str("&quot;"),
+ '\'' => o.push_str("&apos;"),
+ c if (c as u32) < 0x20 && !matches!(c, '\n' | '\r' | '\t') => {}
+ c => o.push(c),
+ }
+ }
+ o
+}
+
+/// Pretty-printing XML writer (two-space indent, one element per line).
+pub(crate) struct XmlWriter {
+ out: String,
+ stack: Vec<String>,
+}
+
+impl XmlWriter {
+ pub fn new(doctype: Option<&str>) -> Self {
+ let mut out = String::from("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
+ if let Some(d) = doctype {
+ let _ = writeln!(out, "<!DOCTYPE {d}>");
+ }
+ Self { out, stack: Vec::new() }
+ }
+
+ fn indent(&mut self) {
+ for _ in 0..self.stack.len() {
+ self.out.push_str(" ");
+ }
+ }
+
+ fn start_tag(&mut self, name: &str, attrs: &[(&str, &str)]) {
+ self.indent();
+ self.out.push('<');
+ self.out.push_str(name);
+ for (k, v) in attrs {
+ let _ = write!(self.out, " {k}=\"{}\"", escape(v));
+ }
+ }
+
+ pub fn open(&mut self, name: &str, attrs: &[(&str, &str)]) {
+ self.start_tag(name, attrs);
+ self.out.push_str(">\n");
+ self.stack.push(name.to_string());
+ }
+
+ pub fn close(&mut self) {
+ let name = self.stack.pop().expect("close without open");
+ self.indent();
+ let _ = writeln!(self.out, "</{name}>");
+ }
+
+ pub fn empty(&mut self, name: &str, attrs: &[(&str, &str)]) {
+ self.start_tag(name, attrs);
+ self.out.push_str("/>\n");
+ }
+
+ /// `<name attrs>value</name>`.
+ pub fn text_attrs(&mut self, name: &str, attrs: &[(&str, &str)], value: &str) {
+ self.start_tag(name, attrs);
+ let _ = writeln!(self.out, ">{}</{name}>", escape(value));
+ }
+
+ pub fn text(&mut self, name: &str, value: impl std::fmt::Display) {
+ self.text_attrs(name, &[], &value.to_string());
+ }
+
+ pub fn finish(mut self) -> String {
+ while !self.stack.is_empty() {
+ self.close();
+ }
+ self.out
+ }
+}
+
+pub(crate) fn child<'a, 'i>(n: Node<'a, 'i>, name: &str) -> Option<Node<'a, 'i>> {
+ n.children().find(|c| c.is_element() && c.tag_name().name() == name)
+}
+
+pub(crate) fn children<'a, 'i>(n: Node<'a, 'i>, name: &'static str) -> impl Iterator<Item = Node<'a, 'i>> {
+ n.children().filter(move |c| c.is_element() && c.tag_name().name() == name)
+}
+
+pub(crate) fn elements<'a, 'i>(n: Node<'a, 'i>) -> impl Iterator<Item = Node<'a, 'i>> {
+ n.children().filter(|c| c.is_element())
+}
+
+/// Trimmed text of a node's direct text content.
+pub(crate) fn text<'a>(n: Node<'a, '_>) -> &'a str {
+ n.text().map(str::trim).unwrap_or("")
+}
+
+/// Text of the element at `path` below `n`.
+pub(crate) fn path_text<'a>(n: Node<'a, '_>, path: &[&str]) -> Option<&'a str> {
+ let mut cur = n;
+ for p in path {
+ cur = child(cur, p)?;
+ }
+ Some(text(cur))
+}
+
+pub(crate) fn child_text<'a>(n: Node<'a, '_>, name: &str) -> Option<&'a str> {
+ child(n, name).map(text)
+}
+
+pub(crate) fn child_i64(n: Node<'_, '_>, name: &str) -> Option<i64> {
+ child_text(n, name).and_then(|t| t.parse::<i64>().ok().or_else(|| t.parse::<f64>().ok().map(|f| f.round() as i64)))
+}
+
+pub(crate) fn child_f64(n: Node<'_, '_>, name: &str) -> Option<f64> {
+ child_text(n, name).and_then(|t| t.parse::<f64>().ok())
+}
+
+pub(crate) fn child_bool(n: Node<'_, '_>, name: &str) -> Option<bool> {
+ child_text(n, name).map(|t| t.eq_ignore_ascii_case("true") || t == "1")
+}
+
+pub(crate) fn bool_str(b: bool) -> &'static str {
+ if b { "TRUE" } else { "FALSE" }
+}
+
+/// Format an f64 compactly (no trailing zeros, no exponent for normal ranges).
+pub(crate) fn num(v: f64) -> String {
+ if v == v.round() && v.abs() < 1e15 {
+ return format!("{}", v as i64);
+ }
+ let s = format!("{v:.6}");
+ let s = s.trim_end_matches('0').trim_end_matches('.');
+ if s == "-0" { "0".into() } else { s.to_string() }
+}
+
+pub(crate) fn parse(text: &str) -> Result<roxmltree::Document<'_>, String> {
+ let opts = roxmltree::ParsingOptions { allow_dtd: true, ..Default::default() };
+ roxmltree::Document::parse_with_options(text, opts).map_err(|e| e.to_string())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn writer_roundtrip() {
+ let mut w = XmlWriter::new(Some("xmeml"));
+ w.open("a", &[("x", "1 & 2")]);
+ w.text("b", "<hi>");
+ w.empty("c", &[]);
+ let s = w.finish();
+ let d = parse(&s).unwrap();
+ let a = d.root_element();
+ assert_eq!(a.attribute("x"), Some("1 & 2"));
+ assert_eq!(child_text(a, "b"), Some("<hi>"));
+ assert!(child(a, "c").is_some());
+ assert_eq!(num(1.5), "1.5");
+ assert_eq!(num(100.0), "100");
+ assert_eq!(num(-0.0000001), "0");
+ }
+}
diff --git a/crates/interchange/tests/edl.rs b/crates/interchange/tests/edl.rs
new file mode 100644
index 000000000..baea077b8
--- /dev/null
+++ b/crates/interchange/tests/edl.rs
@@ -0,0 +1,360 @@
+//! CMX 3600 EDL: golden documents (hand-written from the public CMX 3600 conventions) and round trips.
+
+mod support;
+
+use filmcraft_interchange::{ExportOptions, Format, ImportOptions, ReelMode, detect, export, export_edl_per_track, import, import_with};
+use filmcraft_project::{ItemKind, MediaRef, TrackKind, TransitionAlign};
+use filmcraft_time::{FrameRate, Tick, fields_to_frames};
+use proptest::prelude::*;
+use support::*;
+
+const DF_DISSOLVES: &str = "TITLE: Harbour Cut
+FCM: DROP FRAME
+
+001 HARB01 B C 00:10:00:00 00:10:04:00 01:00:00:00 01:00:04:00
+* FROM CLIP NAME: harbour_wide.mov
+* SOURCE FILE: media/harbour_wide.mov
+
+002 HARB01 V C 00:10:04:00 00:10:04:00 01:00:04:00 01:00:04:00
+002 HARB02 V D 030 00:20:00:00 00:20:05:00 01:00:04:00 01:00:09:00
+* FROM CLIP NAME: harbour_wide.mov
+* TO CLIP NAME: harbour_close.mov
+* SOURCE FILE: media/harbour_wide.mov
+* SOURCE FILE: media/harbour_close.mov
+
+003 GULLS V C 00:30:00:00 00:30:02:00 01:00:09:00 01:00:11:00
+M2 GULLS 060.0 00:30:00:00
+* FROM CLIP NAME: gulls.mov
+* LOC: 01:00:09;15 RED gull lands
+
+004 MUSIC A2 C 00:00:00:00 00:00:11:00 01:00:00:00 01:00:11:00
+* FROM CLIP NAME: score.wav
+
+005 BL V C 00:00:00:00 00:00:00:00 01:00:11:00 01:00:11:00
+005 HARB02 V D 015 00:20:05:00 00:20:07:00 01:00:11:00 01:00:13:00
+* TO CLIP NAME: harbour_close.mov
+* SOURCE FILE: media/harbour_close.mov
+
+006 HARB02 V C 00:20:07:00 00:20:07:00 01:00:13:00 01:00:13:00
+006 BL V D 010 00:00:00:00 00:00:00:10 01:00:13:00 01:00:13:10
+* FROM CLIP NAME: harbour_close.mov
+";
+
+#[test]
+fn golden_drop_frame_dissolves() {
+ assert_eq!(detect(DF_DISSOLVES.as_bytes(), None), Some(Format::Edl));
+ let (imp, rep) = import(DF_DISSOLVES.as_bytes(), Format::Edl, Some("/proj")).unwrap();
+ assert!(rep.mentions("assumed 29.97"), "{rep}");
+ let p = &imp.project;
+ let sid = only_seq(&imp);
+ let s = p.sequence(sid).unwrap();
+ let r = FrameRate::FPS_29_97;
+ assert_eq!(s.settings.frame_rate, r);
+ assert!(s.settings.drop_frame);
+ assert_eq!(p.item(sid).unwrap().name, "Harbour Cut");
+ assert_eq!(s.start_timecode, 107_892); // 01:00:00;00 DF
+
+ let v1 = &s.video_tracks[0];
+ assert_eq!(v1.items.len(), 4, "{:#?}", v1.items);
+ let [a, b, g, c] = [&v1.items[0], &v1.items[1], &v1.items[2], &v1.items[3]];
+ assert_eq!((a.start, a.duration), (f(r, 0), f(r, 120)));
+ assert_eq!(a.source_in, f(r, fields_to_frames(0, 10, 0, 0, r, true)));
+ assert_eq!(a.source_in, f(r, 17_982));
+ assert_eq!(media_key(p, a.item), "/proj/media/harbour_wide.mov");
+ assert_eq!(a.name, "harbour_wide.mov");
+ // dissolve event
+ assert_eq!((b.start, b.duration, b.source_in), (f(r, 120), f(r, 150), f(r, 35_964)));
+ assert_eq!(media_key(p, b.item), "/proj/media/harbour_close.mov");
+ // M2 speed line
+ assert_eq!(g.speed, 2.0);
+ assert_eq!(g.start, f(r, 270));
+ assert_eq!(media_key(p, g.item), "/proj/gulls.mov");
+ // fade in from black, then fade out to black (clip extended through the transition)
+ assert_eq!(c.item, b.item);
+ assert_eq!((c.start, c.duration), (f(r, 330), f(r, 60 + 10)));
+ let ts = &v1.transitions;
+ assert_eq!(ts.len(), 3);
+ assert_eq!((ts[0].start, ts[0].duration, ts[0].from, ts[0].to), (f(r, 120), f(r, 30), Some(a.id), Some(b.id)));
+ assert_eq!(ts[0].align, TransitionAlign::StartAtCut);
+ assert_eq!(ts[0].effect.effect, "cross_dissolve");
+ assert_eq!((ts[1].from, ts[1].to, ts[1].duration), (None, Some(c.id), f(r, 15)));
+ assert_eq!((ts[2].from, ts[2].to, ts[2].start, ts[2].duration), (Some(c.id), None, f(r, 390), f(r, 10)));
+ assert_eq!(ts[2].align, TransitionAlign::EndAtCut);
+
+ // B = V + A1, linked; A2 music.
+ let a1 = &s.audio_tracks[0].items;
+ assert_eq!(a1.len(), 1);
+ assert_eq!(a1[0].link, a.link);
+ assert!(a.link.is_some());
+ let a2 = &s.audio_tracks[1].items;
+ assert_eq!((a2[0].start, a2[0].duration), (f(r, 0), f(r, 330)));
+ // LOC marker
+ assert_eq!(s.markers.len(), 1);
+ assert_eq!(s.markers[0].name, "gull lands");
+ assert_eq!(s.markers[0].start, f(r, 285));
+ assert_eq!(s.markers[0].color, filmcraft_project::Label::Rose);
+ // media without a source file is offline with its reel as tape name
+ let gm = p.item(g.item).unwrap();
+ assert_eq!(gm.metadata.get("Tape Name").map(String::as_str), Some("GULLS"));
+ assert!(gm.as_media().unwrap().offline);
+}
+
+#[test]
+fn explicit_rate_and_wipes_and_keys() {
+ let edl = "TITLE: Keys
+FCM: NON-DROP FRAME
+
+001 BG V C 00:00:00:00 00:00:02:00 00:00:00:00 00:00:02:00
+002 BG V C 00:00:02:00 00:00:02:00 00:00:02:00 00:00:02:00
+002 FG V W001 012 00:00:05:00 00:00:07:00 00:00:02:00 00:00:04:00
+003 BG2 V K B 00:01:00:00 00:01:02:00 00:00:04:00 00:00:06:00
+003 LOGO V K 00:00:00:00 00:00:02:00 00:00:04:00 00:00:06:00
+004 AUDX A3 C 00:00:00:00 00:00:06:00 00:00:00:00 00:00:06:00
+";
+ let opts = ImportOptions { edl_frame_rate: Some(FrameRate::FPS_25), ..Default::default() };
+ let (imp, rep) = import_with(edl.as_bytes(), Format::Edl, &opts).unwrap();
+ let p = &imp.project;
+ let s = p.sequence(only_seq(&imp)).unwrap();
+ let r = FrameRate::FPS_25;
+ assert_eq!(s.start_timecode, 0);
+ assert_eq!(s.video_tracks[0].items.len(), 3);
+ assert_eq!(s.video_tracks[0].transitions[0].effect.effect, "wipe");
+ assert_eq!(s.video_tracks[0].transitions[0].duration, f(r, 12));
+ assert_eq!(s.video_tracks[1].items.len(), 1, "key foreground on V2");
+ assert_eq!(s.video_tracks[1].items[0].start, f(r, 100));
+ assert_eq!(s.audio_tracks.len(), 3);
+ assert_eq!(s.audio_tracks[2].items[0].duration, f(r, 150));
+ assert!(rep.mentions("key"), "{rep}");
+}
+
+fn demo_project(rate: FrameRate, df: bool) -> (filmcraft_project::Project, filmcraft_project::ItemId) {
+ let mut p = filmcraft_project::Project::new("P");
+ let a = media(&mut p, "/media/Beach Day.mov", true, true, rate);
+ let b = media(&mut p, "/media/city.mp4", true, true, rate);
+ let m = media(&mut p, "/media/score.wav", false, true, rate);
+ let s = sequence(&mut p, "Edit 1", rate, df);
+ let va = clip(&mut p, s, TrackKind::Video, 0, a, 0, 100, 10);
+ let aa = clip(&mut p, s, TrackKind::Audio, 0, a, 0, 100, 10);
+ link(&mut p, s, &[va, aa]);
+ let vb = clip(&mut p, s, TrackKind::Video, 0, b, 100, 60, 200);
+ transition(&mut p, s, TrackKind::Video, 0, "cross_dissolve", Some(va), Some(vb), 100, 20, TransitionAlign::StartAtCut);
+ let vc = clip(&mut p, s, TrackKind::Video, 0, a, 200, 50, 500);
+ transition(&mut p, s, TrackKind::Video, 0, "dip_to_black", None, Some(vc), 200, 10, TransitionAlign::StartAtCut);
+ p.sequence_mut(s).unwrap().find_item_mut(vc).unwrap().1.speed = 2.0;
+ clip(&mut p, s, TrackKind::Audio, 1, m, 0, 250, 0);
+ (p, s)
+}
+
+#[test]
+fn export_golden_text() {
+ let (p, s) = demo_project(FrameRate::FPS_25, false);
+ let (bytes, rep) = export(&p, s, Format::Edl, &ExportOptions::default()).unwrap();
+ let text = String::from_utf8(bytes).unwrap();
+ let expected = "TITLE: Edit 1
+FCM: NON-DROP FRAME
+
+001 BEACH_DA B C 00:00:00:10 00:00:04:10 00:00:00:00 00:00:04:00
+* FROM CLIP NAME: Beach Day.mov
+* SOURCE FILE: /media/Beach Day.mov
+
+002 SCORE A2 C 00:00:00:00 00:00:10:00 00:00:00:00 00:00:10:00
+* FROM CLIP NAME: score.wav
+* SOURCE FILE: /media/score.wav
+
+003 BEACH_DA V C 00:00:04:10 00:00:04:10 00:00:04:00 00:00:04:00
+003 CITY V D 020 00:00:08:00 00:00:10:10 00:00:04:00 00:00:06:10
+* FROM CLIP NAME: Beach Day.mov
+* TO CLIP NAME: city.mp4
+* SOURCE FILE: /media/Beach Day.mov
+* SOURCE FILE: /media/city.mp4
+* EFFECT NAME: CROSS DISSOLVE
+
+004 BL V C 00:00:00:00 00:00:00:00 00:00:08:00 00:00:08:00
+004 BEACH_DA V D 010 00:00:20:00 00:00:22:00 00:00:08:00 00:00:10:00
+M2 BEACH_DA 050.0 00:00:20:00
+* TO CLIP NAME: Beach Day.mov
+* SOURCE FILE: /media/Beach Day.mov
+* EFFECT NAME: DIP TO BLACK
+";
+ assert_eq!(text, expected, "{text}");
+ assert!(rep.mentions("Dip to Black"), "{rep}");
+
+ // …and it imports back to the same structure.
+ let o = ImportOptions { edl_frame_rate: Some(FrameRate::FPS_25), ..Default::default() };
+ let (imp, _) = import_with(text.as_bytes(), Format::Edl, &o).unwrap();
+ let si = only_seq(&imp);
+ assert_eq!(structure(&imp.project, si, TrackKind::Video), structure(&p, s, TrackKind::Video));
+ assert_eq!(structure(&imp.project, si, TrackKind::Audio), structure(&p, s, TrackKind::Audio));
+ assert_eq!(links(&imp.project, si), links(&p, s));
+}
+
+#[test]
+fn reel_modes_and_per_track() {
+ let (mut p, s) = demo_project(FrameRate::FPS_24, false);
+ let a = p.items.values().find(|i| i.name == "city.mp4").unwrap().id;
+ clip(&mut p, s, TrackKind::Video, 1, a, 10, 20, 0);
+ let mut o = ExportOptions::default();
+ o.edl.reel_mode = ReelMode::Ax;
+ o.edl.reel_len = 32;
+ let (bytes, _) = export(&p, s, Format::Edl, &o).unwrap();
+ let t = String::from_utf8(bytes).unwrap();
+ assert!(t.lines().filter(|l| l.starts_with("00")).all(|l| l[5..7] == *"AX" || l[5..7] == *"BL"), "{t}");
+ let (docs, rep) = export_edl_per_track(&p, s, &ExportOptions::default()).unwrap();
+ assert_eq!(docs.len(), 2);
+ assert_eq!(docs[1].0, "V2");
+ let v2 = String::from_utf8(docs[1].1.clone()).unwrap();
+ assert!(v2.contains("CITY V C"), "{v2}");
+ assert!(!v2.contains("SCORE"), "audio only in the first list");
+ let _ = rep;
+ // long file names are cut to 8 characters, distinct media keep distinct reels
+ let mut q = filmcraft_project::Project::new("q");
+ let m1 = media(&mut q, "/x/interview_cam_a.mov", true, false, FrameRate::FPS_24);
+ let m2 = media(&mut q, "/x/interview_cam_b.mov", true, false, FrameRate::FPS_24);
+ let sq = sequence(&mut q, "S", FrameRate::FPS_24, false);
+ clip(&mut q, sq, TrackKind::Video, 0, m1, 0, 10, 0);
+ clip(&mut q, sq, TrackKind::Video, 0, m2, 10, 10, 0);
+ let (bytes, _) = export(&q, sq, Format::Edl, &ExportOptions::default()).unwrap();
+ let t = String::from_utf8(bytes).unwrap();
+ assert!(t.contains("001 INTERVIE V"), "{t}");
+ assert!(t.contains("002 INTERVI2 V"), "{t}");
+}
+
+#[test]
+fn drop_frame_roundtrip_59_94() {
+ let r = FrameRate::FPS_59_94;
+ let mut p = filmcraft_project::Project::new("P");
+ let a = media(&mut p, "/m/a.mov", true, false, r);
+ let s = sequence(&mut p, "S", r, true);
+ p.sequence_mut(s).unwrap().start_timecode = fields_to_frames(1, 0, 0, 0, r, true);
+ clip(&mut p, s, TrackKind::Video, 0, a, 3590, 30, 3590);
+ clip(&mut p, s, TrackKind::Video, 0, a, 36_000, 7200, 0);
+ let (imp, text, _) = roundtrip(&p, s, Format::Edl, &ExportOptions::default());
+ assert!(text.contains("FCM: DROP FRAME"));
+ assert!(text.contains("01;00;59;50 01;01;00;24"), "{text}");
+ let si = only_seq(&imp);
+ // 59.94 is not guessable from the list alone, pass it.
+ let (imp2, _) = import_with(text.as_bytes(), Format::Edl, &ImportOptions { edl_frame_rate: Some(r), ..Default::default() }).unwrap();
+ let si2 = only_seq(&imp2);
+ assert_eq!(structure(&imp2.project, si2, TrackKind::Video), structure(&p, s, TrackKind::Video));
+ assert_eq!(imp2.project.sequence(si2).unwrap().start_timecode, p.sequence(s).unwrap().start_timecode);
+ // The guessed rate (59.94 because frame fields exceed 29) also works.
+ assert_eq!(imp.project.sequence(si).unwrap().settings.frame_rate, r);
+}
+
+#[test]
+fn freeze_reverse_and_fade_out() {
+ let r = FrameRate::FPS_24;
+ let mut p = filmcraft_project::Project::new("P");
+ let a = media(&mut p, "/m/a.mov", true, false, r);
+ let s = sequence(&mut p, "S", r, false);
+ let c1 = clip(&mut p, s, TrackKind::Video, 0, a, 0, 48, 100);
+ let c2 = clip(&mut p, s, TrackKind::Video, 0, a, 48, 24, 300);
+ let c3 = clip(&mut p, s, TrackKind::Video, 0, a, 72, 24, 400);
+ {
+ let q = p.sequence_mut(s).unwrap();
+ q.find_item_mut(c1).unwrap().1.reverse = true;
+ q.find_item_mut(c2).unwrap().1.frame_hold = Some(r.tick_of(310));
+ }
+ transition(&mut p, s, TrackKind::Video, 0, "cross_dissolve", Some(c3), None, 84, 12, TransitionAlign::EndAtCut);
+ let (imp, text, _) = roundtrip(&p, s, Format::Edl, &ExportOptions::default());
+ assert!(text.contains("-024.0"), "{text}");
+ assert!(text.contains("000.0"), "{text}");
+ let si = only_seq(&imp);
+ assert_eq!(structure(&imp.project, si, TrackKind::Video), structure(&p, s, TrackKind::Video), "{text}");
+}
+
+#[test]
+fn media_paths_relative_export() {
+ let (p, s) = demo_project(FrameRate::FPS_24, false);
+ let o = ExportOptions { relative_to: Some("/media/edl".into()), ..Default::default() };
+ let (bytes, _) = export(&p, s, Format::Edl, &o).unwrap();
+ let t = String::from_utf8(bytes).unwrap();
+ assert!(t.contains("* SOURCE FILE: ../city.mp4"), "{t}");
+ let (imp, _) = import(t.as_bytes(), Format::Edl, Some("/media/edl")).unwrap();
+ let paths: Vec<String> = imp
+ .project
+ .items
+ .values()
+ .filter_map(|i| match &i.kind {
+ ItemKind::Media(m) => match &m.media {
+ MediaRef::File { path } => Some(path.clone()),
+ _ => None,
+ },
+ _ => None,
+ })
+ .collect();
+ assert!(paths.contains(&"/media/city.mp4".to_string()), "{paths:?}");
+}
+
+#[test]
+fn garbage_is_an_error_not_a_panic() {
+ assert!(import(b"hello world", Format::Edl, None).is_err());
+ assert!(detect(b"hello world", Some("txt")).is_none());
+}
+
+// ---------------------------------------------------------------------------------------------
+// Property: cut lists with linked A/V, dissolves and fades survive export → import exactly.
+// ---------------------------------------------------------------------------------------------
+
+#[derive(Clone, Debug)]
+struct Gen {
+ gap: i64,
+ dur: i64,
+ media: usize,
+ src: i64,
+ with_audio: bool,
+ dissolve: Option<i64>,
+ speed: u8,
+}
+
+fn gen_clip() -> impl Strategy<Value = Gen> {
+ (0i64..3, 12i64..200, 0usize..3, 30i64..5000, any::<bool>(), prop::option::of(1i64..10), 0u8..6).prop_map(
+ |(gap, dur, media, src, with_audio, dissolve, speed)| Gen { gap: if gap == 0 { 0 } else { gap * 7 }, dur, media, src, with_audio, dissolve, speed },
+ )
+}
+
+proptest! {
+ #![proptest_config(ProptestConfig::with_cases(64))]
+ #[test]
+ fn edl_roundtrip(clips in prop::collection::vec(gen_clip(), 1..14), ri in 0usize..4) {
+ let rate = [FrameRate::FPS_24, FrameRate::FPS_25, FrameRate::FPS_29_97, FrameRate::FPS_23_976][ri];
+ let df = rate == FrameRate::FPS_29_97;
+ let mut p = filmcraft_project::Project::new("P");
+ let ms = [media(&mut p, "/a/one.mov", true, true, rate), media(&mut p, "/a/two.mov", true, true, rate), media(&mut p, "/b/three.mxf", true, true, rate)];
+ let s = sequence(&mut p, "Seq", rate, df);
+ let mut t = 0i64;
+ let mut prev: Option<(filmcraft_project::ClipId, i64)> = None;
+ for g in &clips {
+ t += g.gap;
+ let v = clip(&mut p, s, TrackKind::Video, 0, ms[g.media], t, g.dur, g.src);
+ if g.speed == 1 {
+ p.sequence_mut(s).unwrap().find_item_mut(v).unwrap().1.speed = 2.0;
+ }
+ let mut has_tr = false;
+ if let Some(d) = g.dissolve {
+ let d = d.min(g.dur - 1);
+ let from = prev.filter(|(_, end)| *end == t).map(|(c, _)| c);
+ if g.src >= d * 2 {
+ transition(&mut p, s, TrackKind::Video, 0, "cross_dissolve", from, Some(v), t, d, TransitionAlign::StartAtCut);
+ has_tr = true;
+ }
+ }
+ if g.with_audio && g.speed != 1 && !has_tr {
+ let a = clip(&mut p, s, TrackKind::Audio, 0, ms[g.media], t, g.dur, g.src);
+ link(&mut p, s, &[v, a]);
+ }
+ t += g.dur;
+ prev = Some((v, t));
+ }
+ let (imp, text, _) = roundtrip(&p, s, Format::Edl, &ExportOptions::default());
+ let opts = ImportOptions { edl_frame_rate: Some(rate), ..Default::default() };
+ let (imp2, _) = import_with(text.as_bytes(), Format::Edl, &opts).unwrap();
+ let _ = imp;
+ let si = only_seq(&imp2);
+ prop_assert_eq!(structure(&imp2.project, si, TrackKind::Video), structure(&p, s, TrackKind::Video), "{}", text);
+ prop_assert_eq!(structure(&imp2.project, si, TrackKind::Audio), structure(&p, s, TrackKind::Audio), "{}", text);
+ prop_assert_eq!(links(&imp2.project, si), links(&p, s));
+ prop_assert_eq!(imp2.project.sequence(si).unwrap().settings.drop_frame, df);
+ let _ = Tick::ZERO;
+ }
+}
diff --git a/crates/interchange/tests/support/mod.rs b/crates/interchange/tests/support/mod.rs
new file mode 100644
index 000000000..a74865d4e
--- /dev/null
+++ b/crates/interchange/tests/support/mod.rs
@@ -0,0 +1,239 @@
+//! Test helpers: building projects and comparing edit structure.
+#![allow(dead_code)]
+
+use filmcraft_interchange::{ExportOptions, Format, Imported, Report, export, import};
+use filmcraft_media::{Generator, MediaKind};
+use filmcraft_project::{
+ ClipId, ItemId, ItemKind, Label, MediaClip, MediaRef, Project, SequenceSettings, TrackKind, Transition, TransitionAlign, TransitionId, find_effect,
+};
+use filmcraft_time::{FrameRate, Tick, TimeRange};
+
+pub fn media_info(name: &str, video: bool, audio: bool, rate: FrameRate, secs: i64) -> filmcraft_media::MediaInfo {
+ filmcraft_media::MediaInfo {
+ name: name.into(),
+ kind: if video { MediaKind::Movie } else { MediaKind::AudioOnly },
+ duration: Tick(secs * filmcraft_time::TICKS_PER_SECOND),
+ video: video.then(|| filmcraft_media::VideoStreamInfo {
+ width: 1920,
+ height: 1080,
+ frame_rate: rate,
+ par: (1, 1),
+ codec: "h264".into(),
+ pixel_format: "yuv420p".into(),
+ color: Default::default(),
+ has_alpha: false,
+ bitrate: None,
+ }),
+ audio: audio.then(|| filmcraft_media::AudioStreamInfo { sample_rate: 48_000, channels: 2, codec: "aac".into(), bits_per_sample: None }),
+ container: "mp4".into(),
+ start_timecode: None,
+ file_size: None,
+ }
+}
+
+pub fn media(p: &mut Project, path: &str, video: bool, audio: bool, rate: FrameRate) -> ItemId {
+ let name = path.rsplit('/').next().unwrap().to_string();
+ let info = media_info(&name, video, audio, rate, 600);
+ p.add_item(
+ &name,
+ Label::Iris,
+ ItemKind::Media(MediaClip {
+ media: MediaRef::File { path: path.into() },
+ info,
+ interpret: Default::default(),
+ mark_in: None,
+ mark_out: None,
+ markers: vec![],
+ offline: false,
+ proxy: None,
+ }),
+ None,
+ )
+}
+
+pub fn generator(p: &mut Project, name: &str, g: Generator) -> ItemId {
+ let mut info = media_info(name, true, false, FrameRate::FPS_24, 600);
+ info.kind = MediaKind::Synthetic;
+ p.add_item(
+ name,
+ Label::Lavender,
+ ItemKind::Media(MediaClip {
+ media: MediaRef::Generator(g),
+ info,
+ interpret: Default::default(),
+ mark_in: None,
+ mark_out: None,
+ markers: vec![],
+ offline: false,
+ proxy: None,
+ }),
+ None,
+ )
+}
+
+pub fn sequence(p: &mut Project, name: &str, rate: FrameRate, df: bool) -> ItemId {
+ let settings = SequenceSettings { frame_rate: rate, drop_frame: df, ..Default::default() };
+ p.new_sequence(name, settings, 3, 4, None)
+}
+
+/// Place a clip (frames at the sequence rate). Returns its id.
+pub fn clip(p: &mut Project, seq: ItemId, kind: TrackKind, track: usize, item: ItemId, start: i64, dur: i64, src: i64) -> ClipId {
+ let rate = p.sequence(seq).unwrap().settings.frame_rate;
+ let ti = p.make_track_item(item, kind, rate.tick_of(start), TimeRange::new(rate.tick_of(src), rate.tick_of(dur)), rate).unwrap();
+ let id = ti.id;
+ let t = &mut p.sequence_mut(seq).unwrap().tracks_mut(kind)[track];
+ t.items.push(ti);
+ t.sort();
+ id
+}
+
+pub fn link(p: &mut Project, seq: ItemId, clips: &[ClipId]) {
+ let l = p.alloc_id();
+ let s = p.sequence_mut(seq).unwrap();
+ for c in clips {
+ s.find_item_mut(*c).unwrap().1.link = Some(l);
+ }
+}
+
+pub fn transition(
+ p: &mut Project,
+ seq: ItemId,
+ kind: TrackKind,
+ track: usize,
+ effect: &str,
+ from: Option<ClipId>,
+ to: Option<ClipId>,
+ start: i64,
+ dur: i64,
+ align: TransitionAlign,
+) {
+ let id = TransitionId(p.alloc_id());
+ let rate = p.sequence(seq).unwrap().settings.frame_rate;
+ let t = &mut p.sequence_mut(seq).unwrap().tracks_mut(kind)[track];
+ t.transitions.push(Transition {
+ id,
+ effect: find_effect(effect).unwrap().instance(),
+ start: rate.tick_of(start),
+ duration: rate.tick_of(dur),
+ from,
+ to,
+ align,
+ reverse: false,
+ });
+ t.sort();
+}
+
+/// A comparable description of one clip.
+#[derive(Clone, Debug, PartialEq)]
+pub struct C {
+ pub start: Tick,
+ pub dur: Tick,
+ pub src: Tick,
+ pub media: String,
+ pub speed: String,
+ pub reverse: bool,
+ pub enabled: bool,
+}
+
+/// A comparable description of one transition (from/to as clip indices on the track).
+#[derive(Clone, Debug, PartialEq)]
+pub struct T {
+ pub start: Tick,
+ pub dur: Tick,
+ pub effect: String,
+ pub from: Option<usize>,
+ pub to: Option<usize>,
+}
+
+#[derive(Clone, Debug, PartialEq)]
+pub struct Tr {
+ pub clips: Vec<C>,
+ pub transitions: Vec<T>,
+}
+
+pub fn media_key(p: &Project, item: ItemId) -> String {
+ match &p.item(item).unwrap().kind {
+ ItemKind::Media(m) => match &m.media {
+ MediaRef::File { path } => path.clone(),
+ MediaRef::Generator(g) => format!("gen:{}", g.label()),
+ },
+ ItemKind::Sequence(_) => format!("seq:{}", p.item(item).unwrap().name),
+ _ => "other".into(),
+ }
+}
+
+/// Non-empty tracks of a sequence (trailing empty tracks ignored).
+pub fn structure(p: &Project, seq: ItemId, kind: TrackKind) -> Vec<Tr> {
+ let s = p.sequence(seq).unwrap();
+ let mut out: Vec<Tr> = s
+ .tracks(kind)
+ .iter()
+ .map(|t| Tr {
+ clips: t
+ .items
+ .iter()
+ .map(|i| C {
+ start: i.start,
+ dur: i.duration,
+ src: i.frame_hold.unwrap_or(i.source_in),
+ media: media_key(p, i.item),
+ speed: if i.frame_hold.is_some() { "hold".into() } else { format!("{:.3}", i.speed) },
+ reverse: i.reverse,
+ enabled: i.enabled,
+ })
+ .collect(),
+ transitions: t
+ .transitions
+ .iter()
+ .map(|x| T {
+ start: x.start,
+ dur: x.duration,
+ effect: x.effect.effect.clone(),
+ from: x.from.and_then(|f| t.items.iter().position(|i| i.id == f)),
+ to: x.to.and_then(|f| t.items.iter().position(|i| i.id == f)),
+ })
+ .collect(),
+ })
+ .collect();
+ while out.last().is_some_and(|t| t.clips.is_empty()) {
+ out.pop();
+ }
+ out
+}
+
+/// Link partition as sets of (kind, track, clip index).
+pub fn links(p: &Project, seq: ItemId) -> Vec<Vec<(u8, usize, usize)>> {
+ let s = p.sequence(seq).unwrap();
+ let mut groups: std::collections::BTreeMap<u64, Vec<(u8, usize, usize)>> = Default::default();
+ for (k, kind) in [(0u8, TrackKind::Video), (1, TrackKind::Audio)] {
+ for (ti, t) in s.tracks(kind).iter().enumerate() {
+ for (ci, c) in t.items.iter().enumerate() {
+ if let Some(l) = c.link {
+ groups.entry(l).or_default().push((k, ti, ci));
+ }
+ }
+ }
+ }
+ let mut v: Vec<Vec<_>> = groups.into_values().filter(|g| g.len() > 1).collect();
+ for g in &mut v {
+ g.sort();
+ }
+ v.sort();
+ v
+}
+
+pub fn roundtrip(p: &Project, seq: ItemId, format: Format, opts: &ExportOptions) -> (Imported, String, Report) {
+ let (bytes, _rep) = export(p, seq, format, opts).expect("export");
+ let text = String::from_utf8(bytes.clone()).unwrap();
+ let (imp, rep) = import(&bytes, format, None).unwrap_or_else(|e| panic!("import failed: {e}\n{text}"));
+ (imp, text, rep)
+}
+
+pub fn only_seq(imp: &Imported) -> ItemId {
+ assert_eq!(imp.sequences.len(), 1, "expected one top-level sequence");
+ imp.sequences[0]
+}
+
+pub fn f(rate: FrameRate, n: i64) -> Tick {
+ rate.tick_of(n)
+}