forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

reverse.rs314 lines, 10.8 KiBHistoryRawDownload
1//! Reverse clips: the picture a reversed clip shows is the forward picture run
2//! backwards, its sound is the forward sound mirrored, it composes with speed,
3//! and it survives a save. The picture is compared by hash against the same
4//! source played forward through the same session path, so no tolerance is
5//! needed: a reversed frame is bit-identical to the forward frame it mirrors.
6
7use std::collections::HashMap;
8use std::collections::hash_map::DefaultHasher;
9use std::hash::{Hash, Hasher};
10use std::path::{Path, PathBuf};
11use std::sync::OnceLock;
12use std::thread::sleep;
13use std::time::{Duration, Instant};
14
15use engine::audio::AudioSession;
16use engine::project::{Lane, LaneKind, Source, Speed};
17use engine::scale::FitPolicy;
18use engine::scratch::Scratch;
19use engine::{Clip, PlaybackSession, Project};
20
21fn asset(name: &str) -> PathBuf {
22 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
23 .join("../../assets")
24 .join(name)
25}
26
27fn open() -> PlaybackSession {
28 let s = PlaybackSession::open(asset("test_av.mp4")).expect("open test_av.mp4");
29 s.set_gain(0.0);
30 s
31}
32
33/// Every frame of the timeline, as timeline index -> pixel hash.
34fn hashes(s: &mut PlaybackSession) -> HashMap<u32, u64> {
35 s.seek(0.0);
36 s.play();
37 let deadline = Instant::now() + Duration::from_secs(60);
38 let mut out = HashMap::new();
39 loop {
40 s.tick();
41 while let Some(f) = s.try_frame() {
42 let mut h = DefaultHasher::new();
43 f.bgra.hash(&mut h);
44 out.insert(f.index, h.finish());
45 }
46 if s.is_eos() {
47 return out;
48 }
49 assert!(Instant::now() < deadline, "still playing after 60 s");
50 sleep(Duration::from_millis(2));
51 }
52}
53
54/// The forward decode of test_av.mp4, shared by every test that compares against it.
55fn forward_hashes() -> &'static HashMap<u32, u64> {
56 static FORWARD: OnceLock<HashMap<u32, u64>> = OnceLock::new();
57 FORWARD.get_or_init(|| hashes(&mut open()))
58}
59
60#[test]
61fn a_reversed_clip_shows_the_forward_frames_backwards() {
62 let forward = forward_hashes();
63 assert_eq!(forward.len(), 150);
64 let mut s = open();
65 s.set_reverse(Lane::V1, 0, true).expect("reverse");
66 assert!(s.reversed_of(Lane::V1, 0));
67 let back = hashes(&mut s);
68 assert_eq!(back.len(), 150, "every frame arrives");
69 for t in 0..150u32 {
70 assert_eq!(back[&t], forward[&(149 - t)], "timeline frame {t}");
71 }
72 // And forward again.
73 s.set_reverse(Lane::V1, 0, false).expect("unreverse");
74 assert!(!s.reversed_of(Lane::V1, 0));
75 assert_eq!(hashes(&mut s), *forward);
76}
77
78#[test]
79fn reverse_composes_with_speed() {
80 let forward = forward_hashes();
81 let mut s = open();
82 s.set_speed(Lane::V1, 0, Speed::from_permille(2000)).expect("2x");
83 s.set_reverse(Lane::V1, 0, true).expect("reverse");
84 let back = hashes(&mut s);
85 assert_eq!(back.len(), 75);
86 for t in 0..75u32 {
87 assert_eq!(back[&t], forward[&(149 - 2 * t)], "timeline frame {t} at 2x");
88 }
89}
90
91#[test]
92fn reverse_survives_save_and_load_and_undo() {
93 let mut s = open();
94 s.set_reverse(Lane::V1, 0, true).expect("reverse");
95 let out = Scratch::file("edith-reverse-save", "edith");
96 s.save_project(&out).expect("save");
97 let head = std::fs::read(&out).expect("read");
98 assert!(head.starts_with(b"edith 38"), "the newest dialect is written");
99 let back = PlaybackSession::open_project(&out).expect("open");
100 assert!(back.load_warnings().is_empty(), "{:?}", back.load_warnings());
101 assert!(back.reversed_of(Lane::V1, 0));
102 assert!(back.reversed_of(Lane::A1, 0), "the take reverses as one");
103 s.undo();
104 assert!(!s.reversed_of(Lane::V1, 0), "one undo step");
105}
106
107/// A mono 48 kHz second-and-a-bit with a click at each of `at` (seconds).
108fn write_clicks(path: &Path, at: &[f64], secs: f64) {
109 let rate = 48_000u32;
110 let frames = (f64::from(rate) * secs) as usize;
111 let mut pcm = vec![0i16; frames];
112 for t in at {
113 pcm[(t * f64::from(rate)) as usize] = 29_000;
114 }
115 let data_len = (frames * 2) as u32;
116 let mut out = Vec::new();
117 out.extend_from_slice(b"RIFF");
118 out.extend_from_slice(&(36 + data_len).to_le_bytes());
119 out.extend_from_slice(b"WAVEfmt ");
120 out.extend_from_slice(&16u32.to_le_bytes());
121 out.extend_from_slice(&1u16.to_le_bytes());
122 out.extend_from_slice(&1u16.to_le_bytes());
123 out.extend_from_slice(&rate.to_le_bytes());
124 out.extend_from_slice(&(rate * 2).to_le_bytes());
125 out.extend_from_slice(&2u16.to_le_bytes());
126 out.extend_from_slice(&16u16.to_le_bytes());
127 out.extend_from_slice(b"data");
128 out.extend_from_slice(&data_len.to_le_bytes());
129 for v in pcm {
130 out.extend_from_slice(&v.to_le_bytes());
131 }
132 std::fs::write(path, out).expect("write clicks");
133}
134
135fn audio_clip(in_frame: u32, out_frame: u32, speed: u16, reversed: bool) -> Clip {
136 Clip {
137 opacity_keys: Vec::new(),
138 color_keys: Vec::new(),
139 effects: Vec::new(),
140 speed_keys: Vec::new(),
141 transition_kind: Default::default(),
142 reversed,
143 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
144 angle: Default::default(),
145 fade_in: 0,
146 fade_out: 0,
147 transition_out: 0,
148 visualizer: 0,
149 viz_paint: 0,
150 gain_db: 0.0,
151 gain_keys: Vec::new(),
152 pan: 0,
153 pitch: 0.0,
154 transform_keys: Vec::new(),
155 start: 0,
156 in_frame,
157 out_frame,
158 source: 0,
159 link: None,
160 eq: None,
161 color: None,
162 fit: FitPolicy::default(),
163 speed: Speed::from_permille(speed),
164 transform: None,
165 }
166}
167
168/// Where the clicks of a one-clip audio timeline land, in seconds.
169fn clicks_of(file: &Path, clip: Clip) -> Vec<f64> {
170 let fps = 30.0;
171 let project = Project::from_parts(
172 vec![Source::new(file, 0)],
173 vec![(LaneKind::Audio, vec![clip])],
174 Vec::new(),
175 Vec::new(),
176 Vec::new(),
177 )
178 .expect("an audio project");
179 let (meta, rx) = AudioSession::open_mixed_streams_master_at_fade(
180 &project.audio_sources(),
181 &project.audio_segments_from(0, fps),
182 &project.audio_eqs_from(0, fps),
183 &project.audio_speeds_from(0, fps),
184 &project.audio_fades_from(0, fps),
185 fps,
186 &project.audio_gains(),
187 &project.audio_ducks(),
188 &project.audio_voices(),
189 project.limiter(),
190 None,
191 )
192 .expect("open")
193 .expect("audio");
194 let rate = f64::from(meta.sample_rate);
195 let ch = usize::from(meta.channels);
196 let mut out = Vec::new();
197 let mut base = None;
198 let mut run: Option<(u64, f32)> = None;
199 for chunk in rx {
200 let base = *base.get_or_insert(chunk.start_sample);
201 for (i, f) in chunk.samples.chunks(ch).enumerate() {
202 let n = chunk.start_sample - base + i as u64;
203 let v = f[0].abs();
204 match (run, v > 0.3) {
205 (None, true) => run = Some((n, v)),
206 (Some((_, b)), true) if v > b => run = Some((n, v)),
207 (Some((at, _)), false) => {
208 out.push(at as f64 / rate);
209 run = None;
210 }
211 _ => {}
212 }
213 }
214 }
215 out
216}
217
218#[test]
219fn reversed_audio_is_the_forward_samples_mirrored() {
220 let file = Scratch::file("edith-reverse-clicks", "wav");
221 write_clicks(&file, &[0.2, 0.22, 0.6, 1.3], 2.0);
222 // Source frames 0..30 at 30 fps is the first second: three clicks.
223 let fwd = clicks_of(&file, audio_clip(0, 30, 1000, false));
224 assert_eq!(fwd.len(), 3, "{fwd:?}");
225 let back = clicks_of(&file, audio_clip(0, 30, 1000, true));
226 let mut want: Vec<f64> = fwd.iter().map(|t| 1.0 - t).collect();
227 want.reverse();
228 assert_eq!(back.len(), 3, "{back:?}");
229 for (g, w) in back.iter().zip(&want) {
230 assert!((g - w).abs() < 0.0002, "click at {g}, wanted {w}");
231 }
232 // A window that does not start at zero mirrors inside itself.
233 let mid = clicks_of(&file, audio_clip(15, 45, 1000, true));
234 // Clicks at 0.6 and 1.3 s sit in 0.5..1.5 s; mirrored they are 0.9 and 0.2.
235 assert_eq!(mid.len(), 2, "{mid:?}");
236 for (g, w) in mid.iter().zip([0.2, 0.9]) {
237 assert!((g - w).abs() < 0.0002, "{mid:?}");
238 }
239}
240
241#[test]
242fn reversed_audio_at_double_speed_lands_where_the_picture_does() {
243 let file = Scratch::file("edith-reverse-clicks-2x", "wav");
244 write_clicks(&file, &[0.2, 0.6, 1.3], 2.0);
245 // 60 source frames (2 s) at 2x is 30 timeline frames; a click at source
246 // time t is heard at (2 - t) / 2.
247 let back = clicks_of(&file, audio_clip(0, 60, 2000, true));
248 assert!(!back.is_empty(), "something is heard");
249 let want = [0.35, 0.7, 0.9];
250 for w in want {
251 assert!(
252 back.iter().any(|g| (g - w).abs() < 0.03),
253 "no click near {w} in {back:?}"
254 );
255 }
256}
257
258/// Plays backward from timeline frame `from` as a pull consumer would, to the
259/// start: (frame, pixel hash) in the order they arrive.
260fn backwards_from(s: &mut PlaybackSession, from: u32) -> Vec<(u32, u64)> {
261 s.seek(f64::from(from) / s.meta().frame_rate);
262 s.set_rate(-1.0);
263 assert!(s.backward());
264 s.play();
265 let deadline = Instant::now() + Duration::from_secs(60);
266 let mut out = Vec::new();
267 loop {
268 s.tick();
269 while let Some(f) = s.try_frame() {
270 let mut h = DefaultHasher::new();
271 f.bgra.hash(&mut h);
272 out.push((f.index, h.finish()));
273 }
274 if s.is_eos() {
275 return out;
276 }
277 assert!(Instant::now() < deadline, "still playing after 60 s");
278 sleep(Duration::from_millis(2));
279 }
280}
281
282#[test]
283fn backward_playback_draws_the_frames_from_the_playhead_down() {
284 let forward = hashes(&mut open());
285 let mut s = open();
286 let got = backwards_from(&mut s, 90);
287 let want: Vec<u32> = (0..=90).rev().collect();
288 assert_eq!(got.iter().map(|g| g.0).collect::<Vec<_>>(), want, "descending, none missing");
289 for (t, h) in got {
290 assert_eq!(h, forward[&t], "frame {t}");
291 }
292 s.halt_at_end();
293 assert_eq!(s.now(), 0.0);
294 assert_eq!(s.rate(), 1.0, "the end of a backward run is real time again");
295 assert!(s.is_eos());
296}
297
298#[test]
299fn backward_playback_crosses_cuts_and_plays_a_reversed_clip_forward_in_the_file() {
300 let forward = hashes(&mut open());
301 // Cut at 60 and reverse only the first piece: back from 100 the second piece
302 // is drawn last frame first, then the first piece (reversed) frame by frame
303 // up the file.
304 let mut s = open();
305 assert!(s.cut_at(60.0 / 30.0));
306 s.set_reverse(Lane::V1, 0, true).expect("reverse the head piece");
307 let got = backwards_from(&mut s, 100);
308 assert_eq!(got.len(), 101);
309 for (k, (t, h)) in got.iter().enumerate() {
310 assert_eq!(*t, 100 - k as u32);
311 let source = if *t >= 60 { *t } else { 59 - *t };
312 assert_eq!(*h, forward[&source], "timeline frame {t}");
313 }
314}