forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

mod.rs274 lines, 9.6 KiBHistoryRawDownload
1//! Timelines for other editors: OpenTimelineIO ([`otio`], read and written),
2//! Final Cut Pro XML ([`fcpxml`]) and CMX3600 EDL ([`edl`]), write only.
3//!
4//! Every format is written from one plain [`Timeline`] that [`of_project`]
5//! reads off the active sequence. OpenTimelineIO reads back into the same
6//! type, and [`build`] makes it a new sequence of a project.
7
8pub mod edl;
9pub mod fcpxml;
10pub mod otio;
11
12use std::path::PathBuf;
13
14use crate::project::{Clip, Lane, LaneKind, Marker, Project, Speed};
15use crate::transitions::TransitionKind;
16
17/// One sequence, as an editor's timeline: its tracks in order, the markers on
18/// it, and what an export had to leave out.
19#[derive(Clone, Debug, PartialEq)]
20pub struct Timeline {
21 pub name: String,
22 /// Timeline frames per second.
23 pub fps: f64,
24 /// The canvas size the picture is cut at.
25 pub resolution: (u32, u32),
26 /// Video tracks first, then audio, each in lane order.
27 pub tracks: Vec<Track>,
28 pub markers: Vec<Marker>,
29 /// What the export left out, in words for the user.
30 pub notes: Vec<String>,
31}
32
33/// One lane of the timeline.
34#[derive(Clone, Debug, PartialEq)]
35pub struct Track {
36 pub kind: LaneKind,
37 /// Position among the tracks of its kind: `V1` is 0.
38 pub ord: usize,
39 pub items: Vec<Item>,
40}
41
42/// What sits on a track, in order, back to back.
43#[derive(Clone, Debug, PartialEq)]
44pub enum Item {
45 Clip(ClipItem),
46 /// Empty space of this many timeline frames.
47 Gap(u32),
48}
49
50/// A clip: where it plays, from which file, over which source range.
51#[derive(Clone, Debug, PartialEq)]
52pub struct ClipItem {
53 pub path: PathBuf,
54 /// The timeline frame it starts at.
55 pub start: u32,
56 /// The source frames it plays, `in_frame..out_frame`.
57 pub in_frame: u32,
58 pub out_frame: u32,
59 pub speed: Speed,
60 /// Timeline frames it covers: the source range at its speed.
61 pub frames: u32,
62 /// A transition from this clip into the next one: its kind and length in frames.
63 pub transition: Option<(TransitionKind, u32)>,
64}
65
66impl ClipItem {
67 /// The file's name, which is what a clip is called in another editor.
68 pub fn file_name(&self) -> String {
69 self.path.file_name().map_or_else(|| self.path.display().to_string(), |n| n.to_string_lossy().into_owned())
70 }
71}
72
73impl Timeline {
74 /// The timeline frame the last item of any track ends at.
75 pub fn frames(&self) -> u32 {
76 self.tracks
77 .iter()
78 .map(|t| {
79 t.items.iter().fold(0, |at, item| match item {
80 Item::Clip(c) => c.start + c.frames,
81 Item::Gap(n) => at + n,
82 })
83 })
84 .max()
85 .unwrap_or(0)
86 }
87}
88
89/// The timeline of `project`'s active sequence. `project` is a flattened
90/// snapshot ([`crate::PlaybackSession::export_snapshot`]), so a compound clip
91/// already stands for what it plays.
92pub fn of_project(project: &Project, fps: f64, resolution: (u32, u32)) -> Timeline {
93 let mut tracks = Vec::new();
94 let mut notes = Vec::new();
95 for kind in [LaneKind::Video, LaneKind::Audio] {
96 for lane in project.lanes().into_iter().filter(|l| l.kind == kind) {
97 tracks.push(track_of(project, lane));
98 }
99 }
100 if project.subtitle_lanes().iter().any(|&l| !project.sub_lane(l).is_empty()) {
101 notes.push("Subtitles were left out.".to_string());
102 }
103 let styled = tracks.iter().any(|t| {
104 let lane = Lane::new(t.kind, t.ord);
105 project.lane(lane).iter().any(|c| {
106 c.fade_in > 0
107 || c.fade_out > 0
108 || c.eq.is_some()
109 || c.color.is_some()
110 || c.transform.is_some()
111 || c.gain_db != 0.0
112 || c.reversed
113 || !c.effects.is_empty()
114 })
115 });
116 if styled {
117 notes.push("Colour, effects, fades, levels and reverse were left out.".to_string());
118 }
119 Timeline {
120 name: project.sequence_name(project.active_sequence()).unwrap_or("Sequence 1").to_string(),
121 fps,
122 resolution,
123 tracks,
124 markers: project.markers().to_vec(),
125 notes,
126 }
127}
128
129fn track_of(project: &Project, lane: Lane) -> Track {
130 let clips = project.lane(lane);
131 let mut items = Vec::new();
132 let mut cursor = 0;
133 for (i, c) in clips.iter().enumerate() {
134 if c.start > cursor {
135 items.push(Item::Gap(c.start - cursor));
136 }
137 let frames = c.frames();
138 let path = project.sources().get(c.source).map_or_else(PathBuf::new, |s| s.path.clone());
139 // A transition is a dissolve into the next clip only when the two abut.
140 let transition = clips
141 .get(i + 1)
142 .filter(|next| c.transition_out > 0 && next.start == c.start + frames)
143 .map(|_| (c.transition_kind, c.transition_out));
144 items.push(Item::Clip(ClipItem {
145 path,
146 start: c.start,
147 in_frame: c.in_frame,
148 out_frame: c.out_frame,
149 speed: c.speed,
150 frames,
151 transition,
152 }));
153 cursor = c.start + frames;
154 }
155 Track { kind: lane.kind, ord: lane.ord, items }
156}
157
158/// Makes `t` a new sequence of `project`, named after it, and switches to it.
159/// Each clip is taken in by its path, the way a library file is; a transition
160/// that does not sit between two abutting clips is refused.
161pub fn build(project: &mut Project, t: &Timeline) -> crate::Result<u32> {
162 // A name the project already has gets " (2)", " (3)" and so on, as a new sequence does.
163 let name = (1..)
164 .map(|n| match n {
165 1 => t.name.clone(),
166 n => format!("{} ({n})", t.name),
167 })
168 .find(|name| project.sequence_named(name).is_none())
169 .unwrap_or_else(|| t.name.clone());
170 let id = project.new_sequence(Some(name.as_str()))?;
171 project.switch_sequence(id)?;
172 for track in &t.tracks {
173 let lane = Lane::new(track.kind, track.ord);
174 while project.lane_count(track.kind) <= track.ord {
175 project.add_lane(track.kind);
176 }
177 for item in &track.items {
178 let Item::Clip(c) = item else { continue };
179 let source = project.import(&c.path, 0);
180 let mut clip = Clip::source_range(source, c.in_frame, c.out_frame);
181 clip.speed = c.speed;
182 if !project.place(lane, c.start, clip) {
183 return Err(format!("could not place {} on {}", c.path.display(), lane.label()).into());
184 }
185 }
186 let mut idx = 0;
187 for item in &track.items {
188 let Item::Clip(c) = item else { continue };
189 if let Some((kind, frames)) = c.transition
190 && !project.set_transition(lane, idx, kind, frames)
191 {
192 return Err(format!("a transition on {} is not between two clips", lane.label()).into());
193 }
194 idx += 1;
195 }
196 }
197 for marker in &t.markers {
198 project.add_marker(marker.clone())?;
199 }
200 Ok(id)
201}
202
203#[cfg(test)]
204mod tests {
205 use super::*;
206 use crate::project::MarkerColor;
207
208 fn clip(path: &str, start: u32, in_frame: u32, out_frame: u32, transition: Option<(TransitionKind, u32)>) -> Item {
209 Item::Clip(ClipItem {
210 path: PathBuf::from(path),
211 start,
212 in_frame,
213 out_frame,
214 speed: Speed::NORMAL,
215 frames: out_frame - in_frame,
216 transition,
217 })
218 }
219
220 /// Three clips on V1 with a dissolve after the first, three on A1, and a marker.
221 fn cut() -> Timeline {
222 let items = |v: &str, dissolve: Option<(TransitionKind, u32)>| {
223 vec![
224 clip(v, 0, 0, 50, dissolve),
225 clip(v, 50, 10, 60, None),
226 clip(v, 100, 0, 25, None),
227 ]
228 };
229 Timeline {
230 name: "Cut".into(),
231 fps: 25.0,
232 resolution: (1920, 1080),
233 tracks: vec![
234 Track { kind: LaneKind::Video, ord: 0, items: items("/media/a.mp4", Some((TransitionKind::Dissolve, 10))) },
235 Track { kind: LaneKind::Audio, ord: 0, items: items("/media/a.mp4", None) },
236 ],
237 markers: vec![Marker {
238 frame: 60,
239 length: 0,
240 name: "Beat".into(),
241 note: String::new(),
242 color: MarkerColor::Red,
243 }],
244 notes: Vec::new(),
245 }
246 }
247
248 /// The structure survives OTIO export and import, and FCPXML and EDL carry the key lines.
249 #[test]
250 fn otio_round_trip_keeps_tracks_transitions_and_markers() {
251 let mut p = Project::single("/media/a.mp4", 100);
252 let t = cut();
253 build(&mut p, &t).expect("builds");
254 let seen = of_project(&p, 25.0, (1920, 1080));
255 assert_eq!(seen.name, "Cut");
256 assert_eq!(seen.tracks, t.tracks);
257 assert_eq!(seen.markers, t.markers);
258
259 let back = otio::read(&otio::write(&seen), 25.0).expect("reads its own export");
260 assert_eq!(back.tracks, t.tracks);
261 assert_eq!(back.markers, t.markers);
262 assert_eq!(back.name, "Cut");
263
264 let x = fcpxml::write(&seen);
265 assert!(x.contains("<fcpxml version=\"1.10\">"), "{x}");
266 assert!(x.contains("<asset-clip ref=\"r2\" offset=\"0s\""), "{x}");
267 assert!(x.contains("<marker start=\"4/5s\""), "{x}");
268 let e = edl::write(&seen);
269 assert!(e.starts_with("TITLE: Cut\nFCM: NON-DROP FRAME\n"), "{e}");
270 assert!(e.contains("001 A V C 00:00:00:00 00:00:02:00 01:00:00:00 01:00:02:00\n"), "{e}");
271 assert!(e.contains("D 010"), "{e}");
272 assert!(e.contains("* FROM CLIP NAME: a.mp4"), "{e}");
273 }
274}