forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

effects.rs282 lines, 11.4 KiBHistoryRawDownload
1//! A clip's effects stack ([`engine::effects`]) in the picture paths: preview's
2//! composer, the 8-bit export and the 10-bit one. A stack that does nothing --
3//! none, or every effect switched off -- leaves every byte where it was; one that
4//! does something shows in all three, and a key or a mask on an upper lane reveals
5//! the lane beneath. Software encoders only.
6//!
7//! ```text
8//! cargo test --release -p engine --test effects
9//! ```
10
11use std::path::{Path, PathBuf};
12use std::process::Command;
13use std::time::{Duration, Instant};
14
15use engine::PlaybackSession;
16use engine::effects::{Effect, EffectKind};
17use engine::export::{EncoderSeat, ExportSettings, Format};
18use engine::project::{Lane, LaneKind};
19use engine::scratch::Scratch;
20
21const TOP: Lane = Lane::new(LaneKind::Video, 1);
22
23fn asset(name: &str) -> PathBuf {
24 Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets").join(name)
25}
26
27fn open(path: impl AsRef<Path>) -> PlaybackSession {
28 engine::ao::set_silent_output();
29 PlaybackSession::open(path).expect("open")
30}
31
32fn have(tool: &str) -> bool {
33 Command::new(tool).arg("-version").output().is_ok_and(|o| o.status.success())
34}
35
36fn export(session: &PlaybackSession, out: &Path, settings: &ExportSettings) {
37 let handle = session.export_to_with(out, settings);
38 let started = Instant::now();
39 while !handle.is_finished() {
40 assert!(started.elapsed() < Duration::from_secs(600), "the export did not finish in 600 s");
41 std::thread::sleep(Duration::from_millis(20));
42 }
43 handle.result().expect("an outcome").expect("the export");
44}
45
46fn software(range: (u32, u32)) -> ExportSettings {
47 ExportSettings {
48 format: Format::Mp4,
49 seat: EncoderSeat::Software,
50 range: Some(range),
51 ..Default::default()
52 }
53}
54
55/// The mean of a BGRA frame's first channel over a `size`-square box at `(x, y)`.
56fn mean(frame: &engine::decode::Frame, x: u32, y: u32, size: u32) -> f64 {
57 let mut sum = 0.0;
58 for row in y..y + size {
59 for col in x..x + size {
60 let i = ((row * frame.width + col) * 4) as usize;
61 sum += f64::from(frame.bgra[i]) + f64::from(frame.bgra[i + 1]) + f64::from(frame.bgra[i + 2]);
62 }
63 }
64 sum / f64::from(size * size * 3)
65}
66
67fn vignette_and_blur() -> Vec<Effect> {
68 let mut vignette = Effect::new(EffectKind::Vignette);
69 vignette.set("amount", 0.9).unwrap();
70 vignette.set("softness", 0.6).unwrap();
71 let mut blur = Effect::new(EffectKind::Blur);
72 blur.set("radius", 8.0).unwrap();
73 vec![vignette, blur]
74}
75
76#[test]
77fn a_stack_that_does_nothing_leaves_every_byte_alone() {
78 let dir = Scratch::dir("ve_effects_identity");
79 let plain = open(asset("test_av.mp4"));
80 let mut off = open(asset("test_av.mp4"));
81 let stack: Vec<Effect> = vignette_and_blur().into_iter().map(|e| Effect { on: false, ..e }).collect();
82 assert!(off.set_effects(Lane::V1, 0, stack));
83 assert_eq!(off.effects_of(Lane::V1, 0).len(), 2, "the stack is kept, switched off");
84 // The composer: the same picture.
85 assert_eq!(plain.compose_at(20, 640, 360).unwrap().bgra, off.compose_at(20, 640, 360).unwrap().bgra);
86 // The export: the same file, byte for byte.
87 let (a, b) = (dir.join("plain.mp4"), dir.join("off.mp4"));
88 export(&plain, &a, &software((0, 12)));
89 export(&off, &b, &software((0, 12)));
90 assert_eq!(std::fs::read(&a).unwrap(), std::fs::read(&b).unwrap(), "a switched-off stack is no stack");
91}
92
93#[test]
94fn vignette_and_blur_show_in_the_composer_and_one_undo_takes_them_off() {
95 let mut s = open(asset("test_av.mp4"));
96 let before = s.compose_at(20, 640, 360).unwrap();
97 assert!(s.set_effects(Lane::V1, 0, vignette_and_blur()));
98 let after = s.compose_at(20, 640, 360).unwrap();
99 assert!(mean(&after, 0, 0, 24) < mean(&before, 0, 0, 24) * 0.6, "the corner is darker");
100 assert_ne!(before.bgra, after.bgra);
101 assert!(s.undo(), "one undo step");
102 assert_eq!(s.compose_at(20, 640, 360).unwrap().bgra, before.bgra, "undone: the picture it was");
103}
104
105#[test]
106fn a_mask_on_the_upper_lane_reveals_the_lane_beneath() {
107 let dir = Scratch::dir("ve_effects_mask");
108 let project = dir.join("layers.edith");
109 let text = format!(
110 "edith 4\nplayhead 0\nsource 0 {}\nsource 0 {}\n\
111 video 1 0 0 150 0 -\naudio 1 0 0 150 0 -\n\
112 video 2 20 0 60 1 -\n",
113 asset("test_av.mp4").display(),
114 asset("test_av2.mp4").display(),
115 );
116 std::fs::write(&project, text).unwrap();
117 let mut s = PlaybackSession::open_project(&project).expect("open the layers");
118 let (w, h) = (640, 360);
119 let top = s.compose_at(30, w, h).unwrap();
120 assert!(s.set_lane_hidden(TOP, true));
121 let bottom = s.compose_at(30, w, h).unwrap();
122 assert!(s.set_lane_hidden(TOP, false));
123 // A box over the left half, hard-edged: the top clip there, the bottom one elsewhere.
124 let mut mask = Effect::new(EffectKind::RectMask);
125 for (k, v) in [("x", 0.25), ("y", 0.5), ("width", 0.5), ("height", 1.0), ("feather", 0.0)] {
126 mask.set(k, v).unwrap();
127 }
128 assert!(s.set_effects(TOP, 0, vec![mask.clone()]));
129 let masked = s.compose_at(30, w, h).unwrap();
130 let near = |a: &engine::decode::Frame, b: &engine::decode::Frame, x: u32, y: u32| (mean(a, x, y, 16) - mean(b, x, y, 16)).abs() < 3.0;
131 assert!(near(&masked, &top, 60, 160), "inside the mask: the top clip");
132 assert!(near(&masked, &bottom, 520, 160), "outside: the lane beneath");
133 // Inverted, the other way round.
134 mask.set("invert", 1.0).unwrap();
135 assert!(s.set_effects(TOP, 0, vec![mask]));
136 let inverted = s.compose_at(30, w, h).unwrap();
137 assert!(near(&inverted, &bottom, 60, 160) && near(&inverted, &top, 520, 160));
138 // Screen over the bottom is never darker than the bottom.
139 let mut blend = Effect::new(EffectKind::Blend);
140 blend.set("mode", 2.0).unwrap();
141 assert!(s.set_effects(TOP, 0, vec![blend]));
142 let screened = s.compose_at(30, w, h).unwrap();
143 assert!(mean(&screened, 300, 160, 32) >= mean(&bottom, 300, 160, 32) - 1.0);
144}
145
146#[test]
147fn an_eight_bit_export_carries_the_effects() {
148 if !have("ffmpeg") {
149 eprintln!("no ffmpeg: skipping");
150 return;
151 }
152 let dir = Scratch::dir("ve_effects_export8");
153 let plain = open(asset("test_av.mp4"));
154 let mut fx = open(asset("test_av.mp4"));
155 assert!(fx.set_effects(Lane::V1, 0, vignette_and_blur()));
156 let (a, b) = (dir.join("plain.mp4"), dir.join("fx.mp4"));
157 export(&plain, &a, &software((0, 10)));
158 export(&fx, &b, &software((0, 10)));
159 let frame = |p: &Path| {
160 let out = Command::new("ffmpeg")
161 .args(["-v", "error", "-i"])
162 .arg(p)
163 .args(["-frames:v", "1", "-f", "rawvideo", "-pix_fmt", "gray", "-"])
164 .output()
165 .unwrap();
166 out.stdout
167 };
168 let (pa, pb) = (frame(&a), frame(&b));
169 assert_eq!(pa.len(), 1280 * 720);
170 let corner = |f: &[u8]| (0..32).flat_map(|r| (0..32).map(move |c| r * 1280 + c)).map(|i| f64::from(f[i])).sum::<f64>();
171 assert!(corner(&pb) < corner(&pa) * 0.7, "the exported corner is darker");
172}
173
174/// A 10-bit source with a lone blurred clip composes at 10 bits: its export keeps
175/// more than 256 luma levels, which an 8-bit pass could not.
176#[test]
177fn a_ten_bit_export_draws_the_effects_at_ten_bits() {
178 if !have("ffmpeg") {
179 eprintln!("no ffmpeg: skipping");
180 return;
181 }
182 let dir = Scratch::dir("ve_effects_export10");
183 let source = dir.join("ramp.mkv");
184 let (w, h) = (320usize, 240usize);
185 let mut raw = Vec::new();
186 for _ in 0..25 {
187 for y in 0..h {
188 for x in 0..w {
189 raw.extend_from_slice(&((64 + (x + y) * 876 / (w + h - 2)) as u16).to_le_bytes());
190 }
191 }
192 for _ in 0..2 * (w / 2) * (h / 2) {
193 raw.extend_from_slice(&512u16.to_le_bytes());
194 }
195 }
196 let input = dir.join("ramp.yuv");
197 std::fs::write(&input, &raw).unwrap();
198 let made = Command::new("ffmpeg")
199 .args(["-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "yuv420p10le", "-s", "320x240", "-r", "25", "-i"])
200 .arg(&input)
201 .args(["-pix_fmt", "yuv420p10le", "-c:v", "libaom-av1", "-cpu-used", "8", "-crf", "20", "-b:v", "0"])
202 .arg(&source)
203 .status()
204 .is_ok_and(|s| s.success());
205 if !made {
206 eprintln!("no 10-bit source encoder: skipping");
207 return;
208 }
209 let mut s = PlaybackSession::open(&source).expect("open the ramp");
210 let mut blur = Effect::new(EffectKind::Blur);
211 blur.set("radius", 6.0).unwrap();
212 assert!(s.set_effects(Lane::V1, 0, vec![blur, Effect::new(EffectKind::Vignette)]));
213 let out = dir.join("fx.mkv");
214 export(
215 &s,
216 &out,
217 &ExportSettings { format: Format::Av1, video_bit_depth: Some(10), bitrate: Some(50_000_000), ..Default::default() },
218 );
219 let raw = Command::new("ffmpeg")
220 .args(["-v", "error", "-i"])
221 .arg(&out)
222 .args(["-frames:v", "1", "-f", "rawvideo", "-pix_fmt", "yuv420p10le", "-"])
223 .output()
224 .unwrap()
225 .stdout;
226 let luma = &raw[..320 * 240 * 2];
227 let mut seen = [false; 1024];
228 for s in luma.as_chunks::<2>().0 {
229 seen[usize::from(u16::from_le_bytes(*s)).min(1023)] = true;
230 }
231 let levels = seen.iter().filter(|&&s| s).count();
232 assert!(levels > 256, "{levels} luma levels: narrowed to 8 bits somewhere");
233 let last = u16::from_le_bytes([luma[luma.len() - 2], luma[luma.len() - 1]]);
234 assert!(last < 800, "the vignette darkened the white corner: {last}");
235}
236
237/// A camera shake follows timeline time on every path: the export's frame N is
238/// the composer's frame N (the picture preview shows there), not a frame the
239/// shake has moved on from or not reached. With a wide shake, frames ten apart
240/// sit tens of pixels apart, which no encode error comes near.
241#[test]
242fn a_shake_is_at_the_same_offset_in_preview_and_export() {
243 if !have("ffmpeg") {
244 eprintln!("no ffmpeg: skipping");
245 return;
246 }
247 let dir = Scratch::dir("ve_effects_shake");
248 let mut s = open(asset("test_av.mp4"));
249 let mut shake = Effect::new(EffectKind::Shake);
250 shake.set("amount", 100.0).unwrap();
251 shake.set("speed", 3.0).unwrap();
252 assert!(s.set_effects(Lane::V1, 0, vec![shake]));
253 // Start the range past frame 0, so a clip- or range-relative clock would show.
254 let out = dir.join("shake.mp4");
255 export(&s, &out, &software((10, 40)));
256 let raw = Command::new("ffmpeg")
257 .args(["-v", "error", "-i"])
258 .arg(&out)
259 .args(["-f", "rawvideo", "-pix_fmt", "rgb24", "-"])
260 .output()
261 .unwrap()
262 .stdout;
263 let size = 1280 * 720 * 3;
264 let exported = |frame: u32| &raw[(frame - 10) as usize * size..][..size];
265 let composed = |frame: u32| s.compose_at(frame, 1280, 720).unwrap().bgra;
266 let diff = |rgb: &[u8], bgra: &[u8]| -> f64 {
267 let total: u64 = rgb
268 .as_chunks::<3>()
269 .0
270 .iter()
271 .zip(bgra.as_chunks::<4>().0)
272 .map(|(a, b)| u64::from(a[0].abs_diff(b[2])) + u64::from(a[1].abs_diff(b[1])) + u64::from(a[2].abs_diff(b[0])))
273 .sum();
274 total as f64 / (1280.0 * 720.0 * 3.0)
275 };
276 for frame in [15, 30] {
277 let same = diff(exported(frame), &composed(frame));
278 let other = diff(exported(frame), &composed(frame + 8));
279 eprintln!("frame {frame}: same {same:.2}, eight on {other:.2}");
280 assert!(same < 4.0 && same * 3.0 < other, "frame {frame}: export {same:.2} from preview, {other:.2} from eight frames on");
281 }
282}