forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

silence.rs513 lines, 19.1 KiBHistoryRawDownload
1//! The jumpcut, end to end through the front door: a real file scanned for its
2//! silences, the regions that come back cut (or sped up) as **one** edit, and
3//! the timeline that leaves.
4//!
5//! `silence.rs`'s own unit tests own the detection arithmetic. What is measured
6//! here is what an editor would see: how long the timeline is afterwards, that
7//! every lane moved together, that one undo press takes the whole batch back,
8//! and that the refusals name what is in the way. Group consistency is checked
9//! the way a save checks it -- the parts are handed back to
10//! `Project::from_parts`, which is the door a `.edith` comes in through.
11
12use std::path::PathBuf;
13
14use engine::project::{Lane, LaneKind, Speed};
15use engine::scratch::Scratch;
16use engine::silence::{self, Settings};
17use engine::{Clip, Project};
18
19const FPS: f64 = 30.0;
20
21fn asset(name: &str) -> PathBuf {
22 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
23 .join("../../assets")
24 .join(name)
25}
26
27/// The A/V fixture as a fresh project: `V1` and `A1`, one grouped clip each
28/// covering the whole file -- what opening it in the editor gives.
29fn fixture() -> Project {
30 let path = asset("test_av.mp4");
31 let (meta, _) = engine::demux::Demuxer::open(&path).expect("open the fixture");
32 Project::single(&path, meta.frame_count)
33}
34
35/// A link is one span on however many lanes, and a project whose links disagree
36/// is one no save could load: this is that check, through the same door a load
37/// takes.
38fn loadable(project: &Project) {
39 let (sources, lanes, eq, color, transform) = project.without_orphan_sources();
40 Project::from_parts(sources, lanes, eq, color, transform).expect("the lanes still load");
41}
42
43type Spans = Vec<(u32, u32)>;
44
45fn spans(project: &Project) -> (Spans, Spans) {
46 (
47 project.lane_spans(Lane::V1),
48 project.lane_spans(Lane::new(LaneKind::Audio, 0)),
49 )
50}
51
52/// Five cuts, one undo press. The linked picture slides exactly as its sound
53/// does, the timeline is shorter by exactly what was cut, and the press after
54/// the undo reaches the edit that came *before* the jumpcut -- which is what a
55/// loop over `ripple_delete` would have buried under five steps.
56#[test]
57fn a_batch_of_cuts_is_one_edit_and_moves_every_lane_alike() {
58 let mut p = fixture();
59 let was = p.timeline_frames();
60 // An edit first, so the undo stack has something under the batch.
61 assert!(p.split(60));
62 let before = p.lane(Lane::V1).to_vec();
63 let regions = [(10, 5), (30, 5), (50, 5), (70, 5), (90, 5)];
64 p.cut_regions(&regions, &p.lanes().clone())
65 .expect("every lane is in scope");
66
67 let cut: u32 = regions.iter().map(|&(_, len)| len).sum();
68 assert_eq!(p.timeline_frames(), was - cut);
69 let (video, audio) = spans(&p);
70 assert_eq!(video, audio, "the picture and its sound moved apart");
71 loadable(&p);
72
73 // One press takes the whole batch back...
74 assert!(p.undo());
75 assert_eq!(p.lane(Lane::V1), before, "one undo did not restore the lot");
76 assert_eq!(p.timeline_frames(), was);
77 // ...and the next one is the split, not another fifth of the jumpcut.
78 assert!(p.undo());
79 assert_eq!(p.lane(Lane::V1).len(), 1);
80 assert!(!p.undo(), "the batch left extra history behind");
81}
82
83/// Speeding the silences up leaves **no holes**: `set_speed` on its own does
84/// not ripple, and a gap where a silence shrank is the whole failure this
85/// guards. Everything that was contiguous stays contiguous, both lanes shrink
86/// alike, and it is one undo press.
87#[test]
88fn speeding_silences_up_closes_the_room_they_no_longer_need() {
89 let mut p = fixture();
90 let was = p.timeline_frames();
91 let regions = [(30, 20), (80, 20)];
92 p.speed_regions(&regions, Speed::MAX, &p.lanes().clone())
93 .expect("no lane laps");
94
95 // 20 source frames at 4x occupy 5, so each region gives back 15.
96 let shrunk = Speed::MAX.frames(20);
97 let (video, audio) = spans(&p);
98 assert_eq!(video, audio);
99 assert_eq!(p.timeline_frames(), was - 2 * (20 - shrunk));
100 for pair in video.windows(2) {
101 assert_eq!(
102 pair[0].0 + pair[0].1,
103 pair[1].0,
104 "a hole was left where a silence shrank: {video:?}"
105 );
106 }
107 // The pieces that were the silences are the ones running fast, and only
108 // those.
109 let fast: Vec<u32> = p
110 .lane(Lane::V1)
111 .iter()
112 .filter(|c| c.speed == Speed::MAX)
113 .map(|c| c.start)
114 .collect();
115 assert_eq!(fast, vec![30, 30 + shrunk + (80 - 50)]);
116 loadable(&p);
117
118 // Absolute, not compounding: running it again over where those pieces sit
119 // now leaves the timeline byte for byte as it was -- 4x set twice is 4x.
120 let settled = p.lane(Lane::V1).to_vec();
121 let again: Vec<(u32, u32)> = fast.iter().map(|&at| (at, shrunk)).collect();
122 p.speed_regions(&again, Speed::MAX, &p.lanes().clone())
123 .expect("still no lap");
124 assert_eq!(p.lane(Lane::V1), settled, "a second pass compounded");
125
126 // The second pass changed nothing, so it cost no undo step: one press takes
127 // back the one apply, and there is nothing older.
128 assert!(p.undo());
129 assert_eq!(p.lane(Lane::V1).len(), 1, "one press takes back the one apply");
130 assert!(!p.undo());
131}
132
133/// A clip on another lane that laps over the edge of a silence makes speed mode
134/// refuse **by name**: the lanes would shrink by different amounts and the
135/// ripple would pull them apart. The refusal costs no undo step and changes
136/// nothing -- and cutting the same regions is still fine, which is why delete
137/// mode needs no such rule.
138#[test]
139fn speed_mode_refuses_a_clip_that_laps_over_a_silence() {
140 let mut p = fixture();
141 let lane = p.add_lane(LaneKind::Video);
142 assert_eq!(lane.label(), "V2");
143 let broll = Clip {
144 speed_keys: Vec::new(),
145 reversed: false,
146 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
147 angle: Default::default(),
148 fade_in: 0,
149 fade_out: 0,
150 transition_out: 0,
151 transition_kind: Default::default(),
152 visualizer: 0,
153 viz_paint: 0,
154 gain_db: 0.0,
155 gain_keys: Vec::new(),
156 pan: 0,
157 pitch: 0.0,
158 transform_keys: Vec::new(),
159 opacity_keys: Vec::new(),
160 color_keys: Vec::new(),
161 effects: Vec::new(),
162 start: 0,
163 in_frame: 0,
164 out_frame: 20,
165 source: 0,
166 link: None,
167 eq: None,
168 color: None,
169 fit: Default::default(),
170 speed: Speed::NORMAL,
171 transform: None,
172 };
173 assert!(p.place(lane, 40, broll.clone()));
174 let before = spans(&p);
175
176 let err = p
177 .speed_regions(&[(30, 20)], Speed::MAX, &p.lanes().clone())
178 .expect_err("a half-covered region must not be sped up")
179 .to_string();
180 assert!(err.contains("V2"), "{err}");
181 assert!(err.contains("40"), "{err}");
182 assert_eq!(spans(&p), before, "a refusal changed the timeline");
183
184 // No undo step was spent on it: the press below is the `place` above.
185 assert!(p.undo());
186 assert!(p.lane(lane).is_empty());
187
188 // The same regions cut instead: a ripple is uniform, so nothing laps.
189 assert!(p.place(lane, 40, broll.clone()));
190 p.cut_regions(&[(30, 20)], &p.lanes().clone())
191 .expect("a ripple is uniform");
192 loadable(&p);
193}
194
195/// A clip covering the whole fixture, for a second track to carry.
196fn whole(source: usize, frames: u32) -> Clip {
197 Clip {
198 speed_keys: Vec::new(),
199 reversed: false,
200 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
201 angle: Default::default(),
202 fade_in: 0,
203 fade_out: 0,
204 transition_out: 0,
205 transition_kind: Default::default(),
206 visualizer: 0,
207 viz_paint: 0,
208 gain_db: 0.0,
209 gain_keys: Vec::new(),
210 pan: 0,
211 pitch: 0.0,
212 transform_keys: Vec::new(),
213 opacity_keys: Vec::new(),
214 color_keys: Vec::new(),
215 effects: Vec::new(),
216 start: 0,
217 in_frame: 0,
218 out_frame: frames,
219 source,
220 link: None,
221 eq: None,
222 color: None,
223 fit: Default::default(),
224 speed: Speed::NORMAL,
225 transform: None,
226 }
227}
228
229/// The scope is the point: cutting a take's silences must not drag the music
230/// track under it back. The lanes that were named lose exactly what was cut;
231/// the lane that was not is byte for byte what it was, and one press still
232/// takes the whole batch back.
233#[test]
234fn a_scoped_cut_leaves_the_track_it_was_not_given_alone() {
235 let mut p = fixture();
236 let frames = p.timeline_frames();
237 let music = p.add_lane(LaneKind::Audio);
238 assert_eq!(music.label(), "A2");
239 assert!(p.place(music, 0, whole(0, frames)));
240 let untouched = p.lane(music).to_vec();
241
242 // The take's own two lanes, and not the third.
243 let take = [Lane::V1, Lane::A1];
244 let regions = [(10, 5), (30, 5)];
245 p.cut_regions(&regions, &take)
246 .expect("the take is whole inside the scope");
247
248 assert_eq!(p.lane(music), untouched, "the music track moved");
249 let cut: u32 = regions.iter().map(|&(_, len)| len).sum();
250 for lane in take {
251 assert_eq!(
252 p.lane(lane).last().expect("clips").end(),
253 frames - cut,
254 "{} did not lose what was cut",
255 lane.label()
256 );
257 }
258 // The timeline is as long as its longest lane, which is now the music.
259 assert_eq!(p.timeline_frames(), frames);
260 loadable(&p);
261
262 assert!(p.undo());
263 assert_eq!(p.lane(Lane::V1).last().expect("clips").end(), frames);
264 assert_eq!(p.lane(Lane::V1).len(), 1, "one press took the whole batch");
265}
266
267/// One track of a take is refused **by name**, in both modes: moving the sound
268/// of a shot and not its picture leaves a group whose halves disagree about
269/// their span -- a project no save could load. The refusal says which two clips
270/// and what to do, and detaching them is exactly what makes the same call work.
271#[test]
272fn one_track_of_a_take_is_refused_by_name_until_it_is_detached() {
273 let mut p = fixture();
274 let before = spans(&p);
275 let err = p
276 .cut_regions(&[(10, 5)], &[Lane::A1])
277 .expect_err("half a take must not be cut alone")
278 .to_string();
279 assert!(err.contains("A1") && err.contains("V1"), "{err}");
280 assert!(err.contains("detach"), "{err}");
281 // Speed mode lives under the same law and says the same thing.
282 let same = p
283 .speed_regions(&[(30, 20)], Speed::MAX, &[Lane::A1])
284 .expect_err("half a take must not be re-rated alone")
285 .to_string();
286 assert!(same.contains("A1") && same.contains("V1"), "{same}");
287 assert_eq!(spans(&p), before, "a refusal changed the timeline");
288 assert!(!p.undo(), "a refusal cost an undo step");
289
290 // Detached, the sound is its own to cut -- and the picture stays put.
291 assert!(p.ungroup(Lane::A1, 0));
292 let picture = p.lane(Lane::V1).to_vec();
293 p.cut_regions(&[(10, 5)], &[Lane::A1])
294 .expect("a detached half is one track");
295 assert_eq!(p.lane(Lane::V1), picture, "the picture followed anyway");
296 assert_eq!(p.lane(Lane::A1).last().expect("clips").end(), 145);
297 loadable(&p);
298}
299
300/// Scoping every lane is the ripple this always was: the same cuts through the
301/// batch and through `ripple_delete` one at a time land on the same timeline.
302#[test]
303fn every_lane_in_scope_is_the_ripple_it_always_was() {
304 let regions = [(10, 5), (30, 5), (50, 5)];
305 let mut batch = fixture();
306 let all = batch.lanes();
307 batch.cut_regions(&regions, &all).expect("every lane");
308
309 let mut one_at_a_time = fixture();
310 for &(at, len) in regions.iter().rev() {
311 assert!(one_at_a_time.ripple_delete(at, len));
312 }
313 // The ripple is positions, lengths and sources. Link ids are not part of
314 // it: a batch keeps each take paired (the head keeps its id, the tail gets
315 // one fresh id, as a razor split does) where a delete one at a time
316 // detaches what it splits. So compare everything but the link.
317 let unlinked = |lane: &[Clip]| -> Vec<Clip> {
318 lane.iter().map(|c| Clip { link: None, ..c.clone() }).collect()
319 };
320 assert_eq!(unlinked(batch.lane(Lane::V1)), unlinked(one_at_a_time.lane(Lane::V1)));
321 assert_eq!(unlinked(batch.lane(Lane::A1)), unlinked(one_at_a_time.lane(Lane::A1)));
322 // ...at one undo step against three.
323 assert!(batch.undo());
324 assert!(!batch.undo());
325}
326
327/// A rate that cannot address an edge of a silence is refused naming **that**
328/// edge -- not the region's start, which at a slow rate is often the one frame
329/// that *was* addressable. A cut at the wrong frame is a user sent to look in
330/// the wrong place.
331///
332/// At a quarter speed one source frame is four timeline frames, so only every
333/// fourth frame is a cut the clip's own arithmetic can make.
334#[test]
335fn an_unaddressable_edge_is_named_where_it_actually_is() {
336 let mut p = fixture();
337 p.set_speed(Lane::V1, 0, Speed::MIN)
338 .expect("nothing after it");
339 let before = spans(&p);
340 // Starts where the clip starts -- no split needed there -- and ends at a
341 // frame a quarter-speed clip cannot be cut at.
342 let err = p
343 .speed_regions(&[(0, 5)], Speed::MAX, &p.lanes().clone())
344 .expect_err("frame 5 is not a cut this rate can make")
345 .to_string();
346 assert!(err.contains("frame 5"), "{err}");
347 assert!(
348 !err.contains("frame 0:"),
349 "it named the region's start: {err}"
350 );
351 // Rolled back whole, and the refusal cost no undo step: the press below is
352 // the `set_speed` above.
353 assert_eq!(spans(&p), before);
354 assert!(p.undo());
355 assert_eq!(p.lane(Lane::V1)[0].speed, Speed::NORMAL);
356 assert!(!p.undo());
357}
358
359/// The whole chain a person presses one key for: the fixture is scanned, its
360/// silences come back as timeline frames, and cutting them shortens the
361/// timeline by exactly what was found -- with the scan itself having changed
362/// nothing at all.
363///
364/// `test_av.mp4`'s envelope is silent every second at t≈0.75, so the regions
365/// land there ±1 frame.
366#[test]
367fn scanning_a_clip_and_cutting_what_it_finds() {
368 let mut p = fixture();
369 let was = p.timeline_frames();
370 // Nothing to undo yet, and the scan below must not change that: a preview
371 // is not an edit.
372 assert!(!p.undo());
373
374 let audio = Lane::new(LaneKind::Audio, 0);
375 let clip = p.lane(audio)[0].clone();
376 // The clip's own stretch of the file, which is what the card asks for.
377 let range = (
378 f64::from(clip.in_frame) / FPS,
379 f64::from(clip.out_frame) / FPS,
380 );
381 let levels = silence::levels(asset("test_av.mp4"), 0, range)
382 .expect("scan")
383 .expect("the fixture has audio");
384 let cfg = Settings {
385 threshold_db: -40.,
386 min_silence: 0.08,
387 padding: 0.02,
388 min_keep: 0.,
389 };
390 let regions = silence::timeline_regions(&clip, FPS, &silence::regions(&levels, cfg));
391 assert_eq!(regions.len(), 5, "{regions:?}");
392 for (second, &(start, len)) in regions.iter().enumerate() {
393 // The dip of that second, in frames, sits inside the marked region.
394 let dip = (second as f64 + 0.75) * FPS;
395 assert!(
396 (f64::from(start) - 1.0..f64::from(start + len) + 1.0).contains(&dip),
397 "second {second}: [{start}, {}) is not the dip at {dip}",
398 start + len
399 );
400 }
401 assert!(!p.undo(), "the scan took an undo step");
402
403 let cut: u32 = regions.iter().map(|&(_, len)| len).sum();
404 p.cut_regions(&regions, &p.lanes().clone())
405 .expect("every lane is in scope");
406 assert_eq!(p.timeline_frames(), was - cut);
407 let (video, audio_spans) = spans(&p);
408 assert_eq!(video, audio_spans);
409 loadable(&p);
410
411 // What a jumpcut leaves is ordinary clips, so the file it saves to is the
412 // same dialect it always was -- no wire change went with this feature.
413 let dir = Scratch::dir("edith-silence");
414 let file = dir.join("cut.edith");
415 let (sources, lanes, eq, color, transform) = p.without_orphan_sources();
416 engine::edith::save(
417 &file,
418 &sources,
419 &lanes,
420 &p.lane_gains(),
421 &p.lane_subs(),
422 p.subtitles(),
423 &eq,
424 &color,
425 &transform,
426 (1920, 1080),
427 None,
428 p.tone(),
429 false,
430 true,
431 engine::export::EncoderSeat::default(),
432 p.limiter(),
433 None,
434 0,
435 )
436 .expect("save");
437 let text = std::fs::read_to_string(&file).expect("read it back");
438 assert!(
439 text.starts_with("edith 30"),
440 "{:?}",
441 &text[..16.min(text.len())]
442 );
443 let back = engine::edith::load(&file).expect("load");
444 assert_eq!(back.lanes, lanes, "the cut timeline did not round-trip");
445 std::fs::remove_dir_all(&dir).ok();
446
447 assert!(p.undo());
448 assert_eq!(p.timeline_frames(), was);
449}
450
451/// The reverse cut: the same scan, its quiet regions inverted into the
452/// speech between them, and cutting *those* -- what is left is the silences
453/// themselves, a timeline shorter by exactly the speech, far shorter than
454/// the jumpcut's remains (which keep everything but the dips), and one undo
455/// press takes it all back.
456#[test]
457fn keeping_only_silence_cuts_the_speech() {
458 let mut p = fixture();
459 let was = p.timeline_frames();
460 let audio = Lane::new(LaneKind::Audio, 0);
461 let clip = p.lane(audio)[0].clone();
462 let range = (
463 f64::from(clip.in_frame) / FPS,
464 f64::from(clip.out_frame) / FPS,
465 );
466 let levels = silence::levels(asset("test_av.mp4"), 0, range)
467 .expect("scan")
468 .expect("the fixture has audio");
469 let cfg = Settings {
470 threshold_db: -40.,
471 min_silence: 0.08,
472 padding: 0.02,
473 min_keep: 0.,
474 };
475 let quiet = silence::regions(&levels, cfg);
476 assert!(!quiet.is_empty(), "the fixture has silences to keep");
477 let duration = levels.len() as f64 / f64::from(engine::silence::WINDOWS_PER_SEC);
478 let speech = silence::invert(duration, &quiet);
479 let regions = silence::timeline_regions(&clip, FPS, &speech);
480 assert!(!regions.is_empty(), "the fixture has speech to cut");
481
482 let cut: u32 = regions.iter().map(|&(_, len)| len).sum();
483 let kept_quiet: u32 = silence::timeline_regions(&clip, FPS, &quiet)
484 .iter()
485 .map(|&(_, len)| len)
486 .sum();
487 p.cut_regions(&regions, &p.lanes().clone())
488 .expect("every lane is in scope");
489 assert_eq!(p.timeline_frames(), was - cut);
490 // What remains *is* the quiet: the scan's complement covers the span the
491 // silences do not. The two sums differ only where a boundary falls
492 // between frames -- both sides round inward, so one unclaimed frame can
493 // open at every meeting of a silence and the speech beside it, and
494 // nowhere else.
495 let remaining = was - cut;
496 assert!(
497 remaining >= kept_quiet,
498 "{remaining} left against {kept_quiet} of marked quiet"
499 );
500 assert!(
501 remaining - kept_quiet <= (quiet.len() + speech.len()) as u32,
502 "{remaining} left against {kept_quiet} of marked quiet"
503 );
504 // ...and the two cuts are opposites, not neighbours: five brief dips
505 // against the speech around them.
506 let jumpcut_left = was - kept_quiet;
507 assert!(
508 remaining * 4 < jumpcut_left,
509 "{remaining} left against the jumpcut's {jumpcut_left}"
510 );
511 assert!(p.undo());
512 assert_eq!(p.timeline_frames(), was);
513}