Merge branch 'worktree-agent-a292c399d416157b0'
Browse files at this commit3 changed files +320 -24
- crates/engine/src/colorspace.rs +2 -1
- crates/engine/src/export.rs +100 -22
- crates/engine/tests/export_color.rs +218 -1
crates/engine/src/colorspace.rsmodified+2 -1
| @@ -96,7 +96,8 @@ impl ColorDescription { | |||
| 96 | /// [`resolve`](Self::resolve)'s heuristic reads, so a file written here is | 96 | /// [`resolve`](Self::resolve)'s heuristic reads, so a file written here is |
| 97 | /// read back as the space it was written in even by a reader that drops the | 97 | /// read back as the space it was written in even by a reader that drops the |
| 98 | /// tags. Limited range because both encoders here are configured for it, and | 98 | /// tags. Limited range because both encoders here are configured for it, and |
| 99 | - /// SDR because nothing on this path tone-maps yet. | 99 | + /// SDR always: an HDR source is *tone-mapped* into this on the way out |
| 100 | + /// ([`crate::tonemap`]), never carried through and re-tagged. | ||
| 100 | pub fn output(height: u32) -> Self { | 101 | pub fn output(height: u32) -> Self { |
| 101 | Self { | 102 | Self { |
| 102 | matrix: if height >= 720 { | 103 | matrix: if height >= 720 { |
crates/engine/src/export.rsmodified+100 -22
| @@ -64,13 +64,14 @@ use flacenc::error::Verify; | |||
| 64 | use oxideav_core::Muxer as _; | 64 | use oxideav_core::Muxer as _; |
| 65 | 65 | ||
| 66 | use crate::audio::{AudioMeta, AudioSession}; | 66 | use crate::audio::{AudioMeta, AudioSession}; |
| 67 | -use crate::colorspace::{ColorDescription, Matrix}; | 67 | +use crate::colorspace::{ColorDescription, Matrix, Transfer}; |
| 68 | use crate::demux::{Demuxer, VideoMeta}; | 68 | use crate::demux::{Demuxer, VideoMeta}; |
| 69 | use crate::hw::{HwEncoder, HwSession}; | 69 | use crate::hw::{HwEncoder, HwSession}; |
| 70 | use crate::mux::{AudioParams, Av1Params, HevcParams, MkvMuxer, Mp4Muxer, SubParams, VideoParams}; | 70 | use crate::mux::{AudioParams, Av1Params, HevcParams, MkvMuxer, Mp4Muxer, SubParams, VideoParams}; |
| 71 | use crate::project::{LaneKind, Project, Rate}; | 71 | use crate::project::{LaneKind, Project, Rate}; |
| 72 | use crate::scale::Composer; | 72 | use crate::scale::Composer; |
| 73 | use crate::subtitle::{Cue, SubtitleTrack}; | 73 | use crate::subtitle::{Cue, SubtitleTrack}; |
| 74 | +use crate::tonemap::{self, ToneMapper}; | ||
| 74 | 75 | ||
| 75 | /// Progress is reported in permille: an atomic integer the render loop can read | 76 | /// Progress is reported in permille: an atomic integer the render loop can read |
| 76 | /// without a lock, fine enough for any progress bar. | 77 | /// without a lock, fine enough for any progress bar. |
| @@ -962,6 +963,20 @@ fn run( | |||
| 962 | .iter() | 963 | .iter() |
| 963 | .map(|source| source_rate(&source.path, meta.frame_rate)) | 964 | .map(|source| source_rate(&source.path, meta.frame_rate)) |
| 964 | .collect(); | 965 | .collect(); |
| 966 | + // ...and, for a source on an HDR curve, the tone map that brings its samples | ||
| 967 | + // down to the SDR this file is written in ([`crate::tonemap`]). Once per | ||
| 968 | + // source stream: the table costs a couple of milliseconds to build and a | ||
| 969 | + // span reopens its file, so building it here rather than in the loop below | ||
| 970 | + // is the difference between paying that once and paying it per cut. An SDR | ||
| 971 | + // source -- the whole of an ordinary project -- builds no table at all. | ||
| 972 | + let tone: Vec<Option<ToneMapper>> = rates | ||
| 973 | + .iter() | ||
| 974 | + .map(|(_, color)| match color.transfer { | ||
| 975 | + Transfer::Sdr => None, | ||
| 976 | + Transfer::Pq => Some(ToneMapper::new(tonemap::Transfer::Pq)), | ||
| 977 | + Transfer::Hlg => Some(ToneMapper::new(tonemap::Transfer::Hlg)), | ||
| 978 | + }) | ||
| 979 | + .collect(); | ||
| 965 | // ...and the one space they are all written in, the same rule a reader with | 980 | // ...and the one space they are all written in, the same rule a reader with |
| 966 | // no tags to read would apply to this file's height. | 981 | // no tags to read would apply to this file's height. |
| 967 | let out_color = ColorDescription::output(meta.height); | 982 | let out_color = ColorDescription::output(meta.height); |
| @@ -990,7 +1005,7 @@ fn run( | |||
| 990 | // encoder is *not* reopened, so the export is one continuous stream | 1005 | // encoder is *not* reopened, so the export is one continuous stream |
| 991 | // whose GOP boundaries need not line up with the cuts -- nor with the | 1006 | // whose GOP boundaries need not line up with the cuts -- nor with the |
| 992 | // file boundaries, which are just cuts that change the path. | 1007 | // file boundaries, which are just cuts that change the path. |
| 993 | - let (mut pictures, rate, in_frame, color) = match span.from { | 1008 | + let (mut pictures, rate, in_frame, color, mapper) = match span.from { |
| 994 | Some((source, in_frame)) => { | 1009 | Some((source, in_frame)) => { |
| 995 | let entry = sources | 1010 | let entry = sources |
| 996 | .get(source) | 1011 | .get(source) |
| @@ -999,11 +1014,18 @@ fn run( | |||
| 999 | // Opened at the file's own frame, which is the only place the | 1014 | // Opened at the file's own frame, which is the only place the |
| 1000 | // file's numbering is used -- the span's are the timeline's. | 1015 | // file's numbering is used -- the span's are the timeline's. |
| 1001 | let pictures = ClipDecoder::open(&entry.path, rate.source_at(in_frame))?; | 1016 | let pictures = ClipDecoder::open(&entry.path, rate.source_at(in_frame))?; |
| 1002 | - (Some(pictures), rate, in_frame, Some(color)) | 1017 | + ( |
| 1018 | + Some(pictures), | ||
| 1019 | + rate, | ||
| 1020 | + in_frame, | ||
| 1021 | + Some(color), | ||
| 1022 | + tone[source].as_ref(), | ||
| 1023 | + ) | ||
| 1003 | } | 1024 | } |
| 1004 | - // A gap's black is 16/128/128, which is black in every matrix here: | 1025 | + // A gap's black is 16/128/128, which is black in every matrix here |
| 1005 | - // nothing to remap, which is what `None` says. | 1026 | + // and on every curve: nothing to remap and nothing to tone-map, |
| 1006 | - None => (None, Rate::REAL_TIME, 0, None), | 1027 | + // which is what `None` says. |
| 1028 | + None => (None, Rate::REAL_TIME, 0, None, None), | ||
| 1007 | }; | 1029 | }; |
| 1008 | // Mixed spaces on one timeline: a clip coded against another matrix than | 1030 | // Mixed spaces on one timeline: a clip coded against another matrix than |
| 1009 | // the one this file declares is rewritten into it, *after* the grade -- | 1031 | // the one this file declares is rewritten into it, *after* the grade -- |
| @@ -1013,16 +1035,9 @@ fn run( | |||
| 1013 | // the whole of an ordinary project -- take `None` and not a byte is | 1035 | // the whole of an ordinary project -- take `None` and not a byte is |
| 1014 | // touched. | 1036 | // touched. |
| 1015 | // | 1037 | // |
| 1016 | - // ponytail: an HDR source is composited with the matrix treatment alone | 1038 | + // ...and what the samples mean when that remap sees them is not always |
| 1017 | - // and still looks washed out; the tonemap lands here, ahead of this, and | 1039 | + // what the file said, which is [`remap_into`]'s whole question. |
| 1018 | - // is a sibling task's. Until it does, the sentence above holds for SDR | 1040 | + let remap = remap_into(color, mapper.is_some(), out_color.matrix); |
| 1019 | - // only: playback now maps an HDR clip to SDR *before* grading it | ||
| 1020 | - // (`decode::Render::frame`), so an exported HDR grade is not the picture | ||
| 1021 | - // the canvas showed either. | ||
| 1022 | - let remap = color | ||
| 1023 | - .map(|c| c.matrix) | ||
| 1024 | - .filter(|&m| m != out_color.matrix) | ||
| 1025 | - .map(|m| (m, out_color.matrix)); | ||
| 1026 | // What this span is graded by -- the same answer playback's decoder | 1041 | // What this span is graded by -- the same answer playback's decoder |
| 1027 | // carries, so the export is the picture that was watched. `None` for a | 1042 | // carries, so the export is the picture that was watched. `None` for a |
| 1028 | // gap and for an ungraded clip, and that is the path where not a byte | 1043 | // gap and for an ungraded clip, and that is the path where not a byte |
| @@ -1095,9 +1110,9 @@ fn run( | |||
| 1095 | // applied in place: it goes onto a copy, which the encoder then | 1110 | // applied in place: it goes onto a copy, which the encoder then |
| 1096 | // reads instead. | 1111 | // reads instead. |
| 1097 | let params = grade.filter(|p| !p.is_identity()); | 1112 | let params = grade.filter(|p| !p.is_identity()); |
| 1098 | - let (y, u, v) = match (params, remap) { | 1113 | + let (y, u, v) = match (params, remap, mapper) { |
| 1099 | - (None, None) => (y, u, v), | 1114 | + (None, None, None) => (y, u, v), |
| 1100 | - (params, remap) => { | 1115 | + (params, remap, mapper) => { |
| 1101 | let (gy, gu, gv) = &mut graded; | 1116 | let (gy, gu, gv) = &mut graded; |
| 1102 | gy.clear(); | 1117 | gy.clear(); |
| 1103 | gy.extend_from_slice(y); | 1118 | gy.extend_from_slice(y); |
| @@ -1105,9 +1120,13 @@ fn run( | |||
| 1105 | gu.extend_from_slice(u); | 1120 | gu.extend_from_slice(u); |
| 1106 | gv.clear(); | 1121 | gv.clear(); |
| 1107 | gv.extend_from_slice(v); | 1122 | gv.extend_from_slice(v); |
| 1108 | - // Grade in the source's space, then remap the graded | 1123 | + // Tone-map first, so the grade is applied to the SDR picture |
| 1109 | - // result: the order playback's `Decoded::frame` renders in, | 1124 | + // the canvas showed and not to HDR codes; then remap the |
| 1110 | - // and the only order in which preview and export agree. | 1125 | + // graded result. The order playback renders in, and the |
| 1126 | + // only order in which preview and export agree. | ||
| 1127 | + if let Some(mapper) = mapper { | ||
| 1128 | + mapper.map(gy, gu, gv, width as usize, height as usize); | ||
| 1129 | + } | ||
| 1111 | if let Some(params) = params { | 1130 | if let Some(params) = params { |
| 1112 | crate::color::apply_yuv(¶ms, gy, gu, gv); | 1131 | crate::color::apply_yuv(¶ms, gy, gu, gv); |
| 1113 | } | 1132 | } |
| @@ -1182,6 +1201,27 @@ fn run( | |||
| 1182 | Ok(()) | 1201 | Ok(()) |
| 1183 | } | 1202 | } |
| 1184 | 1203 | ||
| 1204 | +/// Which matrix pair a span's samples are rewritten by on the way into a file | ||
| 1205 | +/// whose own matrix is `out` -- `None` when they are already coded against it, | ||
| 1206 | +/// and for a gap, whose 16/128/128 black is black in every matrix here. | ||
| 1207 | +/// | ||
| 1208 | +/// `toned` says the tone map ran on this span: it hands back BT.709 SDR whatever | ||
| 1209 | +/// the source was coded as, so an HDR clip is never *also* given the matrix | ||
| 1210 | +/// treatment its BT.2020 tag would ask for -- one conversion or the other, never | ||
| 1211 | +/// both on one frame -- while a tone-mapped clip on a canvas below 720 lines | ||
| 1212 | +/// still takes its 709 -> 601 step. | ||
| 1213 | +fn remap_into( | ||
| 1214 | + color: Option<ColorDescription>, | ||
| 1215 | + toned: bool, | ||
| 1216 | + out: Matrix, | ||
| 1217 | +) -> Option<(Matrix, Matrix)> { | ||
| 1218 | + let from = match toned { | ||
| 1219 | + true => Matrix::Bt709, | ||
| 1220 | + false => color?.matrix, | ||
| 1221 | + }; | ||
| 1222 | + (from != out).then_some((from, out)) | ||
| 1223 | +} | ||
| 1224 | + | ||
| 1185 | /// What rate `path` was shot at against a timeline at `timeline_fps` | 1225 | /// What rate `path` was shot at against a timeline at `timeline_fps` |
| 1186 | /// ([`Rate`]). [`Rate::REAL_TIME`] for the files that have no rate of their own | 1226 | /// ([`Rate`]). [`Rate::REAL_TIME`] for the files that have no rate of their own |
| 1187 | /// -- a still, a song -- and for one that will not open here: the decoder is | 1227 | /// -- a still, a song -- and for one that will not open here: the decoder is |
| @@ -2421,6 +2461,44 @@ impl SwDecoder { | |||
| 2421 | mod tests { | 2461 | mod tests { |
| 2422 | use super::*; | 2462 | use super::*; |
| 2423 | 2463 | ||
| 2464 | + /// The one rule that keeps a picture from being converted twice: a frame the | ||
| 2465 | + /// tone map has already brought to BT.709 is never handed the 2020 matrix as | ||
| 2466 | + /// well, on either canvas -- and everything else about the remap is | ||
| 2467 | + /// unchanged by the tone map existing. | ||
| 2468 | + #[test] | ||
| 2469 | + fn a_tone_mapped_span_is_never_matrix_remapped_too() { | ||
| 2470 | + let hdr = ColorDescription { | ||
| 2471 | + matrix: Matrix::Bt2020Ncl, | ||
| 2472 | + transfer: Transfer::Pq, | ||
| 2473 | + full_range: false, | ||
| 2474 | + }; | ||
| 2475 | + let sdr = ColorDescription::default(); // BT.601 | ||
| 2476 | + for out in [Matrix::Bt709, Matrix::Bt601] { | ||
| 2477 | + let toned = remap_into(Some(hdr), true, out); | ||
| 2478 | + assert!( | ||
| 2479 | + toned.is_none_or(|(from, _)| from == Matrix::Bt709), | ||
| 2480 | + "tone-mapped onto a {out:?} canvas asked for {toned:?}" | ||
| 2481 | + ); | ||
| 2482 | + // Untouched by any of this: the 2020 clip that was *not* tone-mapped | ||
| 2483 | + // (an unreachable state today, and still the matrix answer), the | ||
| 2484 | + // ordinary 601-on-709 reconcile, and a gap. | ||
| 2485 | + assert_eq!( | ||
| 2486 | + remap_into(Some(hdr), false, out), | ||
| 2487 | + (out != Matrix::Bt2020Ncl).then_some((Matrix::Bt2020Ncl, out)) | ||
| 2488 | + ); | ||
| 2489 | + assert_eq!( | ||
| 2490 | + remap_into(Some(sdr), false, out), | ||
| 2491 | + (out != Matrix::Bt601).then_some((Matrix::Bt601, out)) | ||
| 2492 | + ); | ||
| 2493 | + assert_eq!(remap_into(None, false, out), None); | ||
| 2494 | + } | ||
| 2495 | + assert_eq!( | ||
| 2496 | + remap_into(Some(hdr), true, Matrix::Bt601), | ||
| 2497 | + Some((Matrix::Bt709, Matrix::Bt601)), | ||
| 2498 | + "a tone-mapped clip below 720 lines still takes its 709 -> 601 step" | ||
| 2499 | + ); | ||
| 2500 | + } | ||
| 2501 | + | ||
| 2424 | /// A track of three cues, in whichever clock `track` says: `Some(n)` is a | 2502 | /// A track of three cues, in whichever clock `track` says: `Some(n)` is a |
| 2425 | /// track of the media file, `None` a `.srt` beside it. | 2503 | /// track of the media file, `None` a `.srt` beside it. |
| 2426 | fn subtitles(path: &str, track: Option<u64>) -> SubtitleTrack { | 2504 | fn subtitles(path: &str, track: Option<u64>) -> SubtitleTrack { |
crates/engine/tests/export_color.rsmodified+218 -1
| @@ -12,7 +12,10 @@ | |||
| 12 | //! reading the export by its own tags gives back the picture that went in -- | 12 | //! reading the export by its own tags gives back the picture that went in -- |
| 13 | //! a reconcile, not a second conversion; and | 13 | //! a reconcile, not a second conversion; and |
| 14 | //! 3. a graded clip comes out of the export the way the preview showed it, | 14 | //! 3. a graded clip comes out of the export the way the preview showed it, |
| 15 | -//! which is what makes a grade a decision and not a guess. | 15 | +//! which is what makes a grade a decision and not a guess; and |
| 16 | +//! 4. an HDR source is *tone-mapped* into that space rather than tagged into it | ||
| 17 | +//! ([`engine::tonemap`]) -- once, before the grade, and never on top of a | ||
| 18 | +//! matrix conversion of the same frame. | ||
| 16 | //! | 19 | //! |
| 17 | //! ```text | 20 | //! ```text |
| 18 | //! cargo test -p engine --release --test export_color | 21 | //! cargo test -p engine --release --test export_color |
| @@ -31,6 +34,7 @@ use engine::colorspace::{ColorDescription, Matrix, Transfer, remap}; | |||
| 31 | use engine::demux::Demuxer; | 34 | use engine::demux::Demuxer; |
| 32 | use engine::export::{ExportSettings, Format}; | 35 | use engine::export::{ExportSettings, Format}; |
| 33 | use engine::scratch::Scratch; | 36 | use engine::scratch::Scratch; |
| 37 | +use engine::tonemap::{self, ToneMapper}; | ||
| 34 | 38 | ||
| 35 | fn asset(name: &str) -> PathBuf { | 39 | fn asset(name: &str) -> PathBuf { |
| 36 | PathBuf::from(env!("CARGO_MANIFEST_DIR")) | 40 | PathBuf::from(env!("CARGO_MANIFEST_DIR")) |
| @@ -157,6 +161,40 @@ fn raw_yuv(path: &Path) -> Option<Vec<u8>> { | |||
| 157 | Some(std::fs::read(&*raw).expect("the raw frame")) | 161 | Some(std::fs::read(&*raw).expect("the raw frame")) |
| 158 | } | 162 | } |
| 159 | 163 | ||
| 164 | +/// A one-second 720p fixture whose samples are ordinary 8-bit BT.709 pictures | ||
| 165 | +/// but whose *tags* say BT.2020 PQ -- which is all the colour path reads, so it | ||
| 166 | +/// exercises the tone map without an HDR encoder anywhere near the test. The | ||
| 167 | +/// codes therefore mean something far brighter than they were drawn as, which is | ||
| 168 | +/// the point: an HDR file handed to an SDR display is exactly that mistake. | ||
| 169 | +/// | ||
| 170 | +/// The tags go in through `-x264-params`, not ffmpeg's own `-color_trc`: the | ||
| 171 | +/// latter writes the mp4's `colr` box alone here (measured: ffprobe reads the | ||
| 172 | +/// transfer back as "unknown"), and the bitstream is the answer any reader takes | ||
| 173 | +/// first. `None` where ffmpeg is not installed. | ||
| 174 | +fn pq_fixture() -> Option<Scratch> { | ||
| 175 | + let path = out_path("pq_source", "mp4"); | ||
| 176 | + let made = Command::new("ffmpeg") | ||
| 177 | + .args([ | ||
| 178 | + "-y", | ||
| 179 | + "-v", | ||
| 180 | + "error", | ||
| 181 | + "-f", | ||
| 182 | + "lavfi", | ||
| 183 | + "-i", | ||
| 184 | + "testsrc2=size=1280x720:rate=30:duration=1", | ||
| 185 | + "-c:v", | ||
| 186 | + "libx264", | ||
| 187 | + "-pix_fmt", | ||
| 188 | + "yuv420p", | ||
| 189 | + "-x264-params", | ||
| 190 | + "colorprim=bt2020:transfer=smpte2084:colormatrix=bt2020nc", | ||
| 191 | + ]) | ||
| 192 | + .arg(&*path) | ||
| 193 | + .output() | ||
| 194 | + .ok()?; | ||
| 195 | + made.status.success().then_some(path) | ||
| 196 | +} | ||
| 197 | + | ||
| 160 | fn mean_abs_diff(a: &[u8], b: &[u8]) -> f64 { | 198 | fn mean_abs_diff(a: &[u8], b: &[u8]) -> f64 { |
| 161 | assert_eq!(a.len(), b.len(), "frame sizes differ"); | 199 | assert_eq!(a.len(), b.len(), "frame sizes differ"); |
| 162 | a.iter() | 200 | a.iter() |
| @@ -312,6 +350,185 @@ fn every_format_signals_its_space_in_the_bitstream() { | |||
| 312 | } | 350 | } |
| 313 | } | 351 | } |
| 314 | 352 | ||
| 353 | +/// An HDR source comes out as an SDR file that *says* it is one, in the | ||
| 354 | +/// container and in the bitstream both. The tags are the half a player reads | ||
| 355 | +/// before it reads a pixel: a file of tone-mapped samples still labelled PQ is | ||
| 356 | +/// shown through a second, inverse curve and is worse than either honest answer. | ||
| 357 | +#[test] | ||
| 358 | +fn an_hdr_source_exports_as_a_tagged_sdr_file() { | ||
| 359 | + let Some(source) = pq_fixture() else { | ||
| 360 | + eprintln!("no ffmpeg: skipping the HDR export tags"); | ||
| 361 | + return; | ||
| 362 | + }; | ||
| 363 | + let (meta, _) = Demuxer::open(&source).expect("open the PQ fixture"); | ||
| 364 | + assert_eq!(meta.color.transfer, Transfer::Pq, "the fixture's own curve"); | ||
| 365 | + assert_eq!(meta.color.matrix, Matrix::Bt2020Ncl, "...and its matrix"); | ||
| 366 | + | ||
| 367 | + let session = two_frames(&source); | ||
| 368 | + let out = out_path("hdr_tags", "mp4"); | ||
| 369 | + export(&session, &out, Format::Mp4); | ||
| 370 | + | ||
| 371 | + let (meta, _) = Demuxer::open(&out).expect("reopen the export"); | ||
| 372 | + assert_eq!( | ||
| 373 | + meta.color, | ||
| 374 | + ColorDescription { | ||
| 375 | + matrix: Matrix::Bt709, | ||
| 376 | + transfer: Transfer::Sdr, | ||
| 377 | + full_range: false, | ||
| 378 | + }, | ||
| 379 | + "what the export says about itself" | ||
| 380 | + ); | ||
| 381 | + match probed(&out) { | ||
| 382 | + Some(tags) => { | ||
| 383 | + eprintln!("PQ source -> mp4: ffprobe {tags:?}"); | ||
| 384 | + let want: Vec<String> = ["tv", "bt709", "bt709", "bt709"] | ||
| 385 | + .iter() | ||
| 386 | + .map(|s| s.to_string()) | ||
| 387 | + .collect(); | ||
| 388 | + assert_eq!(tags, want, "range, matrix, transfer, primaries"); | ||
| 389 | + assert_eq!( | ||
| 390 | + probed_frame(&out).expect("ffprobe is installed"), | ||
| 391 | + "bt709", | ||
| 392 | + "what a decoder makes of the coded frame" | ||
| 393 | + ); | ||
| 394 | + } | ||
| 395 | + None => eprintln!("no ffprobe: skipping the external read"), | ||
| 396 | + } | ||
| 397 | + std::fs::remove_file(&out).unwrap(); | ||
| 398 | +} | ||
| 399 | + | ||
| 400 | +/// The order, measured on the samples: tone-map first, grade the SDR picture | ||
| 401 | +/// that comes out. Playback renders in that order, so an export that graded the | ||
| 402 | +/// *HDR* codes and tone-mapped afterwards would be a different picture than the | ||
| 403 | +/// canvas showed -- and with a brightness lift on a curve this steep, a very | ||
| 404 | +/// different one, which is what the swapped-order control here measures. | ||
| 405 | +/// | ||
| 406 | +/// It is also where "converted once" is checked: the reference below is the tone | ||
| 407 | +/// map and the grade and nothing else, no matrix step, so an export that also | ||
| 408 | +/// ran the BT.2020 matrix over those samples could not land on it. | ||
| 409 | +#[test] | ||
| 410 | +fn an_hdr_clip_is_tone_mapped_before_it_is_graded() { | ||
| 411 | + let Some(source) = pq_fixture() else { | ||
| 412 | + eprintln!("no ffmpeg: skipping the tone-map order check"); | ||
| 413 | + return; | ||
| 414 | + }; | ||
| 415 | + let Some(src) = raw_yuv(&source) else { | ||
| 416 | + eprintln!("no ffmpeg: skipping the tone-map order check"); | ||
| 417 | + return; | ||
| 418 | + }; | ||
| 419 | + // A lift, because the curve it is composed with is steepest where the codes | ||
| 420 | + // are: swap the two and the picture is visibly elsewhere. | ||
| 421 | + let grade = engine::color::ColorParams { | ||
| 422 | + brightness: 0.25, | ||
| 423 | + ..Default::default() | ||
| 424 | + }; | ||
| 425 | + let mut session = two_frames(&source); | ||
| 426 | + assert!( | ||
| 427 | + session.set_color(engine::project::Lane::V1, 0, Some(grade)), | ||
| 428 | + "the grade went on the clip" | ||
| 429 | + ); | ||
| 430 | + let out = out_path("hdr_order", "mp4"); | ||
| 431 | + export(&session, &out, Format::Mp4); | ||
| 432 | + let got = raw_yuv(&out).expect("ffmpeg read the export"); | ||
| 433 | + | ||
| 434 | + let (width, height) = (1280usize, 720usize); | ||
| 435 | + let mapper = ToneMapper::new(tonemap::Transfer::Pq); | ||
| 436 | + // The same bytes twice, through the two orders. Whichever way MASTER_NITS is | ||
| 437 | + // set, both sides move with it -- what is asserted is which of them the | ||
| 438 | + // export sits on, not where either lands. | ||
| 439 | + let both = [true, false].map(|tone_first| { | ||
| 440 | + let mut planes = src.clone(); | ||
| 441 | + let (y, chroma) = planes.split_at_mut(width * height); | ||
| 442 | + let (u, v) = chroma.split_at_mut(width * height / 4); | ||
| 443 | + if tone_first { | ||
| 444 | + mapper.map(y, u, v, width, height); | ||
| 445 | + engine::color::apply_yuv(&grade, y, u, v); | ||
| 446 | + } else { | ||
| 447 | + engine::color::apply_yuv(&grade, y, u, v); | ||
| 448 | + mapper.map(y, u, v, width, height); | ||
| 449 | + } | ||
| 450 | + planes | ||
| 451 | + }); | ||
| 452 | + let [ordered, swapped] = both.map(|planes| mean_abs_diff(&got, &planes)); | ||
| 453 | + eprintln!( | ||
| 454 | + "HDR export: {ordered:.2} off tone-map-then-grade, {swapped:.2} off the swapped order" | ||
| 455 | + ); | ||
| 456 | + assert!( | ||
| 457 | + ordered < 3.0, | ||
| 458 | + "the export is {ordered:.2} codes from tone-map-then-grade" | ||
| 459 | + ); | ||
| 460 | + assert!( | ||
| 461 | + swapped > 3.0 * ordered, | ||
| 462 | + "ordered {ordered:.2} vs swapped {swapped:.2}: the two orders are not far enough apart to have measured anything" | ||
| 463 | + ); | ||
| 464 | + std::fs::remove_file(&out).unwrap(); | ||
| 465 | +} | ||
| 466 | + | ||
| 467 | +/// The real thing, where this machine has it: five seconds of a 4K HDR10 film, | ||
| 468 | +/// ten minutes in (the opening two are black and would measure nothing), | ||
| 469 | +/// decoded by the VA-API plugin -- 10-bit HEVC has no software decoder here -- | ||
| 470 | +/// and exported. Skipped, loudly, on a machine without the film. | ||
| 471 | +/// | ||
| 472 | +/// What is asserted is what the synthetic fixture cannot be: that the tone map | ||
| 473 | +/// survives a real grade of real HDR10 pixels. A picture that came out grey | ||
| 474 | +/// (chroma collapsed onto 128) or crushed to black is what a mistuned or | ||
| 475 | +/// double-applied conversion produces, and both are one mean away. | ||
| 476 | +#[test] | ||
| 477 | +fn a_real_hdr_film_exports_as_a_picture() { | ||
| 478 | + let film = Path::new( | ||
| 479 | + "/path/to/a-real-4k-hdr10-film.mkv", | ||
| 480 | + ); | ||
| 481 | + if !film.exists() { | ||
| 482 | + eprintln!("skipped: {} is not on this machine", film.display()); | ||
| 483 | + return; | ||
| 484 | + } | ||
| 485 | + let mut session = PlaybackSession::open(film).expect("open the film"); | ||
| 486 | + assert_eq!(session.meta().color.transfer, Transfer::Pq, "an HDR10 film"); | ||
| 487 | + // A five-second window out of the middle: cut both ends, drop them, and the | ||
| 488 | + // delete closes the gap ahead of what is left, so the export is those five | ||
| 489 | + // seconds and no leading black. | ||
| 490 | + assert!(session.cut_at(605.0), "the tail cut"); | ||
| 491 | + assert!(session.cut_at(600.0), "the head cut"); | ||
| 492 | + assert!(session.delete_clip(engine::project::Lane::V1, 2), "the tail"); | ||
| 493 | + assert!(session.delete_clip(engine::project::Lane::V1, 0), "the head"); | ||
| 494 | + let out = out_path("hdr_film", "mp4"); | ||
| 495 | + export(&session, &out, Format::Mp4); | ||
| 496 | + | ||
| 497 | + let (meta, _) = Demuxer::open(&out).expect("reopen the export"); | ||
| 498 | + assert_eq!( | ||
| 499 | + meta.color, | ||
| 500 | + ColorDescription { | ||
| 501 | + matrix: Matrix::Bt709, | ||
| 502 | + transfer: Transfer::Sdr, | ||
| 503 | + full_range: false, | ||
| 504 | + }, | ||
| 505 | + "a 4K HDR film exported as tagged SDR" | ||
| 506 | + ); | ||
| 507 | + let Some(frame) = raw_yuv(&out) else { | ||
| 508 | + eprintln!("no ffmpeg: skipping the pixel half of the film check"); | ||
| 509 | + return; | ||
| 510 | + }; | ||
| 511 | + let (width, height) = (meta.width as usize, meta.height as usize); | ||
| 512 | + let (y, chroma) = frame.split_at(width * height); | ||
| 513 | + let luma = y.iter().map(|s| f64::from(*s)).sum::<f64>() / y.len() as f64; | ||
| 514 | + let colour = chroma | ||
| 515 | + .iter() | ||
| 516 | + .map(|s| f64::from(s.abs_diff(128))) | ||
| 517 | + .sum::<f64>() | ||
| 518 | + / chroma.len() as f64; | ||
| 519 | + eprintln!("5 s of the film at 600 s: mean luma {luma:.1}, mean chroma distance {colour:.1}"); | ||
| 520 | + // Ranges, not anchors: the exposure the tone map is tuned to is a constant | ||
| 521 | + // in that module and may move. What may not move is that the picture is | ||
| 522 | + // still a picture -- neither crushed to black nor washed to white, and in | ||
| 523 | + // colour. | ||
| 524 | + assert!( | ||
| 525 | + (25.0..200.0).contains(&luma), | ||
| 526 | + "mean luma {luma:.1}: that is not a picture" | ||
| 527 | + ); | ||
| 528 | + assert!(colour > 4.0, "mean chroma distance {colour:.1}: grey"); | ||
| 529 | + std::fs::remove_file(&out).unwrap(); | ||
| 530 | +} | ||
| 531 | + | ||
| 315 | /// Preview and export are the same picture, on the one path where they used to | 532 | /// Preview and export are the same picture, on the one path where they used to |
| 316 | /// differ: a graded clip whose own space is not the file's. Playback grades in | 533 | /// differ: a graded clip whose own space is not the file's. Playback grades in |
| 317 | /// the source's space and converts for the screen, so an export that remapped | 534 | /// the source's space and converts for the screen, so an export that remapped |