forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

otio.rs332 lines, 11.6 KiBHistoryRawDownload
1//! OpenTimelineIO (`.otio`), the JSON timeline format: [`write`] and [`read`].
2//! Tracks become `Video` and `Audio` tracks, clips reference their file by an
3//! absolute `file://` path, speed is a `LinearTimeWarp`, a transition is a
4//! `Transition` (`SMPTE_Dissolve` for a dissolve), and markers sit on the stack.
5
6use std::path::PathBuf;
7
8use serde_json::{json, Value};
9
10use super::{ClipItem, Item, Timeline, Track};
11use crate::project::{LaneKind, Marker, MarkerColor, Speed};
12use crate::transitions::TransitionKind;
13
14const DISSOLVE: &str = "SMPTE_Dissolve";
15
16fn rational(frames: f64, fps: f64) -> Value {
17 json!({ "OTIO_SCHEMA": "RationalTime.1", "rate": fps, "value": frames })
18}
19
20fn range(start: u32, duration: u32, fps: f64) -> Value {
21 json!({
22 "OTIO_SCHEMA": "TimeRange.1",
23 "start_time": rational(f64::from(start), fps),
24 "duration": rational(f64::from(duration), fps),
25 })
26}
27
28fn color_name(color: MarkerColor) -> &'static str {
29 match color {
30 MarkerColor::Red => "RED",
31 MarkerColor::Orange => "ORANGE",
32 MarkerColor::Yellow => "YELLOW",
33 MarkerColor::Green => "GREEN",
34 MarkerColor::Blue => "BLUE",
35 MarkerColor::Purple => "PURPLE",
36 }
37}
38
39/// The nearest of edith's six marker colours to an OpenTimelineIO colour name.
40fn color_of(name: &str) -> MarkerColor {
41 match name {
42 "RED" | "PINK" => MarkerColor::Red,
43 "ORANGE" => MarkerColor::Orange,
44 "YELLOW" => MarkerColor::Yellow,
45 "GREEN" => MarkerColor::Green,
46 "PURPLE" | "MAGENTA" => MarkerColor::Purple,
47 _ => MarkerColor::Blue,
48 }
49}
50
51/// `file:///abs/path` with everything but unreserved characters and `/` escaped.
52fn file_url(path: &std::path::Path) -> String {
53 let mut out = String::from("file://");
54 for b in path.to_string_lossy().bytes() {
55 match b {
56 b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' | b'/' => out.push(char::from(b)),
57 _ => out.push_str(&format!("%{b:02X}")),
58 }
59 }
60 out
61}
62
63fn percent_decode(s: &str) -> String {
64 let bytes = s.as_bytes();
65 let mut out = Vec::with_capacity(bytes.len());
66 let mut i = 0;
67 while i < bytes.len() {
68 let hex = bytes.get(i + 1..i + 3).and_then(|h| std::str::from_utf8(h).ok());
69 match (bytes[i], hex.and_then(|h| u8::from_str_radix(h, 16).ok())) {
70 (b'%', Some(v)) => {
71 out.push(v);
72 i += 3;
73 }
74 _ => {
75 out.push(bytes[i]);
76 i += 1;
77 }
78 }
79 }
80 String::from_utf8_lossy(&out).into_owned()
81}
82
83/// The OpenTimelineIO document for `t`, as pretty JSON.
84pub fn write(t: &Timeline) -> String {
85 let fps = t.fps;
86 let mut tracks = Vec::new();
87 for track in &t.tracks {
88 let (kind, letter) = match track.kind {
89 LaneKind::Audio => ("Audio", 'A'),
90 _ => ("Video", 'V'),
91 };
92 let mut children = Vec::new();
93 for item in &track.items {
94 match item {
95 Item::Gap(n) => children.push(json!({
96 "OTIO_SCHEMA": "Gap.1",
97 "name": "",
98 "source_range": range(0, *n, fps),
99 "effects": [],
100 "markers": [],
101 "metadata": {},
102 })),
103 Item::Clip(c) => {
104 children.push(clip(c, fps));
105 if let Some((kind, frames)) = c.transition {
106 children.push(transition(kind, frames, fps));
107 }
108 }
109 }
110 }
111 tracks.push(json!({
112 "OTIO_SCHEMA": "Track.1",
113 "name": format!("{letter}{}", track.ord + 1),
114 "kind": kind,
115 "source_range": null,
116 "effects": [],
117 "markers": [],
118 "metadata": {},
119 "children": children,
120 }));
121 }
122 let markers: Vec<Value> = t.markers.iter().map(|m| marker(m, fps)).collect();
123 let doc = json!({
124 "OTIO_SCHEMA": "Timeline.1",
125 "name": t.name,
126 "global_start_time": null,
127 "metadata": {
128 "edith": { "width": t.resolution.0, "height": t.resolution.1, "fps": fps, "notes": t.notes },
129 },
130 "tracks": {
131 "OTIO_SCHEMA": "Stack.1",
132 "name": "tracks",
133 "source_range": null,
134 "effects": [],
135 "markers": markers,
136 "metadata": {},
137 "children": tracks,
138 },
139 });
140 serde_json::to_string_pretty(&doc).unwrap_or_default()
141}
142
143fn clip(c: &ClipItem, fps: f64) -> Value {
144 let mut effects = Vec::new();
145 if !c.speed.is_normal() {
146 effects.push(json!({
147 "OTIO_SCHEMA": "LinearTimeWarp.1",
148 "name": "",
149 "effect_name": "Speed",
150 "metadata": {},
151 "time_scalar": f64::from(c.speed.permille()) / 1000.0,
152 }));
153 }
154 json!({
155 "OTIO_SCHEMA": "Clip.2",
156 "name": c.file_name(),
157 "source_range": range(c.in_frame, c.out_frame - c.in_frame, fps),
158 "media_references": {
159 "DEFAULT_MEDIA": {
160 "OTIO_SCHEMA": "ExternalReference.1",
161 "name": c.file_name(),
162 "target_url": file_url(&c.path),
163 "available_range": null,
164 "metadata": {},
165 },
166 },
167 "active_media_reference_key": "DEFAULT_MEDIA",
168 "effects": effects,
169 "markers": [],
170 "metadata": {},
171 })
172}
173
174fn transition(kind: TransitionKind, frames: u32, fps: f64) -> Value {
175 let name = match kind {
176 TransitionKind::Dissolve => DISSOLVE.to_string(),
177 other => other.name(),
178 };
179 json!({
180 "OTIO_SCHEMA": "Transition.1",
181 "name": "",
182 "transition_type": name,
183 "in_offset": rational(f64::from(frames / 2), fps),
184 "out_offset": rational(f64::from(frames - frames / 2), fps),
185 "metadata": {},
186 })
187}
188
189fn marker(m: &Marker, fps: f64) -> Value {
190 json!({
191 "OTIO_SCHEMA": "Marker.2",
192 "name": m.name,
193 "color": color_name(m.color),
194 "marked_range": range(m.frame, m.length, fps),
195 "metadata": { "edith": { "note": m.note } },
196 })
197}
198
199/// The timeline in an OpenTimelineIO document. Times are converted from the
200/// document's own rate to `fps`, the project's, so a file cut at another rate
201/// still lands on the same moments.
202pub fn read(text: &str, fps: f64) -> crate::Result<Timeline> {
203 let doc: Value = serde_json::from_str(text).map_err(|e| format!("not an OpenTimelineIO file: {e}"))?;
204 if !doc["OTIO_SCHEMA"].as_str().is_some_and(|s| s.starts_with("Timeline")) {
205 return Err("not an OpenTimelineIO timeline".into());
206 }
207 let mut notes = Vec::new();
208 let edith = &doc["metadata"]["edith"];
209 let resolution = match (edith["width"].as_u64(), edith["height"].as_u64()) {
210 (Some(w), Some(h)) => (w as u32, h as u32),
211 _ => (1920, 1080),
212 };
213 let stack = &doc["tracks"];
214 let mut tracks = Vec::new();
215 let mut ord = [0usize; 2];
216 for child in stack["children"].as_array().map(Vec::as_slice).unwrap_or(&[]) {
217 let kind = match child["kind"].as_str() {
218 Some("Audio") => LaneKind::Audio,
219 Some("Video") => LaneKind::Video,
220 _ => continue,
221 };
222 let slot = match kind {
223 LaneKind::Audio => 1,
224 _ => 0,
225 };
226 let items = read_items(child, fps, &mut notes)?;
227 tracks.push(Track { kind, ord: ord[slot], items });
228 ord[slot] += 1;
229 }
230 let mut markers = Vec::new();
231 for m in stack["markers"].as_array().map(Vec::as_slice).unwrap_or(&[]) {
232 let (start, length) = span(&m["marked_range"], fps);
233 markers.push(Marker {
234 frame: start,
235 length,
236 name: m["name"].as_str().filter(|n| !n.trim().is_empty()).unwrap_or("Marker").to_string(),
237 note: m["metadata"]["edith"]["note"].as_str().unwrap_or("").to_string(),
238 color: color_of(m["color"].as_str().unwrap_or("")),
239 });
240 }
241 if let Some(list) = edith["notes"].as_array() {
242 notes.extend(list.iter().filter_map(|n| n.as_str().map(str::to_string)));
243 }
244 Ok(Timeline {
245 name: doc["name"].as_str().unwrap_or("Timeline").to_string(),
246 fps,
247 resolution,
248 tracks,
249 markers,
250 notes,
251 })
252}
253
254fn read_items(track: &Value, fps: f64, notes: &mut Vec<String>) -> crate::Result<Vec<Item>> {
255 let mut items: Vec<Item> = Vec::new();
256 let mut cursor = 0u32;
257 for it in track["children"].as_array().map(Vec::as_slice).unwrap_or(&[]) {
258 let schema = it["OTIO_SCHEMA"].as_str().unwrap_or("");
259 if schema.starts_with("Clip") {
260 let media = match it["media_references"].as_object() {
261 Some(refs) => refs.get(it["active_media_reference_key"].as_str().unwrap_or("DEFAULT_MEDIA")).cloned().unwrap_or(Value::Null),
262 None => it["media_reference"].clone(),
263 };
264 let path = path_of(&media)
265 .ok_or_else(|| format!("the clip {} names no file", it["name"].as_str().unwrap_or("")))?;
266 let (in_frame, len) = span(&it["source_range"], fps);
267 let speed = warp(&it["effects"]);
268 let frames = speed.frames(len);
269 items.push(Item::Clip(ClipItem {
270 path,
271 start: cursor,
272 in_frame,
273 out_frame: in_frame + len,
274 speed,
275 frames,
276 transition: None,
277 }));
278 cursor += frames;
279 } else if schema.starts_with("Gap") {
280 let (_, len) = span(&it["source_range"], fps);
281 items.push(Item::Gap(len));
282 cursor += len;
283 } else if schema.starts_with("Transition") {
284 let frames = frames_of(&it["in_offset"], fps) + frames_of(&it["out_offset"], fps);
285 let name = it["transition_type"].as_str().unwrap_or(DISSOLVE);
286 let kind = match name {
287 DISSOLVE => TransitionKind::Dissolve,
288 other => TransitionKind::parse(other).unwrap_or_else(|| {
289 notes.push(format!("a {other} transition became a dissolve"));
290 TransitionKind::Dissolve
291 }),
292 };
293 if let Some(Item::Clip(prev)) = items.last_mut() {
294 prev.transition = Some((kind, frames));
295 }
296 }
297 }
298 Ok(items)
299}
300
301/// The file a media reference names: `file://` URLs are decoded, a plain path is taken as it is.
302fn path_of(media: &Value) -> Option<PathBuf> {
303 let url = media["target_url"].as_str()?;
304 let path = match url.strip_prefix("file://") {
305 Some(rest) => percent_decode(rest),
306 None => url.to_string(),
307 };
308 Some(PathBuf::from(path))
309}
310
311/// The speed a `LinearTimeWarp` effect asks for, normal when there is none.
312fn warp(effects: &Value) -> Speed {
313 effects
314 .as_array()
315 .into_iter()
316 .flatten()
317 .find(|e| e["OTIO_SCHEMA"].as_str().is_some_and(|s| s.starts_with("LinearTimeWarp")))
318 .and_then(|e| e["time_scalar"].as_f64())
319 .map_or(Speed::NORMAL, |s| Speed::from_permille((s * 1000.0).round().clamp(0.0, 65535.0) as u16))
320}
321
322/// A RationalTime as frames at `fps`.
323fn frames_of(time: &Value, fps: f64) -> u32 {
324 let value = time["value"].as_f64().unwrap_or(0.0);
325 let rate = time["rate"].as_f64().filter(|r| *r > 0.0).unwrap_or(fps);
326 (value * fps / rate).round().max(0.0) as u32
327}
328
329/// A TimeRange as (start, duration) in frames at `fps`; zeros for a null range.
330fn span(range: &Value, fps: f64) -> (u32, u32) {
331 (frames_of(&range["start_time"], fps), frames_of(&range["duration"], fps))
332}