forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

ramp_subs.rs211 lines, 7.8 KiBHistoryRawDownload
1//! A speed ramp carries the subtitle cues of its clip with the picture: a cue timed at
2//! source time `s` is written where the ramp puts source time `s` on the timeline (the
3//! inverse of `ramp_source_at`), not where a constant speed would, in Matroska and mp4.
4//!
5//! `test_av.mp4` is 150 frames at 30 fps; a 1x-to-2x ramp over its first 60 timeline
6//! frames covers 90 source frames in those 60, so the file is 90 frames long.
7
8use std::path::{Path, PathBuf};
9use std::process::Command;
10use std::time::{Duration, Instant};
11
12use engine::export::{ExportSettings, Format};
13use engine::project::{Lane, Speed, SpeedKey, ramp_source_at};
14use engine::scratch::Scratch;
15use engine::subtitle::{self, Cue, SubtitleTrack};
16use engine::{ExportHandle, Project};
17
18const MEDIA: &str = "test_av.mp4";
19const FPS: f64 = 30.0;
20/// One frame, in microseconds, which is what a cue may be out by.
21const FRAME_US: i64 = 33_334;
22// The tests check cues and tracks, not pictures, so the picture is kept small.
23const SMALL: (u32, u32) = (64, 48);
24
25fn asset(name: &str) -> PathBuf {
26 PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../assets").join(name)
27}
28
29fn wait(handle: &ExportHandle) {
30 let started = Instant::now();
31 while !handle.is_finished() {
32 assert!(started.elapsed() < Duration::from_secs(1800), "export hung");
33 std::thread::sleep(Duration::from_millis(20));
34 }
35 handle.result().expect("a finished export has an outcome").expect("export");
36}
37
38fn keys() -> [SpeedKey; 2] {
39 [SpeedKey { at: 0, speed: Speed::NORMAL }, SpeedKey { at: 60, speed: Speed::from_permille(2000) }]
40}
41
42/// Timeline microseconds at which the ramp reaches source time `us` (bisection).
43fn ramped_us(us: i64) -> i64 {
44 let want = us as f64 / 1e6 * FPS;
45 let (mut lo, mut hi) = (0.0f64, 1000.0f64);
46 for _ in 0..80 {
47 let mid = (lo + hi) / 2.0;
48 if ramp_source_at(&keys(), mid) < want { lo = mid } else { hi = mid }
49 }
50 ((lo + hi) / 2.0 / FPS * 1e6).round() as i64
51}
52
53fn cue(a: i64, b: i64, text: &str) -> Cue {
54 Cue { start_us: a, end_us: b, text: text.into(), image: None, words: Vec::new(), karaoke: Vec::new() }
55}
56
57fn project(reverse: bool, ramp: bool) -> Project {
58 let track = SubtitleTrack {
59 path: asset(MEDIA),
60 track: Some(2),
61 language: "eng".into(),
62 name: String::new(),
63 label: "eng".into(),
64 bitmap: false,
65 cues: vec![
66 cue(500_000, 1_500_000, "one"),
67 cue(2_000_000, 3_250_000, "two"),
68 cue(4_000_000, 4_750_000, "three"),
69 ],
70 refused: None,
71 };
72 let mut p = Project::single(asset(MEDIA), 150).with_subtitles(vec![track]);
73 if ramp {
74 p.set_speed_ramp(Lane::V1, 0, &keys()).expect("the ramp sets");
75 }
76 if reverse {
77 p.set_reverse(Lane::V1, 0, true).expect("the clip reverses");
78 }
79 p
80}
81
82fn export(name: &str, format: Format, ext: &str, reverse: bool, ramp: bool) -> Scratch {
83 engine::envcfg::set("VE_SW", "1");
84 engine::envcfg::set("VE_SW_ENC", "1");
85 let out = Scratch::file(&format!("ve_ramp_subs_{name}"), ext);
86 let (meta, _) = engine::demux::Demuxer::open(&asset(MEDIA)).expect("probe");
87 let handle = engine::export::start(
88 project(reverse, ramp),
89 meta,
90 &out,
91 &ExportSettings { format, subtitles: vec![0], size: Some(SMALL), ..Default::default() },
92 None,
93 );
94 wait(&handle);
95 out
96}
97
98fn check(got: &[(i64, i64, String)], reverse: bool, ramp: bool) {
99 let want = [(500_000, 1_500_000, "one"), (2_000_000, 3_250_000, "two"), (4_000_000, 4_750_000, "three")];
100 assert_eq!(got.len(), want.len(), "cues: {got:?}");
101 let mut want = want.to_vec();
102 if reverse {
103 want.reverse(); // mirrored, so the last cue plays first
104 }
105 for (g, w) in got.iter().zip(want) {
106 // The clip is 5 s of file. Reversed, a cue [s, e] is mirrored to [5 - e, 5 - s]
107 // before the ramp (if any) carries it onto the timeline.
108 let map = |us: i64| if ramp { ramped_us(us) } else { us };
109 let (a, b) = if reverse { (map(5_000_000 - w.1), map(5_000_000 - w.0)) } else { (map(w.0), map(w.1)) };
110 assert_eq!(g.2, w.2);
111 assert!((g.0 - a).abs() <= FRAME_US, "{} starts {} want {a}", w.2, g.0);
112 assert!((g.1 - b).abs() <= FRAME_US, "{} ends {} want {b}", w.2, g.1);
113 // And it is not where a constant 1x would leave it.
114 if ramp && !reverse && w.0 >= 2_000_000 {
115 assert!((g.0 - w.0).abs() > 4 * FRAME_US, "{} unmapped", w.2);
116 }
117 }
118}
119
120fn srt_times(path: &Path) -> Vec<(i64, i64, String)> {
121 let out = Command::new("ffmpeg")
122 .args(["-v", "error", "-i"])
123 .arg(path)
124 .args(["-map", "0:s:0", "-f", "srt", "-"])
125 .output()
126 .expect("ffmpeg");
127 assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
128 let text = String::from_utf8_lossy(&out.stdout).replace("\r\n", "\n");
129 let t = |s: &str| {
130 let (hms, ms) = s.trim().split_once(',').unwrap();
131 let p: Vec<i64> = hms.split(':').map(|x| x.parse().unwrap()).collect();
132 ((p[0] * 3600 + p[1] * 60 + p[2]) * 1000 + ms.parse::<i64>().unwrap()) * 1000
133 };
134 text.split("\n\n")
135 .filter(|b| !b.trim().is_empty())
136 .map(|b| {
137 let mut l = b.lines();
138 l.next();
139 let (a, e) = l.next().unwrap().split_once("-->").unwrap();
140 (t(a), t(e), l.collect::<Vec<_>>().join("\n"))
141 })
142 .collect()
143}
144
145fn matroska(name: &str, reverse: bool, ramp: bool) {
146 let out = export(name, Format::Hevc, "mkv", reverse, ramp);
147 let tracks = subtitle::of_matroska(&out).expect("read back");
148 assert_eq!(tracks.len(), 1);
149 let got: Vec<_> = tracks[0].cues.iter().map(|c| (c.start_us, c.end_us, c.text.clone())).collect();
150 check(&got, reverse, ramp);
151}
152
153fn mp4(name: &str, reverse: bool, ramp: bool) {
154 let out = export(name, Format::Mp4, "mp4", reverse, ramp);
155 check(&srt_times(&out), reverse, ramp);
156}
157
158#[test]
159fn a_ramped_clips_cues_follow_the_ramp_in_matroska() {
160 matroska("ramp_mkv", false, true);
161}
162
163#[test]
164fn a_ramped_clips_cues_follow_the_ramp_in_mp4() {
165 mp4("ramp_mp4", false, true);
166}
167
168#[test]
169fn a_reversed_clips_cues_are_mirrored_in_matroska() {
170 matroska("rev_mkv", true, false);
171}
172
173#[test]
174fn a_reversed_clips_cues_are_mirrored_in_mp4() {
175 mp4("rev_mp4", true, false);
176}
177
178#[test]
179fn a_reversed_ramped_clips_cues_are_mirrored_then_ramped() {
180 matroska("revramp_mkv", true, true);
181 mp4("revramp_mp4", true, true);
182}
183
184/// A cue's per-word times go through the same ramp as the cue, each word where its own
185/// sound lands; on a reversed clip the words are dropped and the cue shows whole.
186#[test]
187fn a_cues_words_follow_the_ramp_and_drop_on_a_reversed_clip() {
188 let words = vec![
189 (2_000_000, 2_500_000, "a".to_string()),
190 (2_500_000, 3_000_000, "b".to_string()),
191 (3_000_000, 3_250_000, "c".to_string()),
192 ];
193 let with_words = |reverse: bool| {
194 let mut p = project(reverse, true);
195 let mut track = p.subtitles()[0].clone();
196 track.cues[1].words = words.clone();
197 p = p.with_subtitles(vec![track.clone()]);
198 engine::export::timeline_cues(&p, &track, FPS)
199 };
200 let cues = with_words(false);
201 let two = cues.iter().find(|c| c.text == "two").expect("cue two");
202 assert_eq!(two.words.len(), 3, "{:?}", two.words);
203 for ((s, e, w), (gs, ge, gw)) in words.iter().zip(&two.words) {
204 assert_eq!(w, gw);
205 assert!((gs - ramped_us(*s)).abs() <= FRAME_US, "{w} starts {gs} want {}", ramped_us(*s));
206 assert!((ge - ramped_us(*e)).abs() <= FRAME_US, "{w} ends {ge} want {}", ramped_us(*e));
207 }
208 let reversed = with_words(true);
209 let two = reversed.iter().find(|c| c.text == "two").expect("cue two");
210 assert!(two.words.is_empty(), "a reversed clip keeps no words: {:?}", two.words);
211}