forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

project_fuzz.rs1178 lines, 40.0 KiBHistoryRawDownload
1//! Fuzzing the `.edith` project format: whatever a session can build must
2//! save, load back and save again byte for byte; every older dialect must load
3//! and upgrade; and a damaged file must be refused by name, never a panic or a
4//! hang.
5//!
6//! Deterministic: every case comes from a seed, so a failure names the seed
7//! that reproduces it.
8//!
9//! ```text
10//! cargo test --release -p engine --test project_fuzz -- --nocapture
11//! ```
12
13use std::path::{Path, PathBuf};
14use std::sync::mpsc;
15use std::time::Duration;
16
17use engine::color::{ColorKey, ColorParams};
18use engine::duck::Duck;
19use engine::eq::{Band, BandKind, EqParams};
20use engine::export::EncoderSeat;
21use engine::limiter::Limiter;
22use engine::project::{
23 Chapter, Clip, GainKey, LaneKind, Project, Source, Speed, SpeedKey, SubClip, Title, ramp_frames,
24};
25use engine::scale::FitPolicy;
26use engine::scratch::Scratch;
27use engine::subtitle;
28use engine::text::{Outline, Place, TextStyle};
29use engine::tonemap::Preset;
30use engine::transform::{KeyEase, OpacityKey, TransformKey, TransformParams};
31
32/// The number of random projects, and of corrupted files, each test builds.
33const ITERATIONS: u64 = 2000;
34
35/// xorshift64*: no dependency, and a seed replays it exactly.
36struct Rng(u64);
37
38impl Rng {
39 fn new(seed: u64) -> Self {
40 // A zero state would stay zero forever.
41 Rng(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1)
42 }
43
44 fn next_u64(&mut self) -> u64 {
45 let mut x = self.0;
46 x ^= x >> 12;
47 x ^= x << 25;
48 x ^= x >> 27;
49 self.0 = x;
50 x.wrapping_mul(0x2545_F491_4F6C_DD1D)
51 }
52
53 /// Uniform in `lo..=hi`.
54 fn range(&mut self, lo: u32, hi: u32) -> u32 {
55 lo + (self.next_u64() % u64::from(hi - lo + 1)) as u32
56 }
57
58 fn chance(&mut self, percent: u64) -> bool {
59 self.next_u64() % 100 < percent
60 }
61
62 fn f32_in(&mut self, lo: f32, hi: f32) -> f32 {
63 let unit = (self.next_u64() >> 11) as f64 / (1u64 << 53) as f64;
64 lo + (hi - lo) * unit as f32
65 }
66
67 fn pick<T: Copy>(&mut self, items: &[T]) -> T {
68 items[self.range(0, items.len() as u32 - 1) as usize]
69 }
70}
71
72/// Text that exercises every escape the format has, plus multi-byte characters.
73fn some_text(rng: &mut Rng, max_pieces: u32) -> String {
74 const PIECES: &[&str] = &[
75 "a", "Z", " ", "\\", "\n", "\r", "%", "\t", "é", "Ω", "ж", "א", "ก", "漢", "😀",
76 ];
77 let n = rng.range(1, max_pieces);
78 (0..n).map(|_| rng.pick(PIECES)).collect()
79}
80
81/// The scalars a save takes that a `Project` does not carry.
82struct Scalars {
83 resolution: (u32, u32),
84 fps: Option<f64>,
85 proxy: bool,
86 auto_proxy: bool,
87 encoder: EncoderSeat,
88 sample_rate: Option<u32>,
89 playhead: u32,
90}
91
92fn random_scalars(rng: &mut Rng) -> Scalars {
93 Scalars {
94 resolution: rng.pick(&[(1920, 1080), (640, 360), (1280, 720), (33, 17)]),
95 fps: if rng.chance(80) {
96 Some(rng.pick(&[24.0, 29.97, 30.0, 25.0, 23.976]))
97 } else {
98 None
99 },
100 proxy: rng.chance(30),
101 auto_proxy: rng.chance(50),
102 encoder: rng.pick(&[
103 EncoderSeat::Auto,
104 EncoderSeat::Hardware,
105 EncoderSeat::Software,
106 ]),
107 sample_rate: rng.pick(&[None, Some(44_100), Some(48_000)]),
108 playhead: rng.range(0, 400),
109 }
110}
111
112/// What `PlaybackSession` writes, from the public accessors of a `Project`.
113fn save_project(project: &Project, path: &Path, s: &Scalars) -> Vec<u8> {
114 let (sources, lanes, eq, color, transform) = project.without_orphan_sources();
115 engine::edith::save_flagged(
116 path,
117 &sources,
118 &lanes,
119 &project.lane_gains(),
120 &project.lane_subs(),
121 project.subtitles(),
122 &eq,
123 &color,
124 &transform,
125 s.resolution,
126 s.fps,
127 project.tone(),
128 s.proxy,
129 s.auto_proxy,
130 s.encoder,
131 project.limiter(),
132 s.sample_rate,
133 s.playhead,
134 &project.lane_flags(),
135 &project.lane_ducks(),
136 project.cue_edits(),
137 project.cue_adds(),
138 project.titles(),
139 project.chapters(),
140 project.markers(),
141 &project.caption_style(),
142 &project.lane_voices(),
143 &project.lane_names(),
144 )
145 .expect("save");
146 std::fs::read(path).expect("read back the saved file")
147}
148
149/// The same save, from what a load gave back. A fixed point of the format is
150/// exactly this: whatever `load` returns, `save` writes it the same way again.
151fn save_document(doc: &engine::edith::Document, path: &Path) -> Vec<u8> {
152 let mut tracks = subtitle::open_all(&doc.subtitles);
153 for (track, code) in &doc.sub_langs {
154 tracks[*track].language = code.clone();
155 }
156 engine::edith::save_flagged(
157 path,
158 &doc.sources,
159 &doc.lanes,
160 &doc.gains,
161 &doc.subs,
162 &tracks,
163 &doc.eq,
164 &doc.color,
165 &doc.transform,
166 doc.resolution.unwrap_or((1280, 720)),
167 doc.fps,
168 doc.tone,
169 doc.proxy,
170 doc.auto_proxy,
171 doc.encoder,
172 doc.limiter,
173 doc.sample_rate,
174 doc.playhead,
175 &doc.flags,
176 &doc.ducks,
177 &doc.cue_edits,
178 &doc.cue_adds,
179 &doc.titles,
180 &doc.chapters,
181 &doc.markers,
182 &doc.caption_style,
183 &doc.voices,
184 &doc.names,
185 )
186 .expect("re-save");
187 std::fs::read(path).expect("read back the re-saved file")
188}
189
190/// A random but well-formed project, built the way a session builds one: a
191/// `from_parts` for the edit list, then the public setters for everything else.
192/// A setter that refuses a value leaves the project as it was, so the random
193/// draws are allowed to be refused.
194fn random_project(rng: &mut Rng, dir: &Path) -> Project {
195 // Sources: relative names most of the time, the odd spaced, escaped or
196 // absolute one.
197 let nsrc = rng.range(1, 3);
198 let sources: Vec<Source> = (0..nsrc)
199 .map(|i| {
200 let name = match rng.range(0, 9) {
201 0 => format!("/elsewhere/{i} media%25.mov"),
202 1 => format!("sub dir/clip {i}\n2.mp4"),
203 _ => format!("media_{i}.mp4"),
204 };
205 Source::new(name, rng.range(0, 2) as usize)
206 })
207 .collect();
208
209 let eq: Vec<EqParams> = (0..rng.range(0, 3))
210 .map(|_| EqParams {
211 bands: (0..rng.range(0, 4))
212 .map(|_| Band {
213 freq_hz: rng.f32_in(20.0, 20_000.0),
214 gain_db: rng.f32_in(-12.0, 12.0),
215 q: rng.f32_in(0.1, 10.0),
216 kind: rng.pick(&[
217 BandKind::LowShelf,
218 BandKind::Peak,
219 BandKind::HighShelf,
220 BandKind::LowCut,
221 BandKind::HighCut,
222 ]),
223 })
224 .collect(),
225 })
226 .collect();
227 let color: Vec<ColorParams> = (0..rng.range(0, 3))
228 .map(|_| ColorParams {
229 brightness: rng.f32_in(-1.0, 1.0),
230 contrast: rng.f32_in(0.0, 2.0),
231 saturation: rng.f32_in(0.0, 2.0),
232 tint: rng.f32_in(-1.0, 1.0),
233 ..Default::default()
234 })
235 .collect();
236 let transform: Vec<TransformParams> = (0..rng.range(0, 3))
237 .map(|_| random_transform(rng))
238 .collect();
239
240 // Lanes, each a run of clips with gaps, sorted and never overlapping.
241 let nlanes = rng.range(1, 4);
242 let mut next_link = 0;
243 let mut lanes: Vec<(LaneKind, Vec<Clip>)> = Vec::new();
244 for _ in 0..nlanes {
245 let kind = rng.pick(&[LaneKind::Video, LaneKind::Audio]);
246 let mut clips = Vec::new();
247 // A link is a group id, unique to one lane's clips: the setters refuse
248 // two clips of a lane that name the same one.
249 let mut cursor = rng.range(0, 20);
250 for _ in 0..rng.range(0, 4) {
251 let start = cursor + rng.range(0, 15);
252 let in_frame = rng.range(0, 200);
253 let out_frame = in_frame + rng.range(1, 120);
254 let speed = Speed::from_permille(rng.pick(&[1000, 500, 250, 2000, 4000, 1500]));
255 // One clip in four carries a speed ramp (format v35): valid keys only,
256 // strictly increasing, and the clip's footprint is the ramp's.
257 let speed_keys = if rng.chance(25) {
258 let mut at = 0;
259 (0..rng.range(1, 4))
260 .map(|_| {
261 let key = SpeedKey {
262 at,
263 speed: Speed::from_permille(rng.pick(&[250, 500, 1000, 1500, 2000, 4000])),
264 };
265 at += rng.range(1, 40);
266 key
267 })
268 .collect()
269 } else {
270 Vec::new()
271 };
272 let frames = if speed_keys.is_empty() {
273 speed.frames(out_frame - in_frame).max(1)
274 } else {
275 ramp_frames(&speed_keys, out_frame - in_frame)
276 };
277 let fade_in = rng.range(0, frames);
278 clips.push(Clip {
279 start,
280 in_frame,
281 out_frame,
282 source: rng.range(0, nsrc - 1) as usize,
283 link: if rng.chance(50) {
284 next_link += 1;
285 Some(next_link)
286 } else {
287 None
288 },
289 eq: pick_index(rng, eq.len()),
290 color: pick_index(rng, color.len()),
291 transform: pick_index(rng, transform.len()),
292 fit: rng.pick(&[
293 FitPolicy::Fit,
294 FitPolicy::Fill,
295 FitPolicy::Stretch,
296 FitPolicy::Center,
297 ]),
298 speed,
299 fade_in,
300 fade_out: rng.range(0, frames),
301 transition_out: rng.range(0, frames),
302 transition_kind: Default::default(),
303 visualizer: rng.range(0, 255) as u8,
304 viz_paint: rng.next_u64(),
305 // A picture has no volume of its own, and only a picture is placed
306 // by keys: each kind takes the fields its lane can hold.
307 gain_db: if kind == LaneKind::Video {
308 0.0
309 } else {
310 rng.f32_in(-60.0, 24.0)
311 },
312 gain_keys: random_gain_keys(rng, frames),
313 pan: 0,
314 pitch: 0.0,
315 transform_keys: if kind == LaneKind::Video {
316 random_transform_keys(rng, frames)
317 } else {
318 Vec::new()
319 },
320 opacity_keys: if kind == LaneKind::Video {
321 random_opacity_keys(rng, frames)
322 } else {
323 Vec::new()
324 },
325 color_keys: if kind == LaneKind::Video {
326 random_color_keys(rng, frames)
327 } else {
328 Vec::new()
329 },
330 speed_keys,
331 reversed: rng.chance(25),
332 effects: if kind == LaneKind::Video {
333 random_effects(rng)
334 } else {
335 Vec::new()
336 },
337 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
338 angle: Default::default(),
339 });
340 cursor = start + frames;
341 }
342 lanes.push((kind, clips));
343 }
344
345 let mut project = Project::from_parts(sources, lanes, eq, color, transform)
346 .expect("a generated project is well-formed");
347
348 // Lane-level state, through the setters.
349 let laned = project.lanes();
350 for lane in &laned {
351 project.set_lane_gain_db(*lane, rng.f32_in(-60.0, 12.0));
352 match lane.kind {
353 LaneKind::Video => {
354 project.set_lane_hidden(*lane, rng.chance(30));
355 }
356 LaneKind::Audio => {
357 project.set_lane_muted(*lane, rng.chance(30));
358 if rng.chance(40) {
359 let under = rng.range(0, 2) as usize;
360 project.set_lane_duck(*lane, Some(Duck::new(under, rng.f32_in(-40.0, 0.0))));
361 }
362 }
363 LaneKind::Subtitle => {}
364 }
365 project.set_lane_locked(*lane, rng.chance(20));
366 }
367 project.set_tone(rng.pick(&[Preset::Reference, Preset::Standard, Preset::Vivid]));
368 project.set_limiter(Limiter {
369 ceiling_db: rng.f32_in(-6.0, 0.0),
370 on: rng.chance(50),
371 });
372
373 // Titles and chapters, in the frame range the project has.
374 let total = project.timeline_frames().max(1);
375 for _ in 0..rng.range(0, 3) {
376 let frames = rng.range(1, 90);
377 let fade_in = rng.range(0, frames);
378 let _ = project.add_title(Title {
379 start: rng.range(0, total),
380 frames,
381 text: some_text(rng, 12),
382 style: TextStyle {
383 size: rng.range(10, 200),
384 outline: rng.pick(&[Outline::None, Outline::Thin, Outline::Thick]),
385 boxed: rng.chance(50),
386 place: rng.pick(&[Place::Bottom, Place::Top, Place::Centre]),
387 ..TextStyle::default()
388 },
389 fade_in,
390 fade_out: rng.range(0, frames - fade_in),
391 in_anim: Default::default(),
392 out_anim: Default::default(),
393 anim_frames: 0,
394 keys: Vec::new(),
395 });
396 }
397 for _ in 0..rng.range(0, 3) {
398 let _ = project.add_chapter(Chapter {
399 frame: rng.range(0, total),
400 title: some_text(rng, 8),
401 });
402 }
403
404 // Subtitles: a real SRT on disk, so the cues are the file's own.
405 let srt = dir.join("subs.srt");
406 std::fs::write(
407 &srt,
408 "1\n00:00:01,000 --> 00:00:02,500\nhello there\n\n2\n00:00:03,000 --> 00:00:04,000\nsecond cue\n\n",
409 )
410 .expect("write the srt");
411 if rng.chance(70) {
412 project = project.with_subtitles(vec![subtitle::open(&srt, None)]);
413 project.set_subtitle_language(0, "eng");
414 for cue in 0..rng.range(0, 1) as usize {
415 project.set_cue_text(0, cue, &some_text(rng, 6));
416 }
417 if rng.chance(50) {
418 let _ = project.add_cue(0, 5_000_000, 6_000_000, &some_text(rng, 4), false);
419 }
420 if rng.chance(60) {
421 let sub_lane = project.add_lane(LaneKind::Subtitle);
422 let _ = project.place_sub(
423 sub_lane,
424 rng.range(0, 100),
425 SubClip::whole_track(0, 2_000_000, 25.0),
426 );
427 }
428 }
429 project
430}
431
432/// `Option<u16>` index into a table of `len`, or none.
433/// A random effects stack: up to four effects of any kind, each switched on or off,
434/// every value somewhere in its range.
435fn random_effects(rng: &mut Rng) -> Vec<engine::effects::Effect> {
436 use engine::effects::{Effect, EffectKind};
437 let n = rng.range(0, 4) as usize;
438 (0..n)
439 .map(|_| {
440 let kind = rng.pick(&EffectKind::ALL);
441 let mut e = Effect::new(kind);
442 e.on = rng.chance(70);
443 for spec in kind.params() {
444 e.set(spec.name, rng.f32_in(spec.min, spec.max)).unwrap();
445 }
446 e
447 })
448 .collect()
449}
450
451fn pick_index(rng: &mut Rng, len: usize) -> Option<u16> {
452 if len == 0 || rng.chance(40) {
453 None
454 } else {
455 Some(rng.range(0, len as u32 - 1) as u16)
456 }
457}
458
459fn random_transform(rng: &mut Rng) -> TransformParams {
460 TransformParams {
461 pos_x: rng.f32_in(-1.0, 1.0),
462 pos_y: rng.f32_in(-1.0, 1.0),
463 scale: rng.f32_in(0.1, 4.0),
464 rotate: rng.f32_in(-360.0, 360.0),
465 crop_l: rng.f32_in(0.0, 0.5),
466 crop_r: rng.f32_in(0.0, 0.5),
467 crop_t: rng.f32_in(0.0, 0.5),
468 crop_b: rng.f32_in(0.0, 0.5),
469 opacity: rng.f32_in(0.0, 1.0),
470 }
471}
472
473/// Sorted, distinct keys inside a clip of `frames` timeline frames.
474fn random_gain_keys(rng: &mut Rng, frames: u32) -> Vec<GainKey> {
475 let mut at: Vec<u32> = (0..rng.range(0, 3))
476 .map(|_| rng.range(0, frames.saturating_sub(1)))
477 .collect();
478 at.sort_unstable();
479 at.dedup();
480 at.into_iter()
481 .map(|at| GainKey {
482 at,
483 db: rng.f32_in(-60.0, 24.0),
484 ease: rng.pick(&KeyEase::ALL),
485 })
486 .collect()
487}
488
489fn random_opacity_keys(rng: &mut Rng, frames: u32) -> Vec<OpacityKey> {
490 let mut at: Vec<u32> = (0..rng.range(0, 3))
491 .map(|_| rng.range(0, frames.saturating_sub(1)))
492 .collect();
493 at.sort_unstable();
494 at.dedup();
495 at.into_iter()
496 .map(|at| OpacityKey {
497 at,
498 opacity: rng.f32_in(0.0, 1.0),
499 ease: rng.pick(&KeyEase::ALL),
500 })
501 .collect()
502}
503
504fn random_color_keys(rng: &mut Rng, frames: u32) -> Vec<ColorKey> {
505 let mut at: Vec<u32> = (0..rng.range(0, 3))
506 .map(|_| rng.range(0, frames.saturating_sub(1)))
507 .collect();
508 at.sort_unstable();
509 at.dedup();
510 at.into_iter()
511 .map(|at| ColorKey {
512 at,
513 params: ColorParams {
514 brightness: rng.f32_in(-1.0, 1.0),
515 contrast: rng.f32_in(0.0, 2.0),
516 saturation: rng.f32_in(0.0, 2.0),
517 tint: rng.f32_in(-1.0, 1.0),
518 ..Default::default()
519 },
520 ease: rng.pick(&KeyEase::ALL),
521 })
522 .collect()
523}
524
525fn random_transform_keys(rng: &mut Rng, frames: u32) -> Vec<TransformKey> {
526 let mut at: Vec<u32> = (0..rng.range(0, 2))
527 .map(|_| rng.range(0, frames.saturating_sub(1)))
528 .collect();
529 at.sort_unstable();
530 at.dedup();
531 at.into_iter()
532 .map(|at| TransformKey {
533 at,
534 params: random_transform(rng),
535 ease: rng.pick(&KeyEase::ALL),
536 })
537 .collect()
538}
539
540#[test]
541fn random_projects_save_load_and_save_again_byte_for_byte() {
542 let scratch = Scratch::dir("ve_project_fuzz_round_trip");
543 // How many projects carried each feature, so a generator that stopped
544 // drawing one shows up here rather than as a green run that tests nothing.
545 let mut seen = [0u32; 9];
546 for seed in 0..ITERATIONS {
547 let mut rng = Rng::new(seed);
548 let project = random_project(&mut rng, &scratch);
549 let scalars = random_scalars(&mut rng);
550 let path = scratch.join("fuzz.edith");
551
552 let first = save_project(&project, &path, &scalars);
553 let doc = engine::edith::load(&path)
554 .unwrap_or_else(|e| panic!("seed {seed}: a saved project refused to load: {e}"));
555
556 // Every part of the edit list comes back as it went in. What is saved is
557 // what `without_orphan_sources` hands over: its tables hold only what the
558 // clips name, so a clip's table index may be renumbered on the way out.
559 let (_, saved, saved_eq, saved_color, saved_transform) = project.without_orphan_sources();
560 let lanes = project.lanes();
561 assert_eq!(doc.lanes.len(), lanes.len(), "seed {seed}: lane count");
562 for ((lane, (kind, clips)), (_, saved_clips)) in lanes.iter().zip(&doc.lanes).zip(&saved) {
563 assert_eq!(*kind, lane.kind, "seed {seed}: lane kind");
564 if lane.kind != LaneKind::Subtitle {
565 assert_eq!(
566 format!("{saved_clips:?}"),
567 format!("{clips:?}"),
568 "seed {seed}: the clips of {}",
569 lane.label()
570 );
571 }
572 }
573 assert_eq!(
574 format!("{saved_eq:?}"),
575 format!("{:?}", doc.eq),
576 "seed {seed}: equalizers"
577 );
578 assert_eq!(
579 format!("{saved_color:?}"),
580 format!("{:?}", doc.color),
581 "seed {seed}: colours"
582 );
583 assert_eq!(
584 format!("{saved_transform:?}"),
585 format!("{:?}", doc.transform),
586 "seed {seed}: transforms"
587 );
588 assert_eq!(
589 format!("{:?}", project.lane_gains()),
590 format!("{:?}", doc.gains),
591 "seed {seed}: gains"
592 );
593 assert_eq!(
594 format!("{:?}", project.lane_flags()),
595 format!("{:?}", doc.flags),
596 "seed {seed}: flags"
597 );
598 assert_eq!(
599 format!("{:?}", project.lane_ducks()),
600 format!("{:?}", doc.ducks),
601 "seed {seed}: ducks"
602 );
603 assert_eq!(
604 format!("{:?}", project.titles()),
605 format!("{:?}", doc.titles),
606 "seed {seed}: titles"
607 );
608 assert_eq!(
609 format!("{:?}", project.chapters()),
610 format!("{:?}", doc.chapters),
611 "seed {seed}: chapters"
612 );
613 assert_eq!(
614 format!("{:?}", project.cue_edits()),
615 format!("{:?}", doc.cue_edits),
616 "seed {seed}: cue edits"
617 );
618 assert_eq!(
619 format!("{:?}", project.cue_adds()),
620 format!("{:?}", doc.cue_adds),
621 "seed {seed}: cue adds"
622 );
623 assert_eq!(
624 format!("{:?}", project.limiter()),
625 format!("{:?}", doc.limiter),
626 "seed {seed}: limiter"
627 );
628 assert_eq!(project.tone(), doc.tone, "seed {seed}: tone");
629 assert_eq!(doc.playhead, scalars.playhead, "seed {seed}: playhead");
630
631 for (count, has) in seen.iter_mut().zip([
632 !doc.titles.is_empty(),
633 !doc.chapters.is_empty(),
634 !doc.subtitles.is_empty(),
635 !doc.cue_edits.is_empty(),
636 !doc.cue_adds.is_empty(),
637 doc.ducks.iter().any(|d| !d.is_empty()),
638 doc.flags.iter().any(|f| f.hidden || f.muted || f.locked),
639 doc.subs.iter().any(|l| !l.is_empty()),
640 doc.lanes.iter().any(|(_, c)| {
641 c.iter()
642 .any(|c| !c.gain_keys.is_empty() || c.speed.permille() != 1000)
643 }),
644 ]) {
645 *count += u32::from(has);
646 }
647
648 // Saving what came back writes the same bytes: a fixed point.
649 let second = save_document(&doc, &scratch.join("fuzz-again.edith"));
650 assert_eq!(
651 String::from_utf8_lossy(&first),
652 String::from_utf8_lossy(&second),
653 "seed {seed}: the re-save differs from the first save"
654 );
655 }
656 let names = [
657 "titles",
658 "chapters",
659 "subtitles",
660 "cue edits",
661 "cue adds",
662 "ducks",
663 "switches",
664 "captions",
665 "keyed or sped clips",
666 ];
667 for (name, count) in names.iter().zip(seen) {
668 assert!(count > 0, "no generated project had {name}");
669 println!("{name}: {count} of {ITERATIONS} projects");
670 }
671}
672
673/// The lines a version may write, one clip line per lane, for each dialect from
674/// v1 up. Built from the same field rules the loader reads, so it is the file
675/// that version would have written, not a hand-picked one.
676fn synthesize(version: u32) -> String {
677 let mut out = format!("edith {version}\nplayhead 3\n");
678 if version >= 7 {
679 out.push_str("resolution 1280 720\n");
680 }
681 if version >= 9 {
682 out.push_str("fps 30.0\n");
683 }
684 // Versions 1 and 2 wrote the source without its audio stream.
685 if version <= 2 {
686 out.push_str("source media.mp4\n");
687 } else {
688 out.push_str("source 0 media.mp4\n");
689 }
690 if version == 1 {
691 out.push_str("clip 0 30 0\n");
692 return out;
693 }
694 // The clip fields after the first five, in the order the loader reads them,
695 // each present from the version that introduced it.
696 let mut fields: Vec<&str> = Vec::new();
697 if version >= 5 {
698 fields.push("-"); // eq
699 }
700 if version >= 6 {
701 fields.push("-"); // colour
702 }
703 if version >= 7 {
704 fields.push("fit");
705 }
706 if version >= 8 {
707 fields.push("1000"); // speed
708 }
709 if version >= 18 {
710 fields.extend(["0", "0"]); // fades
711 }
712 if version >= 19 {
713 fields.push("0"); // transition
714 }
715 if version >= 20 {
716 fields.push("-"); // transform
717 }
718 if version >= 21 {
719 fields.push("0"); // visualizer flags
720 }
721 if version >= 22 {
722 fields.push("0"); // visualizer paint
723 }
724 // A lane line is `<kind> [<lane>] <start> <in> <out> <source> <link>` and
725 // then the fields above; v4 on numbers the lane, and every older one holds
726 // one lane of each kind.
727 let numbered = if version >= 4 { "1 " } else { "" };
728 for kind in ["video", "audio"] {
729 let mut line = format!("{kind} {numbered}0 0 30 0 -");
730 for field in &fields {
731 line.push(' ');
732 line.push_str(field);
733 }
734 out.push_str(&line);
735 out.push('\n');
736 }
737 out
738}
739
740#[test]
741fn every_older_version_loads_and_upgrades() {
742 let scratch = Scratch::dir("ve_project_fuzz_versions");
743 for version in 1..=engine::edith::NEWEST_VERSION {
744 let text = synthesize(version);
745 let path = scratch.join(format!("v{version}.edith"));
746 std::fs::write(&path, &text).expect("write the old file");
747
748 let doc = engine::edith::load(&path)
749 .unwrap_or_else(|e| panic!("v{version} refused to load: {e}\n{text}"));
750 assert!(!doc.sources.is_empty(), "v{version}: its source came back");
751 assert_eq!(doc.playhead, 3, "v{version}: the playhead came back");
752 assert!(
753 doc.lanes.iter().any(|(_, clips)| !clips.is_empty()),
754 "v{version}: its clip came back"
755 );
756 // Every clip of an old file plays at real time and holds no grade it did
757 // not write, which is what leaving a field out has always meant.
758 for (_, clips) in &doc.lanes {
759 for clip in clips {
760 assert_eq!(clip.in_frame, 0, "v{version}");
761 assert_eq!(clip.out_frame, 30, "v{version}");
762 if version < 8 {
763 assert_eq!(
764 clip.speed,
765 Speed::from_permille(1000),
766 "v{version}: real time"
767 );
768 }
769 }
770 }
771
772 // An upgraded file is written again as the newest dialect, and it loads
773 // to the same document.
774 let again_path = scratch.join(format!("v{version}-up.edith"));
775 let upgraded = save_document(&doc, &again_path);
776 assert!(
777 String::from_utf8_lossy(&upgraded).starts_with("edith "),
778 "v{version}: the upgrade writes a header"
779 );
780 let reloaded = engine::edith::load(&again_path)
781 .unwrap_or_else(|e| panic!("v{version} upgraded and then refused: {e}"));
782 assert_eq!(
783 format!("{:?}", doc.lanes),
784 format!("{:?}", reloaded.lanes),
785 "v{version}: the upgrade keeps the clips"
786 );
787 }
788}
789
790#[test]
791fn a_newer_version_is_refused_by_name() {
792 let scratch = Scratch::dir("ve_project_fuzz_newer");
793 let path = scratch.join("future.edith");
794 let future = engine::edith::NEWEST_VERSION + 1;
795 std::fs::write(&path, format!("edith {future}\nsource 0 a.mp4\n")).unwrap();
796 let err = engine::edith::load(&path).expect_err("a newer file must be refused");
797 assert!(
798 err.to_string()
799 .contains(&format!("unsupported version {future}")),
800 "named: {err}"
801 );
802}
803
804/// Damage that a seed picks: each returns the bytes it leaves behind.
805fn corrupt(rng: &mut Rng, good: &[u8]) -> Vec<u8> {
806 let mut bytes = good.to_vec();
807 match rng.range(0, 6) {
808 // Truncate at a random byte offset.
809 0 => {
810 let at = rng.range(0, bytes.len() as u32) as usize;
811 bytes.truncate(at);
812 }
813 // Flip a few random bytes.
814 1 => {
815 for _ in 0..rng.range(1, 4) {
816 let at = rng.range(0, bytes.len() as u32 - 1) as usize;
817 bytes[at] ^= rng.range(1, 255) as u8;
818 }
819 }
820 // Duplicate or delete a random line.
821 2 | 3 => {
822 let text = String::from_utf8_lossy(&bytes).into_owned();
823 let mut lines: Vec<&str> = text.lines().collect();
824 if !lines.is_empty() {
825 let at = rng.range(0, lines.len() as u32 - 1) as usize;
826 if rng.chance(50) {
827 let dup = lines[at];
828 lines.insert(at, dup);
829 } else {
830 lines.remove(at);
831 }
832 }
833 bytes = (lines.join("\n") + "\n").into_bytes();
834 }
835 // Replace a number with one that is huge, negative, NaN or infinite.
836 _ => {
837 let text = String::from_utf8_lossy(&bytes).into_owned();
838 let mut spans: Vec<(usize, usize)> = Vec::new();
839 let mut start = None;
840 for (i, c) in text.char_indices() {
841 match (c.is_ascii_digit() || c == '.' || c == '-', start) {
842 (true, None) => start = Some(i),
843 (false, Some(s)) => {
844 spans.push((s, i));
845 start = None;
846 }
847 _ => {}
848 }
849 }
850 if let Some(s) = start {
851 spans.push((s, text.len()));
852 }
853 if spans.is_empty() {
854 return bytes;
855 }
856 let (s, e) = spans[rng.range(0, spans.len() as u32 - 1) as usize];
857 let junk = rng.pick(&[
858 "99999999999999999999999999",
859 "-99999999999999999999",
860 "-1",
861 "NaN",
862 "inf",
863 "-inf",
864 "1e308",
865 "-0",
866 "4294967296",
867 "18446744073709551616",
868 "4000000000",
869 "4294967295",
870 "2147483647",
871 "0",
872 "1e-45",
873 "1.5e38",
874 "-3.4e38",
875 "0.0000000000000000000000000000001",
876 "9223372036854775807",
877 ]);
878 let mut out = String::new();
879 out.push_str(&text[..s]);
880 out.push_str(junk);
881 out.push_str(&text[e..]);
882 bytes = out.into_bytes();
883 }
884 }
885 bytes
886}
887
888/// Loads `path` on a worker thread: `Ok(Ok(()))` for a load, `Ok(Err(why))` for
889/// a refusal, and `Err(what)` for a panic or a load that does not return in time.
890fn load_guarded(path: PathBuf) -> Result<Result<(), String>, String> {
891 let (tx, rx) = mpsc::channel();
892 std::thread::spawn(move || {
893 let outcome = std::panic::catch_unwind(|| engine::edith::load(&path).map(|_| ()));
894 let _ = tx.send(outcome);
895 });
896 match rx.recv_timeout(Duration::from_secs(10)) {
897 Ok(Ok(loaded)) => Ok(loaded.map_err(|e| e.to_string())),
898 Ok(Err(panic)) => Err(format!(
899 "panicked: {}",
900 panic
901 .downcast_ref::<String>()
902 .cloned()
903 .or_else(|| panic.downcast_ref::<&str>().map(|s| s.to_string()))
904 .unwrap_or_else(|| "no message".to_string())
905 )),
906 Err(_) => Err("did not return within 10 s".to_string()),
907 }
908}
909
910#[test]
911fn damaged_files_are_refused_or_loaded_never_panic_or_hang() {
912 let scratch = Scratch::dir("ve_project_fuzz_corrupt");
913 let path = scratch.join("damaged.edith");
914 let mut failures = Vec::new();
915 for seed in 0..ITERATIONS {
916 let mut rng = Rng::new(seed ^ 0xC0FF_EE00);
917 let project = random_project(&mut rng, &scratch);
918 let good = save_project(&project, &path, &random_scalars(&mut rng));
919 let bytes = corrupt(&mut rng, &good);
920 std::fs::write(&path, &bytes).expect("write the damaged file");
921
922 match load_guarded(path.clone()) {
923 Ok(Ok(())) => {}
924 Ok(Err(message)) => {
925 if message.is_empty() {
926 failures.push(format!("seed {seed}: an empty refusal"));
927 }
928 }
929 Err(what) => failures.push(format!("seed {seed}: {what}")),
930 }
931 }
932 assert!(
933 failures.is_empty(),
934 "{} failures:\n{}",
935 failures.len(),
936 failures.join("\n")
937 );
938}
939
940/// A value the setters may be handed by a caller that is not careful: out of
941/// every range, huge, negative or not a number at all.
942fn wild_f32(rng: &mut Rng) -> f32 {
943 match rng.range(0, 9) {
944 0 => f32::NAN,
945 1 => f32::INFINITY,
946 2 => -1.0e30,
947 3 => 1.0e30,
948 4 => 0.0,
949 _ => rng.f32_in(-400.0, 400.0),
950 }
951}
952
953/// Whatever the setters accept must save to a file that loads: a setter that
954/// takes a value the loader would refuse is a project that cannot be saved
955/// without losing the work it holds.
956#[test]
957fn wild_values_the_setters_accept_still_save_and_load() {
958 let scratch = Scratch::dir("ve_project_fuzz_wild");
959 for seed in 0..ITERATIONS {
960 let mut rng = Rng::new(seed ^ 0x5EED_0F51);
961 let mut project = random_project(&mut rng, &scratch);
962 let lanes = project.lanes();
963 for lane in lanes.iter().copied() {
964 let len = project.lane(lane).len();
965 if len == 0 {
966 continue;
967 }
968 let idx = rng.range(0, len as u32 - 1) as usize;
969 match lane.kind {
970 LaneKind::Audio => {
971 project.set_clip_gain(lane, idx, wild_f32(&mut rng));
972 project.set_lane_duck(
973 lane,
974 Some(Duck {
975 under: rng.range(0, 4) as usize,
976 depth_db: wild_f32(&mut rng),
977 threshold_db: wild_f32(&mut rng),
978 attack_ms: wild_f32(&mut rng),
979 release_ms: wild_f32(&mut rng),
980 }),
981 );
982 }
983 LaneKind::Video => {
984 let keys: Vec<TransformKey> = (0..rng.range(0, 300))
985 .map(|_| TransformKey {
986 at: rng.range(0, 500),
987 params: TransformParams {
988 opacity: wild_f32(&mut rng),
989 ..random_transform(&mut rng)
990 },
991 ease: KeyEase::Linear,
992 })
993 .collect();
994 project.set_transform_keys(lane, idx, keys);
995 project.set_transform(
996 lane,
997 idx,
998 Some(TransformParams {
999 scale: wild_f32(&mut rng),
1000 ..random_transform(&mut rng)
1001 }),
1002 );
1003 }
1004 LaneKind::Subtitle => {}
1005 }
1006 let keys: Vec<GainKey> = (0..rng.range(0, 300))
1007 .map(|_| GainKey {
1008 at: rng.range(0, 500),
1009 db: wild_f32(&mut rng),
1010 ease: KeyEase::Linear,
1011 })
1012 .collect();
1013 project.set_gain_keys(lane, idx, keys);
1014 project.set_eq(
1015 lane,
1016 idx,
1017 Some(EqParams {
1018 bands: vec![Band {
1019 freq_hz: wild_f32(&mut rng),
1020 gain_db: wild_f32(&mut rng),
1021 q: wild_f32(&mut rng),
1022 kind: BandKind::Peak,
1023 }],
1024 }),
1025 );
1026 project.set_color(
1027 lane,
1028 idx,
1029 Some(ColorParams {
1030 brightness: wild_f32(&mut rng),
1031 contrast: wild_f32(&mut rng),
1032 saturation: wild_f32(&mut rng),
1033 tint: wild_f32(&mut rng),
1034 ..Default::default()
1035 }),
1036 );
1037 project.set_lane_gain_db(lane, wild_f32(&mut rng));
1038 }
1039 let long: String = std::iter::repeat_n("x", rng.range(0, 600) as usize).collect();
1040 let _ = project.add_title(Title {
1041 start: rng.range(0, 1000),
1042 frames: rng.range(0, 200_000_000),
1043 text: long.clone(),
1044 style: TextStyle {
1045 size: rng.range(0, 400),
1046 outline: Outline::Thick,
1047 boxed: true,
1048 place: Place::Top,
1049 ..TextStyle::default()
1050 },
1051 fade_in: rng.range(0, 1000),
1052 fade_out: rng.range(0, 1000),
1053 in_anim: Default::default(),
1054 out_anim: Default::default(),
1055 anim_frames: 0,
1056 keys: Vec::new(),
1057 });
1058 let _ = project.add_chapter(Chapter {
1059 frame: rng.range(0, 1000),
1060 title: long,
1061 });
1062 project.set_limiter(Limiter {
1063 ceiling_db: wild_f32(&mut rng),
1064 on: true,
1065 });
1066
1067 let scalars = random_scalars(&mut rng);
1068 let path = scratch.join("wild.edith");
1069 save_project(&project, &path, &scalars);
1070 if let Err(e) = engine::edith::load(&path) {
1071 panic!("seed {seed}: a project the setters accepted refuses to load: {e}");
1072 }
1073 }
1074}
1075
1076/// A plain clip at `start` of source 0, for the `from_parts` refusals below.
1077fn plain_clip(start: u32) -> Clip {
1078 Clip {
1079 start,
1080 in_frame: 0,
1081 out_frame: 30,
1082 source: 0,
1083 link: None,
1084 eq: None,
1085 color: None,
1086 transform: None,
1087 fit: FitPolicy::default(),
1088 speed: Speed::from_permille(1000),
1089 fade_in: 0,
1090 fade_out: 0,
1091 transition_out: 0,
1092 transition_kind: Default::default(),
1093 visualizer: 0,
1094 viz_paint: 0,
1095 gain_db: 0.0,
1096 gain_keys: Vec::new(),
1097 pan: 0,
1098 pitch: 0.0,
1099 transform_keys: Vec::new(),
1100 opacity_keys: Vec::new(),
1101 color_keys: Vec::new(),
1102 effects: Vec::new(),
1103 speed_keys: Vec::new(),
1104 reversed: false,
1105 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
1106 angle: Default::default(),
1107 }
1108}
1109
1110/// Regression: `Project::from_parts` used to take a clip the setters refuse --
1111/// a volume on a picture, placement keys on a sound, a gain outside its range --
1112/// and the save of it then wrote a file the loader refused. Each is refused at
1113/// the door now, by the same rule the setter applies.
1114#[test]
1115fn from_parts_refuses_what_the_setters_and_the_loader_refuse() {
1116 let source = || vec![Source::new("a.mp4", 0)];
1117 let key = TransformKey {
1118 at: 0,
1119 params: random_transform(&mut Rng::new(1)),
1120 ease: KeyEase::Linear,
1121 };
1122
1123 let mut video_gain = plain_clip(0);
1124 video_gain.gain_db = -6.0;
1125 let err = Project::from_parts(
1126 source(),
1127 vec![(LaneKind::Video, vec![video_gain])],
1128 vec![],
1129 vec![],
1130 vec![],
1131 )
1132 .expect_err("a picture with a volume must be refused");
1133 assert!(err.to_string().contains("no volume"), "named: {err}");
1134
1135 let mut audio_keys = plain_clip(0);
1136 audio_keys.transform_keys = vec![key];
1137 let err = Project::from_parts(
1138 source(),
1139 vec![(LaneKind::Audio, vec![audio_keys])],
1140 vec![],
1141 vec![],
1142 vec![],
1143 )
1144 .expect_err("a sound with placement keys must be refused");
1145 assert!(err.to_string().contains("placement keys"), "named: {err}");
1146
1147 let mut loud = plain_clip(0);
1148 loud.gain_db = 100.0;
1149 let err = Project::from_parts(
1150 source(),
1151 vec![(LaneKind::Audio, vec![loud])],
1152 vec![],
1153 vec![],
1154 vec![],
1155 )
1156 .expect_err("a gain past the range must be refused");
1157 assert!(
1158 err.to_string().contains("outside its range"),
1159 "named: {err}"
1160 );
1161
1162 // And what they accept, the loader reads back: an audio clip at -6 dB.
1163 let mut quiet = plain_clip(0);
1164 quiet.gain_db = -6.0;
1165 let project = Project::from_parts(
1166 source(),
1167 vec![(LaneKind::Audio, vec![quiet])],
1168 vec![],
1169 vec![],
1170 vec![],
1171 )
1172 .expect("an audio clip at -6 dB is well-formed");
1173 let scratch = Scratch::dir("ve_project_fuzz_from_parts");
1174 let path = scratch.join("quiet.edith");
1175 save_project(&project, &path, &random_scalars(&mut Rng::new(2)));
1176 let doc = engine::edith::load(&path).expect("a saved -6 dB clip loads");
1177 assert_eq!(doc.lanes[0].1[0].gain_db, -6.0);
1178}