forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

mixed_fps.rs531 lines, 21.7 KiBHistoryRawDownload
1//! Clips shot at other frame rates on one timeline: what a 25 fps and a 23.976
2//! fps file do on the 30 fps timeline `test_av.mp4` scaffolds.
3//!
4//! Everything goes through the front door -- `import`, `place_stream_at`,
5//! `seek`, `export_to_with`, `open_project` -- because the whole claim is that a
6//! *user* can put two rates on one timeline and watch both at the speed they
7//! were shot at. `project.rs`'s own `rate_composes_with_speed` owns the
8//! arithmetic; what is measured here is that the pictures and the file agree
9//! with it.
10//!
11//! ```text
12//! cargo test -p engine --test mixed_fps
13//! ```
14
15use std::path::{Path, PathBuf};
16use std::thread::sleep;
17use std::time::{Duration, Instant};
18
19use engine::export::{ExportSettings, Format};
20use engine::project::{Edge, Lane, Rate, Speed};
21use engine::scratch::Scratch;
22use engine::{DecodeSession, Frame, PlaybackSession};
23
24/// The timeline's rate, which `test_av.mp4` (30 fps, 5 s) defines.
25const FPS: f64 = 30.0;
26
27fn asset(name: &str) -> PathBuf {
28 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
29 .join("../../assets")
30 .join(name)
31}
32
33/// Silent, for `tests/playback.rs`'s reason: the suite plays real files.
34fn open(path: impl AsRef<Path>) -> PlaybackSession {
35 let session = PlaybackSession::open(path).expect("open");
36 session.set_gain(0.0);
37 session
38}
39
40fn next_frame(session: &mut PlaybackSession, what: &str) -> Frame {
41 let deadline = Instant::now() + Duration::from_secs(10);
42 loop {
43 if let Some(frame) = session.try_frame() {
44 return frame;
45 }
46 assert!(Instant::now() < deadline, "no frame after {what}");
47 sleep(Duration::from_millis(4));
48 }
49}
50
51/// One frame of a file, decoded straight from it: the picture a mapping is
52/// checked against, in the file's *own* numbering.
53fn source_frame(path: &Path, index: u32) -> Vec<u8> {
54 let (_, rx, _cancel) = DecodeSession::open_range(path, index, index + 1).expect("open_range");
55 let frame = rx
56 .recv_timeout(Duration::from_secs(10))
57 .expect("reference frame");
58 assert_eq!(frame.index, index, "open_range starts where it is told");
59 frame.bgra
60}
61
62/// Imports `path` and drags it onto the end of the timeline, the way a library
63/// row reaches a lane.
64fn import_and_place(session: &mut PlaybackSession, path: &Path) {
65 session.import(path).expect("the file joins this timeline");
66 let end = session.timeline_duration();
67 assert!(
68 session
69 .place_stream_at(end, path, 0, None)
70 .expect("a file just imported is on this timeline"),
71 "the drag onto the end of the timeline"
72 );
73}
74
75fn wait(handle: &engine::ExportHandle) -> engine::Result<()> {
76 let deadline = Instant::now() + Duration::from_secs(180);
77 while !handle.is_finished() {
78 assert!(Instant::now() < deadline, "export did not finish");
79 sleep(Duration::from_millis(20));
80 }
81 handle.result().expect("a finished export has an outcome")
82}
83
84/// How different two pictures are, sampled: a re-encode moves every pixel a
85/// little and a *different* picture of `testsrc2` moves them a lot, so the two
86/// are never close to the threshold below.
87fn difference(a: &[u8], b: &[u8]) -> f64 {
88 assert_eq!(a.len(), b.len(), "two pictures of one size");
89 let (mut sum, mut n) = (0f64, 0u32);
90 for i in (0..a.len()).step_by(997) {
91 sum += f64::from(a[i].abs_diff(b[i]));
92 n += 1;
93 }
94 sum / f64::from(n.max(1))
95}
96
97/// A file's length is the seconds it lasts, in the timeline's frames -- not the
98/// frames it holds. That is the whole of what placing another rate means: 50
99/// frames of 25 fps and 48 of 23.976 fps are both two seconds, and two seconds
100/// of a 30 fps timeline is 60 frames.
101#[test]
102fn a_file_at_another_rate_is_placed_for_the_seconds_it_lasts() {
103 let mut session = open(asset("test_av.mp4"));
104 assert_eq!(session.file_frames(&asset("test_av.mp4")), 150, "5 s at 30");
105
106 let pal = asset("test_25fps.mp4");
107 session
108 .import(&pal)
109 .expect("25 fps joins a 30 fps timeline");
110 assert_eq!(session.file_frames(&pal), 60, "50 frames at 25 fps is 2 s");
111
112 // 24000/1001: 48 frames is 2.002 s, which is 60.06 frames of 30 fps --
113 // rounded *up*, so the last picture is still reachable by a trim.
114 let ntsc = asset("test_23976fps.mp4");
115 session.import(&ntsc).expect("23.976 joins it too");
116 assert_eq!(session.file_frames(&ntsc), 61);
117
118 // ...and placed, both are as long on the timeline as they are in the ear.
119 let end = session.timeline_duration();
120 session
121 .place_stream_at(end, &pal, 0, None)
122 .expect("the drag");
123 assert!(
124 (session.timeline_duration() - (5.0 + 2.0)).abs() < 1e-9,
125 "a 2 s clip made the timeline {} s",
126 session.timeline_duration()
127 );
128 let end = session.timeline_duration();
129 session
130 .place_stream_at(end, &ntsc, 0, None)
131 .expect("the drag");
132 // The take is held to its sound, which is 2.000 s (60 frames) against the
133 // picture's 2.002 s: one length on both lanes, so the picture's last frame is
134 // not placed.
135 assert!(
136 (session.timeline_duration() - (5.0 + 2.0 + 60. / FPS)).abs() < 1e-9,
137 "{} s",
138 session.timeline_duration()
139 );
140 // ...and the sound that came down with each take is the same length as its
141 // picture: a placed take is one linked group, so a rate that stretched only
142 // the picture would slide the two apart on the very first drag.
143 let (video, audio) = (session.lane_clips(Lane::V1), session.lane_clips(Lane::A1));
144 assert_eq!(video.len(), 3, "the 30 fps take and the two others");
145 assert_eq!(audio.len(), video.len(), "one audio clip per take");
146 for (v, a) in video.iter().zip(audio) {
147 assert_eq!((v.start, v.len()), (a.start, a.len()), "{v:?} vs {a:?}");
148 }
149}
150
151/// The NTSC ratio, which the 23.976 fps fixture is shot at: 24000/1001 over 30
152/// is exactly 800/1001, and it stays exact however far the timeline runs. A rate
153/// rounded to a float -- or to milli-fps -- would leave a fraction of a frame
154/// per clip to pile up into a visible drift over an hour, which is why the
155/// mapping is built out of the muxer's own timescales and not a division.
156#[test]
157fn a_23_976_rate_is_exact_and_never_drifts() {
158 let ntsc = Rate::from_fps(24_000.0 / 1001.0, FPS).expect("23.976 over 30");
159 assert!(
160 (ntsc.as_f64() - 800.0 / 1001.0).abs() < 1e-15,
161 "{}",
162 ntsc.as_f64()
163 );
164 // Independent integer arithmetic, out to an hour of source and past it: 800
165 // source frames per 1001 timeline ones, and a file's length is that ceiled
166 // (the last picture must still be reachable by a trim).
167 for source in [1u64, 2, 24, 1000, 86_486, 500_000, 1_000_000] {
168 assert_eq!(
169 u64::from(ntsc.timeline_at(source as u32)),
170 (source * 1001).div_ceil(800),
171 "{source} source frames"
172 );
173 }
174 // ...and the two directions stay each other's inverse at every one of them:
175 // the frame an export writes at timeline frame `d` is the frame playback is
176 // holding there, which is what `timeline_at`'s ceil buys.
177 for d in [0u32, 1, 2, 3, 1000, 100_000, 1_000_000] {
178 let source = ntsc.source_at(d);
179 assert!(ntsc.timeline_at(source) <= d, "frame {d} is not yet due");
180 assert!(
181 ntsc.timeline_at(source + 1) > d,
182 "the next frame is due too early at {d}"
183 );
184 }
185 // A timeline's own rate conforms by nothing at all, exactly -- whichever of
186 // the two rates it is written at.
187 assert!(Rate::from_fps(FPS, FPS).expect("30 over 30").is_real_time());
188 assert!(
189 Rate::from_fps(24_000.0 / 1001.0, 24_000.0 / 1001.0)
190 .expect("ntsc over ntsc")
191 .is_real_time()
192 );
193 // A rate no timescale can name is refused rather than read 1:1 in silence:
194 // the one thing `matches_timeline` still turns a file away for.
195 assert!(Rate::from_fps(0.0, FPS).is_err(), "not a rate at all");
196}
197
198/// The picture on screen at a timeline frame is the picture the *file* holds
199/// there: frame `floor(offset * 25/30)` of a 25 fps clip, which is what playing
200/// at the speed it was shot at means, frame for frame.
201#[test]
202fn playback_shows_the_frame_the_file_holds_there() {
203 let pal = asset("test_25fps.mp4");
204 let mut session = open(asset("test_av.mp4"));
205 import_and_place(&mut session, &pal);
206 session.pause();
207 // The clip starts at timeline frame 150 (5 s) and runs 60 frames.
208 let start = 150u32;
209 for offset in [0u32, 1, 5, 6, 29, 30, 47, 59] {
210 let at = start + offset;
211 session.seek(f64::from(at) / FPS);
212 let landed = next_frame(&mut session, "a seek into the 25 fps clip");
213 assert_eq!(landed.index, at, "a seek lands on the frame it asked for");
214 let want = (u64::from(offset) * 25_000 / 30_000) as u32;
215 assert!(
216 landed.bgra == source_frame(&pal, want),
217 "timeline frame {at} (offset {offset}) is not source frame {want}"
218 );
219 }
220 // Past the last picture the file holds, the clip is still on the timeline:
221 // its last frame is shown, not black and not a panic.
222 session.seek(f64::from(start + 59) / FPS);
223 let last = next_frame(&mut session, "the last frame of the clip");
224 assert!(last.bgra == source_frame(&pal, 49), "source frame 49 last");
225 // ...and the frame in front of it is the 30 fps take, frame for frame: a
226 // rate belongs to the source that has one, so the clip beside it is read
227 // exactly as it was before any of this existed.
228 let av = asset("test_av.mp4");
229 session.seek(f64::from(start - 1) / FPS);
230 let before = next_frame(&mut session, "the last frame of the 30 fps take");
231 assert_eq!(before.index, start - 1);
232 assert!(
233 before.bgra == source_frame(&av, start - 1),
234 "the 30 fps clip is still frame for frame"
235 );
236}
237
238/// A trim of a clip at another rate is dragged in *timeline* frames and commits
239/// the source range those frames are worth -- so the box is exactly the room it
240/// was dragged to, and the picture at its new edge is the file's own frame
241/// there.
242#[test]
243fn a_clip_at_another_rate_trims_to_the_room_it_was_dragged_to() {
244 let pal = asset("test_25fps.mp4");
245 let mut session = open(asset("test_av.mp4"));
246 import_and_place(&mut session, &pal);
247 session.pause();
248 let start = 150u32;
249 // Drag its tail back to 30 timeline frames of room: one second, which at 25
250 // fps is the file's first 25 pictures.
251 assert!(
252 session.trim_clip(Lane::V1, 1, Edge::End, start + 30),
253 "trim the tail of the 25 fps clip"
254 );
255 let clip = session.lane_clips(Lane::V1)[1].clone();
256 assert_eq!((clip.start, clip.len()), (start, 30), "{clip:?}");
257 session.seek(f64::from(start + 29) / FPS);
258 let last = next_frame(&mut session, "the trimmed tail");
259 assert!(
260 last.bgra == source_frame(&pal, 24),
261 "one second of a 25 fps file ends on its frame 24"
262 );
263 // ...and its head, dragged forward into source it keeps: 6 timeline frames
264 // in is 5 source frames in, and the tail did not move.
265 assert!(session.trim_clip(Lane::V1, 1, Edge::Start, start + 6));
266 let clip = session.lane_clips(Lane::V1)[1].clone();
267 assert_eq!((clip.start, clip.len()), (start + 6, 24), "{clip:?}");
268 session.seek(f64::from(start + 6) / FPS);
269 let head = next_frame(&mut session, "the trimmed head");
270 assert!(
271 head.bgra == source_frame(&pal, 5),
272 "6 frames of a 30 fps timeline is 5 frames of a 25 fps file"
273 );
274}
275
276/// A speed and a frame rate compose: a 2x 25 fps clip on a 30 fps timeline is
277/// half as many timeline frames and reads twice as far into the file for each
278/// of them.
279#[test]
280fn a_speeded_clip_at_another_rate_is_exactly_both() {
281 let pal = asset("test_25fps.mp4");
282 let mut session = open(asset("test_av.mp4"));
283 import_and_place(&mut session, &pal);
284 session
285 .set_speed(Lane::V1, 1, Speed::from_permille(2000))
286 .expect("nothing is in the way of a clip that got shorter");
287 session.pause();
288 let start = 150u32;
289 assert!(
290 (session.timeline_duration() - (5.0 + 1.0)).abs() < 1e-9,
291 "2 s at 2x is 1 s: {}",
292 session.timeline_duration()
293 );
294 for offset in [0u32, 3, 14, 29] {
295 let at = start + offset;
296 session.seek(f64::from(at) / FPS);
297 let landed = next_frame(&mut session, "a seek into the speeded clip");
298 assert_eq!(landed.index, at);
299 // The speed picks the clip's (timeline-rate) frame, the rate picks the
300 // file's -- in that order, which is the order the decoder's door
301 // applies them.
302 let want = (u64::from(offset) * 2 * 25_000 / 30_000) as u32;
303 assert!(
304 landed.bgra == source_frame(&pal, want),
305 "2x at offset {offset} is not source frame {want}"
306 );
307 }
308}
309
310/// A saved project reloads at the same lengths: `open_project` recomputes every
311/// source's rate from the file, so a mixed-rate timeline is not one that only
312/// the session that built it could hold.
313#[test]
314fn a_mixed_rate_project_reloads_unchanged() {
315 let pal = asset("test_25fps.mp4");
316 let mut session = open(asset("test_av.mp4"));
317 import_and_place(&mut session, &pal);
318 let duration = session.timeline_duration();
319 let spans = session.clip_spans();
320 let path = Scratch::file("edith-mixed", "edith");
321 session.save_project(&path).expect("save");
322
323 let reloaded = PlaybackSession::open_project(&path).expect("a mixed-rate project reopens");
324 assert_eq!(reloaded.clip_spans(), spans, "the same clips, in seconds");
325 assert!((reloaded.timeline_duration() - duration).abs() < 1e-9);
326 assert_eq!(reloaded.file_frames(&pal), 60, "the length was recomputed");
327}
328
329/// The project's rate is the user's to pick, exactly as its resolution is. The
330/// timeline is *conformed* to it -- the same seconds of the same footage,
331/// counted on a new grid -- every source is read through a [`Rate`] against it,
332/// the media's own rate stays reachable, and a save comes back at the rate it
333/// was cut at rather than at the media's.
334#[test]
335fn the_project_rate_is_picked_and_the_timeline_is_conformed_to_it() {
336 let pal = asset("test_25fps.mp4");
337 let mut session = open(asset("test_av.mp4"));
338 import_and_place(&mut session, &pal);
339 let duration = session.timeline_duration();
340 assert_eq!(session.native_frame_rate(), FPS, "the media's own rate");
341 assert!(!session.set_frame_rate(FPS), "the rate already in force");
342 assert!(!session.set_frame_rate(0.0), "not a rate at all");
343
344 assert!(
345 session.set_frame_rate(24.0),
346 "24 is a rate a timescale can name"
347 );
348 assert_eq!(session.meta().frame_rate, 24.0);
349 assert!(
350 (session.timeline_duration() - duration).abs() < 1.0 / 24.0,
351 "the timeline is {} s where it was {duration} s",
352 session.timeline_duration()
353 );
354 // Both files are read through a rate against the new grid now: 5 s and 2 s,
355 // in 24ths.
356 assert_eq!(session.file_frames(&asset("test_av.mp4")), 120, "5 s at 24");
357 assert_eq!(session.file_frames(&pal), 48, "2 s at 24");
358 // ...and each take is still one take on both lanes: every frame number goes
359 // through one map, so a picture cannot drift off its sound.
360 let (video, audio) = (session.lane_clips(Lane::V1), session.lane_clips(Lane::A1));
361 assert_eq!(video.len(), 2, "the 30 fps take and the 25 fps one");
362 for (v, a) in video.iter().zip(audio) {
363 assert_eq!((v.start, v.len()), (a.start, a.len()), "{v:?} vs {a:?}");
364 }
365
366 let path = Scratch::file("edith-rate", "edith");
367 session.save_project(&path).expect("save");
368 let reloaded = PlaybackSession::open_project(&path).expect("a retimed project reopens");
369 assert_eq!(reloaded.meta().frame_rate, 24.0, "the rate it was cut at");
370 assert_eq!(
371 reloaded.clip_spans(),
372 session.clip_spans(),
373 "the same clips"
374 );
375 assert_eq!(reloaded.file_frames(&pal), 48, "recomputed against 24");
376 assert_eq!(
377 reloaded.native_frame_rate(),
378 FPS,
379 "the way back is still there"
380 );
381 std::fs::remove_file(&path).ok();
382
383 // ...and that way back is a pick like any other: the media's own rate.
384 let native = session.native_frame_rate();
385 assert!(session.set_frame_rate(native), "back to the media's own");
386 assert_eq!(session.file_frames(&pal), 60, "2 s at 30 again");
387 assert!(
388 (session.timeline_duration() - duration).abs() < 1.0 / 24.0,
389 "{} s after the round trip, {duration} s before",
390 session.timeline_duration()
391 );
392}
393
394/// ...and an export of it comes out at that rate: the file is written at 24 fps,
395/// as many frames as the conformed timeline has, with its sound as long as its
396/// picture.
397#[test]
398fn an_export_runs_at_the_rate_the_project_was_cut_at() {
399 let mut session = open(asset("test_av.mp4"));
400 assert!(
401 session.trim_clip(Lane::V1, 0, Edge::End, 30),
402 "one second of the 30 fps take"
403 );
404 assert!(session.set_frame_rate(24.0), "cut it at 24 instead");
405 let total = (session.timeline_duration() * 24.0).round() as u32;
406 assert_eq!(total, 24, "one second, in 24ths");
407
408 let out = Scratch::file("edith-rate", "mp4");
409 wait(&session.export_to_with(
410 &out,
411 &ExportSettings {
412 format: Format::Mp4,
413 ..ExportSettings::default()
414 },
415 ))
416 .expect("the export");
417
418 let (meta, _rx, _cancel) = DecodeSession::open_range(&out, 0, u32::MAX).expect("reopen");
419 assert!(
420 (meta.frame_rate - 24.0).abs() < 0.01,
421 "the export runs at the picked rate: {}",
422 meta.frame_rate
423 );
424 assert_eq!(
425 meta.frame_count, total,
426 "the export is the timeline's length"
427 );
428 let secs = engine::AudioSession::duration_secs(&out)
429 .expect("probe the export")
430 .expect("the export has sound");
431 assert!(
432 (secs - f64::from(total) / 24.0).abs() < 0.05,
433 "sound is {secs} s under a second of picture"
434 );
435 std::fs::remove_file(&out).ok();
436}
437
438/// The export is what was watched: as many frames as the timeline has, and the
439/// 25 fps clip walked through its file at 25 fps -- 25 pictures over 30 frames,
440/// not 30 of them and not 25 held to the end.
441#[test]
442fn an_export_of_two_rates_runs_at_the_speed_it_was_shot() {
443 let pal = asset("test_25fps.mp4");
444 let mut session = open(asset("test_av.mp4"));
445 // A short head of the 30 fps take, then the whole of the 25 fps one --
446 // enough of each to be a mixed timeline, short enough to encode in a test.
447 // The sound comes with it: a placed take is one linked group.
448 assert!(
449 session.trim_clip(Lane::V1, 0, Edge::End, 15),
450 "trim the 30 fps take to half a second"
451 );
452 import_and_place(&mut session, &pal);
453 assert!(
454 session.trim_clip(Lane::V1, 1, Edge::End, 45),
455 "one second of the 25 fps clip"
456 );
457 let total = (session.timeline_duration() * FPS).round() as u32;
458 assert_eq!(total, 45, "15 frames of 30 fps and 30 of the 25 fps clip");
459
460 let out = Scratch::file("edith-mixed", "mp4");
461 wait(&session.export_to_with(
462 &out,
463 &ExportSettings {
464 format: Format::Mp4,
465 ..ExportSettings::default()
466 },
467 ))
468 .expect("the export");
469
470 // Duration first: the file is as long as the timeline, so the mixed rates
471 // did not stretch or shorten it.
472 let (meta, rx, _cancel) = DecodeSession::open_range(&out, 0, u32::MAX).expect("reopen");
473 assert!(
474 (meta.frame_rate - FPS).abs() < 0.01,
475 "the export runs at the timeline's rate: {}",
476 meta.frame_rate
477 );
478 assert_eq!(
479 meta.frame_count, total,
480 "the export is the timeline's length"
481 );
482 let written: Vec<Vec<u8>> = rx.into_iter().map(|frame| frame.bgra).collect();
483 assert_eq!(written.len() as u32, total, "every frame came back");
484
485 // ...and motion: inside the 25 fps clip, 30 exported frames show 25
486 // pictures, so 5 of them are a picture held from the frame before. A clip
487 // played at the wrong rate would hold none (too fast, and it would run out
488 // of file) or hold half of them (too slow).
489 let held = (16..total as usize)
490 .filter(|&i| difference(&written[i - 1], &written[i]) < 2.0)
491 .count();
492 assert_eq!(
493 held, 5,
494 "30 timeline frames of a 25 fps clip hold 5 pictures over"
495 );
496
497 // ...and *which* picture each of those frames is: the very one playback
498 // holds there, which is the whole reason the two conversions are one
499 // floor/ceil pair. Nearer its own source frame than either neighbour rather
500 // than equal to it -- the export is re-encoded, so no pixel survives whole.
501 for offset in [0u32, 1, 6, 12, 24, 29] {
502 let want = (u64::from(offset) * 25_000 / 30_000) as u32;
503 let mine = difference(&written[(15 + offset) as usize], &source_frame(&pal, want));
504 for other in [want.saturating_sub(1), want + 1] {
505 if other == want {
506 continue;
507 }
508 assert!(
509 mine < difference(&written[(15 + offset) as usize], &source_frame(&pal, other)),
510 "exported frame {offset} of the 25 fps clip is nearer source \
511 frame {other} than its own {want}"
512 );
513 }
514 }
515
516 // The sound came out as long as the picture, from a *packet copy*: a clip
517 // counts timeline frames whatever its file was shot at, so the window this
518 // export trimmed the 25 fps file's AAC to is whole timeline frames and the
519 // copy is in sync. This is the assertion behind the note in
520 // `export::copy_audio` that says not to turn a conformed lane into a
521 // re-encode.
522 let secs = engine::AudioSession::duration_secs(&out)
523 .expect("probe the export")
524 .expect("the export has sound");
525 let want = f64::from(total) / FPS;
526 assert!(
527 (secs - want).abs() < 0.05,
528 "sound is {secs} s under {want} s of picture"
529 );
530 std::fs::remove_file(&out).ok();
531}