forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

fcpxml.rs248 lines, 9.2 KiBHistoryRawDownload
1//! Final Cut Pro XML 1.10 (`.fcpxml`), written for Final Cut Pro, DaVinci
2//! Resolve and Premiere. The first video track is the spine: its clips and
3//! gaps, back to back at their timeline offsets. Audio clips are connected
4//! to the spine element they start inside, on lanes -1, -2 and so on, and
5//! markers sit on the element they fall in.
6
7use std::path::PathBuf;
8use std::fmt::Write as _;
9
10use super::{Item, Timeline};
11use crate::project::LaneKind;
12
13/// Rational seconds for `frames` at `fps`, reduced: `12/5s`, `3s`, `0s`.
14fn time(frames: u32, fps: f64) -> String {
15 let (scale, ticks) = crate::mux::frame_timing(fps).unwrap_or((fps.round() as u32, 1));
16 let (mut n, mut d) = (u64::from(frames) * u64::from(ticks), u64::from(scale));
17 if n == 0 {
18 return "0s".to_string();
19 }
20 let g = gcd(n, d);
21 n /= g;
22 d /= g;
23 match d {
24 1 => format!("{n}s"),
25 _ => format!("{n}/{d}s"),
26 }
27}
28
29fn gcd(a: u64, b: u64) -> u64 {
30 if b == 0 { a.max(1) } else { gcd(b, a % b) }
31}
32
33fn esc(s: &str) -> String {
34 s.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;").replace('"', "&quot;")
35}
36
37/// The format name Final Cut uses for a canvas: `FFVideoFormat1080p25`.
38fn format_name(height: u32, fps: f64) -> String {
39 let rate = match fps {
40 f if (f - 29.97).abs() < 0.01 => "2997".to_string(),
41 f if (f - 23.976).abs() < 0.01 => "2398".to_string(),
42 f if (f - 59.94).abs() < 0.01 => "5994".to_string(),
43 f => format!("{}", f.round()),
44 };
45 format!("FFVideoFormat{height}p{rate}")
46}
47
48/// One asset: a file the timeline uses, with its id and how far its clips reach.
49struct Asset {
50 path: PathBuf,
51 id: String,
52 reach: u32,
53 video: bool,
54 audio: bool,
55}
56
57/// A spine element: a clip or a gap, its timeline span, and its children.
58struct Element {
59 start: u32,
60 end: u32,
61 /// Source frame at the element's start, `0` for a gap.
62 in_frame: u32,
63 /// The opening tag without its closing `>` or `/>`.
64 open: String,
65 /// A time map, for a clip at a changed speed.
66 time_map: String,
67 /// Connected clips and markers, in their own lines.
68 children: String,
69 /// `</asset-clip>` or `</gap>`.
70 close: &'static str,
71}
72
73impl Element {
74 fn render(&self, out: &mut String) {
75 if self.children.is_empty() && self.time_map.is_empty() && self.close == "</asset-clip>" {
76 let _ = writeln!(out, " {}/>", self.open);
77 } else {
78 let _ = writeln!(out, " {}>{}{}\n {}", self.open, self.time_map, self.children, self.close);
79 }
80 }
81}
82
83/// The FCPXML document for `t`.
84pub fn write(t: &Timeline) -> String {
85 let fps = t.fps;
86 let (w, h) = t.resolution;
87 let format = format_name(h, fps);
88 let total = t.frames();
89
90 // Assets, numbered from r2 (r1 is the format), in order of first use.
91 let mut assets: Vec<Asset> = Vec::new();
92 for track in &t.tracks {
93 for item in &track.items {
94 let Item::Clip(c) = item else { continue };
95 let video = track.kind != LaneKind::Audio;
96 let idx = match assets.iter().position(|a| a.path == c.path) {
97 Some(i) => i,
98 None => {
99 assets.push(Asset {
100 path: c.path.clone(),
101 id: format!("r{}", assets.len() + 2),
102 reach: 0,
103 video: false,
104 audio: false,
105 });
106 assets.len() - 1
107 }
108 };
109 let a = &mut assets[idx];
110 a.reach = a.reach.max(c.out_frame);
111 a.video |= video;
112 a.audio |= !video;
113 }
114 }
115 let asset_id = |path: &PathBuf| assets.iter().find(|a| &a.path == path).map_or("r0", |a| a.id.as_str()).to_string();
116
117 // The spine: the first video track, or one gap spanning everything when there is none.
118 let spine_track = t.tracks.iter().find(|tr| tr.kind != LaneKind::Audio);
119 let mut spine: Vec<Element> = Vec::new();
120 match spine_track {
121 Some(track) => {
122 let mut at = 0;
123 for item in &track.items {
124 match item {
125 Item::Gap(n) => {
126 spine.push(gap(at, *n, fps));
127 at += n;
128 }
129 Item::Clip(c) => {
130 let open = format!(
131 "<asset-clip ref=\"{}\" offset=\"{}\" name=\"{}\" start=\"{}\" duration=\"{}\" format=\"r1\"",
132 asset_id(&c.path),
133 time(c.start, fps),
134 esc(&c.file_name()),
135 time(c.in_frame, fps),
136 time(c.frames, fps),
137 );
138 // A changed speed is a time map from the clip's first frame to its last.
139 let time_map = match c.speed.is_normal() {
140 true => String::new(),
141 false => format!(
142 "\n<timeMap><timept time=\"0s\" value=\"{}\" interp=\"linear\"/><timept time=\"{}\" value=\"{}\" interp=\"linear\"/></timeMap>",
143 time(c.in_frame, fps),
144 time(c.frames, fps),
145 time(c.out_frame, fps),
146 ),
147 };
148 spine.push(Element {
149 start: c.start,
150 end: c.start + c.frames,
151 in_frame: c.in_frame,
152 open,
153 time_map,
154 children: String::new(),
155 close: "</asset-clip>",
156 });
157 at = c.start + c.frames;
158 }
159 }
160 }
161 }
162 None => spine.push(gap(0, total, fps)),
163 }
164
165 // Connected audio: each audio clip hangs off the spine element its start falls in.
166 let mut lane_no = 0;
167 for track in t.tracks.iter().filter(|tr| tr.kind == LaneKind::Audio) {
168 lane_no += 1;
169 for item in &track.items {
170 let Item::Clip(c) = item else { continue };
171 let Some(el) = spine.iter_mut().find(|e| e.start <= c.start && c.start < e.end) else { continue };
172 let local = c.start - el.start + el.in_frame;
173 let _ = write!(
174 el.children,
175 "\n<asset-clip ref=\"{}\" lane=\"-{lane_no}\" offset=\"{}\" name=\"{}\" start=\"{}\" duration=\"{}\" audioRole=\"dialogue\"/>",
176 asset_id(&c.path),
177 time(local, fps),
178 esc(&c.file_name()),
179 time(c.in_frame, fps),
180 time(c.frames, fps),
181 );
182 }
183 }
184
185 // Markers: on the spine element they fall in, in that element's own time.
186 for m in &t.markers {
187 if let Some(el) = spine.iter_mut().find(|e| e.start <= m.frame && m.frame < e.end) {
188 let local = m.frame - el.start + el.in_frame;
189 let _ = write!(
190 el.children,
191 "\n<marker start=\"{}\" duration=\"{}\" value=\"{}\"/>",
192 time(local, fps),
193 time(1, fps),
194 esc(&m.name),
195 );
196 }
197 }
198
199 let mut out = String::new();
200 out.push_str("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE fcpxml>\n<fcpxml version=\"1.10\">\n <resources>\n");
201 let _ = writeln!(
202 out,
203 " <format id=\"r1\" name=\"{format}\" frameDuration=\"{}\" width=\"{w}\" height=\"{h}\" colorSpace=\"1-1-1 (Rec. 709)\"/>",
204 time(1, fps),
205 );
206 for a in &assets {
207 let src = format!("file://{}", a.path.to_string_lossy().replace(' ', "%20"));
208 let mut kinds = String::new();
209 if a.video {
210 kinds.push_str(" format=\"r1\" hasVideo=\"1\"");
211 }
212 if a.audio {
213 kinds.push_str(" hasAudio=\"1\" audioSources=\"1\" audioChannels=\"2\" audioRate=\"48000\"");
214 }
215 let _ = writeln!(
216 out,
217 " <asset id=\"{}\" name=\"{}\" src=\"{}\" start=\"0s\" duration=\"{}\"{kinds}/>",
218 a.id,
219 esc(&a.path.file_name().map_or_else(String::new, |n| n.to_string_lossy().into_owned())),
220 esc(&src),
221 time(a.reach, fps),
222 );
223 }
224 out.push_str(" </resources>\n <library>\n");
225 let _ = writeln!(out, " <event name=\"edith\">\n <project name=\"{}\">", esc(&t.name));
226 let _ = writeln!(
227 out,
228 " <sequence format=\"r1\" duration=\"{}\" tcStart=\"0s\" tcFormat=\"NDF\" audioLayout=\"stereo\" audioRate=\"48k\">\n <spine>",
229 time(total, fps),
230 );
231 for el in &spine {
232 el.render(&mut out);
233 }
234 out.push_str(" </spine>\n </sequence>\n </project>\n </event>\n </library>\n</fcpxml>\n");
235 out
236}
237
238fn gap(at: u32, frames: u32, fps: f64) -> Element {
239 Element {
240 start: at,
241 end: at + frames,
242 in_frame: 0,
243 open: format!("<gap name=\"Gap\" offset=\"{}\" start=\"0s\" duration=\"{}\"", time(at, fps), time(frames, fps)),
244 time_map: String::new(),
245 children: String::new(),
246 close: "</gap>",
247 }
248}