mirror of
https://github.com/storytold/filmcraft.git
synced 2026-12-02 20:19:02 -05:00
Merge pull request #4858 from storytold/codex/filmcraft-shared-aaf
interchange: use shared AAF schema reader and writer
This commit is contained in:
6 files changed
+35
-1553
No files matched your search
@@ -32,10 +32,12 @@
|
||||
//! sequences (a composition that others use becomes a nested sequence), media items (linked by path; embedded audio is returned as WAV files for the
|
||||
//! caller to write) and markers.
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(dead_code)] // The structural tests use only part of the AAF schema constants.
|
||||
mod ids;
|
||||
mod read;
|
||||
#[cfg(test)]
|
||||
#[allow(dead_code)] // Retained as an independent fixture reader and writer for structural tests.
|
||||
pub(crate) mod store;
|
||||
mod write;
|
||||
|
||||
use filmcraft_project::{ItemId, Project};
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -61,8 +63,19 @@ pub fn export(project: &Project, sequence: ItemId, opts: &AafOptions) -> Result<
|
||||
crate::warn_marker_metadata_loss(project, sequence, &mut report);
|
||||
let name = opts.name.clone().or_else(|| project.item(sequence).map(|i| i.name.clone())).unwrap_or_else(|| "Sequence".into());
|
||||
let doc = comp::from_project(project, sequence, &name, &opts.media, comp::Nests::Compositions, &mut report)?;
|
||||
let version = if opts.small_sectors { filmcraft_cfb::Version::V3 } else { filmcraft_cfb::Version::V4 };
|
||||
let bytes = write::write(&doc, version, &mut report)?;
|
||||
let identity = craft_aaf::Identity {
|
||||
company: "FilmCraft",
|
||||
product: "FilmCraft",
|
||||
version: env!("CARGO_PKG_VERSION"),
|
||||
platform: "FilmCraft",
|
||||
product_id: [0x4d, 0x4c, 0x49, 0x46, 0x52, 0x43, 0x46, 0x41, b'T', b'-', b'A', b'A', b'F', b'-', b'E', b'P'],
|
||||
};
|
||||
let options = craft_aaf::aaf::WriteOptions { identity, small_sectors: opts.small_sectors };
|
||||
let references = craft_aaf::aaf::ReferenceOptions { source_slot_rate: false, encode_relative_locator: false };
|
||||
let mut shared_report = craft_aaf::Report::default();
|
||||
let bytes = craft_aaf::aaf::write_with_references(&crate::omf::shared_model::to_shared(doc), &options, &references, &mut shared_report)
|
||||
.map_err(crate::omf::shared_model::error)?;
|
||||
crate::omf::shared_model::merge_report(&mut report, shared_report);
|
||||
Ok((bytes, report))
|
||||
}
|
||||
|
||||
@@ -70,7 +83,17 @@ pub fn export(project: &Project, sequence: ItemId, opts: &AafOptions) -> Result<
|
||||
/// as WAV files whose paths are the paths of the imported media items.
|
||||
pub fn import(bytes: &[u8], opts: &ImportOptions) -> Result<(Imported, Vec<ExtractedMedia>, Report)> {
|
||||
let mut report = Report::default();
|
||||
let doc = read::read(bytes, &mut report)?;
|
||||
let options = craft_aaf::aaf::ReadOptions {
|
||||
source_slot_rate: false,
|
||||
infer_clip_name: false,
|
||||
decode_relative_locator: false,
|
||||
report_flattening: false,
|
||||
permissive_pcm: true,
|
||||
};
|
||||
let mut shared_report = craft_aaf::Report::default();
|
||||
let doc = craft_aaf::aaf::read_with_options(bytes, &options, &mut shared_report).map_err(crate::omf::shared_model::error)?;
|
||||
crate::omf::shared_model::merge_report(&mut report, shared_report);
|
||||
let doc = crate::omf::shared_model::from_shared(doc);
|
||||
let (imported, extracted) = comp::to_project(doc, opts, &mut report)?;
|
||||
let mut imported = imported;
|
||||
crate::bound_start_timecodes(&mut imported, &mut report);
|
||||
@@ -80,13 +103,7 @@ pub fn import(bytes: &[u8], opts: &ImportOptions) -> Result<(Imported, Vec<Extra
|
||||
/// Whether `bytes` look like an AAF file (a compound file whose root has the AAF root class or a
|
||||
/// `Header-2` storage).
|
||||
pub fn sniff(bytes: &[u8]) -> bool {
|
||||
if !filmcraft_cfb::sniff(bytes) {
|
||||
return false;
|
||||
}
|
||||
match filmcraft_cfb::CompoundFile::open(bytes) {
|
||||
Ok(cf) => cf.root().clsid == ids::ROOT || cf.find("Header-2").is_ok(),
|
||||
Err(_) => false,
|
||||
}
|
||||
craft_aaf::aaf::sniff(bytes)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -1,705 +0,0 @@
|
||||
//! AAF objects → composition model.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use filmcraft_time::{FrameRate, Tick};
|
||||
|
||||
use super::ids::{cls, ddef, def, pid};
|
||||
use super::store::{self, Auid, Obj, Value, rational_of, utf16_of};
|
||||
use crate::comp::{CClip, CItem, CKind, CMarker, CTrack, CTransition, Composition, Document, Gain, Source, units_to_ticks};
|
||||
use crate::{Error, Report, Result};
|
||||
|
||||
type MobId = [u8; 32];
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum DataKind {
|
||||
Picture,
|
||||
Sound,
|
||||
Timecode,
|
||||
Other,
|
||||
}
|
||||
|
||||
fn data_kind(o: &Obj) -> DataKind {
|
||||
match o.weak_key(pid::DATA_DEFINITION).and_then(|k| <Auid>::try_from(k).ok()) {
|
||||
Some(k) if k == ddef::PICTURE || k == ddef::LEGACY_PICTURE => DataKind::Picture,
|
||||
Some(k) if k == ddef::SOUND || k == ddef::LEGACY_SOUND => DataKind::Sound,
|
||||
Some(k) if k == ddef::TIMECODE || k == ddef::LEGACY_TIMECODE => DataKind::Timecode,
|
||||
Some(_) => DataKind::Other,
|
||||
None => DataKind::Other,
|
||||
}
|
||||
}
|
||||
|
||||
fn len_of(o: &Obj) -> i64 {
|
||||
o.i64(pid::LENGTH).unwrap_or(0).max(0)
|
||||
}
|
||||
|
||||
/// The value of an indirect property: (type id, bytes).
|
||||
fn indirect(d: &[u8]) -> Option<(Auid, &[u8])> {
|
||||
if d.len() >= 17 && (d[0] == 0x4C || d[0] == 0x42) {
|
||||
return Some((d[1..17].try_into().ok()?, &d[17..]));
|
||||
}
|
||||
if d.len() >= 16 {
|
||||
return Some((d[..16].try_into().ok()?, &d[16..]));
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn tagged_values(o: &Obj, p: u16) -> Vec<(String, String)> {
|
||||
o.objs(p)
|
||||
.iter()
|
||||
.filter_map(|t| {
|
||||
let name = t.string(pid::TAG_NAME)?;
|
||||
let (ty, v) = indirect(t.data(pid::TAG_VALUE)?)?;
|
||||
let value = if ty == def::TYPE_STRING || v.len() % 2 == 0 { utf16_of(v) } else { String::new() };
|
||||
Some((name, value))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn indirect_f64(d: &[u8]) -> Option<f64> {
|
||||
let (_, v) = indirect(d)?;
|
||||
match v.len() {
|
||||
8 => rational_of(v).filter(|r| r.1 != 0).map(|(n, d)| n as f64 / d as f64),
|
||||
4 => Some(i32::from_le_bytes(v.try_into().ok()?) as f64),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
struct R<'a> {
|
||||
report: &'a mut Report,
|
||||
mobs: HashMap<MobId, &'a Obj>,
|
||||
essence: HashMap<MobId, &'a [u8]>,
|
||||
doc: Document,
|
||||
/// (file mob id, slot id, master key) → source index
|
||||
sources: HashMap<(MobId, u32, String), usize>,
|
||||
/// Composition mobs read as nested compositions: their index in `doc.nested`.
|
||||
nests: HashMap<MobId, usize>,
|
||||
/// The compositions being read, outermost first.
|
||||
open: Vec<MobId>,
|
||||
}
|
||||
|
||||
struct NestClip<'a> {
|
||||
mob_id: MobId,
|
||||
slot_id: u32,
|
||||
rate: (i64, i64),
|
||||
kind: CKind,
|
||||
name: String,
|
||||
mob: &'a Obj,
|
||||
}
|
||||
|
||||
/// Compositions nested deeper than this are read as gaps.
|
||||
const MAX_NESTING: usize = 16;
|
||||
|
||||
pub(crate) fn read(bytes: &[u8], report: &mut Report) -> Result<Document> {
|
||||
let root = store::read(bytes).map_err(|e| Error::Parse { format: "AAF", message: e })?;
|
||||
let header = root.strong(pid::ROOT_HEADER).ok_or_else(|| Error::Parse { format: "AAF", message: "no header object".into() })?;
|
||||
let content = header.strong(pid::CONTENT).ok_or_else(|| Error::Parse { format: "AAF", message: "no content storage".into() })?;
|
||||
let mut mobs = HashMap::new();
|
||||
for m in content.objs(pid::MOBS) {
|
||||
if let Some(id) = m.mob_id(pid::MOB_ID) {
|
||||
mobs.insert(id, m);
|
||||
}
|
||||
}
|
||||
let mut essence = HashMap::new();
|
||||
for e in content.objs(pid::ESSENCE_DATA) {
|
||||
if let (Some(id), Some(d)) = (e.mob_id(pid::ESSENCE_MOB_ID), e.stream(pid::ESSENCE_STREAM)) {
|
||||
essence.insert(id, d);
|
||||
}
|
||||
}
|
||||
let mut r = R { report, mobs, essence, doc: Document::default(), sources: HashMap::new(), nests: HashMap::new(), open: Vec::new() };
|
||||
// Top-level compositions: those no other composition uses, among the ones tagged top-level
|
||||
// when any are. (Premiere Pro tags a nested sequence's composition top-level too; it is still
|
||||
// only a nested sequence.) Compositions that only use each other in a circle all count. The
|
||||
// label older FilmCraft versions wrote for top-level counts as top-level too.
|
||||
let comps: Vec<&Obj> = content.objs(pid::MOBS).iter().filter(|m| m.class == cls::COMPOSITION_MOB).collect();
|
||||
let mut referenced = HashSet::new();
|
||||
for c in &comps {
|
||||
collect_refs(c, &mut referenced);
|
||||
}
|
||||
let is_top = |c: &&Obj| c.auid(pid::USAGE_CODE).is_some_and(|u| u == def::USAGE_TOP_LEVEL || u == def::USAGE_TOP_LEVEL_OLD);
|
||||
let tagged_top: Vec<&Obj> = comps.iter().copied().filter(is_top).collect();
|
||||
let pool = if tagged_top.is_empty() { comps } else { tagged_top };
|
||||
let unused: Vec<&Obj> = pool.iter().copied().filter(|c| c.mob_id(pid::MOB_ID).is_none_or(|id| !referenced.contains(&id))).collect();
|
||||
let top = if unused.is_empty() { pool } else { unused };
|
||||
for c in top {
|
||||
r.open.extend(c.mob_id(pid::MOB_ID));
|
||||
let comp = r.composition(c);
|
||||
r.open.clear();
|
||||
r.doc.compositions.push(comp);
|
||||
}
|
||||
if r.doc.compositions.is_empty() {
|
||||
return Err(Error::Empty);
|
||||
}
|
||||
Ok(r.doc)
|
||||
}
|
||||
|
||||
fn collect_refs(o: &Obj, out: &mut HashSet<MobId>) {
|
||||
if o.class == cls::SOURCE_CLIP
|
||||
&& let Some(id) = o.mob_id(pid::SOURCE_ID)
|
||||
{
|
||||
out.insert(id);
|
||||
}
|
||||
for (_, v) in &o.props {
|
||||
match v {
|
||||
Value::Strong(c) => collect_refs(c, out),
|
||||
Value::StrongVec(v) | Value::StrongSet(v, _) => v.iter().for_each(|c| collect_refs(c, out)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn rate_of(o: &Obj, p: u16) -> Option<(i64, i64)> {
|
||||
o.rational(p).filter(|r| r.0 > 0 && r.1 > 0)
|
||||
}
|
||||
|
||||
impl R<'_> {
|
||||
fn composition(&mut self, c: &Obj) -> Composition {
|
||||
let name = c.string(pid::MOB_NAME).unwrap_or_else(|| "Sequence".into());
|
||||
let slots = c.objs(pid::SLOTS);
|
||||
let pic_rate = slots
|
||||
.iter()
|
||||
.filter(|s| s.class == cls::TIMELINE_MOB_SLOT)
|
||||
.find(|s| s.strong(pid::SEGMENT).is_some_and(|g| matches!(data_kind(g), DataKind::Picture | DataKind::Timecode)))
|
||||
.and_then(|s| rate_of(s, pid::EDIT_RATE))
|
||||
.or_else(|| slots.iter().find_map(|s| rate_of(s, pid::EDIT_RATE)))
|
||||
.unwrap_or((25, 1));
|
||||
let rate = FrameRate::new(pic_rate.0, pic_rate.1);
|
||||
let tags = tagged_values(c, pid::MOB_USER_COMMENTS);
|
||||
let tag = |n: &str| tags.iter().find(|(k, _)| k == n).map(|(_, v)| v.clone());
|
||||
let (mut width, mut height) = tag("FilmCraft Frame Size")
|
||||
.and_then(|s| s.split_once('x').and_then(|(a, b)| Some((a.trim().parse().ok()?, b.trim().parse().ok()?))))
|
||||
.unwrap_or((0, 0));
|
||||
let mut sample_rate = tag("FilmCraft Audio Sample Rate").and_then(|s| s.parse().ok()).unwrap_or(0u32);
|
||||
let mut comp =
|
||||
Composition { name, rate, sample_rate: 48_000, width: 1920, height: 1080, start_tc: 0, drop: false, tracks: Vec::new(), markers: Vec::new() };
|
||||
let (mut nv, mut na) = (0, 0);
|
||||
for s in slots {
|
||||
let Some(seg) = s.strong(pid::SEGMENT) else { continue };
|
||||
if s.class == cls::EVENT_MOB_SLOT {
|
||||
let er = rate_of(s, pid::EVENT_EDIT_RATE).unwrap_or(pic_rate);
|
||||
comp.markers.extend(markers_of(seg, er));
|
||||
continue;
|
||||
}
|
||||
let er = rate_of(s, pid::EDIT_RATE).unwrap_or(pic_rate);
|
||||
let origin = s.i64(pid::ORIGIN).unwrap_or(0);
|
||||
match data_kind(seg) {
|
||||
DataKind::Timecode => {
|
||||
if let Some(tc) = find_class(seg, cls::TIMECODE) {
|
||||
comp.start_tc = tc.i64(pid::TC_START).unwrap_or(0);
|
||||
comp.drop = tc.u8(pid::TC_DROP).unwrap_or(0) != 0;
|
||||
}
|
||||
}
|
||||
kind @ (DataKind::Picture | DataKind::Sound) => {
|
||||
let ckind = if kind == DataKind::Picture { CKind::Picture } else { CKind::Sound };
|
||||
if ckind == CKind::Sound && sample_rate == 0 && er.1 == 1 && er.0 >= 8000 {
|
||||
sample_rate = er.0 as u32;
|
||||
}
|
||||
// Premiere Pro writes every video track into one slot: a nested scope with a
|
||||
// segment per track, the lowest track first. (A scope whose last segment
|
||||
// refers to the others is an effect over layers: one track, as before.)
|
||||
let layers: Vec<&Obj> = if ckind == CKind::Picture && seg.class == cls::NESTED_SCOPE && !refers_to_scope(seg, 0) {
|
||||
seg.objs(pid::NESTED_SLOTS).iter().collect()
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
let layered = !layers.is_empty();
|
||||
let whole = units_to_ticks(len_of(seg), er.0, er.1);
|
||||
for layer in if layered { layers } else { vec![seg] } {
|
||||
let mut items = self.segment(layer, er, ckind, 0);
|
||||
if layered {
|
||||
fit(&mut items, whole);
|
||||
}
|
||||
if origin > 0 {
|
||||
// material before the origin is not shown
|
||||
trim_front(&mut items, units_to_ticks(origin, er.0, er.1));
|
||||
}
|
||||
let number = s.u32(pid::PHYSICAL_TRACK_NUMBER).unwrap_or(0);
|
||||
let name = s.string(pid::SLOT_NAME).unwrap_or_default();
|
||||
let channels = if ckind == CKind::Sound {
|
||||
items
|
||||
.iter()
|
||||
.filter_map(|i| match i {
|
||||
CItem::Clip(c) => self.doc.sources.get(c.source).map(|s| s.channels),
|
||||
_ => None,
|
||||
})
|
||||
.max()
|
||||
.unwrap_or(1)
|
||||
.min(6)
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let n = if ckind == CKind::Picture {
|
||||
nv += 1;
|
||||
nv
|
||||
} else {
|
||||
na += 1;
|
||||
na
|
||||
};
|
||||
comp.tracks.push(CTrack { kind: ckind, name, number: if number > 0 && !layered { number } else { n }, channels, items });
|
||||
}
|
||||
}
|
||||
DataKind::Other => self.report.info("a slot of an unsupported data kind was skipped"),
|
||||
}
|
||||
}
|
||||
if width == 0 {
|
||||
// no size in the file: that of the first picture this composition shows, else of any
|
||||
let own = comp.tracks.iter().filter(|t| t.kind == CKind::Picture).flat_map(|t| &t.items).find_map(|i| match i {
|
||||
CItem::Clip(c) => self.doc.sources.get(c.source).filter(|s| s.kind == CKind::Picture && s.width > 0 && s.nested.is_none()),
|
||||
_ => None,
|
||||
});
|
||||
let pic = own.or_else(|| self.doc.sources.iter().find(|s| s.kind == CKind::Picture && s.width > 0));
|
||||
(width, height) = pic.map_or((1920, 1080), |p| (p.width, p.height));
|
||||
}
|
||||
comp.width = width;
|
||||
comp.height = height;
|
||||
if sample_rate > 0 {
|
||||
comp.sample_rate = sample_rate;
|
||||
}
|
||||
comp
|
||||
}
|
||||
|
||||
/// Items of a segment (a sequence or a single component).
|
||||
fn segment(&mut self, seg: &Obj, rate: (i64, i64), kind: CKind, depth: usize) -> Vec<CItem> {
|
||||
if depth > 32 {
|
||||
self.report.warn("segments nested too deeply were skipped");
|
||||
return vec![CItem::Filler(units_to_ticks(len_of(seg), rate.0, rate.1))];
|
||||
}
|
||||
if seg.class == cls::SEQUENCE {
|
||||
let mut out = Vec::new();
|
||||
for c in seg.objs(pid::COMPONENTS) {
|
||||
out.extend(self.component(c, rate, kind, depth + 1));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
self.component(seg, rate, kind, depth + 1)
|
||||
}
|
||||
|
||||
fn component(&mut self, c: &Obj, rate: (i64, i64), kind: CKind, depth: usize) -> Vec<CItem> {
|
||||
let len = units_to_ticks(len_of(c), rate.0, rate.1);
|
||||
match c.class {
|
||||
x if x == cls::FILLER => vec![CItem::Filler(len)],
|
||||
x if x == cls::SOURCE_CLIP => vec![self.clip(c, rate, kind, None)],
|
||||
x if x == cls::SEQUENCE => self.segment(c, rate, kind, depth),
|
||||
x if x == cls::TRANSITION => {
|
||||
let cut = units_to_ticks(c.i64(pid::CUT_POINT).unwrap_or(0), rate.0, rate.1);
|
||||
let og = c.strong(pid::OPERATION_GROUP);
|
||||
let effect = og
|
||||
.and_then(|o| tagged_values(o, pid::COMPONENT_USER_COMMENTS).into_iter().find(|(k, _)| k == "FilmCraft Effect").map(|(_, v)| v))
|
||||
.unwrap_or_else(|| {
|
||||
let op = og.and_then(|o| o.weak_key(pid::OPERATION)).and_then(|k| <Auid>::try_from(k).ok());
|
||||
match (kind, op) {
|
||||
(CKind::Sound, _) => "constant_power".into(),
|
||||
(_, Some(o)) if o == def::VIDEO_FADE_TO_BLACK => "dip_to_black".into(),
|
||||
(_, Some(o)) if o == def::SMPTE_VIDEO_WIPE => "wipe".into(),
|
||||
_ => "cross_dissolve".into(),
|
||||
}
|
||||
});
|
||||
vec![CItem::Transition(CTransition { len, cut: cut.clamp(Tick::ZERO, len), effect })]
|
||||
}
|
||||
x if x == cls::OPERATION_GROUP => {
|
||||
let op = c.weak_key(pid::OPERATION).and_then(|k| <Auid>::try_from(k).ok());
|
||||
let inputs = c.objs(pid::INPUT_SEGMENTS);
|
||||
let Some(input) = inputs.first() else {
|
||||
self.report.info("an effect without input was imported as a gap");
|
||||
return vec![CItem::Filler(len)];
|
||||
};
|
||||
let gain = if op == Some(def::MONO_AUDIO_GAIN) {
|
||||
self.gain(c, len, rate)
|
||||
} else {
|
||||
self.report.warn("effects other than audio gain are not imported (their first input is used)");
|
||||
None
|
||||
};
|
||||
let mut items = self.segment(input, rate, kind, depth);
|
||||
// the operation's length rules
|
||||
fit(&mut items, len);
|
||||
if let Some(g) = gain {
|
||||
match items.as_mut_slice() {
|
||||
[CItem::Clip(cl)] => cl.gain = Some(g),
|
||||
_ => self.report.warn("audio gain around several clips was not imported"),
|
||||
}
|
||||
}
|
||||
items
|
||||
}
|
||||
x if x == cls::SELECTOR => match c.strong(pid::SELECTED) {
|
||||
Some(s) => {
|
||||
let mut items = self.segment(s, rate, kind, depth);
|
||||
fit(&mut items, len);
|
||||
items
|
||||
}
|
||||
None => vec![CItem::Filler(len)],
|
||||
},
|
||||
x if x == cls::NESTED_SCOPE => match c.objs(pid::NESTED_SLOTS).last() {
|
||||
Some(s) => {
|
||||
let mut items = self.segment(s, rate, kind, depth);
|
||||
fit(&mut items, len);
|
||||
items
|
||||
}
|
||||
None => vec![CItem::Filler(len)],
|
||||
},
|
||||
_ => {
|
||||
self.report.info("an unsupported component was imported as a gap");
|
||||
vec![CItem::Filler(len)]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn gain(&mut self, og: &Obj, len: Tick, _rate: (i64, i64)) -> Option<Gain> {
|
||||
let p = og
|
||||
.objs(pid::PARAMETERS)
|
||||
.iter()
|
||||
.find(|p| p.auid(pid::PARAMETER_DEFINITION) == Some(def::PARAM_AMPLITUDE))
|
||||
.or_else(|| og.objs(pid::PARAMETERS).first())?;
|
||||
if p.class == cls::CONSTANT_VALUE {
|
||||
return p.data(pid::CONSTANT_VALUE).and_then(indirect_f64).map(Gain::Constant);
|
||||
}
|
||||
if p.class == cls::VARYING_VALUE {
|
||||
let linear = p.weak_key(pid::INTERPOLATION).and_then(|k| <Auid>::try_from(k).ok()) != Some(def::INTERP_CONSTANT);
|
||||
let points: Vec<(Tick, f64)> = p
|
||||
.objs(pid::POINT_LIST)
|
||||
.iter()
|
||||
.filter_map(|cp| {
|
||||
let (n, d) = cp.rational(pid::CP_TIME).filter(|r| r.1 != 0)?;
|
||||
let v = cp.data(pid::CP_VALUE).and_then(indirect_f64)?;
|
||||
Some((Tick((len.0 as i128 * n as i128 / d as i128).clamp(-(1i128 << 56), 1i128 << 56) as i64), v))
|
||||
})
|
||||
.collect();
|
||||
return (!points.is_empty()).then_some(Gain::Varying { linear, points });
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn clip(&mut self, c: &Obj, rate: (i64, i64), kind: CKind, master_key: Option<String>) -> CItem {
|
||||
let len = units_to_ticks(len_of(c), rate.0, rate.1);
|
||||
let start = units_to_ticks(c.i64(pid::START_TIME).unwrap_or(0), rate.0, rate.1);
|
||||
let name = tagged_values(c, pid::COMPONENT_USER_COMMENTS).into_iter().find(|(k, _)| k == "Clip Name").map(|(_, v)| v).unwrap_or_default();
|
||||
let (Some(id), Some(slot)) = (c.mob_id(pid::SOURCE_ID), c.u32(pid::SOURCE_MOB_SLOT_ID)) else { return CItem::Filler(len) };
|
||||
if id == [0; 32] {
|
||||
return CItem::Filler(len);
|
||||
}
|
||||
if let Some(mob) = self.mobs.get(&id).copied().filter(|m| m.class == cls::COMPOSITION_MOB) {
|
||||
return self.nest_clip(c, NestClip { mob, mob_id: id, slot_id: slot, rate, kind, name });
|
||||
}
|
||||
match self.resolve(id, slot, start, kind, master_key, 0) {
|
||||
Some((source, t)) => CItem::Clip(CClip { len, source, start: t, gain: None, name }),
|
||||
None => CItem::Filler(len),
|
||||
}
|
||||
}
|
||||
|
||||
/// A source clip that points at a composition: a nested sequence (Premiere Pro writes its
|
||||
/// nested sequences this way). The composition is read once, however many clips use it.
|
||||
fn nest_clip(&mut self, c: &Obj, clip: NestClip<'_>) -> CItem {
|
||||
let NestClip { mob, mob_id: id, slot_id, rate, kind, name } = clip;
|
||||
let len = units_to_ticks(len_of(c), rate.0, rate.1);
|
||||
let index = match self.nests.get(&id) {
|
||||
Some(&i) => i,
|
||||
None => {
|
||||
if self.open.contains(&id) || self.open.len() >= MAX_NESTING {
|
||||
self.report.warn("a composition nested in itself or nested too deeply was imported as a gap");
|
||||
return CItem::Filler(len);
|
||||
}
|
||||
self.open.push(id);
|
||||
let comp = self.composition(mob);
|
||||
self.open.pop();
|
||||
let i = self.doc.nested.len();
|
||||
self.doc.nested.push(comp);
|
||||
self.nests.insert(id, i);
|
||||
i
|
||||
}
|
||||
};
|
||||
// the start counts edit units of the slot the clip points at
|
||||
let slot_rate = mob.objs(pid::SLOTS).iter().find(|s| s.u32(pid::SLOT_ID) == Some(slot_id)).and_then(|s| rate_of(s, pid::EDIT_RATE)).unwrap_or(rate);
|
||||
let start = units_to_ticks(c.i64(pid::START_TIME).unwrap_or(0), slot_rate.0, slot_rate.1);
|
||||
let skey = (id, if kind == CKind::Picture { 0 } else { 1 }, "composition".to_string());
|
||||
let source =
|
||||
match self.sources.get(&skey) {
|
||||
Some(&i) => i,
|
||||
None => {
|
||||
let Some(comp) = self.doc.nested.get(index) else { return CItem::Filler(len) };
|
||||
let length =
|
||||
comp.tracks
|
||||
.iter()
|
||||
.map(|t| {
|
||||
Tick(t.items.iter().fold(0i64, |a, i| {
|
||||
if matches!(i, CItem::Transition(_)) { a.saturating_sub(i.len().0) } else { a.saturating_add(i.len().0) }
|
||||
}))
|
||||
})
|
||||
.max()
|
||||
.unwrap_or(Tick::ZERO);
|
||||
let channels = if kind == CKind::Sound { 2 } else { 0 };
|
||||
let s = Source {
|
||||
key: format!("composition:{}", hex(&id)),
|
||||
name: comp.name.clone(),
|
||||
kind,
|
||||
path: None,
|
||||
channel: None,
|
||||
channels,
|
||||
file_channels: channels,
|
||||
width: comp.width,
|
||||
height: comp.height,
|
||||
frame_rate: comp.rate,
|
||||
sample_rate: comp.sample_rate,
|
||||
bits: 16,
|
||||
length,
|
||||
offset: Tick::ZERO,
|
||||
start_tc: None,
|
||||
tc_rate: comp.rate,
|
||||
embedded: None,
|
||||
markers: Vec::new(),
|
||||
nested: Some(index),
|
||||
};
|
||||
let i = self.doc.sources.len();
|
||||
self.doc.sources.push(s);
|
||||
self.sources.insert(skey, i);
|
||||
i
|
||||
}
|
||||
};
|
||||
CItem::Clip(CClip { len, source, start, gain: None, name })
|
||||
}
|
||||
|
||||
/// Follow a source reference to a file source mob: (source index, file time).
|
||||
fn resolve(&mut self, id: MobId, slot_id: u32, start: Tick, kind: CKind, master_key: Option<String>, depth: usize) -> Option<(usize, Tick)> {
|
||||
if depth > 16 {
|
||||
return None;
|
||||
}
|
||||
let Some(mob) = self.mobs.get(&id).copied() else {
|
||||
self.report.warn("a clip references a mob that is not in the file (imported as a gap)");
|
||||
return None;
|
||||
};
|
||||
let slot = mob.objs(pid::SLOTS).iter().find(|s| s.u32(pid::SLOT_ID) == Some(slot_id))?;
|
||||
let rate = rate_of(slot, pid::EDIT_RATE).unwrap_or((25, 1));
|
||||
let seg = slot.strong(pid::SEGMENT)?;
|
||||
if mob.class == cls::COMPOSITION_MOB {
|
||||
self.report.warn("nested compositions are not supported (imported as gaps)");
|
||||
return None;
|
||||
}
|
||||
if mob.class == cls::MASTER_MOB {
|
||||
let key = master_key.unwrap_or_else(|| hex(&id));
|
||||
let clip = first_clip(seg)?;
|
||||
let inner = units_to_ticks(clip.i64(pid::START_TIME).unwrap_or(0), rate.0, rate.1);
|
||||
let next = clip.mob_id(pid::SOURCE_ID)?;
|
||||
let next_slot = clip.u32(pid::SOURCE_MOB_SLOT_ID)?;
|
||||
if next == [0; 32] {
|
||||
return None;
|
||||
}
|
||||
let markers = mob
|
||||
.objs(pid::SLOTS)
|
||||
.iter()
|
||||
.filter(|s| s.class == cls::EVENT_MOB_SLOT)
|
||||
.flat_map(|s| s.strong(pid::SEGMENT).map(|g| markers_of(g, rate_of(s, pid::EVENT_EDIT_RATE).unwrap_or(rate))).unwrap_or_default())
|
||||
.collect::<Vec<_>>();
|
||||
let r = self.resolve(next, next_slot, start + inner, kind, Some(key), depth + 1)?;
|
||||
let src = &mut self.doc.sources[r.0];
|
||||
if src.markers.is_empty() {
|
||||
src.markers = markers;
|
||||
}
|
||||
if src.name.is_empty()
|
||||
&& let Some(n) = mob.string(pid::MOB_NAME)
|
||||
{
|
||||
src.name = n;
|
||||
}
|
||||
return Some(r);
|
||||
}
|
||||
// a source mob: file (has a file descriptor) or physical (tape / import)
|
||||
let desc = mob.strong(pid::ESSENCE_DESCRIPTION);
|
||||
let is_file = desc.is_some_and(|d| d.get(pid::SAMPLE_RATE).is_some() || d.get(pid::LOCATOR).is_some() || self.essence.contains_key(&id));
|
||||
if !is_file {
|
||||
return None;
|
||||
}
|
||||
let key = master_key.unwrap_or_else(|| hex(&id));
|
||||
let skey = (id, slot_id, key.clone());
|
||||
if let Some(&i) = self.sources.get(&skey) {
|
||||
return Some((i, start));
|
||||
}
|
||||
let d = desc?;
|
||||
let seg_kind = match data_kind(seg) {
|
||||
DataKind::Picture => CKind::Picture,
|
||||
DataKind::Sound => CKind::Sound,
|
||||
_ => kind,
|
||||
};
|
||||
let path = d.objs(pid::LOCATOR).iter().find_map(|l| l.string(pid::URL_STRING)).map(|u| crate::common::file_url_to_path(&u));
|
||||
let file_rate = rate_of(d, pid::SAMPLE_RATE).unwrap_or(rate);
|
||||
let length =
|
||||
d.i64(pid::FILE_LENGTH).map(|l| units_to_ticks(l, file_rate.0, file_rate.1)).unwrap_or_else(|| units_to_ticks(len_of(seg), rate.0, rate.1));
|
||||
let sound_slots = mob.objs(pid::SLOTS).iter().filter(|s| s.strong(pid::SEGMENT).is_some_and(|g| data_kind(g) == DataKind::Sound)).count();
|
||||
let file_channels = d.u32(pid::CHANNELS).unwrap_or(1).max(1);
|
||||
let channel = (seg_kind == CKind::Sound && file_channels > 1 && sound_slots > 1)
|
||||
.then(|| slot.u32(pid::PHYSICAL_TRACK_NUMBER).unwrap_or(slot_id).saturating_sub(1).min(file_channels - 1));
|
||||
let mut layout = d.u8(pid::FRAME_LAYOUT).unwrap_or(0);
|
||||
if layout > 4 {
|
||||
layout = 0;
|
||||
}
|
||||
let stored_h = d.u32(pid::STORED_HEIGHT).unwrap_or(0);
|
||||
let fr = FrameRate::new(file_rate.0, file_rate.1);
|
||||
// timecode from the physical source mob
|
||||
let tc = first_clip(seg).and_then(|clip| {
|
||||
let tid = clip.mob_id(pid::SOURCE_ID)?;
|
||||
let tape = self.mobs.get(&tid)?;
|
||||
let tslot = tape.objs(pid::SLOTS).iter().find_map(|s| {
|
||||
let g = s.strong(pid::SEGMENT)?;
|
||||
let t = find_class(g, cls::TIMECODE)?;
|
||||
Some((t.i64(pid::TC_START).unwrap_or(0), t.u16(pid::TC_FPS).unwrap_or(25).max(1) as i64, rate_of(s, pid::EDIT_RATE)))
|
||||
})?;
|
||||
let off = units_to_ticks(clip.i64(pid::START_TIME).unwrap_or(0), rate.0, rate.1);
|
||||
let tcr = tslot.2.map(|r| FrameRate::new(r.0, r.1)).unwrap_or_else(|| FrameRate::new(tslot.1, 1));
|
||||
Some((tslot.0 + tcr.frame_at(off), tcr))
|
||||
});
|
||||
let mut s = Source {
|
||||
key,
|
||||
name: mob.string(pid::MOB_NAME).unwrap_or_default(),
|
||||
kind: seg_kind,
|
||||
path,
|
||||
channel,
|
||||
channels: if channel.is_some() { 1 } else { file_channels },
|
||||
file_channels,
|
||||
width: d.u32(pid::STORED_WIDTH).unwrap_or(0),
|
||||
height: if matches!(layout, 1 | 3) { stored_h.saturating_mul(2) } else { stored_h },
|
||||
frame_rate: if seg_kind == CKind::Picture { fr } else { FrameRate::FPS_25 },
|
||||
sample_rate: d.rational(pid::AUDIO_SAMPLING_RATE).filter(|r| r.1 > 0 && r.0 > 0).map(|r| (r.0 / r.1) as u32).unwrap_or(file_rate.0 as u32),
|
||||
bits: d.u32(pid::QUANTIZATION_BITS).unwrap_or(16).clamp(8, 32) as u16,
|
||||
length,
|
||||
offset: Tick::ZERO,
|
||||
start_tc: tc.map(|t| t.0),
|
||||
tc_rate: tc.map(|t| t.1).unwrap_or(fr),
|
||||
embedded: None,
|
||||
markers: Vec::new(),
|
||||
nested: None,
|
||||
};
|
||||
if s.kind == CKind::Sound {
|
||||
s.frame_rate = FrameRate::FPS_25;
|
||||
if let Some(data) = self.essence.get(&id) {
|
||||
s.embedded = Some(data.to_vec());
|
||||
// embedded essence may be a whole WAVE / AIFF file
|
||||
if let Some((pcm, ch, sr, bits)) = crate::wav::parse_wav(data) {
|
||||
s.embedded = Some(pcm);
|
||||
s.file_channels = ch as u32;
|
||||
s.channels = if s.channel.is_some() { 1 } else { ch as u32 };
|
||||
s.sample_rate = sr;
|
||||
s.bits = bits;
|
||||
}
|
||||
}
|
||||
}
|
||||
if s.kind == CKind::Picture && s.width == 0 {
|
||||
s.width = 1920;
|
||||
s.height = 1080;
|
||||
}
|
||||
let i = self.doc.sources.len();
|
||||
self.doc.sources.push(s);
|
||||
self.sources.insert(skey, i);
|
||||
Some((i, start))
|
||||
}
|
||||
}
|
||||
|
||||
/// Drop `t` from the front of a track's items (slot origin).
|
||||
fn trim_front(items: &mut Vec<CItem>, mut t: Tick) {
|
||||
while t > Tick::ZERO && !items.is_empty() {
|
||||
let l = items[0].len();
|
||||
if matches!(items[0], CItem::Transition(_)) {
|
||||
items.remove(0);
|
||||
continue;
|
||||
}
|
||||
if l <= t {
|
||||
items.remove(0);
|
||||
t -= l;
|
||||
} else {
|
||||
match &mut items[0] {
|
||||
CItem::Filler(x) => *x -= t,
|
||||
CItem::Clip(c) => {
|
||||
c.len -= t;
|
||||
c.start += t;
|
||||
}
|
||||
CItem::Transition(_) => {}
|
||||
}
|
||||
t = Tick::ZERO;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Make the items exactly `len` long (an operation group / selector is as long as itself).
|
||||
fn fit(items: &mut Vec<CItem>, len: Tick) {
|
||||
let total = Tick(items.iter().fold(0i64, |a, i| if matches!(i, CItem::Transition(_)) { a.saturating_sub(i.len().0) } else { a.saturating_add(i.len().0) }));
|
||||
if total == len || items.is_empty() {
|
||||
if items.is_empty() {
|
||||
items.push(CItem::Filler(len));
|
||||
}
|
||||
return;
|
||||
}
|
||||
if total < len {
|
||||
items.push(CItem::Filler(len - total));
|
||||
return;
|
||||
}
|
||||
let mut excess = total - len;
|
||||
while excess > Tick::ZERO {
|
||||
match items.last_mut() {
|
||||
Some(CItem::Filler(x)) | Some(CItem::Clip(CClip { len: x, .. })) if *x > excess => {
|
||||
*x -= excess;
|
||||
excess = Tick::ZERO;
|
||||
}
|
||||
Some(CItem::Transition(_)) => {
|
||||
items.pop();
|
||||
}
|
||||
Some(other) => {
|
||||
excess -= other.len();
|
||||
items.pop();
|
||||
}
|
||||
None => break,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether anything inside `o` is a scope reference (a nested scope used as an effect's layers).
|
||||
fn refers_to_scope(o: &Obj, depth: usize) -> bool {
|
||||
if o.class == cls::SCOPE_REFERENCE {
|
||||
return true;
|
||||
}
|
||||
if depth > 32 {
|
||||
return false;
|
||||
}
|
||||
o.props.iter().any(|(_, v)| match v {
|
||||
Value::Strong(c) => refers_to_scope(c, depth + 1),
|
||||
Value::StrongVec(v) | Value::StrongSet(v, _) => v.iter().any(|c| refers_to_scope(c, depth + 1)),
|
||||
_ => false,
|
||||
})
|
||||
}
|
||||
|
||||
fn first_clip(seg: &Obj) -> Option<&Obj> {
|
||||
if seg.class == cls::SOURCE_CLIP {
|
||||
return Some(seg);
|
||||
}
|
||||
if seg.class == cls::SEQUENCE {
|
||||
return seg.objs(pid::COMPONENTS).iter().find_map(first_clip);
|
||||
}
|
||||
// essence group (choices 0x0501) / operation group inputs
|
||||
seg.objs(0x0501).iter().find_map(first_clip).or_else(|| seg.objs(pid::INPUT_SEGMENTS).iter().find_map(first_clip))
|
||||
}
|
||||
|
||||
fn find_class(seg: &Obj, class: Auid) -> Option<&Obj> {
|
||||
if seg.class == class {
|
||||
return Some(seg);
|
||||
}
|
||||
seg.objs(pid::COMPONENTS).iter().find_map(|c| find_class(c, class))
|
||||
}
|
||||
|
||||
fn markers_of(seg: &Obj, rate: (i64, i64)) -> Vec<CMarker> {
|
||||
let events: Vec<&Obj> = if seg.class == cls::SEQUENCE { seg.objs(pid::COMPONENTS).iter().collect() } else { vec![seg] };
|
||||
events
|
||||
.into_iter()
|
||||
.filter(|e| e.class == cls::COMMENT_MARKER || e.class == cls::DESCRIPTIVE_MARKER || e.get(pid::POSITION).is_some())
|
||||
.map(|e| {
|
||||
let tags = tagged_values(e, pid::COMPONENT_USER_COMMENTS);
|
||||
let tag = |n: &str| tags.iter().find(|(k, _)| k == n).map(|(_, v)| v.clone());
|
||||
let comment = e.string(pid::COMMENT).unwrap_or_default();
|
||||
let start = units_to_ticks(e.i64(pid::POSITION).unwrap_or(0), rate.0, rate.1);
|
||||
CMarker {
|
||||
start,
|
||||
duration: units_to_ticks(e.i64(pid::LENGTH).unwrap_or(0).max(0), rate.0, rate.1),
|
||||
name: tag("Name").unwrap_or_else(|| comment.clone()),
|
||||
comment: tag("Comment").unwrap_or_else(|| if tags.is_empty() { String::new() } else { comment.clone() }),
|
||||
color: tag("Color"),
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn hex(b: &[u8]) -> String {
|
||||
b.iter().map(|x| format!("{x:02x}")).collect()
|
||||
}
|
||||
@@ -1,795 +0,0 @@
|
||||
//! Composition model → AAF objects.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use filmcraft_time::{FrameRate, Tick};
|
||||
|
||||
use super::ids::{META_DICTIONARY, ROOT, cls, ddef, def, path, pid};
|
||||
use super::store::{self, Auid, Obj, Value, rational, utf16z};
|
||||
use crate::comp::{CItem, CKind, CMarker, Composition, Document, Gain, Source, ticks_to_units};
|
||||
use crate::{Error, Report, Result};
|
||||
|
||||
/// UMID-style mob id (SMPTE 330 basic UMID): label, length 0x13, instance 0, material number.
|
||||
pub(crate) fn mob_id(seed: u64, n: u64) -> [u8; 32] {
|
||||
let mut id = [0u8; 32];
|
||||
id[..12].copy_from_slice(&[0x06, 0x0A, 0x2B, 0x34, 0x01, 0x01, 0x01, 0x05, 0x01, 0x01, 0x0F, 0x20]);
|
||||
id[12] = 0x13;
|
||||
let a = mix(seed ^ n.wrapping_mul(0x9E37_79B9_7F4A_7C15));
|
||||
let b = mix(a ^ 0xD6E8_FEB8_6659_FD93);
|
||||
id[16..24].copy_from_slice(&a.to_le_bytes());
|
||||
id[24..32].copy_from_slice(&b.to_le_bytes());
|
||||
// a "random" material number per RFC 4122 v4 layout keeps it a valid UUID
|
||||
id[22] = (id[22] & 0x0F) | 0x40;
|
||||
id[24] = (id[24] & 0x3F) | 0x80;
|
||||
id
|
||||
}
|
||||
|
||||
fn mix(mut z: u64) -> u64 {
|
||||
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
|
||||
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
|
||||
z ^ (z >> 31)
|
||||
}
|
||||
|
||||
pub(crate) fn fnv(s: &[u8], h: u64) -> u64 {
|
||||
s.iter().fold(h, |h, &b| (h ^ b as u64).wrapping_mul(0x0000_0100_0000_01B3))
|
||||
}
|
||||
|
||||
fn timestamp() -> Vec<u8> {
|
||||
// 1970-01-01 00:00:00.00: FilmCraft writes reproducible files
|
||||
let mut v = 1970i16.to_le_bytes().to_vec();
|
||||
v.extend_from_slice(&[1, 1, 0, 0, 0, 0]);
|
||||
v
|
||||
}
|
||||
|
||||
fn weak(path: [u16; 3], key: Auid) -> Value {
|
||||
Value::Weak(path.to_vec(), pid::IDENTIFICATION, key.to_vec())
|
||||
}
|
||||
|
||||
fn data_def(kind: CKind) -> Auid {
|
||||
match kind {
|
||||
CKind::Picture => ddef::PICTURE,
|
||||
CKind::Sound => ddef::SOUND,
|
||||
}
|
||||
}
|
||||
|
||||
/// An indirect value: byte order, type id, value.
|
||||
pub(crate) fn indirect(ty: Auid, v: &[u8]) -> Vec<u8> {
|
||||
let mut d = vec![0x4C];
|
||||
d.extend_from_slice(&ty);
|
||||
d.extend_from_slice(v);
|
||||
d
|
||||
}
|
||||
|
||||
fn tagged(name: &str, value: &str) -> Obj {
|
||||
Obj::new(cls::TAGGED_VALUE).data_prop(pid::TAG_NAME, utf16z(name)).data_prop(pid::TAG_VALUE, indirect(def::TYPE_STRING, &utf16z(value)))
|
||||
}
|
||||
|
||||
fn gain_rational(g: f64) -> Vec<u8> {
|
||||
rational((g.max(0.0) * 65536.0).round().min(i32::MAX as f64) as i64, 65536)
|
||||
}
|
||||
|
||||
fn definition(class: Auid, id: Auid, name: &str) -> Obj {
|
||||
Obj::new(class).data_prop(pid::IDENTIFICATION, id.to_vec()).data_prop(pid::NAME, utf16z(name)).data_prop(pid::DESCRIPTION, utf16z(""))
|
||||
}
|
||||
|
||||
struct W<'a> {
|
||||
report: &'a mut Report,
|
||||
inexact: bool,
|
||||
}
|
||||
|
||||
struct IdGen {
|
||||
seed: u64,
|
||||
next: u64,
|
||||
}
|
||||
|
||||
impl IdGen {
|
||||
fn for_document(doc: &Document, comp: &Composition) -> Self {
|
||||
let mut seed = fnv(comp.name.as_bytes(), 0xCBF2_9CE4_8422_2325);
|
||||
for source in &doc.sources {
|
||||
seed = fnv(source.path.as_deref().unwrap_or("").as_bytes(), fnv(source.key.as_bytes(), seed));
|
||||
}
|
||||
seed = fnv(&(comp.tracks.len() as u64).to_le_bytes(), seed);
|
||||
Self { seed, next: 0 }
|
||||
}
|
||||
|
||||
fn next(&mut self) -> [u8; 32] {
|
||||
self.next += 1;
|
||||
mob_id(self.seed, self.next)
|
||||
}
|
||||
}
|
||||
|
||||
struct MediaOutput {
|
||||
mobs: Vec<Obj>,
|
||||
essence: Vec<Obj>,
|
||||
master_ref: HashMap<usize, ([u8; 32], u32)>,
|
||||
}
|
||||
|
||||
type FileMob = ((Option<String>, usize, CKind), [u8; 32], Vec<Obj>, usize);
|
||||
|
||||
struct GroupSlots {
|
||||
master_id: [u8; 32],
|
||||
tape_id: [u8; 32],
|
||||
timecode: Option<(i64, filmcraft_time::FrameRate)>,
|
||||
master_slots: Vec<Obj>,
|
||||
tape_slots: Vec<Obj>,
|
||||
files: Vec<FileMob>,
|
||||
master_ref: HashMap<usize, ([u8; 32], u32)>,
|
||||
}
|
||||
|
||||
struct GroupSlotBuilder<'a, 'b> {
|
||||
doc: &'a Document,
|
||||
master_id: [u8; 32],
|
||||
tape_id: [u8; 32],
|
||||
ids: &'b mut IdGen,
|
||||
files: &'b mut Vec<FileMob>,
|
||||
master_slots: &'b mut Vec<Obj>,
|
||||
tape_slots: &'b mut Vec<Obj>,
|
||||
master_ref: &'b mut HashMap<usize, ([u8; 32], u32)>,
|
||||
}
|
||||
|
||||
struct FileSlotInput<'a> {
|
||||
source: &'a Source,
|
||||
file_slot: u32,
|
||||
length: i64,
|
||||
has_timecode: bool,
|
||||
tape_id: [u8; 32],
|
||||
member_index: usize,
|
||||
slots: &'a mut Vec<Obj>,
|
||||
rate: (i64, i64),
|
||||
}
|
||||
|
||||
impl W<'_> {
|
||||
/// Edit units at `rate` of tick `t`.
|
||||
fn u(&mut self, t: Tick, rate: (i64, i64)) -> i64 {
|
||||
let (n, exact) = ticks_to_units(t, rate.0, rate.1);
|
||||
if !exact {
|
||||
self.inexact = true;
|
||||
}
|
||||
n
|
||||
}
|
||||
}
|
||||
|
||||
fn source_rate(s: &Source) -> (i64, i64) {
|
||||
match s.kind {
|
||||
CKind::Picture => (s.frame_rate.num, s.frame_rate.den),
|
||||
CKind::Sound => (s.sample_rate.max(1) as i64, 1),
|
||||
}
|
||||
}
|
||||
|
||||
fn write_media(doc: &Document, w: &mut W<'_>, ids: &mut IdGen) -> MediaOutput {
|
||||
let mut groups: Vec<(String, Vec<usize>)> = Vec::new();
|
||||
for (index, source) in doc.sources.iter().enumerate() {
|
||||
if source.nested.is_some() {
|
||||
continue;
|
||||
}
|
||||
match groups.iter_mut().find(|(key, _)| *key == source.key) {
|
||||
Some((_, members)) => members.push(index),
|
||||
None => groups.push((source.key.clone(), vec![index])),
|
||||
}
|
||||
}
|
||||
|
||||
let mut output = MediaOutput { mobs: Vec::new(), essence: Vec::new(), master_ref: HashMap::new() };
|
||||
for (_, members) in groups {
|
||||
write_source_group(doc, &members, w, ids, &mut output);
|
||||
}
|
||||
output
|
||||
}
|
||||
|
||||
fn write_source_group(doc: &Document, members: &[usize], w: &mut W<'_>, ids: &mut IdGen, output: &mut MediaOutput) {
|
||||
let first = &doc.sources[members[0]];
|
||||
let slots = build_group_slots(doc, members, w, ids);
|
||||
output.master_ref.extend(slots.master_ref);
|
||||
let mut master_slots = slots.master_slots;
|
||||
add_master_markers(doc, members, w, &mut master_slots);
|
||||
output.mobs.push(
|
||||
Obj::new(cls::MASTER_MOB)
|
||||
.data_prop(pid::MOB_ID, slots.master_id.to_vec())
|
||||
.data_prop(pid::MOB_NAME, utf16z(&first.name))
|
||||
.data_prop(pid::MOB_LAST_MODIFIED, timestamp())
|
||||
.data_prop(pid::MOB_CREATION_TIME, timestamp())
|
||||
.with(pid::SLOTS, Value::StrongVec(master_slots)),
|
||||
);
|
||||
let tape_id = slots.tape_id;
|
||||
let timecode = slots.timecode;
|
||||
let tape_slots = slots.tape_slots;
|
||||
add_file_mobs(doc, slots.files, w, output);
|
||||
add_tape_mob(first, tape_id, timecode, tape_slots, output);
|
||||
}
|
||||
|
||||
fn build_group_slots(doc: &Document, members: &[usize], w: &mut W<'_>, ids: &mut IdGen) -> GroupSlots {
|
||||
let master_id = ids.next();
|
||||
let tape_id = ids.next();
|
||||
let timecode = members.iter().find_map(|&i| doc.sources[i].start_tc.map(|t| (t, doc.sources[i].tc_rate)));
|
||||
let mut tape_slots = Vec::new();
|
||||
if let Some((start, rate)) = timecode {
|
||||
tape_slots.push(timecode_slot(members, doc, w, start, rate));
|
||||
}
|
||||
let mut files: Vec<FileMob> = Vec::new();
|
||||
let mut master_slots = Vec::new();
|
||||
let mut master_ref = HashMap::new();
|
||||
let mut builder = GroupSlotBuilder {
|
||||
doc,
|
||||
master_id,
|
||||
tape_id,
|
||||
ids,
|
||||
files: &mut files,
|
||||
master_slots: &mut master_slots,
|
||||
tape_slots: &mut tape_slots,
|
||||
master_ref: &mut master_ref,
|
||||
};
|
||||
for (member_index, &source_index) in members.iter().enumerate() {
|
||||
builder.add_source(source_index, member_index, timecode.is_some(), w);
|
||||
}
|
||||
GroupSlots { master_id, tape_id, timecode, master_slots, tape_slots, files, master_ref }
|
||||
}
|
||||
|
||||
fn timecode_slot(members: &[usize], doc: &Document, w: &mut W<'_>, start: i64, rate: FrameRate) -> Obj {
|
||||
let edit_rate = (rate.num, rate.den);
|
||||
let len = members.iter().map(|&i| doc.sources[i].length).max().unwrap_or(Tick::ZERO);
|
||||
let units = w.u(len, edit_rate);
|
||||
timeline_slot(
|
||||
1,
|
||||
"TC1",
|
||||
0,
|
||||
edit_rate,
|
||||
Obj::new(cls::TIMECODE)
|
||||
.with(pid::DATA_DEFINITION, weak(path::DATA_DEFS, ddef::TIMECODE))
|
||||
.data_prop(pid::LENGTH, units.to_le_bytes().to_vec())
|
||||
.data_prop(pid::TC_START, start.to_le_bytes().to_vec())
|
||||
.data_prop(pid::TC_FPS, (rate.timecode_base().clamp(1, u16::MAX as i64) as u16).to_le_bytes().to_vec())
|
||||
.data_prop(pid::TC_DROP, vec![0]),
|
||||
)
|
||||
}
|
||||
|
||||
impl GroupSlotBuilder<'_, '_> {
|
||||
fn add_source(&mut self, source_index: usize, member_index: usize, has_timecode: bool, w: &mut W<'_>) {
|
||||
let source = &self.doc.sources[source_index];
|
||||
let rate = source_rate(source);
|
||||
let embedded_key = if source.embedded.is_some() { source_index } else { usize::MAX };
|
||||
let file_key = (source.path.clone(), embedded_key, source.kind);
|
||||
let file_slot = source.channel.map_or(1, |channel| channel + 1);
|
||||
let len_units = w.u(source.length, rate);
|
||||
let file_index = match self.files.iter().position(|file| file.0 == file_key) {
|
||||
Some(index) => index,
|
||||
None => {
|
||||
self.files.push((file_key, self.ids.next(), Vec::new(), source_index));
|
||||
self.files.len() - 1
|
||||
}
|
||||
};
|
||||
let file_id = self.files[file_index].1;
|
||||
add_file_slot(FileSlotInput {
|
||||
source,
|
||||
file_slot,
|
||||
length: len_units,
|
||||
has_timecode,
|
||||
tape_id: self.tape_id,
|
||||
member_index,
|
||||
slots: &mut self.files[file_index].2,
|
||||
rate,
|
||||
});
|
||||
if has_timecode {
|
||||
let tape_slot_id = 2 + member_index as u32;
|
||||
self.tape_slots.push(timeline_slot(
|
||||
tape_slot_id,
|
||||
&slot_name(source.kind, member_index as u32 + 1),
|
||||
member_index as u32 + 1,
|
||||
rate,
|
||||
source_clip(source.kind, len_units, [0; 32], 0, 0),
|
||||
));
|
||||
}
|
||||
let master_slot = member_index as u32 + 1;
|
||||
self.master_slots.push(timeline_slot(
|
||||
master_slot,
|
||||
&slot_name(source.kind, master_slot),
|
||||
master_slot,
|
||||
rate,
|
||||
source_clip(source.kind, len_units, file_id, file_slot, 0),
|
||||
));
|
||||
self.master_ref.insert(source_index, (self.master_id, master_slot));
|
||||
}
|
||||
}
|
||||
|
||||
fn add_file_slot(input: FileSlotInput<'_>) {
|
||||
let FileSlotInput { source, file_slot, length, has_timecode, tape_id, member_index, slots, rate } = input;
|
||||
if slots.iter().any(|slot| slot.u32(pid::SLOT_ID) == Some(file_slot)) {
|
||||
return;
|
||||
}
|
||||
let tape_slot_id = if has_timecode { 2 + member_index as u32 } else { 0 };
|
||||
let mob_id = if has_timecode { tape_id } else { [0; 32] };
|
||||
let clip = source_clip(source.kind, length, mob_id, tape_slot_id, 0);
|
||||
slots.push(timeline_slot(file_slot, &slot_name(source.kind, file_slot), file_slot, rate, clip));
|
||||
}
|
||||
|
||||
fn add_master_markers(doc: &Document, members: &[usize], w: &mut W<'_>, master_slots: &mut Vec<Obj>) {
|
||||
let first = &doc.sources[members[0]];
|
||||
let marker_rate =
|
||||
members.iter().map(|&i| &doc.sources[i]).find(|source| source.kind == CKind::Picture).map(source_rate).unwrap_or_else(|| source_rate(first));
|
||||
let markers: Vec<&CMarker> = members.iter().flat_map(|&i| doc.sources[i].markers.iter()).collect();
|
||||
if markers.is_empty() {
|
||||
return;
|
||||
}
|
||||
let mut unique: Vec<CMarker> = markers.into_iter().cloned().collect();
|
||||
unique.sort_by(|a, b| (a.start, &a.name).cmp(&(b.start, &b.name)));
|
||||
unique.dedup();
|
||||
master_slots.push(event_slot(w, members.len() as u32 + 1, marker_rate, &unique));
|
||||
}
|
||||
|
||||
fn add_file_mobs(doc: &Document, files: Vec<FileMob>, w: &mut W<'_>, output: &mut MediaOutput) {
|
||||
for (_, file_id, slots, source_index) in files {
|
||||
let source = &doc.sources[source_index];
|
||||
let desc = descriptor(w, source);
|
||||
output.mobs.push(
|
||||
Obj::new(cls::SOURCE_MOB)
|
||||
.data_prop(pid::MOB_ID, file_id.to_vec())
|
||||
.data_prop(pid::MOB_NAME, utf16z(&source.name))
|
||||
.data_prop(pid::MOB_LAST_MODIFIED, timestamp())
|
||||
.data_prop(pid::MOB_CREATION_TIME, timestamp())
|
||||
.with(pid::SLOTS, Value::StrongVec(slots))
|
||||
.with(pid::ESSENCE_DESCRIPTION, Value::Strong(Box::new(desc))),
|
||||
);
|
||||
if let Some(data) = &source.embedded {
|
||||
output
|
||||
.essence
|
||||
.push(Obj::new(cls::ESSENCE_DATA).data_prop(pid::ESSENCE_MOB_ID, file_id.to_vec()).with(pid::ESSENCE_STREAM, Value::Stream(data.clone())));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn add_tape_mob(first: &Source, tape_id: [u8; 32], timecode: Option<(i64, FrameRate)>, tape_slots: Vec<Obj>, output: &mut MediaOutput) {
|
||||
let Some(_) = timecode else { return };
|
||||
let reel = first.path.as_deref().map(crate::common::file_stem).unwrap_or(&first.name).to_string();
|
||||
output.mobs.push(
|
||||
Obj::new(cls::SOURCE_MOB)
|
||||
.data_prop(pid::MOB_ID, tape_id.to_vec())
|
||||
.data_prop(pid::MOB_NAME, utf16z(&reel))
|
||||
.data_prop(pid::MOB_LAST_MODIFIED, timestamp())
|
||||
.data_prop(pid::MOB_CREATION_TIME, timestamp())
|
||||
.with(pid::SLOTS, Value::StrongVec(tape_slots))
|
||||
.with(pid::ESSENCE_DESCRIPTION, Value::Strong(Box::new(Obj::new(cls::TAPE_DESCRIPTOR)))),
|
||||
);
|
||||
}
|
||||
|
||||
/// Serialise a composition document.
|
||||
pub(crate) fn write(doc: &Document, version: filmcraft_cfb::Version, report: &mut Report) -> Result<Vec<u8>> {
|
||||
let comp = doc.compositions.first().ok_or(Error::Empty)?;
|
||||
let mut w = W { report, inexact: false };
|
||||
let mut ids = IdGen::for_document(doc, comp);
|
||||
let MediaOutput { mut mobs, essence, master_ref } = write_media(doc, &mut w, &mut ids);
|
||||
let mut used_ops: Vec<Auid> = Vec::new();
|
||||
let mut uses_varying = false;
|
||||
|
||||
// ---- nested compositions: a clip refers to one as it does to a master mob, through the
|
||||
// composition's first track of the clip's kind (a broken-out channel: that channel's track)
|
||||
let mut refs = Refs { mobs: master_ref, rates: HashMap::new() };
|
||||
let nested_ids: Vec<[u8; 32]> = doc.nested.iter().map(|_| ids.next()).collect();
|
||||
for (si, s) in doc.sources.iter().enumerate() {
|
||||
let Some((comp, id)) = s.nested.and_then(|n| Some((doc.nested.get(n)?, nested_ids.get(n)?))) else { continue };
|
||||
let of_kind: Vec<usize> = comp.tracks.iter().enumerate().filter(|(_, t)| t.kind == s.kind).map(|(i, _)| i).collect();
|
||||
let Some(&track) = s.channel.and_then(|c| of_kind.get(c as usize)).or(of_kind.first()) else { continue };
|
||||
let rate = match s.kind {
|
||||
CKind::Picture => (comp.rate.num, comp.rate.den),
|
||||
CKind::Sound => (comp.sample_rate.max(1) as i64, 1),
|
||||
};
|
||||
refs.mobs.insert(si, (*id, track as u32 + 2));
|
||||
refs.rates.insert(si, rate);
|
||||
}
|
||||
|
||||
// ---- the compositions: the exported sequence first
|
||||
let comp_id = ids.next();
|
||||
let composition_mobs = {
|
||||
let mut composition_writer = CompositionWriter { w: &mut w, doc, refs: &refs, used_ops: &mut used_ops, uses_varying: &mut uses_varying };
|
||||
let mut output = vec![composition_writer.write(comp, comp_id, true)];
|
||||
output.extend(doc.nested.iter().zip(&nested_ids).map(|(nested, id)| composition_writer.write(nested, *id, false)));
|
||||
output
|
||||
};
|
||||
mobs.splice(0..0, composition_mobs);
|
||||
if w.inexact {
|
||||
w.report.info("some times are not on whole edit units and were rounded");
|
||||
}
|
||||
|
||||
// ---- dictionary
|
||||
let mut ddefs = Vec::new();
|
||||
for (id, name) in [(ddef::PICTURE, "Picture"), (ddef::SOUND, "Sound"), (ddef::TIMECODE, "Timecode"), (ddef::DESCRIPTIVE_METADATA, "DescriptiveMetadata")] {
|
||||
ddefs.push(definition(cls::DATA_DEFINITION, id, name));
|
||||
}
|
||||
let mut opdefs = Vec::new();
|
||||
for op in &used_ops {
|
||||
let (name, dd, inputs) = match *op {
|
||||
x if x == def::VIDEO_DISSOLVE => ("Video Dissolve", ddef::PICTURE, 2),
|
||||
x if x == def::VIDEO_FADE_TO_BLACK => ("Video Fade To Black", ddef::PICTURE, 1),
|
||||
x if x == def::SMPTE_VIDEO_WIPE => ("SMPTE Video Wipe", ddef::PICTURE, 2),
|
||||
x if x == def::MONO_AUDIO_DISSOLVE => ("Mono Audio Dissolve", ddef::SOUND, 2),
|
||||
_ => ("Mono Audio Gain", ddef::SOUND, 1i32),
|
||||
};
|
||||
let params: Vec<Vec<u8>> = if *op == def::MONO_AUDIO_GAIN {
|
||||
vec![def::PARAM_AMPLITUDE.to_vec()]
|
||||
} else if *op == def::VIDEO_DISSOLVE {
|
||||
vec![def::PARAM_LEVEL.to_vec()]
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
let mut o = definition(cls::OPERATION_DEFINITION, *op, name)
|
||||
.with(pid::OPDEF_DATA_DEFINITION, weak(path::DATA_DEFS, dd))
|
||||
.data_prop(pid::OPDEF_IS_TIME_WARP, vec![0])
|
||||
.data_prop(pid::OPDEF_NUMBER_INPUTS, inputs.to_le_bytes().to_vec());
|
||||
if !params.is_empty() {
|
||||
o.set(pid::OPDEF_PARAMETERS_DEFINED, Value::WeakVec(path::PARAMETER_DEFS.to_vec(), pid::IDENTIFICATION, params));
|
||||
}
|
||||
opdefs.push(o);
|
||||
}
|
||||
let pdefs = vec![
|
||||
definition(cls::PARAMETER_DEFINITION, def::PARAM_LEVEL, "Level").data_prop(pid::PARAMDEF_DISPLAY_UNITS, utf16z("")),
|
||||
definition(cls::PARAMETER_DEFINITION, def::PARAM_AMPLITUDE, "Amplitude").data_prop(pid::PARAMDEF_DISPLAY_UNITS, utf16z("")),
|
||||
];
|
||||
let idefs = if uses_varying || !used_ops.is_empty() {
|
||||
vec![
|
||||
definition(cls::INTERPOLATION_DEFINITION, def::INTERP_LINEAR, "Linear"),
|
||||
definition(cls::INTERPOLATION_DEFINITION, def::INTERP_CONSTANT, "Constant"),
|
||||
]
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
let cdefs = vec![
|
||||
definition(cls::CONTAINER_DEFINITION, def::CONTAINER_EXTERNAL, "External Container"),
|
||||
definition(cls::CONTAINER_DEFINITION, def::CONTAINER_AAF, "AAF Container"),
|
||||
];
|
||||
let mut dict = Obj::new(cls::DICTIONARY)
|
||||
.with(pid::DATA_DEFINITIONS, Value::StrongSet(ddefs, pid::IDENTIFICATION))
|
||||
.with(pid::PARAMETER_DEFINITIONS, Value::StrongSet(pdefs, pid::IDENTIFICATION))
|
||||
.with(pid::CONTAINER_DEFINITIONS, Value::StrongSet(cdefs, pid::IDENTIFICATION));
|
||||
if !opdefs.is_empty() {
|
||||
dict.set(pid::OPERATION_DEFINITIONS, Value::StrongSet(opdefs, pid::IDENTIFICATION));
|
||||
}
|
||||
if !idefs.is_empty() {
|
||||
dict.set(pid::INTERPOLATION_DEFINITIONS, Value::StrongSet(idefs, pid::IDENTIFICATION));
|
||||
}
|
||||
|
||||
let mut content = Obj::new(cls::CONTENT_STORAGE).with(pid::MOBS, Value::StrongSet(mobs, pid::MOB_ID));
|
||||
if !essence.is_empty() {
|
||||
content.set(pid::ESSENCE_DATA, Value::StrongSet(essence, pid::ESSENCE_MOB_ID));
|
||||
}
|
||||
let ident = Obj::new(cls::IDENTIFICATION)
|
||||
.data_prop(pid::COMPANY_NAME, utf16z("FilmCraft"))
|
||||
.data_prop(pid::PRODUCT_NAME, utf16z("FilmCraft"))
|
||||
.data_prop(pid::PRODUCT_VERSION_STRING, utf16z(env!("CARGO_PKG_VERSION")))
|
||||
.data_prop(pid::PRODUCT_ID, super::ids::guid(0x46494C4D, 0x4352, 0x4146, *b"T-AAF-EP").to_vec())
|
||||
.data_prop(pid::DATE, timestamp())
|
||||
.data_prop(pid::PLATFORM, utf16z("FilmCraft"))
|
||||
.data_prop(pid::GENERATION_AUID, mob_id(ids.seed, 0)[16..].to_vec());
|
||||
let header = Obj::new(cls::HEADER)
|
||||
.data_prop(pid::BYTE_ORDER, 0x4949i16.to_le_bytes().to_vec())
|
||||
.data_prop(pid::LAST_MODIFIED, timestamp())
|
||||
.data_prop(pid::VERSION, vec![1, 1])
|
||||
.data_prop(pid::OBJECT_MODEL_VERSION, 1u32.to_le_bytes().to_vec())
|
||||
.data_prop(pid::OPERATIONAL_PATTERN, def::OP_EDIT_PROTOCOL.to_vec())
|
||||
.with(pid::CONTENT, Value::Strong(Box::new(content)))
|
||||
.with(pid::DICTIONARY, Value::Strong(Box::new(dict)))
|
||||
.with(pid::IDENTIFICATION_LIST, Value::StrongVec(vec![ident]));
|
||||
// The meta-dictionary holds only extensions to the baseline object model, and everything written
|
||||
// here is baseline, so its class and type definition sets are empty; readers that load them
|
||||
// (pyaaf2) still need the sets to be there (#323).
|
||||
let meta = Obj::new(META_DICTIONARY)
|
||||
.with(pid::META_CLASS_DEFINITIONS, Value::StrongSet(Vec::new(), pid::META_IDENTIFICATION))
|
||||
.with(pid::META_TYPE_DEFINITIONS, Value::StrongSet(Vec::new(), pid::META_IDENTIFICATION));
|
||||
let root = Obj::new(ROOT).with(pid::ROOT_META_DICTIONARY, Value::Strong(Box::new(meta))).with(pid::ROOT_HEADER, Value::Strong(Box::new(header)));
|
||||
store::write(&root, version).map_err(Error::Other)
|
||||
}
|
||||
|
||||
/// Where clips find their sources: source index → (mob id, slot id), and for nested compositions
|
||||
/// the edit rate of that slot.
|
||||
#[derive(Default)]
|
||||
struct Refs {
|
||||
mobs: HashMap<usize, ([u8; 32], u32)>,
|
||||
rates: HashMap<usize, (i64, i64)>,
|
||||
}
|
||||
|
||||
/// The composition mob of `comp`. Slot 1 is its timecode; its tracks follow from slot 2 in order.
|
||||
struct CompositionWriter<'a, 'b, 'c> {
|
||||
w: &'a mut W<'c>,
|
||||
doc: &'b Document,
|
||||
refs: &'b Refs,
|
||||
used_ops: &'a mut Vec<Auid>,
|
||||
uses_varying: &'a mut bool,
|
||||
}
|
||||
|
||||
impl CompositionWriter<'_, '_, '_> {
|
||||
fn write(&mut self, comp: &Composition, id: [u8; 32], top: bool) -> Obj {
|
||||
let w = &mut *self.w;
|
||||
let doc = self.doc;
|
||||
let refs = self.refs;
|
||||
let used_ops = &mut *self.used_ops;
|
||||
let uses_varying = &mut *self.uses_varying;
|
||||
let crate_rate = (comp.rate.num, comp.rate.den);
|
||||
let mut slots = Vec::new();
|
||||
let total = comp
|
||||
.tracks
|
||||
.iter()
|
||||
.map(|t| {
|
||||
let mut c = Tick::ZERO;
|
||||
for i in &t.items {
|
||||
match i {
|
||||
CItem::Transition(x) => c -= x.len,
|
||||
other => c += other.len(),
|
||||
}
|
||||
}
|
||||
c
|
||||
})
|
||||
.max()
|
||||
.unwrap_or(Tick::ZERO);
|
||||
let total_units = w.u(total, crate_rate);
|
||||
slots.push(timeline_slot(
|
||||
1,
|
||||
"TC1",
|
||||
0,
|
||||
crate_rate,
|
||||
Obj::new(cls::TIMECODE)
|
||||
.with(pid::DATA_DEFINITION, weak(path::DATA_DEFS, ddef::TIMECODE))
|
||||
.data_prop(pid::LENGTH, total_units.to_le_bytes().to_vec())
|
||||
.data_prop(pid::TC_START, comp.start_tc.to_le_bytes().to_vec())
|
||||
.data_prop(pid::TC_FPS, (comp.rate.timecode_base().clamp(1, u16::MAX as i64) as u16).to_le_bytes().to_vec())
|
||||
.data_prop(pid::TC_DROP, vec![comp.drop as u8]),
|
||||
));
|
||||
let mut slot_id = 2u32;
|
||||
for t in &comp.tracks {
|
||||
let rate = match t.kind {
|
||||
CKind::Picture => crate_rate,
|
||||
CKind::Sound => (comp.sample_rate.max(1) as i64, 1),
|
||||
};
|
||||
let dd = data_def(t.kind);
|
||||
let mut comps = Vec::new();
|
||||
let mut cursor = Tick::ZERO;
|
||||
for it in &t.items {
|
||||
match it {
|
||||
CItem::Filler(l) => {
|
||||
let n = w.u(cursor + *l, rate) - w.u(cursor, rate);
|
||||
cursor += *l;
|
||||
comps
|
||||
.push(Obj::new(cls::FILLER).with(pid::DATA_DEFINITION, weak(path::DATA_DEFS, dd)).data_prop(pid::LENGTH, n.to_le_bytes().to_vec()));
|
||||
}
|
||||
CItem::Clip(c) => {
|
||||
let n = w.u(cursor + c.len, rate) - w.u(cursor, rate);
|
||||
let s = &doc.sources[c.source];
|
||||
let (mid, mslot) = refs.mobs.get(&c.source).copied().unwrap_or(([0; 32], 0));
|
||||
// (a nested composition counts the start in its own slot's edit units)
|
||||
let start = w.u(c.start, refs.rates.get(&c.source).copied().unwrap_or(rate));
|
||||
let mut sc = source_clip(t.kind, n, mid, mslot, start);
|
||||
if !c.name.is_empty() && c.name != s.name {
|
||||
sc.set(pid::COMPONENT_USER_COMMENTS, Value::StrongVec(vec![tagged("Clip Name", &c.name)]));
|
||||
}
|
||||
let seg = match (&c.gain, t.kind) {
|
||||
(Some(g), CKind::Sound) => {
|
||||
if !used_ops.contains(&def::MONO_AUDIO_GAIN) {
|
||||
used_ops.push(def::MONO_AUDIO_GAIN);
|
||||
}
|
||||
let param = match g {
|
||||
Gain::Constant(a) => Obj::new(cls::CONSTANT_VALUE)
|
||||
.data_prop(pid::PARAMETER_DEFINITION, def::PARAM_AMPLITUDE.to_vec())
|
||||
.data_prop(pid::CONSTANT_VALUE, indirect(def::TYPE_RATIONAL, &gain_rational(*a))),
|
||||
Gain::Varying { linear, points } => {
|
||||
*uses_varying = true;
|
||||
let pts = points
|
||||
.iter()
|
||||
.map(|(off, a)| {
|
||||
let o = w.u(cursor + *off, rate) - w.u(cursor, rate);
|
||||
Obj::new(cls::CONTROL_POINT)
|
||||
.data_prop(pid::CP_TIME, rational(o, n.max(1)))
|
||||
.data_prop(pid::CP_VALUE, indirect(def::TYPE_RATIONAL, &gain_rational(*a)))
|
||||
.data_prop(pid::CP_EDIT_HINT, vec![0])
|
||||
})
|
||||
.collect();
|
||||
Obj::new(cls::VARYING_VALUE)
|
||||
.data_prop(pid::PARAMETER_DEFINITION, def::PARAM_AMPLITUDE.to_vec())
|
||||
.with(
|
||||
pid::INTERPOLATION,
|
||||
weak(path::INTERPOLATION_DEFS, if *linear { def::INTERP_LINEAR } else { def::INTERP_CONSTANT }),
|
||||
)
|
||||
.with(pid::POINT_LIST, Value::StrongVec(pts))
|
||||
}
|
||||
};
|
||||
Obj::new(cls::OPERATION_GROUP)
|
||||
.with(pid::DATA_DEFINITION, weak(path::DATA_DEFS, dd))
|
||||
.data_prop(pid::LENGTH, n.to_le_bytes().to_vec())
|
||||
.with(pid::OPERATION, weak(path::OPERATION_DEFS, def::MONO_AUDIO_GAIN))
|
||||
.with(pid::INPUT_SEGMENTS, Value::StrongVec(vec![sc]))
|
||||
.with(pid::PARAMETERS, Value::StrongVec(vec![param]))
|
||||
}
|
||||
_ => sc,
|
||||
};
|
||||
comps.push(seg);
|
||||
cursor += c.len;
|
||||
}
|
||||
CItem::Transition(x) => {
|
||||
let ts = cursor - x.len;
|
||||
let n = w.u(cursor, rate) - w.u(ts, rate);
|
||||
let cut = w.u(ts + x.cut, rate) - w.u(ts, rate);
|
||||
cursor = ts;
|
||||
let op = transition_op(t.kind, &x.effect);
|
||||
if !used_ops.contains(&op) {
|
||||
used_ops.push(op);
|
||||
}
|
||||
let mut og = Obj::new(cls::OPERATION_GROUP)
|
||||
.with(pid::DATA_DEFINITION, weak(path::DATA_DEFS, dd))
|
||||
.data_prop(pid::LENGTH, n.to_le_bytes().to_vec())
|
||||
.with(pid::OPERATION, weak(path::OPERATION_DEFS, op))
|
||||
.with(pid::COMPONENT_USER_COMMENTS, Value::StrongVec(vec![tagged("FilmCraft Effect", &x.effect)]));
|
||||
if op == def::VIDEO_DISSOLVE {
|
||||
*uses_varying = true;
|
||||
let pts = [(0, 0), (1, 1)]
|
||||
.iter()
|
||||
.map(|&(t, v)| {
|
||||
Obj::new(cls::CONTROL_POINT)
|
||||
.data_prop(pid::CP_TIME, rational(t, 1))
|
||||
.data_prop(pid::CP_VALUE, indirect(def::TYPE_RATIONAL, &rational(v, 1)))
|
||||
.data_prop(pid::CP_EDIT_HINT, vec![0])
|
||||
})
|
||||
.collect();
|
||||
og.set(
|
||||
pid::PARAMETERS,
|
||||
Value::StrongVec(vec![
|
||||
Obj::new(cls::VARYING_VALUE)
|
||||
.data_prop(pid::PARAMETER_DEFINITION, def::PARAM_LEVEL.to_vec())
|
||||
.with(pid::INTERPOLATION, weak(path::INTERPOLATION_DEFS, def::INTERP_LINEAR))
|
||||
.with(pid::POINT_LIST, Value::StrongVec(pts)),
|
||||
]),
|
||||
);
|
||||
}
|
||||
comps.push(
|
||||
Obj::new(cls::TRANSITION)
|
||||
.with(pid::DATA_DEFINITION, weak(path::DATA_DEFS, dd))
|
||||
.data_prop(pid::LENGTH, n.to_le_bytes().to_vec())
|
||||
.data_prop(pid::CUT_POINT, cut.to_le_bytes().to_vec())
|
||||
.with(pid::OPERATION_GROUP, Value::Strong(Box::new(og))),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
let len: i64 = comps
|
||||
.iter()
|
||||
.map(|c| {
|
||||
let l = c.i64(pid::LENGTH).unwrap_or(0);
|
||||
if c.class == cls::TRANSITION { -l } else { l }
|
||||
})
|
||||
.sum();
|
||||
let seq = Obj::new(cls::SEQUENCE)
|
||||
.with(pid::DATA_DEFINITION, weak(path::DATA_DEFS, dd))
|
||||
.data_prop(pid::LENGTH, len.to_le_bytes().to_vec())
|
||||
.with(pid::COMPONENTS, Value::StrongVec(comps));
|
||||
slots.push(timeline_slot(slot_id, &t.name, t.number, rate, seq));
|
||||
slot_id += 1;
|
||||
}
|
||||
if !comp.markers.is_empty() {
|
||||
slots.push(event_slot(w, slot_id, crate_rate, &comp.markers));
|
||||
}
|
||||
let mut mob = Obj::new(cls::COMPOSITION_MOB)
|
||||
.data_prop(pid::MOB_ID, id.to_vec())
|
||||
.data_prop(pid::MOB_NAME, utf16z(&comp.name))
|
||||
.data_prop(pid::MOB_LAST_MODIFIED, timestamp())
|
||||
.data_prop(pid::MOB_CREATION_TIME, timestamp());
|
||||
// only the exported sequence is a top-level composition; a nested sequence is found through
|
||||
// the clips that use it
|
||||
if top {
|
||||
mob.set(pid::USAGE_CODE, Value::Data(def::USAGE_TOP_LEVEL.to_vec()));
|
||||
}
|
||||
mob.with(pid::SLOTS, Value::StrongVec(slots)).with(
|
||||
pid::MOB_USER_COMMENTS,
|
||||
Value::StrongVec(vec![
|
||||
tagged("FilmCraft Frame Size", &format!("{}x{}", comp.width, comp.height)),
|
||||
tagged("FilmCraft Audio Sample Rate", &comp.sample_rate.to_string()),
|
||||
]),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fn slot_name(kind: CKind, n: u32) -> String {
|
||||
match kind {
|
||||
CKind::Picture => format!("V{n}"),
|
||||
CKind::Sound => format!("A{n}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn timeline_slot(id: u32, name: &str, number: u32, rate: (i64, i64), segment: Obj) -> Obj {
|
||||
let mut o = Obj::new(cls::TIMELINE_MOB_SLOT)
|
||||
.data_prop(pid::SLOT_ID, id.to_le_bytes().to_vec())
|
||||
.data_prop(pid::SLOT_NAME, utf16z(name))
|
||||
.data_prop(pid::EDIT_RATE, rational(rate.0, rate.1))
|
||||
.data_prop(pid::ORIGIN, 0i64.to_le_bytes().to_vec())
|
||||
.with(pid::SEGMENT, Value::Strong(Box::new(segment)));
|
||||
if number > 0 {
|
||||
o.set(pid::PHYSICAL_TRACK_NUMBER, Value::Data(number.to_le_bytes().to_vec()));
|
||||
}
|
||||
o
|
||||
}
|
||||
|
||||
fn source_clip(kind: CKind, len: i64, source: [u8; 32], slot: u32, start: i64) -> Obj {
|
||||
Obj::new(cls::SOURCE_CLIP)
|
||||
.with(pid::DATA_DEFINITION, weak(path::DATA_DEFS, data_def(kind)))
|
||||
.data_prop(pid::LENGTH, len.to_le_bytes().to_vec())
|
||||
.data_prop(pid::SOURCE_ID, source.to_vec())
|
||||
.data_prop(pid::SOURCE_MOB_SLOT_ID, slot.to_le_bytes().to_vec())
|
||||
.data_prop(pid::START_TIME, start.to_le_bytes().to_vec())
|
||||
}
|
||||
|
||||
fn event_slot(w: &mut W, id: u32, rate: (i64, i64), markers: &[CMarker]) -> Obj {
|
||||
let comps = markers
|
||||
.iter()
|
||||
.map(|m| {
|
||||
let pos = w.u(m.start, rate);
|
||||
let len = w.u(m.start + m.duration, rate) - pos;
|
||||
let mut tags = vec![tagged("Name", &m.name), tagged("Comment", &m.comment)];
|
||||
if let Some(c) = &m.color {
|
||||
tags.push(tagged("Color", c));
|
||||
}
|
||||
Obj::new(cls::COMMENT_MARKER)
|
||||
.with(pid::DATA_DEFINITION, weak(path::DATA_DEFS, ddef::DESCRIPTIVE_METADATA))
|
||||
.data_prop(pid::LENGTH, len.to_le_bytes().to_vec())
|
||||
.data_prop(pid::POSITION, pos.to_le_bytes().to_vec())
|
||||
.data_prop(pid::COMMENT, utf16z(if m.comment.is_empty() { &m.name } else { &m.comment }))
|
||||
.with(pid::COMPONENT_USER_COMMENTS, Value::StrongVec(tags))
|
||||
})
|
||||
.collect();
|
||||
Obj::new(cls::EVENT_MOB_SLOT)
|
||||
.data_prop(pid::SLOT_ID, id.to_le_bytes().to_vec())
|
||||
.data_prop(pid::SLOT_NAME, utf16z("Markers"))
|
||||
.data_prop(pid::EVENT_EDIT_RATE, rational(rate.0, rate.1))
|
||||
.with(
|
||||
pid::SEGMENT,
|
||||
Value::Strong(Box::new(
|
||||
Obj::new(cls::SEQUENCE)
|
||||
.with(pid::DATA_DEFINITION, weak(path::DATA_DEFS, ddef::DESCRIPTIVE_METADATA))
|
||||
.with(pid::COMPONENTS, Value::StrongVec(comps)),
|
||||
)),
|
||||
)
|
||||
}
|
||||
|
||||
fn transition_op(kind: CKind, effect: &str) -> Auid {
|
||||
match kind {
|
||||
CKind::Sound => def::MONO_AUDIO_DISSOLVE,
|
||||
CKind::Picture => match effect {
|
||||
"dip_to_black" => def::VIDEO_FADE_TO_BLACK,
|
||||
e if e.contains("wipe") => def::SMPTE_VIDEO_WIPE,
|
||||
_ => def::VIDEO_DISSOLVE,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn descriptor(w: &mut W, s: &Source) -> Obj {
|
||||
let rate = source_rate(s);
|
||||
let len = w.u(s.length, rate);
|
||||
let container = if s.embedded.is_some() { def::CONTAINER_AAF } else { def::CONTAINER_EXTERNAL };
|
||||
let mut d = match s.kind {
|
||||
CKind::Picture => Obj::new(cls::CDCI_DESCRIPTOR)
|
||||
.data_prop(pid::STORED_WIDTH, s.width.to_le_bytes().to_vec())
|
||||
.data_prop(pid::STORED_HEIGHT, s.height.to_le_bytes().to_vec())
|
||||
.data_prop(pid::FRAME_LAYOUT, vec![0])
|
||||
.data_prop(pid::IMAGE_ASPECT_RATIO, rational(s.width.max(1) as i64, s.height.max(1) as i64))
|
||||
.data_prop(pid::VIDEO_LINE_MAP, {
|
||||
let mut v = 2u32.to_le_bytes().to_vec();
|
||||
v.extend_from_slice(&4u32.to_le_bytes());
|
||||
v.extend_from_slice(&0i32.to_le_bytes());
|
||||
v.extend_from_slice(&0i32.to_le_bytes());
|
||||
v
|
||||
})
|
||||
.data_prop(pid::COMPONENT_WIDTH, 8u32.to_le_bytes().to_vec())
|
||||
.data_prop(pid::HORIZONTAL_SUBSAMPLING, 2u32.to_le_bytes().to_vec()),
|
||||
CKind::Sound => {
|
||||
// Channel counts and rates come from the project: saturate, as these fields can't
|
||||
// hold more anyway.
|
||||
let block = s.file_channels.max(1).saturating_mul((s.bits as u32).div_ceil(8));
|
||||
Obj::new(cls::PCM_DESCRIPTOR)
|
||||
.data_prop(pid::AUDIO_SAMPLING_RATE, rational(s.sample_rate as i64, 1))
|
||||
.data_prop(pid::LOCKED, vec![1])
|
||||
.data_prop(pid::CHANNELS, s.file_channels.max(1).to_le_bytes().to_vec())
|
||||
.data_prop(pid::QUANTIZATION_BITS, (s.bits as u32).to_le_bytes().to_vec())
|
||||
.data_prop(pid::BLOCK_ALIGN, u16::try_from(block).unwrap_or(u16::MAX).to_le_bytes().to_vec())
|
||||
.data_prop(pid::AVERAGE_BPS, block.saturating_mul(s.sample_rate).to_le_bytes().to_vec())
|
||||
}
|
||||
};
|
||||
d.set(pid::SAMPLE_RATE, Value::Data(rational(rate.0, rate.1)));
|
||||
d.set(pid::FILE_LENGTH, Value::Data(len.to_le_bytes().to_vec()));
|
||||
d.set(pid::CONTAINER_FORMAT, weak(path::CONTAINER_DEFS, container));
|
||||
if let Some(p) = &s.path {
|
||||
let url = if crate::common::is_absolute(p) { crate::common::path_to_file_url(p, false) } else { p.clone() };
|
||||
d.set(pid::LOCATOR, Value::StrongVec(vec![Obj::new(cls::NETWORK_LOCATOR).data_prop(pid::URL_STRING, utf16z(&url))]));
|
||||
}
|
||||
d
|
||||
}
|
||||
@@ -15,7 +15,7 @@ use filmcraft_project::{
|
||||
AudioChannels, ClipId, Interpolation, ItemId, ItemKind, Keyframe, Label, Marker, MarkerId, MarkerKind, MediaRef, Param, ParamValue, Project, Sequence,
|
||||
Track, TrackItem, TrackKind, Transition, TransitionAlign, TransitionId, find_effect,
|
||||
};
|
||||
use filmcraft_time::{FrameRate, TICKS_PER_SECOND, Tick};
|
||||
use filmcraft_time::{FrameRate, Tick};
|
||||
|
||||
use crate::common::{Builder, MediaSpec, base_item, db_to_gain, file_name, file_stem, gain_to_db, param, set_param, settings_for, transition_effect};
|
||||
use crate::essence::{EssenceData, EssenceKey, MediaOptions};
|
||||
@@ -83,16 +83,6 @@ pub(crate) enum CItem {
|
||||
Transition(CTransition),
|
||||
}
|
||||
|
||||
impl CItem {
|
||||
pub fn len(&self) -> Tick {
|
||||
match self {
|
||||
CItem::Filler(l) => *l,
|
||||
CItem::Clip(c) => c.len,
|
||||
CItem::Transition(t) => t.len,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(crate) struct CClip {
|
||||
pub len: Tick,
|
||||
@@ -1001,31 +991,6 @@ fn link_clips(b: &mut Builder, seq: &mut Sequence) {
|
||||
/// The largest time read from a document (about 3.3 days).
|
||||
pub(crate) const MAX_TIME: Tick = Tick(1 << 56);
|
||||
|
||||
/// Ticks of `n` edit units at rate `num/den` (rounded to the nearest tick).
|
||||
pub(crate) fn units_to_ticks(n: i64, num: i64, den: i64) -> Tick {
|
||||
if num <= 0 || den <= 0 {
|
||||
return Tick::ZERO;
|
||||
}
|
||||
let t = n as i128 * den as i128 * TICKS_PER_SECOND as i128;
|
||||
let q = t.div_euclid(num as i128);
|
||||
let r = t.rem_euclid(num as i128);
|
||||
// documents are untrusted: keep every time far from overflow (±3 days)
|
||||
Tick((q + if r * 2 >= num as i128 { 1 } else { 0 }).clamp(-MAX_TIME.0 as i128, MAX_TIME.0 as i128) as i64)
|
||||
}
|
||||
|
||||
/// Edit units at rate `num/den` nearest to `t`; the flag is false when `t` is not on a unit.
|
||||
pub(crate) fn ticks_to_units(t: Tick, num: i64, den: i64) -> (i64, bool) {
|
||||
if num <= 0 || den <= 0 {
|
||||
return (0, false);
|
||||
}
|
||||
let x = t.0 as i128 * num as i128;
|
||||
let d = den as i128 * TICKS_PER_SECOND as i128;
|
||||
let q = x.div_euclid(d);
|
||||
let r = x.rem_euclid(d);
|
||||
let n = q + if r * 2 >= d { 1 } else { 0 };
|
||||
(n.clamp(i64::MIN as i128, i64::MAX as i128) as i64, r == 0)
|
||||
}
|
||||
|
||||
/// The name an exported audio track gets: the track's own name (what an editor called it, e.g.
|
||||
/// a role such as `Dialogue.Dialogue-1`, which is what a sound editor's DAW shows), else `A<n>`;
|
||||
/// a track broken out to mono gets its channel after it (`L` / `R`, the 5.1 names, or a number).
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
//! sequence. Premiere Pro's OMF export does the same.
|
||||
|
||||
pub(crate) use craft_aaf::omf::bento;
|
||||
mod shared_model;
|
||||
pub(crate) mod shared_model;
|
||||
|
||||
use filmcraft_project::{ItemId, Project};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
@@ -157,28 +157,28 @@ fn l_source(s: shared::Source) -> local::Source {
|
||||
nested: s.nested,
|
||||
}
|
||||
}
|
||||
pub(super) fn to_shared(d: local::Document) -> shared::Document {
|
||||
pub(crate) fn to_shared(d: local::Document) -> shared::Document {
|
||||
shared::Document {
|
||||
compositions: d.compositions.into_iter().map(s_comp).collect(),
|
||||
sources: d.sources.into_iter().map(s_source).collect(),
|
||||
nested: d.nested.into_iter().map(s_comp).collect(),
|
||||
}
|
||||
}
|
||||
pub(super) fn from_shared(d: shared::Document) -> local::Document {
|
||||
pub(crate) fn from_shared(d: shared::Document) -> local::Document {
|
||||
local::Document {
|
||||
compositions: d.compositions.into_iter().map(l_comp).collect(),
|
||||
sources: d.sources.into_iter().map(l_source).collect(),
|
||||
nested: d.nested.into_iter().map(l_comp).collect(),
|
||||
}
|
||||
}
|
||||
pub(super) fn error(e: craft_aaf::Error) -> crate::Error {
|
||||
pub(crate) fn error(e: craft_aaf::Error) -> crate::Error {
|
||||
match e {
|
||||
craft_aaf::Error::Parse { format, message } => crate::Error::Parse { format, message },
|
||||
craft_aaf::Error::Empty => crate::Error::Empty,
|
||||
craft_aaf::Error::Other(s) => crate::Error::Other(s),
|
||||
}
|
||||
}
|
||||
pub(super) fn merge_report(dst: &mut crate::Report, src: craft_aaf::Report) {
|
||||
pub(crate) fn merge_report(dst: &mut crate::Report, src: craft_aaf::Report) {
|
||||
for e in src.entries {
|
||||
let level = match e.level {
|
||||
craft_aaf::report::Level::Info => crate::Level::Info,
|
||||
|
||||
Reference in new issue
Block a user