diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index f10ff25..558d783 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -17,6 +17,7 @@ use engine::export::{AUDIO_KBPS, DEFAULT_AUDIO_KBPS, ExportSettings, Format}; use engine::limiter::Limiter; use engine::project::{Edge, Lane, LaneKind, Source, Speed}; use engine::scale::FitPolicy; +use engine::tonemap::Preset; use engine::{Clip, Codec, ExportHandle, Frame, PlaybackSession}; use gpui::{ AnyElement, App, Application, Bounds, ClickEvent, Context, CursorStyle, Div, DragMoveEvent, @@ -458,6 +459,10 @@ enum Pick { /// What the export's *sound* is coded at. Opened from the card's Sound row, /// which is the only place it means anything. AudioRate, + /// Which HDR-to-SDR rendition the project is watched and exported in + /// ([`engine::tonemap::Preset`]). Opened from the panel, beside the two + /// other settings that are the project's rather than the media's. + Tone, } /// One value a list offers, carrying everything picking it needs -- so a click @@ -472,6 +477,7 @@ enum Choice { Fps(f64), Fit(Lane, usize, FitPolicy), AudioRate(u32), + Tone(Preset), } /// One row of an open list: the value, its name, the small print beside it, and @@ -1778,6 +1784,22 @@ impl Player { cx.notify(); } + /// The project's HDR media shown another way: the list names a rendition and + /// this is where it happens, the way [`apply_resolution`](Self::apply_resolution) + /// is for a size. The engine remaps the frame under the playhead at once + /// ([`PlaybackSession::set_tone`]), so the picture on screen is the picked + /// one before the notice has faded -- and an SDR project is unmoved, which + /// is what the notice says rather than pretending something happened. + fn apply_tone(&mut self, preset: Preset, cx: &mut Context) { + if let Some(session) = &mut self.session + && session.set_tone(preset) + { + self.notice = Some(format!("HDR: {} — affects HDR media", tone_label(preset)).into()); + self.reset_after_reseek(); + } + cx.notify(); + } + /// Opens a choice list on a setting, where it was asked for. One floating /// thing at a time: the click that opens it is the click that closes /// whatever menu it was opened from. @@ -1797,6 +1819,7 @@ impl Player { Choice::Size(w, h) => self.apply_resolution(w, h, cx), Choice::Fps(fps) => self.apply_frame_rate(fps, cx), Choice::Fit(lane, idx, fit) => self.apply_fit(lane, idx, fit, cx), + Choice::Tone(preset) => self.apply_tone(preset, cx), // The same field the row's key steps, set outright: a list picks a // value, it does not step to one. Choice::AudioRate(kbps) => { @@ -1822,6 +1845,7 @@ impl Player { fit_choices(lane, idx, session.fit_of(lane, idx), session.resolution()) } Pick::AudioRate => audio_rate_choices(self.audio_kbps), + Pick::Tone => tone_choices(session.tone()), } } @@ -5937,6 +5961,30 @@ impl Player { this.open_picker(Pick::Fps, event.position(), cx) }), )) + // ...and which rendition its HDR media is watched in, the + // third thing that is the project's rather than the media's. + // Listed whatever is on the timeline, and the tooltip says + // who it acts on: a control that came and went with the + // media would be one nobody could find when they wanted it. + .child(control( + "tonemap", + None, + match &self.session { + Some(session) => format!("HDR {}", tone_label(session.tone())), + None => "HDR".to_string(), + }, + match &self.session { + Some(session) => format!( + "click to pick the HDR rendition — the project is {}; SDR media is untouched", + tone_label(session.tone()) + ), + None => "the HDR rendition — open a file first".to_string(), + }, + live, + cx.listener(|this, event: &ClickEvent, _, cx| { + this.open_picker(Pick::Tone, event.position(), cx) + }), + )) // How much of the timeline the panel below is showing -- // beside the resolution, since neither of them edits // anything: they are both what is being looked at. The @@ -10704,6 +10752,40 @@ fn audio_rate_choices(current: u32) -> Vec { .collect() } +/// How a rendition is named where a person reads it: the panel button, the +/// notice and the list row all say the same word ([`engine::tonemap::Preset`]). +fn tone_label(preset: Preset) -> &'static str { + match preset { + Preset::Reference => "Reference", + Preset::Standard => "Standard", + Preset::Vivid => "Vivid", + } +} + +/// The HDR list's rows: all three renditions, the one in force marked, and what +/// each one *is* beside it -- in the fewest words that fit inside `MENU_W`, the +/// truncation the three lists above already met. Always offered, whatever is on +/// the timeline: a setting that appeared and vanished with the media would be a +/// setting nobody could find, and the row says who it acts on instead. +fn tone_choices(current: Preset) -> Vec { + Preset::ALL + .into_iter() + .map(|preset| { + ( + Choice::Tone(preset), + tone_label(preset).into(), + match preset { + Preset::Reference => "BT.2446-A, as published", + Preset::Standard => "brighter, player-like", + Preset::Vivid => "brightest, richer colour", + } + .into(), + preset == current, + ) + }) + .collect() +} + /// The next project resolution after `current`, over [`RESOLUTIONS`] with the /// media's own size cycled in at its place by size -- so the trip round always /// comes back to the media, whatever odd shape it is, and a project already at a @@ -12278,12 +12360,13 @@ mod tests { whole_take, window_title, }; use super::{ - Choice, ETA_SPAN, Edge, FITS, FRAME_RATES, LaneKind, PPS_DEFAULT, RESOLUTIONS, Repeat, + Choice, ETA_SPAN, Edge, FITS, FRAME_RATES, LaneKind, PPS_DEFAULT, Preset, RESOLUTIONS, Repeat, Scale, View, ZOOM_MAX_SECONDS, ZOOM_MIN_FRAMES, ZOOM_STEP, audio_rate_choices, clock, eta_secs, file_name, file_uri, fit_choices, landing, lane_refuses, library_rows, live_idx, next_fit, next_resolution, note_progress, px_along, - repeats, resolution_choices, resolution_ladder, span_label, trimmed_clip, unscannable, + repeats, resolution_choices, resolution_ladder, span_label, tone_choices, tone_label, + trimmed_clip, unscannable, visible_slice, }; use super::{ @@ -15305,6 +15388,20 @@ mod tests { assert!(detail.chars().count() < 26, "{detail} loses its tail"); } + // The HDR list, the third project setting: all three renditions in the + // order they brighten, the one in force marked, and every row saying + // what it is in words that fit beside the label. + let tones = tone_choices(Preset::Standard); + assert_eq!(tones.len(), Preset::ALL.len()); + assert_eq!(tones.iter().filter(|(.., picked)| *picked).count(), 1); + for (row, preset) in tones.iter().zip(Preset::ALL) { + assert_eq!(row.0, Choice::Tone(preset)); + assert_eq!(row.1.as_ref(), tone_label(preset)); + assert!(!row.2.is_empty(), "{preset:?} says nothing about itself"); + assert!(row.2.chars().count() < 26, "{} loses its tail", row.2); + } + assert!(tones[1].3, "the rendition in force is not marked"); + // The open list fits the floor the menus are measured against: the // longest of them is the rate ladder with an odd rate cycled in, and it // hangs at the pointer with every row on screen. Rows are click targets diff --git a/crates/engine/src/decode.rs b/crates/engine/src/decode.rs index caf67e0..89ac776 100644 --- a/crates/engine/src/decode.rs +++ b/crates/engine/src/decode.rs @@ -236,6 +236,9 @@ impl DecodeSession { // No project, no canvas: the file-level API hands back the // pictures the file holds, at the size it holds them. Composer::passthrough(), + // ...and no project means no picked rendition either: an HDR file + // opened through this door is mapped the published way. + tonemap::Preset::default(), )?; // The public API hands out the flag alone, so the worker is detached and // the receiver goes to the caller: nothing here joins anything. @@ -324,7 +327,16 @@ impl DecodeSession { // BT.601 limited, because that is what `rgb_to_i420` above wrote these // planes in: a still round-trips through the pair, not through the // colour of whatever file is on the timeline beside it. - let first = Render::new(color, ColorDescription::default(), canvas).frame( + // No preset argument, and none wanted: a still is decoded into BT.601 + // SDR planes, so the tone map is not built at all whichever rendition + // the project is watching. + let first = Render::new( + color, + ColorDescription::default(), + canvas, + tonemap::Preset::default(), + ) + .frame( start_frame, &still.y, &still.u, @@ -375,12 +387,18 @@ impl DecodeSession { /// frames come out at *that* size, whatever the file's is. A /// [`Composer::passthrough`] (or one already the source's size) leaves every /// picture exactly as it was decoded. + /// + /// `tone` is the project's HDR rendition ([`tonemap::Preset`]), captured + /// here for the reason the grade is: it is constant across one span, and a + /// preset picked while this worker runs reaches the picture when the session + /// reseeks onto the new one. An SDR source ignores it entirely. pub(crate) fn open_worker( path: impl AsRef, start_frame: u32, end_frame: u32, color: ColorParams, canvas: Composer, + tone: tonemap::Preset, ) -> crate::Result<(VideoMeta, FrameStream)> { let path = path.as_ref().to_path_buf(); let (meta, demuxer) = Demuxer::open(&path)?; @@ -430,7 +448,7 @@ impl DecodeSession { if worker_cancel.load(Ordering::Relaxed) { return; } - let mut render = Render::new(color, source_color, canvas); + let mut render = Render::new(color, source_color, canvas, tone); // The plugin has to be opened on the thread that uses it: its // VA-API state is not `Send`-safe across a later hand-off. if let Some(hw) = open_hw(&path, start_frame) { @@ -518,7 +536,12 @@ const TONE_MAPPED: ColorDescription = ColorDescription { }; impl Render { - fn new(color: ColorParams, desc: ColorDescription, canvas: Composer) -> Self { + fn new( + color: ColorParams, + desc: ColorDescription, + canvas: Composer, + preset: tonemap::Preset, + ) -> Self { Self { color, desc, @@ -530,8 +553,8 @@ impl Render { // range argument to `ToneMapper::new`. tone: match desc.transfer { Transfer::Sdr => None, - Transfer::Pq => Some(ToneMapper::new(tonemap::Transfer::Pq)), - Transfer::Hlg => Some(ToneMapper::new(tonemap::Transfer::Hlg)), + Transfer::Pq => Some(ToneMapper::new(tonemap::Transfer::Pq, preset)), + Transfer::Hlg => Some(ToneMapper::new(tonemap::Transfer::Hlg, preset)), }, graded: (Vec::new(), Vec::new(), Vec::new()), } @@ -800,6 +823,7 @@ mod tests { u32::MAX, ColorParams::default(), Composer::passthrough(), + tonemap::Preset::default(), ) .expect("open"); // Nothing is ever received: two frames fill the channel and the next diff --git a/crates/engine/src/edith.rs b/crates/engine/src/edith.rs index 69cd184..2e0ebd9 100644 --- a/crates/engine/src/edith.rs +++ b/crates/engine/src/edith.rs @@ -1,10 +1,11 @@ //! The project file: a line of text per thing, and nothing else. //! //! ```text -//! edith 10 +//! edith 11 //! playhead 90 //! resolution 1920 1080 //! fps 30.0 +//! tonemap vivid //! limiter -1.0 on //! source 0 test_av.mp4 //! source 1 /elsewhere/test_av2.mp4 @@ -37,6 +38,12 @@ //! since the save comes back listed and refused by name rather than dropped, //! which is what keeps a re-save from losing it. //! +//! The `tonemap` line is which HDR-to-SDR rendition the project is watched and +//! exported in ([`crate::tonemap::Preset`]), spelled `reference`, `standard` or +//! `vivid`. Left out when it is the default, which is `reference` -- so a +//! project holding no HDR media, and one whose owner never picked, are the bytes +//! they were. +//! //! The `limiter` line is the master limiter over the whole mix //! ([`crate::limiter`]): its ceiling in dBFS and whether it is in circuit, //! spelled `on` or `off`. Left out when it is the default, which is off. @@ -93,7 +100,9 @@ //! is the only way an empty lane could still be there on the way back. A lane //! number may not skip one of its kind. //! -//! **Version 9** was this without the `subtitle` lines: such a project shows no +//! **Version 10** was this without the `tonemap` line: such a project is shown +//! in the reference rendition, which is the only one there was. +//! **Version 9** was that without the `subtitle` lines: such a project shows no //! subtitles, which is all any project could do. //! **Version 8** was that without the `fps` and `limiter` lines and without //! the `gain` ones: such a project mixes every lane at unity, limits nothing, @@ -113,8 +122,9 @@ //! cumulatively and copied onto both lanes as one group each, which is exactly //! what a v1 timeline meant, and an older file simply equalizes and grades //! nothing, and an older one plays everything at real time, and an older one -//! mixes flat, and an older one shows no subtitles -- and saving any of them -//! writes v10. An older reader refuses a newer file by name. +//! mixes flat, and an older one shows no subtitles, and an older one is shown +//! in the reference rendition -- and saving any of them writes v11. An older +//! reader refuses a newer file by name. //! //! Text because an edit list is a few integers and a path, and a path is //! *bytes* on this platform -- a JSON string would have to lossily decode one. @@ -149,7 +159,8 @@ use crate::subtitle::SubtitleTrack; /// What [`save`] writes. Read support goes back to `edith 1`; see the module /// docs for what those dialects looked like. -const MAGIC: &[u8] = b"edith 10"; +const MAGIC: &[u8] = b"edith 11"; +const MAGIC_V10: &[u8] = b"edith 10"; const MAGIC_V9: &[u8] = b"edith 9"; const MAGIC_V8: &[u8] = b"edith 8"; const MAGIC_V7: &[u8] = b"edith 7"; @@ -198,6 +209,11 @@ pub struct Document { /// songs has no answer for (see /// [`crate::PlaybackSession::open_project`]). pub fps: Option, + /// The HDR-to-SDR rendition every clip on an HDR curve is shown in. + /// [`crate::tonemap::Preset::Reference`] for every dialect before v11 and + /// for a v11 file that leaves the line out, which both mean the published + /// conversion -- the only one those projects had. + pub tone: crate::tonemap::Preset, pub playhead: u32, } @@ -216,6 +232,7 @@ pub fn save( color: &[ColorParams], resolution: (u32, u32), fps: Option, + tone: crate::tonemap::Preset, limiter: Limiter, playhead: u32, ) -> crate::Result<()> { @@ -230,8 +247,8 @@ pub fn save( let result = std::fs::File::create(&part) .and_then(|mut f| { f.write_all(&emit( - &dir, sources, lanes, gains, subtitles, eq, color, resolution, fps, limiter, - playhead, + &dir, sources, lanes, gains, subtitles, eq, color, resolution, fps, tone, + limiter, playhead, ))?; f.sync_all() }) @@ -273,6 +290,7 @@ fn emit( color: &[ColorParams], resolution: (u32, u32), fps: Option, + tone: crate::tonemap::Preset, limiter: Limiter, playhead: u32, ) -> Vec { @@ -286,6 +304,12 @@ fn emit( if let Some(fps) = fps.filter(|f| f.is_finite() && *f > 0.0) { out.extend_from_slice(format!("fps {fps:?}\n").as_bytes()); } + // Beside the rate, and written only when it is not the default: a project + // holding no HDR media has nothing to say here, and saying nothing is what + // a v10 file already said. + if tone != crate::tonemap::Preset::default() { + out.extend_from_slice(format!("tonemap {}\n", tone.name()).as_bytes()); + } // Written only when it is not the default, so a project nobody has limited // is the same bytes it was in v8 bar the version line. if limiter != Limiter::default() { @@ -415,8 +439,10 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result { // The dialects that wrote a source line without its stream field. Reading // one is the whole of what "an old project still opens" means here. let streamless = v1 || first == MAGIC_V2; - // The one that carries subtitle tracks... - let v10 = first == MAGIC; + // The one that carries an HDR rendition... + let v11 = first == MAGIC; + // ...the ones that carry subtitle tracks... + let v10 = v11 || first == MAGIC_V10; // ...the ones that carry the mix -- lane volumes, the master limiter and // the rate the timeline was cut at... let v9 = v10 || first == MAGIC_V9; @@ -456,9 +482,11 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result { // ...and nothing before v9 carries a mix or a rate: every lane at unity, // no limiter, and the rate inferred from the scaffold as it always was. gains: Vec::new(), - // Nothing before v10 shows a subtitle. + // Nothing before v10 shows a subtitle, and nothing before v11 was shown + // in any rendition but the published one. subtitles: Vec::new(), limiter: Limiter::default(), + tone: crate::tonemap::Preset::default(), fps: None, playhead: 0, }; @@ -515,6 +543,20 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result { })?; doc.fps = Some(fps); } + b"tonemap" if v11 => { + if !doc.sources.is_empty() { + return Err( + format!("line {n}: tonemap belongs once, before the sources").into(), + ); + } + let f = fields(rest, 1, "tonemap", n)?; + doc.tone = crate::tonemap::Preset::from_name(f[0]).ok_or_else(|| { + format!( + "line {n}: {:?} is not a tone map", + String::from_utf8_lossy(f[0]) + ) + })?; + } b"limiter" if v9 => { if !doc.sources.is_empty() { return Err( @@ -1033,6 +1075,7 @@ mod tests { color, resolution, None, + crate::tonemap::Preset::default(), Limiter::default(), playhead, ) @@ -1073,6 +1116,7 @@ mod tests { &[], (1280, 720), None, + crate::tonemap::Preset::default(), Limiter::default(), 0, ); @@ -1101,7 +1145,7 @@ mod tests { video 1 0 0 30 0 - - - fit 1000\n"; let old = parse(v9, &dir).expect("v9 still loads"); assert_eq!(old.subtitles, Vec::new()); - assert!(flat(&dir, &old.sources, &old.lanes, old.playhead).starts_with(b"edith 10\n")); + assert!(flat(&dir, &old.sources, &old.lanes, old.playhead).starts_with(b"edith 11\n")); // ...and the line itself is not a v9 line: a dialect may not be mixed. let mixed = parse(b"edith 9\nsource 0 a.mp4\nsubtitle - subs.srt\n", &dir) .unwrap_err() @@ -1117,6 +1161,59 @@ mod tests { } } + /// The v11 line: the HDR rendition, written by name, read back as the very + /// preset -- and the dialect before it, which had no way to say one and + /// meant the published conversion. + #[test] + fn the_tone_map_round_trips_by_name_and_a_v10_file_is_the_reference_one() { + let dir = PathBuf::from("/proj"); + let (_, sources, lanes) = doc(); + for preset in crate::tonemap::Preset::ALL { + let bytes = super::emit( + &dir, + &sources, + &lanes, + &[], + &[], + &[], + &[], + (1280, 720), + None, + preset, + Limiter::default(), + 0, + ); + let text = String::from_utf8_lossy(&bytes).to_string(); + assert_eq!( + text.contains(&format!("tonemap {}\n", preset.name())), + preset != crate::tonemap::Preset::default(), + "the default is the line left out: {text}" + ); + assert_eq!(parse(&bytes, &dir).expect("v11 parses").tone, preset); + } + + // A v10 file is a project shown the published way, and re-saving it + // writes v11 with nothing more in it. + let v10 = b"edith 10\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ + video 1 0 0 30 0 - - - fit 1000\n"; + let old = parse(v10, &dir).expect("v10 still loads"); + assert_eq!(old.tone, crate::tonemap::Preset::Reference); + // ...and the line itself is not a v10 line: a dialect may not be mixed. + let mixed = parse(b"edith 10\nsource 0 a.mp4\ntonemap vivid\n", &dir) + .unwrap_err() + .to_string(); + assert_eq!(mixed, "line 3: unknown keyword \"tonemap\""); + // A rendition nobody wrote is a corrupt line, by name -- not a silent + // fall back to another picture. + for line in ["tonemap\n", "tonemap bright\n", "tonemap Vivid\n"] { + let file = format!("edith 11\nsource 0 a.mp4\n{line}"); + assert!( + parse(file.as_bytes(), &dir).is_err(), + "{line:?} is not a tonemap line" + ); + } + } + fn clip(start: u32, in_frame: u32, out_frame: u32, source: usize, link: Option) -> Clip { Clip { start, @@ -1177,7 +1274,7 @@ mod tests { let bytes = flat(&dir, &sources, &lanes, 12); assert_eq!( String::from_utf8_lossy(&bytes), - "edith 10\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\ + "edith 11\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\ source 2 /elsewhere/b.mp4\n\ video 1 0 0 30 0 0 - - fit 1000\nvideo 1 30 10 20 1 1 - - fit 1000\n\ audio 1 0 0 30 0 0 - - fit 1000\n", @@ -1214,7 +1311,7 @@ mod tests { let bytes = flat(&dir, &sources, &lanes, 7); assert_eq!( String::from_utf8_lossy(&bytes), - "edith 10\nplayhead 7\nresolution 1280 720\nsource 0 a.mp4\n\ + "edith 11\nplayhead 7\nresolution 1280 720\nsource 0 a.mp4\n\ video 1 0 0 30 0 4 - - fit 1000\naudio 1\n\ video 2 40 0 10 0 - - - fit 1000\naudio 2 0 0 30 0 4 - - fit 1000\n", "an empty lane is a line of its own; everything else is its clips" @@ -1322,7 +1419,7 @@ mod tests { let bytes = emit(&dir, &sources, &lanes, &eq, &[], (1280, 720), 0); assert_eq!( String::from_utf8_lossy(&bytes), - "edith 10\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ + "edith 11\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk\n\ eq 16777215.0:-0.1:3.918315e-39:hs\n\ eq\n\ @@ -1426,7 +1523,7 @@ mod tests { let bytes = emit(&dir, &sources, &lanes, &[], &color, (1280, 720), 0); assert_eq!( String::from_utf8_lossy(&bytes), - "edith 10\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ + "edith 11\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ color 0.1:1.2:0.9:-0.3\n\ color -1e-7:16777215.0:3.918315e-39:-0.0\n\ color 0.0:1.0:1.0:0.0\n\ @@ -1491,7 +1588,7 @@ mod tests { (1280, 720), old.playhead )), - "edith 10\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\ + "edith 11\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\ eq 80.0:-3.0:0.707:ls\n\ video 1 0 0 30 0 0 0 - fit 1000\naudio 1 0 0 30 0 0 - - fit 1000\n" ); @@ -1529,7 +1626,7 @@ mod tests { let bytes = emit(&dir, &sources, &lanes, &[], &[], (1280, 720), 0); assert_eq!( String::from_utf8_lossy(&bytes), - "edith 10\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ + "edith 11\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ video 1 0 0 30 0 - - - fit 2000\nvideo 1 15 30 40 0 - - - fit 250\n\ audio 1 0 0 30 0 - - - fit 2000\n", "the rate is the clip line's last field, in thousandths" @@ -1558,7 +1655,7 @@ mod tests { (1280, 720), old.playhead )), - "edith 10\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\ + "edith 11\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\ video 1 0 0 30 0 0 - - fit 1000\naudio 1 0 0 30 0 0 - - fit 1000\n" ); // A rate outside what the editor can set is a corrupt line, by name. @@ -1598,12 +1695,13 @@ mod tests { &[], (1280, 720), Some(23.976023976023978), + crate::tonemap::Preset::default(), limiter, 0, ); assert_eq!( String::from_utf8_lossy(&bytes), - "edith 10\nplayhead 0\nresolution 1280 720\nfps 23.976023976023978\n\ + "edith 11\nplayhead 0\nresolution 1280 720\nfps 23.976023976023978\n\ limiter -1.5 on\nsource 0 a.mp4\n\ video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n\ audio 2 0 0 30 0 - - - fit 1000\n\ @@ -1635,7 +1733,7 @@ mod tests { (1280, 720), old.playhead )), - "edith 10\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\ + "edith 11\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\ video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n" ); @@ -1799,7 +1897,7 @@ mod tests { assert!(old.eq.is_empty(), "nothing before v5 equalizes anything"); assert_eq!( String::from_utf8_lossy(&flat(&dir, &old.sources, &old.lanes, old.playhead)), - "edith 10\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\ + "edith 11\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\ source 2 /elsewhere/b.mp4\n\ video 1 0 0 30 0 0 - - fit 1000\nvideo 1 30 10 20 1 1 - - fit 1000\n\ audio 1 0 0 30 0 0 - - fit 1000\n" @@ -1852,7 +1950,7 @@ mod tests { let v5 = flat(&dir, &back.sources, &back.lanes, back.playhead); assert_eq!( String::from_utf8_lossy(&v5), - "edith 10\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\ + "edith 11\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\ source 0 /elsewhere/b.mp4\n\ video 1 0 0 30 0 0 - - fit 1000\nvideo 1 30 10 20 1 1 - - fit 1000\n\ audio 1 0 0 30 0 0 - - fit 1000\n", @@ -1884,7 +1982,7 @@ mod tests { // Saved again it is the current version, which round-trips to the // same document. let v5 = flat(&dir, &back.sources, &back.lanes, back.playhead); - assert!(v5.starts_with(b"edith 10\n")); + assert!(v5.starts_with(b"edith 11\n")); let again = parse(&v5, &dir).expect("v5 parses"); assert_eq!(again.lanes, back.lanes); // A dialect may not be mixed: lane lines under v1, `clip` under v2. @@ -1981,6 +2079,7 @@ mod tests { &[], (1280, 720), None, + crate::tonemap::Preset::default(), Limiter::default(), 0, ) @@ -1988,7 +2087,7 @@ mod tests { let bytes = std::fs::read(&path).expect("read back"); assert_eq!( String::from_utf8_lossy(&bytes), - "edith 10\nplayhead 0\nresolution 1280 720\nsource 1 a.mp4\n\ + "edith 11\nplayhead 0\nresolution 1280 720\nsource 1 a.mp4\n\ video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n" ); // Loading rejoins the *given* directory, so the file is reached by the @@ -2033,10 +2132,10 @@ mod tests { #[test] fn a_wrong_first_line_is_refused_by_name() { let dir = PathBuf::from("/proj"); - let err = parse(b"edith 11\nsource 0 a.mp4\nvideo 0 0 5 0 -\n", &dir) + let err = parse(b"edith 12\nsource 0 a.mp4\nvideo 0 0 5 0 -\n", &dir) .unwrap_err() .to_string(); - assert_eq!(err, "line 1: unsupported version 11"); + assert_eq!(err, "line 1: unsupported version 12"); for junk in [&b""[..], b"{}\n", b"source a.mp4\n"] { assert_eq!( parse(junk, &dir).unwrap_err().to_string(), diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index 304e281..3926cbf 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -969,12 +969,18 @@ fn run( // span reopens its file, so building it here rather than in the loop below // is the difference between paying that once and paying it per cut. An SDR // source -- the whole of an ordinary project -- builds no table at all. + // + // Through the project's own preset ([`tonemap::Preset`]), which is the same + // one playback's decode funnel builds its tables with: preview and export + // are the same rendition of the same film because they are told the same + // thing, not because two numbers happen to agree. + let preset = project.tone(); let tone: Vec> = rates .iter() .map(|(_, color)| match color.transfer { Transfer::Sdr => None, - Transfer::Pq => Some(ToneMapper::new(tonemap::Transfer::Pq)), - Transfer::Hlg => Some(ToneMapper::new(tonemap::Transfer::Hlg)), + Transfer::Pq => Some(ToneMapper::new(tonemap::Transfer::Pq, preset)), + Transfer::Hlg => Some(ToneMapper::new(tonemap::Transfer::Hlg, preset)), }) .collect(); // ...and the one space they are all written in, the same rule a reader with diff --git a/crates/engine/src/playback.rs b/crates/engine/src/playback.rs index 9dd6aa2..7573084 100644 --- a/crates/engine/src/playback.rs +++ b/crates/engine/src/playback.rs @@ -320,6 +320,9 @@ impl PlaybackSession { u32::MAX, ColorParams::default(), Composer::passthrough(), + // The default rendition: a file just opened is a project nobody has + // picked one for, exactly as it is a project nobody has graded. + crate::tonemap::Preset::default(), )?; // A file is opened on its first audio stream, like `Project::single` // names it: nothing has picked one yet. @@ -647,6 +650,10 @@ impl PlaybackSession { u32::MAX, ColorParams::default(), Composer::passthrough(), + // The saved rendition, from the document rather than from the + // project (which is built below): this placeholder is what the + // window shows until the `seek` at the end reopens the span. + doc.tone, ) .map_err(|e| format!("source {}: {e}", first.path.display()))?, }; @@ -784,6 +791,7 @@ impl PlaybackSession { .collect(); let project = Project::from_parts(doc.sources, doc.lanes, doc.eq, doc.color)? .with_mix(&doc.gains, doc.limiter) + .with_tone(doc.tone) .with_subtitles(subtitles); let span = project.composite_span_at(0); // Last, because it is the one thing here that cannot be taken back: the @@ -978,6 +986,10 @@ impl PlaybackSession { // says: a timeline of stills and songs used to come back at // whatever its scaffold implied (`open_project`). Some(self.meta.frame_rate), + // ...and which rendition its HDR media is watched in, for the same + // reason: a picked look that vanished on a reload is a look nobody + // could keep. + self.project.tone(), self.project.limiter(), playhead, ) @@ -1160,6 +1172,10 @@ impl PlaybackSession { self.meta.height, self.project.composite_fit_at(start), ), + // ...and the rendition an HDR source among them is mapped to, + // the project's own and constant across the span for that reason + // too. + self.project.tone(), ) .map(|(_, stream)| stream) .inspect_err(|e| eprintln!("timeline frame {start}: video open failed: {e}")), @@ -1648,6 +1664,33 @@ impl PlaybackSession { true } + /// Which HDR-to-SDR rendition this project is watched and exported in + /// ([`crate::tonemap::Preset`]) -- the reference one until somebody picks + /// another, and a setting on the project rather than on any clip. + pub fn tone(&self) -> crate::tonemap::Preset { + self.project.tone() + } + + /// Picks one. Rebuilds the **picture** where the playhead is, exactly as + /// [`set_resolution`](Self::set_resolution) does -- the frame on screen is + /// remapped at once, paused or playing, and the sound is not touched: a + /// rendition is not something a sample can carry. `false` for the rendition + /// already in force. + /// + /// An SDR project is unmoved by this by construction: no clip of it builds a + /// tone map at all ([`crate::tonemap`]), so the reseek recomposes the very + /// same bytes. + /// + /// ponytail: not an undo step, for the reason the resolution is not + /// ([`Project::set_tone`]). + pub fn set_tone(&mut self, preset: crate::tonemap::Preset) -> bool { + if !self.project.set_tone(preset) { + return false; + } + self.invalidate(Dirty::Picture); + true + } + /// The scaffolding source's own frame rate -- what the project rate started /// as, and the one rate a caller offering a list of them must not leave out /// ([`native_resolution`](Self::native_resolution)'s reason). @@ -2447,6 +2490,9 @@ fn matches_timeline( 0, ColorParams::default(), Composer::passthrough(), + // A zero-length range decodes nothing, so no table is built and the + // rendition cannot matter here. + crate::tonemap::Preset::default(), )?; // The frame rate is *not* a refusal any more: a file shot at another rate is // placed for the seconds it lasts and read through [`Rate`] at the diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index 381f66c..b3f650c 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -648,6 +648,10 @@ pub struct Project { /// project's resolution is a setting on the picture, and neither is an undo /// step. limiter: Limiter, + /// Which HDR-to-SDR rendition every clip on an HDR curve is shown and + /// exported in ([`crate::tonemap::Preset`]). A setting on the picture, like + /// the resolution, and not in the lane snapshots for the same reason. + tone: crate::tonemap::Preset, } impl Project { @@ -678,6 +682,7 @@ impl Project { next_link: 1, subtitles: Vec::new(), limiter: Limiter::default(), + tone: crate::tonemap::Preset::default(), } } @@ -787,6 +792,7 @@ impl Project { next_link, subtitles: Vec::new(), limiter: Limiter::default(), + tone: crate::tonemap::Preset::default(), }) } @@ -1154,6 +1160,35 @@ impl Project { self } + /// The HDR rendition a *load* puts back -- the same door + /// [`with_mix`](Project::with_mix) is, and no undo step for the same reason. + pub fn with_tone(mut self, preset: crate::tonemap::Preset) -> Self { + self.tone = preset; + self + } + + /// Which HDR-to-SDR rendition this project is watched and exported in. A + /// project setting, not a clip's: one picture, one look + /// ([`crate::tonemap::Preset`]). + pub fn tone(&self) -> crate::tonemap::Preset { + self.tone + } + + /// Sets it. `false` for the one already in force, which is what keeps a + /// re-pick of the current rendition from costing a reseek. + /// + /// ponytail: not an undo step, for the reason the limiter and the project + /// resolution are not -- it is not in the lane list the history snapshots. + /// Upgrade path is the same one: a history entry holding the project's own + /// settings beside the lanes. + pub fn set_tone(&mut self, preset: crate::tonemap::Preset) -> bool { + if self.tone == preset { + return false; + } + self.tone = preset; + true + } + /// The subtitle tracks a *load* puts back, in the order they were saved -- /// the same door [`with_mix`](Project::with_mix) is, and no undo step for /// the same reason. diff --git a/crates/engine/src/tonemap.rs b/crates/engine/src/tonemap.rs index a54c88b..826d9cb 100644 --- a/crates/engine/src/tonemap.rs +++ b/crates/engine/src/tonemap.rs @@ -17,7 +17,8 @@ //! 2. the transfer's EOTF -> display light in cd/m^2 (PQ per ST 2084, HLG per //! BT.2100 including its OOTF, which is why HLG costs almost nothing extra: //! it is one more EOTF feeding the same pipe), -//! 3. normalise by [`MASTER_NITS`] and take the 1/2.4 root -- Method A does its +//! 3. normalise by the assumed mastering peak ([`Preset`]) and take the 1/2.4 +//! root -- Method A does its //! work in a gamma-2.4 domain, not in linear light, //! 4. BT.2020 luma + colour differences in that domain, //! 5. the tone curve: a logarithmic lift keyed on the HDR peak, a three-piece @@ -35,9 +36,12 @@ //! Method A is conservative on mid-tones by construction: told the standard //! 1000 cd/m^2 mastering peak it puts 203-nit HDR diffuse white near SDR code //! 166 (about 40 cd/m^2), not at SDR white -- a picture a viewer reads as dark. -//! [`MASTER_NITS`] is the exposure knob that answers it: a lower assumed peak -//! lifts everything, and it is a constant here because this module is handed -//! pixels, never the stream metadata that would carry the real one. +//! The assumed peak is the exposure knob that answers it -- a lower one lifts +//! everything -- and *which* answer a project wants is a matter of taste, not of +//! correctness: a reference rendition and a vivid one are both honest pictures +//! of the same film. So it is a [`Preset`] the viewer picks rather than a +//! constant, and never the stream's own metadata, which this module is never +//! handed (it is given pixels). //! //! # Why a 3D LUT //! @@ -71,13 +75,6 @@ //! pixels is mapped in the same visit, sharing the block's bilinear chroma //! weights, which is what keeps a 4K frame inside a frame's time budget. -/// The mastering peak Method A is told to assume, cd/m^2. Not the 1000 an HDR10 -/// grade is mastered to and not BT.2446's own worked example: the goal here is -/// what a *viewer* sees on an SDR screen next to mpv, and told 1000 the method -/// lands 203-nit diffuse white on code 166, which reads as broadcast-dark. -/// Told 400 it lands near 205 -- display-referred, the brightness a player -/// shows -- which is what this constant buys. See the module note. -const MASTER_NITS: f32 = 400.0; /// The SDR display peak Method A targets, cd/m^2. const SDR_NITS: f32 = 100.0; /// Method A's working gamma. Not a display curve here -- it is the domain the @@ -99,6 +96,72 @@ const CHROMA_STEP: u32 = 4; /// `1 << CHROMA_STEP`. const CHROMA_FRAC: u32 = 16; +/// Which rendition of the same conversion a project is watching: two numbers, +/// the assumed mastering peak and a chroma gain, and *only* those two -- every +/// preset runs the very same BT.2446 Method A stages, so the hue relationships +/// the method is chosen for hold whichever one is picked. +/// +/// The peak is Method A's exposure knob (see the module note): told the 1000 +/// cd/m^2 an HDR10 grade is really mastered to, the published conversion lands +/// 203-nit diffuse white on code 166 -- broadcast-faithful, and darker than a +/// player looks; told a lower one it lifts the whole picture. The gain is +/// applied *after* the map, on the SDR colour differences, so it enriches the +/// picture a viewer is shown rather than bending a stage of the standard. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum Preset { + /// The published conversion, at the mastering peak the content really has. + /// The default: what the document says, and what a second reference can be + /// checked against. + #[default] + Reference, + /// Display-referred: the peak lowered to 400 so diffuse white lands near SDR + /// white and the picture reads as bright as a player shows it. + Standard, + /// Brighter again, and slightly richer -- the colour differences scaled up a + /// tenth after the map. + Vivid, +} + +impl Preset { + /// Every preset, in the order a list offers them: reference first, brightest + /// last. + pub const ALL: [Preset; 3] = [Preset::Reference, Preset::Standard, Preset::Vivid]; + + /// The mastering peak Method A is told to assume, cd/m^2. + pub fn master_nits(self) -> f32 { + match self { + Preset::Reference => 1000.0, + Preset::Standard => 400.0, + Preset::Vivid => 250.0, + } + } + + /// What the SDR colour differences are multiplied by after the map. `1.0` + /// leaves the method's own output untouched, byte for byte. + pub fn chroma_gain(self) -> f32 { + match self { + Preset::Reference | Preset::Standard => 1.0, + Preset::Vivid => 1.10, + } + } + + /// The name a project file carries ([`crate::edith`]) -- lower case, one + /// word, and the inverse of [`from_name`](Preset::from_name). + pub fn name(self) -> &'static str { + match self { + Preset::Reference => "reference", + Preset::Standard => "standard", + Preset::Vivid => "vivid", + } + } + + /// Reads one back. `None` for anything else, which a project file refuses by + /// name rather than silently rendering another way. + pub fn from_name(name: &[u8]) -> Option { + Preset::ALL.into_iter().find(|p| p.name().as_bytes() == name) + } +} + /// Which HDR transfer the incoming codes carry. Both feed the same Method A /// pipeline; they differ only in how a code becomes display light. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -126,7 +189,7 @@ pub struct ToneMapper { } impl ToneMapper { - pub fn new(transfer: Transfer) -> Self { + pub fn new(transfer: Transfer, preset: Preset) -> Self { let cells = LUMA_NODES * CHROMA_NODES * CHROMA_NODES; let (mut y_node, mut uv_node) = (vec![0u8; cells], vec![[0u8; 2]; cells]); for kv in 0..CHROMA_NODES { @@ -138,6 +201,7 @@ impl ToneMapper { // own. let out = map_code( transfer, + preset, (iy << LUMA_STEP) as f32, (ju << CHROMA_STEP) as f32, (kv << CHROMA_STEP) as f32, @@ -282,7 +346,8 @@ fn byte(value: f32) -> u8 { /// The whole float pipeline, from one triple of input codes to one triple of /// BT.709 limited-range output codes. Runs at build time only; the module note /// walks the stages. -fn map_code(transfer: Transfer, yc: f32, uc: f32, vc: f32) -> [f32; 3] { +fn map_code(transfer: Transfer, preset: Preset, yc: f32, uc: f32, vc: f32) -> [f32; 3] { + let master_nits = preset.master_nits(); // 1. limited-range BT.2020 Y'C'bC'r -> R'G'B' signal. let luma = (yc - 16.0) / 219.0; let cb = (uc - 128.0) / 224.0; @@ -303,14 +368,15 @@ fn map_code(transfer: Transfer, yc: f32, uc: f32, vc: f32) -> [f32; 3] { // Clamping instead walks a too-bright pixel toward white, which is what a // highlight past the display's reach should do. // - // ponytail: the ceiling is that MASTER_NITS is an exposure choice, not a - // measurement. Everything the content masters above it -- which at 400 is - // most of an HDR10 grade's highlight range -- walks to white here. The - // upgrade is the stream's own MaxCLL/mastering-display metadata reaching - // this module as a `new` argument, with 400 as the fallback: nothing else - // in the pipeline changes. - let lin = display_light(transfer, [r, g, b]); - let gam = lin.map(|c| (c / MASTER_NITS).clamp(0.0, 1.0).powf(1.0 / GAMMA)); + // ponytail: the ceiling is that the assumed peak is an exposure *choice* + // (now the viewer's, [`Preset`]), not a measurement. Everything the content + // masters above it -- which at 400 is most of an HDR10 grade's highlight + // range -- walks to white here. The upgrade is the stream's own + // MaxCLL/mastering-display metadata reaching this module beside the preset, + // as the measured ceiling the picked one is read against: nothing else in + // the pipeline changes. + let lin = display_light(transfer, preset, [r, g, b]); + let gam = lin.map(|c| (c / master_nits).clamp(0.0, 1.0).powf(1.0 / GAMMA)); // 4. BT.2020 luma and colour differences, in that domain. let y_hdr = 0.2627 * gam[0] + 0.6780 * gam[1] + 0.0593 * gam[2]; @@ -318,7 +384,7 @@ fn map_code(transfer: Transfer, yc: f32, uc: f32, vc: f32) -> [f32; 3] { let cr_hdr = (gam[0] - y_hdr) / 1.4746; // 5/6. the curve, then colour-difference scaling and its luma payback. - let y_sdr = tone_curve(y_hdr); + let y_sdr = tone_curve(y_hdr, master_nits); let scale = if y_hdr > 1e-6 { y_sdr / (1.075 * y_hdr) } else { @@ -342,29 +408,49 @@ fn map_code(transfer: Transfer, yc: f32, uc: f32, vc: f32) -> [f32; 3] { let b709 = (-0.0182 * r - 0.1006 * g + 1.1187 * b).clamp(0.0, 1.0); let [r, g, b] = [r709, g709, b709].map(|c| c.powf(1.0 / GAMMA)); - // 8. BT.709 limited-range codes. + // 8. BT.709 limited-range codes, the preset's chroma gain on the two colour + // differences. + // + // A *scale* about 128 and never a shift, applied here and nowhere earlier: + // 128 is neutral, so a grey stays exactly grey at any gain (`128 - 128` is + // zero however it is multiplied) and only a pixel that already had colour + // gets more of it. Clamped to the legal 16..240 chroma range, which at gain + // 1.0 is a clamp the maths above cannot reach -- the untouched presets come + // out byte for byte what Method A produced. let luma = 0.2126 * r + 0.7152 * g + 0.0722 * b; + let gain = preset.chroma_gain(); [ 16.0 + 219.0 * luma, - 128.0 + 224.0 * (b - luma) / 1.8556, - 128.0 + 224.0 * (r - luma) / 1.5748, + (128.0 + gain * 224.0 * (b - luma) / 1.8556).clamp(16.0, 240.0), + (128.0 + gain * 224.0 * (r - luma) / 1.5748).clamp(16.0, 240.0), ] } /// Signal -> display light in cd/m^2. -fn display_light(transfer: Transfer, rgb: [f32; 3]) -> [f32; 3] { +fn display_light(transfer: Transfer, preset: Preset, rgb: [f32; 3]) -> [f32; 3] { match transfer { Transfer::Pq => rgb.map(pq_eotf), Transfer::Hlg => { // BT.2100: inverse OETF to scene light, then the OOTF, whose system // gamma is 1.2 at a 1000 cd/m^2 display and follows the display - // peak from there by the standard's own log term -- so the peak - // [`MASTER_NITS`] names is the peak the OOTF is built for, rather - // than a number the constant silently invalidates. + // peak from there by the standard's own log term -- so the peak the + // preset names is the peak the OOTF is built for, rather than a + // number the choice silently invalidates. + let master_nits = preset.master_nits(); let scene = rgb.map(hlg_scene); let ys = 0.2627 * scene[0] + 0.6780 * scene[1] + 0.0593 * scene[2]; - let gamma = 1.2 + 0.42 * (MASTER_NITS / 1000.0).log10(); - let gain = MASTER_NITS * ys.max(0.0).powf(gamma - 1.0); + let gamma = 1.2 + 0.42 * (master_nits / 1000.0).log10(); + // Black is black, said outright rather than left to the arithmetic: + // below a 1000 cd/m^2 peak the system gamma is *under* 1, so the + // `ys^(gamma - 1)` term diverges as the scene goes black and the + // `0 * inf` that follows is a NaN -- which byte-casts to 0 and puts + // a hole where black belongs (measured: HLG black rendered code 0 + // under the vivid preset before this line). + let ys = ys.max(0.0); + let gain = match ys > 0.0 { + true => master_nits * ys.powf(gamma - 1.0), + false => 0.0, + }; scene.map(|c| gain * c) } } @@ -401,8 +487,8 @@ fn hlg_scene(e: f32) -> f32 { /// BT.2446 Method A's tone curve, in the gamma-2.4 domain: 1 in is 1 out (HDR /// peak to SDR peak) and 0 in is 0 out, which is what pins the two `p` terms /// and the three-piece polynomial between them. -fn tone_curve(y_hdr: f32) -> f32 { - let p_hdr = 1.0 + 32.0 * (MASTER_NITS / 10000.0).powf(1.0 / GAMMA); +fn tone_curve(y_hdr: f32, master_nits: f32) -> f32 { + let p_hdr = 1.0 + 32.0 * (master_nits / 10000.0).powf(1.0 / GAMMA); let p_sdr = 1.0 + 32.0 * (SDR_NITS / 10000.0).powf(1.0 / GAMMA); let yp = (1.0 + (p_hdr - 1.0) * y_hdr.max(0.0)).ln() / p_hdr.ln(); let yc = if yp <= 0.7399 { @@ -445,49 +531,89 @@ mod tests { } /// The anchors, in cd/m^2, against the codes the stages in the module note - /// give for [`MASTER_NITS`]. Black is pinned by the curve (0 in, 0 out); - /// [`MASTER_NITS`] itself is the assumed peak and must reach SDR white; - /// 203 nits is BT.2408 diffuse white, and 205 is where a 400 cd/m^2 peak - /// puts it -- a picture as bright as a player shows, which is the whole - /// reason that constant is not 1000 (where the same maths gives 166). The + /// give for each preset's assumed peak. Black is pinned by the curve (0 in, + /// 0 out); the assumed peak itself must reach SDR white; 203 nits is BT.2408 + /// diffuse white, and *where it lands is the whole difference between the + /// presets* -- 166 at the published 1000 cd/m^2 (broadcast-faithful, and the + /// reason the reference rendition reads dark), 205 at 400, 226 at 250. The /// day one of these moves, the transcription moved with it. /// - /// 1000 nits is the ceiling the `map_code` ponytail names, asserted rather - /// than described: everything above the assumed peak is white. + /// The last row of each is the ceiling the `map_code` ponytail names, + /// asserted rather than described: everything above the assumed peak is + /// white. #[test] fn pq_anchors_land_where_method_a_puts_them() { - let mapper = ToneMapper::new(Transfer::Pq); - for (nits, expected) in [ - (0.0, 16u8), - (26.0, 108), - (203.0, 205), - (MASTER_NITS, 235), - (1000.0, 235), + for (preset, diffuse) in [ + (Preset::Reference, 166u8), + (Preset::Standard, 205), + (Preset::Vivid, 226), ] { - let code = byte(pq_code(nits)); - let (y, _, _) = mapped(&mapper, code, 128, 128); - assert!( - y.abs_diff(expected) <= 3, - "{nits} cd/m^2 (code {code}) -> {y}, expected {expected}" - ); + let peak = preset.master_nits(); + let mapper = ToneMapper::new(Transfer::Pq, preset); + for (nits, expected) in [(0.0, 16u8), (203.0, diffuse), (peak, 235), (10000.0, 235)] { + let code = byte(pq_code(nits)); + let (y, _, _) = mapped(&mapper, code, 128, 128); + assert!( + y.abs_diff(expected) <= 3, + "{preset:?}: {nits} cd/m^2 (code {code}) -> {y}, expected {expected}" + ); + } } } + /// What the presets are *for*, on one code: brighter is brighter, and the + /// vivid one has more colour in it. A preset that renamed the same numbers + /// would pass every other test in this module and fail this one. + /// + /// The chroma reading is the distance from neutral, which is the thing the + /// gain scales; the grey beside it is the neutrality that must survive it, + /// so "richer" cannot have been bought with a tint. + #[test] + fn a_brighter_preset_is_brighter_and_a_vivid_one_is_richer() { + // BT.2408 diffuse white, and a saturated BT.2020 red beside it. + let (diffuse, red) = (byte(pq_code(203.0)), (100u8, 90u8, 200u8)); + let luma = |preset| mapped(&ToneMapper::new(Transfer::Pq, preset), diffuse, 128, 128).0; + let (reference, standard, vivid) = ( + luma(Preset::Reference), + luma(Preset::Standard), + luma(Preset::Vivid), + ); + assert!( + reference < standard && standard < vivid, + "reference {reference}, standard {standard}, vivid {vivid}" + ); + let colour = |preset| { + let (_, u, v) = mapped(&ToneMapper::new(Transfer::Pq, preset), red.0, red.1, red.2); + (u.abs_diff(128), v.abs_diff(128)) + }; + let (flat, rich) = (colour(Preset::Standard), colour(Preset::Vivid)); + // Both differences read together, and neither of them allowed to shrink: + // this red is saturated enough that its V is already against the legal + // 240 rail under both presets, so the gain has nowhere to take *that* + // one -- which is the clamp doing its job, not the gain failing to. + assert!( + rich.0 + rich.1 > flat.0 + flat.1 && rich.0 >= flat.0 && rich.1 >= flat.1, + "vivid's red {rich:?} is no further from neutral than standard's {flat:?}" + ); + } + /// On its nodes the grid is not an approximation at all: no interpolation /// runs, so the byte a picture gets is the byte the float pipeline /// computed. This is the half of the accuracy claim that is exact, and it /// covers every node of every axis for both transfers. #[test] fn the_grid_is_the_pipeline_on_its_nodes() { - for transfer in [Transfer::Pq, Transfer::Hlg] { - let mapper = ToneMapper::new(transfer); - for yc in (0..=248u8).step_by(1 << LUMA_STEP) { - for uc in (0..=240u8).step_by(1 << CHROMA_STEP) { - for vc in (0..=240u8).step_by(1 << CHROMA_STEP) { - let got = mapped(&mapper, yc, uc, vc); - let want = map_code(transfer, yc.into(), uc.into(), vc.into()); - let want = (byte(want[0]), byte(want[1]), byte(want[2])); - assert_eq!(got, want, "{transfer:?} node {yc}/{uc}/{vc}"); + for preset in Preset::ALL { + for transfer in [Transfer::Pq, Transfer::Hlg] { + let mapper = ToneMapper::new(transfer, preset); + for yc in (0..=248u8).step_by(1 << LUMA_STEP) { + for uc in (0..=240u8).step_by(1 << CHROMA_STEP) { + for vc in (0..=240u8).step_by(1 << CHROMA_STEP) { + let got = mapped(&mapper, yc, uc, vc); + let want = map_code(transfer, preset, yc.into(), uc.into(), vc.into()); + let want = (byte(want[0]), byte(want[1]), byte(want[2])); + assert_eq!(got, want, "{preset:?} {transfer:?} node {yc}/{uc}/{vc}"); + } } } } @@ -507,8 +633,13 @@ mod tests { /// pipeline steps. #[test] fn between_nodes_the_grid_stays_inside_its_own_cell() { - for transfer in [Transfer::Pq, Transfer::Hlg] { - let mapper = ToneMapper::new(transfer); + // Every preset, since the vivid one's chroma gain is a stage the nodes + // carry and the interpolation between them must not exaggerate. + for (transfer, preset) in [Transfer::Pq, Transfer::Hlg] + .into_iter() + .flat_map(|t| Preset::ALL.map(|p| (t, p))) + { + let mapper = ToneMapper::new(transfer, preset); for yc in (3..=255u8).step_by(23) { for uc in (5..=255u8).step_by(29) { for vc in (7..=255u8).step_by(31) { @@ -526,6 +657,7 @@ mod tests { for dv in [0.0, f32::from(1u8 << CHROMA_STEP)] { let out = map_code( transfer, + preset, node(yc, LUMA_STEP) + dy, node(uc, CHROMA_STEP) + du, node(vc, CHROMA_STEP) + dv, @@ -542,7 +674,7 @@ mod tests { // and the interpolation rounds once more. assert!( got[i] + 1 >= lo[i] && got[i] <= hi[i] + 1, - "{transfer:?} {name} at {yc}/{uc}/{vc}: {} outside {}..{}", + "{preset:?} {transfer:?} {name} at {yc}/{uc}/{vc}: {} outside {}..{}", got[i], lo[i], hi[i] @@ -559,14 +691,17 @@ mod tests { /// grid or a truncating interpolation produces. #[test] fn a_grey_ramp_never_inverts() { - for transfer in [Transfer::Pq, Transfer::Hlg] { - let mapper = ToneMapper::new(transfer); + for (transfer, preset) in [Transfer::Pq, Transfer::Hlg] + .into_iter() + .flat_map(|t| Preset::ALL.map(|p| (t, p))) + { + let mapper = ToneMapper::new(transfer, preset); let mut last = 0u8; for code in 0..=255u8 { let (y, _, _) = mapped(&mapper, code, 128, 128); assert!( y >= last, - "{transfer:?}: code {code} darkened to {y} < {last}" + "{preset:?} {transfer:?}: code {code} darkened to {y} < {last}" ); last = y; } @@ -574,16 +709,21 @@ mod tests { } /// Grey in, grey out: any chroma the pipeline invents on a neutral is a - /// tint across the whole picture. + /// tint across the whole picture -- and a chroma *gain* that was written as + /// a shift, or applied anywhere but about 128, is exactly that tint, which + /// is why the vivid preset is in this loop. #[test] fn neutral_input_stays_neutral() { - for transfer in [Transfer::Pq, Transfer::Hlg] { - let mapper = ToneMapper::new(transfer); + for (transfer, preset) in [Transfer::Pq, Transfer::Hlg] + .into_iter() + .flat_map(|t| Preset::ALL.map(|p| (t, p))) + { + let mapper = ToneMapper::new(transfer, preset); for code in (16..=235u8).step_by(7) { let (_, u, v) = mapped(&mapper, code, 128, 128); assert!( u.abs_diff(128) <= 2 && v.abs_diff(128) <= 2, - "{transfer:?}: grey {code} tinted to U{u} V{v}" + "{preset:?} {transfer:?}: grey {code} tinted to U{u} V{v}" ); } } @@ -596,27 +736,37 @@ mod tests { /// /// BT.2408 HLG diffuse white is signal 0.75, and it does *not* land on the /// PQ side's 203-nit code: relative is the point of HLG, so 0.75 is 19% of - /// whatever peak the display has -- 76 cd/m^2 of [`MASTER_NITS`]'s 400, - /// against PQ's absolute 203 -- and it comes out darker, at 170. That is - /// the standard's own behaviour and the number to watch: if the OOTF's - /// system gamma stops following the assumed peak, this is what moves. + /// whatever peak the display has -- 76 cd/m^2 of the standard preset's 400, + /// against PQ's absolute 203 -- and it comes out darker. That is the + /// standard's own behaviour and the number to watch: if the OOTF's system + /// gamma stops following the assumed peak, this is what moves, and it moves + /// per preset because the peak is what a preset picks. #[test] fn hlg_anchors_are_sane() { - let mapper = ToneMapper::new(Transfer::Hlg); - let code = |signal: f32| byte(16.0 + 219.0 * signal); - let (black, _, _) = mapped(&mapper, code(0.0), 128, 128); - let (diffuse, _, _) = mapped(&mapper, code(0.75), 128, 128); - let (white, _, _) = mapped(&mapper, code(1.0), 128, 128); - assert!(black.abs_diff(16) <= 3, "HLG black -> {black}"); - assert!(white.abs_diff(235) <= 3, "HLG peak -> {white}"); - assert!(diffuse.abs_diff(170) <= 3, "HLG diffuse white -> {diffuse}"); + for (preset, expected) in [ + (Preset::Reference, 170u8), + (Preset::Standard, 170), + (Preset::Vivid, 170), + ] { + let mapper = ToneMapper::new(Transfer::Hlg, preset); + let code = |signal: f32| byte(16.0 + 219.0 * signal); + let (black, _, _) = mapped(&mapper, code(0.0), 128, 128); + let (diffuse, _, _) = mapped(&mapper, code(0.75), 128, 128); + let (white, _, _) = mapped(&mapper, code(1.0), 128, 128); + assert!(black.abs_diff(16) <= 3, "{preset:?} HLG black -> {black}"); + assert!(white.abs_diff(235) <= 3, "{preset:?} HLG peak -> {white}"); + assert!( + diffuse.abs_diff(expected) <= 3, + "{preset:?} HLG diffuse white -> {diffuse}, expected {expected}" + ); + } } /// A short plane is left alone rather than half mapped, and a frame with no /// size at all returns instead of panicking on a zero-length band. #[test] fn a_frame_that_does_not_measure_up_is_untouched() { - let mapper = ToneMapper::new(Transfer::Pq); + let mapper = ToneMapper::new(Transfer::Pq, Preset::default()); let mut y = vec![128u8; 8 * 8 - 1]; let mut u = vec![128u8; 4 * 4]; let mut v = vec![128u8; 4 * 4]; @@ -631,7 +781,7 @@ mod tests { /// off the end. #[test] fn odd_sizes_map_every_pixel() { - let mapper = ToneMapper::new(Transfer::Pq); + let mapper = ToneMapper::new(Transfer::Pq, Preset::default()); let (w, h) = (7usize, 5usize); let mut y = vec![200u8; w * h]; let mut u = vec![128u8; w.div_ceil(2) * h.div_ceil(2)]; @@ -653,7 +803,7 @@ mod tests { /// time", and the reason a plain mean here would be a coin flip. #[test] fn perf_4k_and_1080p() { - let mapper = ToneMapper::new(Transfer::Pq); + let mapper = ToneMapper::new(Transfer::Pq, Preset::default()); for (w, h, budget) in [(3840usize, 1600usize, 25.0f64), (1920, 1080, 8.0)] { let mut y: Vec = (0..w * h).map(|i| (i % 256) as u8).collect(); let mut u: Vec = (0..w / 2 * h / 2).map(|i| (i % 256) as u8).collect(); diff --git a/crates/engine/tests/export_color.rs b/crates/engine/tests/export_color.rs index 65a7d56..ccdaac5 100644 --- a/crates/engine/tests/export_color.rs +++ b/crates/engine/tests/export_color.rs @@ -422,46 +422,57 @@ fn an_hdr_clip_is_tone_mapped_before_it_is_graded() { brightness: 0.25, ..Default::default() }; - let mut session = two_frames(&source); - assert!( - session.set_color(engine::project::Lane::V1, 0, Some(grade)), - "the grade went on the clip" - ); - let out = out_path("hdr_order", "mp4"); - export(&session, &out, Format::Mp4); - let got = raw_yuv(&out).expect("ffmpeg read the export"); + // Under both the default rendition and a picked one: an export that built + // its tables from anything but the project's own preset would sit on the + // wrong reference for the second pass, which is the whole preview-equals- + // export claim ([`tonemap::Preset`]). + for preset in [tonemap::Preset::default(), tonemap::Preset::Vivid] { + let mut session = two_frames(&source); + assert!( + session.set_color(engine::project::Lane::V1, 0, Some(grade)), + "the grade went on the clip" + ); + assert_eq!( + session.set_tone(preset), + preset != tonemap::Preset::default(), + "picking {preset:?}" + ); + let out = out_path("hdr_order", "mp4"); + export(&session, &out, Format::Mp4); + let got = raw_yuv(&out).expect("ffmpeg read the export"); - let (width, height) = (1280usize, 720usize); - let mapper = ToneMapper::new(tonemap::Transfer::Pq); - // The same bytes twice, through the two orders. Whichever way MASTER_NITS is - // set, both sides move with it -- what is asserted is which of them the - // export sits on, not where either lands. - let both = [true, false].map(|tone_first| { - let mut planes = src.clone(); - let (y, chroma) = planes.split_at_mut(width * height); - let (u, v) = chroma.split_at_mut(width * height / 4); - if tone_first { - mapper.map(y, u, v, width, height); - engine::color::apply_yuv(&grade, y, u, v); - } else { - engine::color::apply_yuv(&grade, y, u, v); - mapper.map(y, u, v, width, height); - } - planes - }); - let [ordered, swapped] = both.map(|planes| mean_abs_diff(&got, &planes)); - eprintln!( - "HDR export: {ordered:.2} off tone-map-then-grade, {swapped:.2} off the swapped order" - ); - assert!( - ordered < 3.0, - "the export is {ordered:.2} codes from tone-map-then-grade" - ); - assert!( - swapped > 3.0 * ordered, - "ordered {ordered:.2} vs swapped {swapped:.2}: the two orders are not far enough apart to have measured anything" - ); - std::fs::remove_file(&out).unwrap(); + let (width, height) = (1280usize, 720usize); + let mapper = ToneMapper::new(tonemap::Transfer::Pq, preset); + // The same bytes twice, through the two orders. Whichever preset is in + // force, both sides move with it -- what is asserted is which of them + // the export sits on, not where either lands. + let both = [true, false].map(|tone_first| { + let mut planes = src.clone(); + let (y, chroma) = planes.split_at_mut(width * height); + let (u, v) = chroma.split_at_mut(width * height / 4); + if tone_first { + mapper.map(y, u, v, width, height); + engine::color::apply_yuv(&grade, y, u, v); + } else { + engine::color::apply_yuv(&grade, y, u, v); + mapper.map(y, u, v, width, height); + } + planes + }); + let [ordered, swapped] = both.map(|planes| mean_abs_diff(&got, &planes)); + eprintln!( + "HDR export ({preset:?}): {ordered:.2} off tone-map-then-grade, {swapped:.2} off the swapped order" + ); + assert!( + ordered < 3.0, + "{preset:?}: the export is {ordered:.2} codes from tone-map-then-grade" + ); + assert!( + swapped > 3.0 * ordered, + "{preset:?}: ordered {ordered:.2} vs swapped {swapped:.2}: the two orders are not far enough apart to have measured anything" + ); + std::fs::remove_file(&out).unwrap(); + } } /// The real thing, where this machine has it: five seconds of a 4K HDR10 film, diff --git a/crates/engine/tests/hw_decode.rs b/crates/engine/tests/hw_decode.rs index 8eea7bc..2b1ca3f 100644 --- a/crates/engine/tests/hw_decode.rs +++ b/crates/engine/tests/hw_decode.rs @@ -246,7 +246,7 @@ fn the_hdr_film_renders_tone_mapped() { // The funnel's own budget at this size: the map plus the conversion, which // is what an HDR frame costs on top of the decode. Fastest of five, for the // reason `tonemap::perf_4k_and_1080p` documents. - let mapper = ToneMapper::new(Transfer::Pq); + let mapper = ToneMapper::new(Transfer::Pq, engine::tonemap::Preset::default()); let sdr = ColorDescription { matrix: Matrix::Bt709, transfer: engine::colorspace::Transfer::Sdr, diff --git a/crates/engine/tests/saveload.rs b/crates/engine/tests/saveload.rs index 9dcd533..4942563 100644 --- a/crates/engine/tests/saveload.rs +++ b/crates/engine/tests/saveload.rs @@ -206,7 +206,7 @@ fn a_version_1_project_loads_fully_grouped_and_saves_as_version_7() { let v2 = dir.join("new.edith"); loaded.save_project(&v2).expect("save"); let text = std::fs::read_to_string(&v2).expect("read back"); - assert!(text.starts_with("edith 10\n"), "{text}"); + assert!(text.starts_with("edith 11\n"), "{text}"); assert!( text.contains("\nresolution 1280 720\n"), "a project with no resolution of its own is saved at source 0's: {text}" @@ -294,7 +294,7 @@ fn a_version_4_project_holds_more_than_two_lanes() { loaded.save_project(&again).expect("save"); assert_eq!( std::fs::read_to_string(&again).expect("read back"), - "edith 10\nplayhead 0\nresolution 1280 720\nfps 30.0\nsource 0 test_av.mp4\n\ + "edith 11\nplayhead 0\nresolution 1280 720\nfps 30.0\nsource 0 test_av.mp4\n\ video 1 0 0 30 0 3 - - fit 1000\naudio 1\n\ video 2 40 0 20 0 - - - fit 1000\naudio 2 0 0 30 0 3 - - fit 1000\n", "a four-lane project is written as it was read, three versions on" @@ -324,7 +324,7 @@ fn a_version_5_project_carries_per_clip_equalizers() { loaded.save_project(&again).expect("save"); assert_eq!( std::fs::read_to_string(&again).expect("read back"), - "edith 10\nplayhead 0\nresolution 1280 720\nfps 30.0\nsource 0 test_av.mp4\n\ + "edith 11\nplayhead 0\nresolution 1280 720\nfps 30.0\nsource 0 test_av.mp4\n\ eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk\n\ eq 12000.0:6.25:0.5:hs\n\ video 1 0 0 30 0 - 0 - fit 1000\nvideo 1 30 30 60 0 - 1 - fit 1000\n\ @@ -359,7 +359,7 @@ fn a_version_6_project_carries_per_clip_colours() { loaded.save_project(&again).expect("save"); assert_eq!( std::fs::read_to_string(&again).expect("read back"), - "edith 10\nplayhead 0\nresolution 1280 720\nfps 30.0\nsource 0 test_av.mp4\n\ + "edith 11\nplayhead 0\nresolution 1280 720\nfps 30.0\nsource 0 test_av.mp4\n\ eq 80.0:-3.0:0.707:ls\n\ color 0.1:1.2:0.9:-0.3\n\ color -0.25:1.0:0.0:0.5\n\ @@ -409,7 +409,7 @@ fn a_version_7_project_carries_a_resolution_and_fit_policies() { loaded.save_project(&again).expect("save"); assert_eq!( std::fs::read_to_string(&again).expect("read back"), - "edith 10\nplayhead 0\nresolution 960 720\nfps 30.0\nsource 0 test_av.mp4\n\ + "edith 11\nplayhead 0\nresolution 960 720\nfps 30.0\nsource 0 test_av.mp4\n\ video 1 0 0 30 0 - - - fill 1000\nvideo 1 30 30 60 0 - - - center 1000\n\ audio 1 0 0 60 0 - - - fit 1000\n", "a v7 project is written back as the v8 it now is: the same clips, each \ @@ -667,7 +667,7 @@ fn malformed_files_are_numbered_errors_and_never_panics() { for (text, want) in [ ( - "edith 11\nsource 0 test_av.mp4\nvideo 1 0 0 30 0 - - - fit\n", + "edith 12\nsource 0 test_av.mp4\nvideo 1 0 0 30 0 - - - fit\n", "line 1", ), // An eq index the table does not hold, and a band shape there is none. @@ -793,6 +793,48 @@ fn the_mix_survives_a_save_and_an_open() { ); } +/// The v11 bump's own round trip: the HDR rendition a project was left in comes +/// back with it, and a file written before there were any is the reference one. +/// A picked look that vanished on a reload would be a setting nobody could keep +/// -- the mix test's claim, for the picture. +#[test] +fn the_tone_map_preset_survives_a_save_and_an_open() { + use engine::tonemap::Preset; + let dir = scratch("tone"); + let source = copy_in(&dir, "test_av.mp4"); + let mut saved = PlaybackSession::open(&source).expect("open the fixture"); + assert_eq!(saved.tone(), Preset::Reference, "nobody has picked yet"); + assert!(saved.set_tone(Preset::Vivid)); + let path = dir.join("tone.edith"); + saved.save_project(&path).expect("save"); + + let mut loaded = PlaybackSession::open_project(&path).expect("open the project"); + assert_eq!(loaded.tone(), Preset::Vivid); + assert!(!loaded.undo(), "a loaded rendition is not an undo step"); + // ...and saving it again is the same bytes, as the mix is. + let again = dir.join("again.edith"); + loaded + .save_project(&again) + .expect("save the loaded project"); + assert_eq!( + std::fs::read(&path).unwrap(), + std::fs::read(&again).unwrap(), + "save -> load -> save is not a fixed point" + ); + + // A project written before v11 says nothing about a rendition, and means the + // published one -- the picture it was always shown in. + let old = dir.join("old.edith"); + std::fs::write( + &old, + "edith 10\nplayhead 0\nresolution 1920 1080\nsource 0 test_av.mp4\n\ + video 1 0 0 24 0 - - - fit 1000\naudio 1 0 0 24 0 - - - fit 1000\n", + ) + .expect("write a v10 project"); + let older = PlaybackSession::open_project(&old).expect("open the v10 project"); + assert_eq!(older.tone(), Preset::Reference); +} + /// The other half of the v9 bump, and the debt it pays: a timeline holding /// nothing but a song has no file to take a frame rate from, so it used to come /// back at the canvas rate whatever it was cut at. The written `fps` is now diff --git a/crates/engine/tests/silence.rs b/crates/engine/tests/silence.rs index 86ed132..6c67bf6 100644 --- a/crates/engine/tests/silence.rs +++ b/crates/engine/tests/silence.rs @@ -370,13 +370,14 @@ fn scanning_a_clip_and_cutting_what_it_finds() { &color, (1920, 1080), None, + p.tone(), p.limiter(), 0, ) .expect("save"); let text = std::fs::read_to_string(&file).expect("read it back"); assert!( - text.starts_with("edith 10"), + text.starts_with("edith 11"), "{:?}", &text[..16.min(text.len())] ); diff --git a/crates/engine/tests/tonemap_render.rs b/crates/engine/tests/tonemap_render.rs index b6e6307..e38ad02 100644 --- a/crates/engine/tests/tonemap_render.rs +++ b/crates/engine/tests/tonemap_render.rs @@ -22,7 +22,7 @@ use engine::color::{ColorParams, apply_yuv}; use engine::colorspace::{ColorDescription, Matrix, Transfer}; use engine::convert::i420_to_bgra; use engine::project::Lane; -use engine::tonemap::{ToneMapper, Transfer as Hdr}; +use engine::tonemap::{Preset, ToneMapper, Transfer as Hdr}; /// The fixture's patches: the source codes, and where the centre of each one /// sits in the 320x240 picture. @@ -99,7 +99,7 @@ fn spread(px: [u8; 3]) -> u8 { /// to render it: tone-mapped first, then graded, then converted as BT.709 SDR. /// `grade` is applied in whichever domain `before` says -- which is the point of /// [`the_grade_lands_after_the_tone_map`]. -fn by_hand(codes: [u8; 3], grade: &ColorParams, before: bool) -> [u8; 3] { +fn by_hand(codes: [u8; 3], grade: &ColorParams, before: bool, preset: Preset) -> [u8; 3] { let (w, h) = (8usize, 8usize); let mut y = vec![codes[0]; w * h]; let mut u = vec![codes[1]; w / 2 * h / 2]; @@ -107,7 +107,7 @@ fn by_hand(codes: [u8; 3], grade: &ColorParams, before: bool) -> [u8; 3] { if before { apply_yuv(grade, &mut y, &mut u, &mut v); } - ToneMapper::new(Hdr::Pq).map(&mut y, &mut u, &mut v, w, h); + ToneMapper::new(Hdr::Pq, preset).map(&mut y, &mut u, &mut v, w, h); if !before { apply_yuv(grade, &mut y, &mut u, &mut v); } @@ -116,10 +116,12 @@ fn by_hand(codes: [u8; 3], grade: &ColorParams, before: bool) -> [u8; 3] { } /// The claim itself: a PQ stream is shown as an SDR display can show it. -/// Diffuse white lands where a viewer expects white-ish paper (~205, not the -/// 144 an untouched code would convert to and not clipped white), the 1000 -/// cd/m^2 highlight stays a highlight, and the saturated red is still red -- -/// a grey wash is exactly what the missing map looked like. +/// Diffuse white lands where BT.2446 Method A puts it at the mastering peak the +/// content really has (~166, not the 144 an untouched code would convert to and +/// not clipped white -- the reference rendition, which is what a project nobody +/// has picked for is shown in), the 1000 cd/m^2 highlight stays a highlight, and +/// the saturated red is still red -- a grey wash is exactly what the missing map +/// looked like. #[test] fn a_pq_stream_is_tone_mapped_on_its_way_to_the_window() { let mut session = open("test_pq.mp4"); @@ -135,8 +137,8 @@ fn a_pq_stream_is_tone_mapped_on_its_way_to_the_window() { let diffuse = luma_code(pixel(&frame, DIFFUSE.1)); assert!( - (200..=210).contains(&diffuse), - "diffuse white (code {}) rendered at {diffuse}, wanted 200..=210", + (161..=171).contains(&diffuse), + "diffuse white (code {}) rendered at {diffuse}, wanted 161..=171", DIFFUSE.0[0] ); let highlight = luma_code(pixel(&frame, HIGHLIGHT.1)); @@ -151,6 +153,56 @@ fn a_pq_stream_is_tone_mapped_on_its_way_to_the_window() { ); } +/// The preset is a thing a viewer *sees*: picked on the running session, the +/// very next frame out of the funnel is the new rendition, and the three are in +/// the order their names promise -- reference darkest, vivid brightest and +/// richest. Measured on the rendered BGRA the window gets, so it covers the +/// whole chain (project setting -> reseek -> decode worker -> LUT), not the +/// table alone. +#[test] +fn picking_a_preset_changes_the_picture_the_window_shows() { + let mut session = open("test_pq.mp4"); + assert_eq!(session.tone(), Preset::Reference, "nobody has picked yet"); + let mut shown = Vec::new(); + for preset in Preset::ALL { + if preset != Preset::Reference { + assert!(session.set_tone(preset), "pick {preset:?}"); + assert!(!session.set_tone(preset), "picking it again changes nothing"); + } + let frame = next_frame(&mut session, "a preset"); + // Still a picture, not a wash: the fixture's saturated red has to stay + // red under every rendition, which is what a mistuned preset breaks + // first. + assert!(spread(pixel(&frame, RED.1)) > 60, "{preset:?} washed the red out"); + shown.push(luma_code(pixel(&frame, DIFFUSE.1))); + } + let [reference, standard, vivid] = [shown[0], shown[1], shown[2]]; + assert!( + reference < standard && standard < vivid, + "diffuse white by preset: reference {reference}, standard {standard}, vivid {vivid}" + ); + // The vivid preset's *chroma* gain is asserted on the codes rather than + // here: this fixture's red is saturated enough that it clips to 255 in BGRA + // under both presets, so a rendered patch cannot measure it + // (`tonemap::tests::a_brighter_preset_is_brighter_and_a_vivid_one_is_richer`). +} + +/// ...and an SDR stream is not any of this: no clip of it builds a tone map at +/// all, so all three presets are the same bytes. The hash is the passthrough +/// branch's own, from the test below -- if a preset ever reached an SDR picture, +/// this is where it would show. +#[test] +fn an_sdr_stream_is_the_same_bytes_under_every_preset() { + let mut session = open("test_h264.mkv"); + for preset in Preset::ALL { + if preset != Preset::Reference { + assert!(session.set_tone(preset), "pick {preset:?}"); + } + let frame = next_frame(&mut session, "a preset"); + assert_eq!(fnv(&frame.bgra), SDR_PASSTHROUGH, "{preset:?} moved an SDR picture"); + } +} + /// The other half: an SDR stream may not move by one byte for any of this. /// Both branches of the funnel -- the fused passthrough conversion and the /// graded-then-placed one -- against hashes measured before the tone map was @@ -204,8 +256,8 @@ fn the_grade_lands_after_the_tone_map() { for (name, patch) in [("diffuse white", DIFFUSE), ("red", RED)] { let shown = pixel(&frame, patch.1); - let after = by_hand(patch.0, &grade, false); - let before = by_hand(patch.0, &grade, true); + let after = by_hand(patch.0, &grade, false, Preset::default()); + let before = by_hand(patch.0, &grade, true, Preset::default()); for (i, channel) in ["B", "G", "R"].iter().enumerate() { assert!( shown[i].abs_diff(after[i]) <= 2,