forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

tonemap_render.rs341 lines, 14.1 KiBHistoryRawDownload
1//! An HDR stream reaching the window tone-mapped, through the door the window
2//! itself opens ([`PlaybackSession`]) rather than through [`engine::tonemap`]
3//! alone -- which is the whole of the claim: a PQ file used to be shown as if
4//! its curve were SDR, i.e. grey-washed and flat, and the map has to run inside
5//! the decode funnel for that to stop.
6//!
7//! `test_pq.mp4` is four flat patches whose codes `scripts/gen_fixtures.sh`
8//! writes into the planes by hand, so every number below is named rather than
9//! measured-and-blessed: BT.2408 diffuse white (203 cd/m^2 is PQ code 144), the
10//! 1000 cd/m^2 highlight (code 181) and a saturated BT.2020 red.
11//!
12//! ```text
13//! cargo test -p engine --release --test tonemap_render -- --test-threads=1
14//! ```
15
16use std::path::PathBuf;
17use std::thread::sleep;
18use std::time::{Duration, Instant};
19
20use engine::PlaybackSession;
21use engine::color::{ColorParams, apply_yuv};
22use engine::colorspace::{ColorDescription, Matrix, Transfer};
23use engine::convert::i420_to_bgra;
24use engine::project::Lane;
25use engine::tonemap::{Preset, ToneMapper, Transfer as Hdr};
26
27/// The fixture's patches: the source codes, and where the centre of each one
28/// sits in the 320x240 picture.
29const DIFFUSE: ([u8; 3], (usize, usize)) = ([144, 128, 128], (80, 60));
30const HIGHLIGHT: ([u8; 3], (usize, usize)) = ([181, 128, 128], (240, 60));
31const RED: ([u8; 3], (usize, usize)) = ([100, 90, 200], (160, 180));
32
33/// What the tone map hands the rest of the funnel: BT.709, SDR, limited range.
34const SDR: ColorDescription = ColorDescription {
35 matrix: Matrix::Bt709,
36 transfer: Transfer::Sdr,
37 full_range: false,
38};
39
40/// Frame 0 of `test_h264.mkv` as this engine rendered it before the tone map
41/// existed -- passthrough, ungraded -- and the same file on a 640x360 canvas
42/// with a grade on it, which is the other branch of the funnel. Measured on
43/// `main`; an SDR stream may not move by one byte.
44const SDR_PASSTHROUGH: u64 = 0x9EF1_6F6F_5310_BCEE;
45/// Re-pinned at the colour merge: lane-colour keeps graded samples inside the valid code range (1-254), which moves a graded SDR picture; the passthrough hash is unchanged.
46const SDR_GRADED_AND_PLACED: u64 = 0x6078_31F1_73F3_1AEF;
47
48fn asset(name: &str) -> PathBuf {
49 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
50 .join("../../assets")
51 .join(name)
52}
53
54fn fnv(b: &[u8]) -> u64 {
55 b.iter().fold(0xcbf2_9ce4_8422_2325u64, |h, &x| {
56 (h ^ u64::from(x)).wrapping_mul(0x100_0000_01b3)
57 })
58}
59
60/// Silent and software-decoded: the fixture is H.264 on purpose, so the bytes
61/// are the same on a machine with a VA-API plugin and one without (hence
62/// `--test-threads=1`).
63fn open(name: &str) -> PlaybackSession {
64 engine::envcfg::set("VE_SW", "1");
65 let session = PlaybackSession::open(asset(name)).expect("open");
66 session.set_gain(0.0);
67 session
68}
69
70fn next_frame(session: &mut PlaybackSession, what: &str) -> engine::Frame {
71 let deadline = Instant::now() + Duration::from_secs(30);
72 loop {
73 if let Some(frame) = session.try_frame() {
74 return frame;
75 }
76 assert!(Instant::now() < deadline, "no frame after {what}");
77 sleep(Duration::from_millis(4));
78 }
79}
80
81/// One pixel of a rendered frame, as (B, G, R).
82fn pixel(frame: &engine::Frame, (x, y): (usize, usize)) -> [u8; 3] {
83 let at = (y * frame.width as usize + x) * 4;
84 [frame.bgra[at], frame.bgra[at + 1], frame.bgra[at + 2]]
85}
86
87/// The limited-range BT.709 luma code a rendered pixel carries: the unit the
88/// tone map's own anchors are named in, read back off the BGRA the window gets.
89fn luma_code(bgra: [u8; 3]) -> u8 {
90 let (b, g, r) = (f32::from(bgra[0]), f32::from(bgra[1]), f32::from(bgra[2]));
91 (16.0 + 219.0 * (0.2126 * r + 0.7152 * g + 0.0722 * b) / 255.0).round() as u8
92}
93
94/// How far one pixel is from grey.
95fn spread(px: [u8; 3]) -> u8 {
96 px.iter().max().unwrap() - px.iter().min().unwrap()
97}
98
99/// One flat patch of `codes`, rendered by hand the way the funnel is supposed
100/// to render it: tone-mapped first, then graded, then converted as BT.709 SDR.
101/// `grade` is applied in whichever domain `before` says -- which is the point of
102/// [`the_grade_lands_after_the_tone_map`].
103fn by_hand(
104 codes: [u8; 3],
105 grade: &ColorParams,
106 before: bool,
107 preset: Preset,
108 peak: Option<f32>,
109) -> [u8; 3] {
110 let (w, h) = (8usize, 8usize);
111 let mut y = vec![codes[0]; w * h];
112 let mut u = vec![codes[1]; w / 2 * h / 2];
113 let mut v = vec![codes[2]; w / 2 * h / 2];
114 if before {
115 apply_yuv(grade, &mut y, &mut u, &mut v, w, false);
116 }
117 ToneMapper::new(Hdr::Pq, preset, peak).map(&mut y, &mut u, &mut v, w, h);
118 if !before {
119 apply_yuv(grade, &mut y, &mut u, &mut v, w, false);
120 }
121 let bgra = i420_to_bgra(&SDR, &y, &u, &v, w, h);
122 [bgra[0], bgra[1], bgra[2]]
123}
124
125/// The claim itself: a PQ stream is shown as an SDR display can show it.
126/// Diffuse white lands where BT.2446 Method A puts it at the mastering peak the
127/// content really has (~166, not the 144 an untouched code would convert to and
128/// not clipped white -- the reference rendition, which is what a project nobody
129/// has picked for is shown in), the 1000 cd/m^2 highlight stays a highlight, and
130/// the saturated red is still red -- a grey wash is exactly what the missing map
131/// looked like.
132#[test]
133fn a_pq_stream_is_tone_mapped_on_its_way_to_the_window() {
134 let mut session = open("test_pq.mp4");
135 assert_eq!(session.meta().color.transfer, Transfer::Pq, "fixture tags");
136 assert_eq!(
137 session.meta().color.matrix,
138 Matrix::Bt2020Ncl,
139 "fixture tags"
140 );
141
142 let frame = next_frame(&mut session, "an open");
143 assert_eq!((frame.width, frame.height), (320, 240));
144
145 let diffuse = luma_code(pixel(&frame, DIFFUSE.1));
146 assert!(
147 (161..=171).contains(&diffuse),
148 "diffuse white (code {}) rendered at {diffuse}, wanted 161..=171",
149 DIFFUSE.0[0]
150 );
151 let highlight = luma_code(pixel(&frame, HIGHLIGHT.1));
152 assert!(
153 (225..=239).contains(&highlight) && highlight > diffuse,
154 "the 1000 cd/m^2 highlight rendered at {highlight}"
155 );
156 let red = pixel(&frame, RED.1);
157 assert!(
158 spread(red) > 60 && red[2] > red[0] && red[2] > red[1],
159 "the saturated red washed out to {red:?}"
160 );
161}
162
163/// The preset is a thing a viewer *sees*: picked on the running session, the
164/// very next frame out of the funnel is the new rendition, and the three are in
165/// the order their names promise -- reference darkest, vivid brightest and
166/// richest. Measured on the rendered BGRA the window gets, so it covers the
167/// whole chain (project setting -> reseek -> decode worker -> LUT), not the
168/// table alone.
169#[test]
170fn picking_a_preset_changes_the_picture_the_window_shows() {
171 let mut session = open("test_pq.mp4");
172 assert_eq!(session.tone(), Preset::Reference, "nobody has picked yet");
173 let mut shown = Vec::new();
174 for preset in Preset::ALL {
175 if preset != Preset::Reference {
176 assert!(session.set_tone(preset), "pick {preset:?}");
177 assert!(!session.set_tone(preset), "picking it again changes nothing");
178 }
179 let frame = next_frame(&mut session, "a preset");
180 // Still a picture, not a wash: the fixture's saturated red has to stay
181 // red under every rendition, which is what a mistuned preset breaks
182 // first.
183 assert!(spread(pixel(&frame, RED.1)) > 60, "{preset:?} washed the red out");
184 shown.push(luma_code(pixel(&frame, DIFFUSE.1)));
185 }
186 let [reference, standard, vivid] = [shown[0], shown[1], shown[2]];
187 assert!(
188 reference < standard && standard < vivid,
189 "diffuse white by preset: reference {reference}, standard {standard}, vivid {vivid}"
190 );
191 // The vivid preset's *chroma* gain is asserted on the codes rather than
192 // here: this fixture's red is saturated enough that it clips to 255 in BGRA
193 // under both presets, so a rendered patch cannot measure it
194 // (`tonemap::tests::a_brighter_preset_is_brighter_and_a_vivid_one_is_richer`).
195}
196
197/// ...and an SDR stream is not any of this: no clip of it builds a tone map at
198/// all, so all three presets are the same bytes. The hash is the passthrough
199/// branch's own, from the test below -- if a preset ever reached an SDR picture,
200/// this is where it would show.
201#[test]
202fn an_sdr_stream_is_the_same_bytes_under_every_preset() {
203 let mut session = open("test_h264.mkv");
204 for preset in Preset::ALL {
205 if preset != Preset::Reference {
206 assert!(session.set_tone(preset), "pick {preset:?}");
207 }
208 let frame = next_frame(&mut session, "a preset");
209 assert_eq!(fnv(&frame.bgra), SDR_PASSTHROUGH, "{preset:?} moved an SDR picture");
210 }
211}
212
213/// The other half: an SDR stream may not move by one byte for any of this.
214/// Both branches of the funnel -- the fused passthrough conversion and the
215/// graded-then-placed one -- against hashes measured before the tone map was
216/// wired in.
217#[test]
218fn an_sdr_stream_is_byte_for_byte_the_picture_it_was() {
219 let mut session = open("test_h264.mkv");
220 assert_eq!(session.meta().color.transfer, Transfer::Sdr);
221 let plain = next_frame(&mut session, "an open");
222 assert_eq!(fnv(&plain.bgra), SDR_PASSTHROUGH, "the passthrough branch");
223
224 assert!(session.set_resolution(640, 360), "shrink the canvas");
225 assert!(
226 session.set_color(
227 Lane::V1,
228 0,
229 Some(ColorParams {
230 saturation: 1.4,
231 brightness: 0.1,
232 ..Default::default()
233 })
234 ),
235 "grade the clip"
236 );
237 let placed = next_frame(&mut session, "a resize and a grade");
238 assert_eq!((placed.width, placed.height), (640, 360));
239 assert_eq!(
240 fnv(&placed.bgra),
241 SDR_GRADED_AND_PLACED,
242 "the graded-and-placed branch"
243 );
244}
245
246/// Order: the grade is a look applied to the picture the viewer sees, so it
247/// lands on the *tone-mapped* samples. Graded before the map instead, the same
248/// numbers give a different pixel -- the second assert is what makes the first
249/// one mean anything.
250#[test]
251fn the_grade_lands_after_the_tone_map() {
252 let grade = ColorParams {
253 saturation: 1.5,
254 brightness: 0.08,
255 ..Default::default()
256 };
257 let mut session = open("test_pq.mp4");
258 assert!(
259 session.set_color(Lane::V1, 0, Some(grade)),
260 "grade the clip"
261 );
262 let frame = next_frame(&mut session, "a grade");
263
264 for (name, patch) in [("diffuse white", DIFFUSE), ("red", RED)] {
265 let shown = pixel(&frame, patch.1);
266 let after = by_hand(patch.0, &grade, false, Preset::default(), None);
267 let before = by_hand(patch.0, &grade, true, Preset::default(), None);
268 for (i, channel) in ["B", "G", "R"].iter().enumerate() {
269 assert!(
270 shown[i].abs_diff(after[i]) <= 2,
271 "{name} {channel}: shown {shown:?}, tone-map-then-grade {after:?}"
272 );
273 }
274 assert!(
275 after.iter().zip(&before).any(|(a, b)| a.abs_diff(*b) > 4),
276 "{name}: grading before the map gives the same pixel, so this proves nothing"
277 );
278 }
279}
280
281/// The film's own declared peak, all the way to the window: `test_hdr_bright.mkv`
282/// carries the same four patches as `test_pq.mp4` and a container MaxCLL of
283/// 4000 cd/m^2, so a funnel that read the metadata renders it at 4000 and one
284/// that ignored it renders it at the 1000 an undeclared file is assumed at --
285/// two plainly different pictures, which is why that fixture says 4000 and the
286/// older metadata ones say the 1000 nothing can tell apart from the fallback.
287///
288/// Both sides are computed by hand through the same `ToneMapper`, so what is
289/// asserted is which number the *funnel* built its table with, not where Method
290/// A puts a patch.
291#[test]
292fn a_films_declared_peak_reaches_the_window() {
293 let mut session = open("test_hdr_bright.mkv");
294 assert_eq!(session.meta().color.transfer, Transfer::Pq, "fixture tags");
295 assert_eq!(session.tone(), Preset::Reference, "nobody has picked yet");
296 let frame = next_frame(&mut session, "an open");
297 let flat = ColorParams::default();
298 for (patch, name) in [(DIFFUSE, "diffuse white"), (HIGHLIGHT, "the highlight")] {
299 let shown = luma_code(pixel(&frame, patch.1));
300 let declared = luma_code(by_hand(patch.0, &flat, false, Preset::Reference, Some(4000.0)));
301 let ignored = luma_code(by_hand(patch.0, &flat, false, Preset::Reference, None));
302 assert!(
303 shown.abs_diff(declared) <= 2,
304 "{name} rendered at {shown}, {declared} at the film's declared 4000 cd/m^2"
305 );
306 assert!(
307 shown.abs_diff(ignored) > 8,
308 "{name}: {shown} is indistinguishable from the {ignored} of an ignored peak"
309 );
310 }
311}
312
313/// ...and both tiers a peak can live in reach the table, on the fixtures that
314/// exist for each: `test_hdr_meta.mkv` declares its 1000 in the container,
315/// `test_hdr_sei.mkv` only inside the HEVC bitstream. Neither can be told apart
316/// from the fallback in a *picture* (1000 is what an undeclared file is assumed
317/// at, and both are black), so what is asserted is the number the table is
318/// built at -- the same `Demuxer::light().peak()` hand-off the decode funnel
319/// and the export table make.
320#[test]
321fn either_tier_of_metadata_is_what_the_table_is_built_at() {
322 for (name, tier) in [
323 ("test_hdr_meta.mkv", "container"),
324 ("test_hdr_meta.mp4", "container"),
325 ("test_hdr_sei.mkv", "bitstream SEI"),
326 ("test_hdr_bright.mkv", "container"),
327 ] {
328 let (_, demuxer) = engine::demux::Demuxer::open(&asset(name)).expect("open");
329 let peak = demuxer.light().peak();
330 let want = match name {
331 "test_hdr_bright.mkv" => 4000.0,
332 _ => 1000.0,
333 };
334 assert_eq!(peak, Some(want), "{name} ({tier} tier)");
335 let mapper = ToneMapper::new(Hdr::Pq, Preset::Reference, peak);
336 assert_eq!(mapper.peak(), want, "{name}: the table's assumed peak");
337 }
338 // An SDR file declares nothing, and nothing is what the map is told.
339 let (_, demuxer) = engine::demux::Demuxer::open(&asset("test_av.mp4")).expect("open");
340 assert_eq!(demuxer.light().peak(), None, "an SDR file's peak");
341}