forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

opacity.rs190 lines, 7.6 KiBHistoryRawDownload
1//! Clip opacity: how much of a picture shows over what is beneath it.
2//!
3//! The blend is on the stored Y'CbCr code values, as a dissolve blends them:
4//! gamma-encoded video levels, not linear light. So 50% white over black is
5//! the midpoint of the two luma codes (limited range, black 16, white 235),
6//! which is 126 -- mid grey as the eye reads it.
7
8use std::path::{Path, PathBuf};
9
10use engine::PlaybackSession;
11use engine::project::{Lane, LaneKind};
12
13/// The second video lane, the one a layer sits on.
14const TOP: Lane = Lane::new(LaneKind::Video, 1);
15use engine::scale::{Composer, FitPolicy};
16use engine::scratch::Scratch;
17use engine::transform::TransformParams;
18
19fn asset(name: &str) -> PathBuf {
20 Path::new(env!("CARGO_MANIFEST_DIR"))
21 .join("../../assets")
22 .join(name)
23}
24
25fn open(path: impl AsRef<Path>) -> PlaybackSession {
26 engine::ao::set_silent_output();
27 PlaybackSession::open(path).expect("open")
28}
29
30fn with_opacity(opacity: f32) -> TransformParams {
31 TransformParams {
32 opacity,
33 ..TransformParams::default()
34 }
35}
36
37#[test]
38fn white_at_half_opacity_over_black_is_mid_grey() {
39 // A 64x64 white picture (luma 235, neutral chroma) on a black canvas.
40 let (w, h) = (64u32, 64u32);
41 let y = vec![235u8; (w * h) as usize];
42 let c = vec![128u8; ((w / 2) * (h / 2)) as usize];
43 let mut composer = Composer::new(w, h, FitPolicy::Stretch);
44 let (out_y, out_u, _, _, _) = composer.place_transformed(&y, &c, &c, w, h, &with_opacity(0.5));
45 // 16 + (235 - 16) / 2 = 125.5, rounded up to 126.
46 assert!(out_y.iter().all(|&v| v == 126), "luma {:?}", &out_y[..4]);
47 assert!(out_u.iter().all(|&v| v == 128), "chroma stays neutral");
48
49 // Opaque and transparent are the two exact ends.
50 let (full, ..) = composer.place_transformed(&y, &c, &c, w, h, &with_opacity(1.0));
51 assert!(full.iter().all(|&v| v == 235));
52 let (none, ..) = composer.place_transformed(&y, &c, &c, w, h, &with_opacity(0.0));
53 assert!(none.iter().all(|&v| v == 16), "0 is the black canvas");
54}
55
56#[test]
57fn a_single_clip_at_half_opacity_is_half_as_bright() {
58 let mut session = open(asset("test_av.mp4"));
59 // At the project's own size: a box resize averages clipped super-white
60 // samples, which is not linear, and would blur the check below.
61 let full = session.compose_at(10, 1280, 720).expect("opaque frame");
62 assert!(session.set_transform(Lane::V1, 0, Some(with_opacity(0.5))));
63 let half = session.compose_at(10, 1280, 720).expect("half frame");
64 // Per colour channel (the alpha byte is skipped), the half frame is half the
65 // opaque one: the fade is linear in code values and RGB is linear in them
66 // too. Where a channel would clip in the opaque picture the halving is not
67 // exact, so only the unclipped channels are compared.
68 let mut worst: f64 = 0.0;
69 let mut compared = 0usize;
70 for (px_full, px_half) in full.bgra.chunks(4).zip(half.bgra.chunks(4)) {
71 for c in 0..3 {
72 let (f, h) = (f64::from(px_full[c]), f64::from(px_half[c]));
73 if (32.0..=223.0).contains(&f) {
74 compared += 1;
75 worst = worst.max((h - f / 2.0).abs());
76 }
77 }
78 }
79 assert!(
80 compared > full.bgra.len() / 16,
81 "too few unclipped channels: {compared}"
82 );
83 assert!(
84 worst <= 2.5,
85 "half strays {worst} from half of opaque over {compared}"
86 );
87}
88
89#[test]
90fn a_layer_at_half_opacity_is_the_mean_of_the_two_layers() {
91 let dir = Scratch::dir("ve_opacity_layers");
92 let project = dir.join("layers.edith");
93 // Bottom: test_av.mp4 for the whole timeline. Top: test_av2.mp4 from frame 20
94 // for 60 frames, which is the second lane the playback tests use too.
95 let text = format!(
96 "edith 4\nplayhead 0\nsource 0 {}\nsource 0 {}\n\
97 video 1 0 0 150 0 -\naudio 1 0 0 150 0 -\n\
98 video 2 20 0 60 1 -\n",
99 asset("test_av.mp4").display(),
100 asset("test_av2.mp4").display(),
101 );
102 std::fs::write(&project, text).expect("write the project");
103 let mut session = PlaybackSession::open_project(&project).expect("open the layers");
104 let at = 30; // inside the top layer
105
106 let (w, h) = (1280, 720);
107 assert!(session.set_transform(TOP, 0, Some(with_opacity(0.0))));
108 let bottom = session.compose_at(at, w, h).expect("bottom only").bgra;
109 assert!(session.set_transform(TOP, 0, Some(with_opacity(1.0))));
110 let top = session.compose_at(at, w, h).expect("top only").bgra;
111 assert!(session.set_transform(TOP, 0, Some(with_opacity(0.5))));
112 let mix = session.compose_at(at, w, h).expect("half").bgra;
113
114 // Per byte, the half-opacity frame is the midpoint of the two layers, to
115 // within rounding -- but only where neither layer clips. The blend is in
116 // code values and the conversion clamps to 0..=255, so a super-white
117 // source byte (255 here) would otherwise pull the midpoint off.
118 let mut worst: f64 = 0.0;
119 let mut compared = 0usize;
120 for ((&m, &b), &t) in mix.iter().zip(&bottom).zip(&top) {
121 if (20..=235).contains(&b) && (20..=235).contains(&t) {
122 compared += 1;
123 worst = worst.max((f64::from(m) - (f64::from(b) + f64::from(t)) / 2.0).abs());
124 }
125 }
126 assert!(
127 compared > bottom.len() / 10,
128 "too few unclipped bytes: {compared}"
129 );
130 assert!(worst < 4.0, "half opacity strays {worst} from the midpoint");
131 let spread = bottom
132 .iter()
133 .zip(&top)
134 .map(|(&b, &t)| (f64::from(b) - f64::from(t)).abs())
135 .sum::<f64>()
136 / bottom.len() as f64;
137 assert!(spread > 5.0, "the two layers should differ");
138 std::fs::remove_file(&project).ok();
139}
140
141#[test]
142fn opacity_survives_a_save_and_a_reopen_and_default_writes_nothing_new() {
143 let dir = Scratch::dir("ve_opacity_save");
144 let path = dir.join("half.edith");
145 let mut session = open(asset("test_av.mp4"));
146 assert!(session.set_transform(Lane::V1, 0, Some(with_opacity(0.25))));
147 session.save_project(&path).expect("save");
148 let bytes = std::fs::read(&path).unwrap();
149 assert!(
150 bytes.starts_with(b"edith 31\n"),
151 "a layer that is not opaque needs v31"
152 );
153
154 let loaded = PlaybackSession::open_project(&path).expect("reopen");
155 let back = loaded
156 .transform_of(Lane::V1, 0)
157 .expect("the transform is kept");
158 assert_eq!(back.opacity.to_bits(), 0.25f32.to_bits());
159
160 // A clip at the default opacity writes the v30 bytes it always did, and
161 // never a ninth field.
162 let plain_path = dir.join("plain.edith");
163 let mut plain = open(asset("test_av.mp4"));
164 assert!(plain.set_transform(Lane::V1, 0, Some(with_opacity(1.0))));
165 plain.save_project(&plain_path).expect("save plain");
166 let plain_bytes = std::fs::read(&plain_path).unwrap();
167 assert!(plain_bytes.starts_with(b"edith 30\n"));
168 assert!(!String::from_utf8_lossy(&plain_bytes).contains("transform 0:0:1:0:0:0:0:0:"));
169}
170
171#[test]
172fn an_opacity_outside_zero_to_one_is_refused_on_load() {
173 let dir = Scratch::dir("ve_opacity_range");
174 let path = dir.join("bad.edith");
175 let text = "edith 31\nplayhead 0\nresolution 1280 720\nsource 0 X\n\
176 transform 0:0:1:0:0:0:0:0:1.5\n";
177 std::fs::write(&path, text).unwrap();
178 let err = engine::edith::load(&path)
179 .expect_err("refused")
180 .to_string();
181 assert!(err.contains("opacity"), "{err}");
182
183 // A ninth field is a v31 thing; a v30 file with one is refused as such.
184 let old = text.replace("edith 31", "edith 30").replace(":1.5", ":0.5");
185 std::fs::write(&path, old).unwrap();
186 let err = engine::edith::load(&path)
187 .expect_err("refused")
188 .to_string();
189 assert!(err.contains("transform wants 8 fields"), "{err}");
190}