forge
Explore
Log in

Don't you dare go Hollow

The HDR rendition is a row you pick, not a constant someone chose for you

Browse files at this commit

09671f738a7594a9c7388914c80a395997d29a2bAhmet Kaan GümüşParent: 7744ff1
  • feat
    • the HDR rendition is a row you pick, not a constant someone chose for you
Show full message
✨ feat(tonemap): the HDR rendition is a row you pick, not a constant someone chose for you

BT.2446 Method A's assumed mastering peak was a constant in the module: 400
cd/m^2, one exposure decided for everybody. It 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 becomes a project setting with three renditions through
the very same curve, which is what keeps the hues right whichever is picked:

  Reference  1000 nits, chroma 1.0   the published conversion (diffuse white 166)
  Standard    400 nits, chroma 1.0   display-referred, as bright as a player
  Vivid       250 nits, chroma 1.10  brightest, and a tenth more colour

The chroma gain is a scale about 128 in the SDR codes, after the map and clamped
to the legal range: a grey stays exactly grey at any gain, and at 1.0 it is a
clamp the maths cannot reach, so the other two presets are byte for byte what
Method A produced. HLG's OOTF gain is guarded at black -- below a 1000 cd/m^2
peak the system gamma is under 1, and the 0 * inf that follows byte-cast to 0
and put a hole where black belongs.

The preset lives on the Project beside the limiter (a setting, not an undo step),
reaches the decode workers and the export through the same value, and is saved as
a `tonemap` line in edith 11 -- left out when it is the default, so a project
holding no HDR media is the bytes it was, and a v10 file loads as the reference
rendition, which is the only one it ever had. Picking one rebuilds the picture
under the playhead the way a resize does; an SDR project is unmoved.

The panel names it beside the resolution and the rate -- the third thing that is
the project's rather than the media's -- and a click opens the three renditions
with the one in force marked. No stroke: this is a list to look at.
crates/app/src/main.rsmodified+99 -2
@@ -17,6 +17,7 @@ use engine::export::{AUDIO_KBPS, DEFAULT_AUDIO_KBPS, ExportSettings, Format};
17 use engine::limiter::Limiter;17 use engine::limiter::Limiter;
18 use engine::project::{Edge, Lane, LaneKind, Source, Speed};18 use engine::project::{Edge, Lane, LaneKind, Source, Speed};
19 use engine::scale::FitPolicy;19 use engine::scale::FitPolicy;
20+use engine::tonemap::Preset;
20 use engine::{Clip, Codec, ExportHandle, Frame, PlaybackSession};21 use engine::{Clip, Codec, ExportHandle, Frame, PlaybackSession};
21 use gpui::{22 use gpui::{
22 AnyElement, App, Application, Bounds, ClickEvent, Context, CursorStyle, Div, DragMoveEvent,23 AnyElement, App, Application, Bounds, ClickEvent, Context, CursorStyle, Div, DragMoveEvent,
@@ -458,6 +459,10 @@ enum Pick {
458 /// What the export's *sound* is coded at. Opened from the card's Sound row,459 /// What the export's *sound* is coded at. Opened from the card's Sound row,
459 /// which is the only place it means anything.460 /// which is the only place it means anything.
460 AudioRate,461 AudioRate,
462+ /// Which HDR-to-SDR rendition the project is watched and exported in
463+ /// ([`engine::tonemap::Preset`]). Opened from the panel, beside the two
464+ /// other settings that are the project's rather than the media's.
465+ Tone,
461 }466 }
462 467
463 /// One value a list offers, carrying everything picking it needs -- so a click468 /// One value a list offers, carrying everything picking it needs -- so a click
@@ -472,6 +477,7 @@ enum Choice {
472 Fps(f64),477 Fps(f64),
473 Fit(Lane, usize, FitPolicy),478 Fit(Lane, usize, FitPolicy),
474 AudioRate(u32),479 AudioRate(u32),
480+ Tone(Preset),
475 }481 }
476 482
477 /// One row of an open list: the value, its name, the small print beside it, and483 /// One row of an open list: the value, its name, the small print beside it, and
@@ -1778,6 +1784,22 @@ impl Player {
1778 cx.notify();1784 cx.notify();
1779 }1785 }
1780 1786
1787+ /// The project's HDR media shown another way: the list names a rendition and
1788+ /// this is where it happens, the way [`apply_resolution`](Self::apply_resolution)
1789+ /// is for a size. The engine remaps the frame under the playhead at once
1790+ /// ([`PlaybackSession::set_tone`]), so the picture on screen is the picked
1791+ /// one before the notice has faded -- and an SDR project is unmoved, which
1792+ /// is what the notice says rather than pretending something happened.
1793+ fn apply_tone(&mut self, preset: Preset, cx: &mut Context<Self>) {
1794+ if let Some(session) = &mut self.session
1795+ && session.set_tone(preset)
1796+ {
1797+ self.notice = Some(format!("HDR: {} — affects HDR media", tone_label(preset)).into());
1798+ self.reset_after_reseek();
1799+ }
1800+ cx.notify();
1801+ }
1802+
1781 /// Opens a choice list on a setting, where it was asked for. One floating1803 /// Opens a choice list on a setting, where it was asked for. One floating
1782 /// thing at a time: the click that opens it is the click that closes1804 /// thing at a time: the click that opens it is the click that closes
1783 /// whatever menu it was opened from.1805 /// whatever menu it was opened from.
@@ -1797,6 +1819,7 @@ impl Player {
1797 Choice::Size(w, h) => self.apply_resolution(w, h, cx),1819 Choice::Size(w, h) => self.apply_resolution(w, h, cx),
1798 Choice::Fps(fps) => self.apply_frame_rate(fps, cx),1820 Choice::Fps(fps) => self.apply_frame_rate(fps, cx),
1799 Choice::Fit(lane, idx, fit) => self.apply_fit(lane, idx, fit, cx),1821 Choice::Fit(lane, idx, fit) => self.apply_fit(lane, idx, fit, cx),
1822+ Choice::Tone(preset) => self.apply_tone(preset, cx),
1800 // The same field the row's key steps, set outright: a list picks a1823 // The same field the row's key steps, set outright: a list picks a
1801 // value, it does not step to one.1824 // value, it does not step to one.
1802 Choice::AudioRate(kbps) => {1825 Choice::AudioRate(kbps) => {
@@ -1822,6 +1845,7 @@ impl Player {
1822 fit_choices(lane, idx, session.fit_of(lane, idx), session.resolution())1845 fit_choices(lane, idx, session.fit_of(lane, idx), session.resolution())
1823 }1846 }
1824 Pick::AudioRate => audio_rate_choices(self.audio_kbps),1847 Pick::AudioRate => audio_rate_choices(self.audio_kbps),
1848+ Pick::Tone => tone_choices(session.tone()),
1825 }1849 }
1826 }1850 }
1827 1851
@@ -5937,6 +5961,30 @@ impl Player {
5937 this.open_picker(Pick::Fps, event.position(), cx)5961 this.open_picker(Pick::Fps, event.position(), cx)
5938 }),5962 }),
5939 ))5963 ))
5964+ // ...and which rendition its HDR media is watched in, the
5965+ // third thing that is the project's rather than the media's.
5966+ // Listed whatever is on the timeline, and the tooltip says
5967+ // who it acts on: a control that came and went with the
5968+ // media would be one nobody could find when they wanted it.
5969+ .child(control(
5970+ "tonemap",
5971+ None,
5972+ match &self.session {
5973+ Some(session) => format!("HDR {}", tone_label(session.tone())),
5974+ None => "HDR".to_string(),
5975+ },
5976+ match &self.session {
5977+ Some(session) => format!(
5978+ "click to pick the HDR rendition — the project is {}; SDR media is untouched",
5979+ tone_label(session.tone())
5980+ ),
5981+ None => "the HDR rendition — open a file first".to_string(),
5982+ },
5983+ live,
5984+ cx.listener(|this, event: &ClickEvent, _, cx| {
5985+ this.open_picker(Pick::Tone, event.position(), cx)
5986+ }),
5987+ ))
5940 // How much of the timeline the panel below is showing --5988 // How much of the timeline the panel below is showing --
5941 // beside the resolution, since neither of them edits5989 // beside the resolution, since neither of them edits
5942 // anything: they are both what is being looked at. The5990 // anything: they are both what is being looked at. The
@@ -10704,6 +10752,40 @@ fn audio_rate_choices(current: u32) -> Vec<ChoiceRow> {
10704 .collect()10752 .collect()
10705 }10753 }
10706 10754
10755+/// How a rendition is named where a person reads it: the panel button, the
10756+/// notice and the list row all say the same word ([`engine::tonemap::Preset`]).
10757+fn tone_label(preset: Preset) -> &'static str {
10758+ match preset {
10759+ Preset::Reference => "Reference",
10760+ Preset::Standard => "Standard",
10761+ Preset::Vivid => "Vivid",
10762+ }
10763+}
10764+
10765+/// The HDR list's rows: all three renditions, the one in force marked, and what
10766+/// each one *is* beside it -- in the fewest words that fit inside `MENU_W`, the
10767+/// truncation the three lists above already met. Always offered, whatever is on
10768+/// the timeline: a setting that appeared and vanished with the media would be a
10769+/// setting nobody could find, and the row says who it acts on instead.
10770+fn tone_choices(current: Preset) -> Vec<ChoiceRow> {
10771+ Preset::ALL
10772+ .into_iter()
10773+ .map(|preset| {
10774+ (
10775+ Choice::Tone(preset),
10776+ tone_label(preset).into(),
10777+ match preset {
10778+ Preset::Reference => "BT.2446-A, as published",
10779+ Preset::Standard => "brighter, player-like",
10780+ Preset::Vivid => "brightest, richer colour",
10781+ }
10782+ .into(),
10783+ preset == current,
10784+ )
10785+ })
10786+ .collect()
10787+}
10788+
10707 /// The next project resolution after `current`, over [`RESOLUTIONS`] with the10789 /// The next project resolution after `current`, over [`RESOLUTIONS`] with the
10708 /// media's own size cycled in at its place by size -- so the trip round always10790 /// media's own size cycled in at its place by size -- so the trip round always
10709 /// comes back to the media, whatever odd shape it is, and a project already at a10791 /// comes back to the media, whatever odd shape it is, and a project already at a
@@ -12278,12 +12360,13 @@ mod tests {
12278 whole_take, window_title,12360 whole_take, window_title,
12279 };12361 };
12280 use super::{12362 use super::{
12281- Choice, ETA_SPAN, Edge, FITS, FRAME_RATES, LaneKind, PPS_DEFAULT, RESOLUTIONS, Repeat,12363+ Choice, ETA_SPAN, Edge, FITS, FRAME_RATES, LaneKind, PPS_DEFAULT, Preset, RESOLUTIONS, Repeat,
12282 Scale, View,12364 Scale, View,
12283 ZOOM_MAX_SECONDS, ZOOM_MIN_FRAMES, ZOOM_STEP, audio_rate_choices, clock, eta_secs, file_name, file_uri,12365 ZOOM_MAX_SECONDS, ZOOM_MIN_FRAMES, ZOOM_STEP, audio_rate_choices, clock, eta_secs, file_name, file_uri,
12284 fit_choices, landing, lane_refuses, library_rows, live_idx, next_fit, next_resolution,12366 fit_choices, landing, lane_refuses, library_rows, live_idx, next_fit, next_resolution,
12285 note_progress, px_along,12367 note_progress, px_along,
12286- repeats, resolution_choices, resolution_ladder, span_label, trimmed_clip, unscannable,12368+ repeats, resolution_choices, resolution_ladder, span_label, tone_choices, tone_label,
12369+ trimmed_clip, unscannable,
12287 visible_slice,12370 visible_slice,
12288 };12371 };
12289 use super::{12372 use super::{
@@ -15305,6 +15388,20 @@ mod tests {
15305 assert!(detail.chars().count() < 26, "{detail} loses its tail");15388 assert!(detail.chars().count() < 26, "{detail} loses its tail");
15306 }15389 }
15307 15390
15391+ // The HDR list, the third project setting: all three renditions in the
15392+ // order they brighten, the one in force marked, and every row saying
15393+ // what it is in words that fit beside the label.
15394+ let tones = tone_choices(Preset::Standard);
15395+ assert_eq!(tones.len(), Preset::ALL.len());
15396+ assert_eq!(tones.iter().filter(|(.., picked)| *picked).count(), 1);
15397+ for (row, preset) in tones.iter().zip(Preset::ALL) {
15398+ assert_eq!(row.0, Choice::Tone(preset));
15399+ assert_eq!(row.1.as_ref(), tone_label(preset));
15400+ assert!(!row.2.is_empty(), "{preset:?} says nothing about itself");
15401+ assert!(row.2.chars().count() < 26, "{} loses its tail", row.2);
15402+ }
15403+ assert!(tones[1].3, "the rendition in force is not marked");
15404+
15308 // The open list fits the floor the menus are measured against: the15405 // The open list fits the floor the menus are measured against: the
15309 // longest of them is the rate ladder with an odd rate cycled in, and it15406 // longest of them is the rate ladder with an odd rate cycled in, and it
15310 // hangs at the pointer with every row on screen. Rows are click targets15407 // hangs at the pointer with every row on screen. Rows are click targets
crates/engine/src/decode.rsmodified+29 -5
@@ -236,6 +236,9 @@ impl DecodeSession {
236 // No project, no canvas: the file-level API hands back the236 // No project, no canvas: the file-level API hands back the
237 // pictures the file holds, at the size it holds them.237 // pictures the file holds, at the size it holds them.
238 Composer::passthrough(),238 Composer::passthrough(),
239+ // ...and no project means no picked rendition either: an HDR file
240+ // opened through this door is mapped the published way.
241+ tonemap::Preset::default(),
239 )?;242 )?;
240 // The public API hands out the flag alone, so the worker is detached and243 // The public API hands out the flag alone, so the worker is detached and
241 // the receiver goes to the caller: nothing here joins anything.244 // the receiver goes to the caller: nothing here joins anything.
@@ -324,7 +327,16 @@ impl DecodeSession {
324 // BT.601 limited, because that is what `rgb_to_i420` above wrote these327 // BT.601 limited, because that is what `rgb_to_i420` above wrote these
325 // planes in: a still round-trips through the pair, not through the328 // planes in: a still round-trips through the pair, not through the
326 // colour of whatever file is on the timeline beside it.329 // colour of whatever file is on the timeline beside it.
327- let first = Render::new(color, ColorDescription::default(), canvas).frame(330+ // No preset argument, and none wanted: a still is decoded into BT.601
331+ // SDR planes, so the tone map is not built at all whichever rendition
332+ // the project is watching.
333+ let first = Render::new(
334+ color,
335+ ColorDescription::default(),
336+ canvas,
337+ tonemap::Preset::default(),
338+ )
339+ .frame(
328 start_frame,340 start_frame,
329 &still.y,341 &still.y,
330 &still.u,342 &still.u,
@@ -375,12 +387,18 @@ impl DecodeSession {
375 /// frames come out at *that* size, whatever the file's is. A387 /// frames come out at *that* size, whatever the file's is. A
376 /// [`Composer::passthrough`] (or one already the source's size) leaves every388 /// [`Composer::passthrough`] (or one already the source's size) leaves every
377 /// picture exactly as it was decoded.389 /// picture exactly as it was decoded.
390+ ///
391+ /// `tone` is the project's HDR rendition ([`tonemap::Preset`]), captured
392+ /// here for the reason the grade is: it is constant across one span, and a
393+ /// preset picked while this worker runs reaches the picture when the session
394+ /// reseeks onto the new one. An SDR source ignores it entirely.
378 pub(crate) fn open_worker(395 pub(crate) fn open_worker(
379 path: impl AsRef<Path>,396 path: impl AsRef<Path>,
380 start_frame: u32,397 start_frame: u32,
381 end_frame: u32,398 end_frame: u32,
382 color: ColorParams,399 color: ColorParams,
383 canvas: Composer,400 canvas: Composer,
401+ tone: tonemap::Preset,
384 ) -> crate::Result<(VideoMeta, FrameStream)> {402 ) -> crate::Result<(VideoMeta, FrameStream)> {
385 let path = path.as_ref().to_path_buf();403 let path = path.as_ref().to_path_buf();
386 let (meta, demuxer) = Demuxer::open(&path)?;404 let (meta, demuxer) = Demuxer::open(&path)?;
@@ -430,7 +448,7 @@ impl DecodeSession {
430 if worker_cancel.load(Ordering::Relaxed) {448 if worker_cancel.load(Ordering::Relaxed) {
431 return;449 return;
432 }450 }
433- let mut render = Render::new(color, source_color, canvas);451+ let mut render = Render::new(color, source_color, canvas, tone);
434 // The plugin has to be opened on the thread that uses it: its452 // The plugin has to be opened on the thread that uses it: its
435 // VA-API state is not `Send`-safe across a later hand-off.453 // VA-API state is not `Send`-safe across a later hand-off.
436 if let Some(hw) = open_hw(&path, start_frame) {454 if let Some(hw) = open_hw(&path, start_frame) {
@@ -518,7 +536,12 @@ const TONE_MAPPED: ColorDescription = ColorDescription {
518 };536 };
519 537
520 impl Render {538 impl Render {
521- fn new(color: ColorParams, desc: ColorDescription, canvas: Composer) -> Self {539+ fn new(
540+ color: ColorParams,
541+ desc: ColorDescription,
542+ canvas: Composer,
543+ preset: tonemap::Preset,
544+ ) -> Self {
522 Self {545 Self {
523 color,546 color,
524 desc,547 desc,
@@ -530,8 +553,8 @@ impl Render {
530 // range argument to `ToneMapper::new`.553 // range argument to `ToneMapper::new`.
531 tone: match desc.transfer {554 tone: match desc.transfer {
532 Transfer::Sdr => None,555 Transfer::Sdr => None,
533- Transfer::Pq => Some(ToneMapper::new(tonemap::Transfer::Pq)),556+ Transfer::Pq => Some(ToneMapper::new(tonemap::Transfer::Pq, preset)),
534- Transfer::Hlg => Some(ToneMapper::new(tonemap::Transfer::Hlg)),557+ Transfer::Hlg => Some(ToneMapper::new(tonemap::Transfer::Hlg, preset)),
535 },558 },
536 graded: (Vec::new(), Vec::new(), Vec::new()),559 graded: (Vec::new(), Vec::new(), Vec::new()),
537 }560 }
@@ -800,6 +823,7 @@ mod tests {
800 u32::MAX,823 u32::MAX,
801 ColorParams::default(),824 ColorParams::default(),
802 Composer::passthrough(),825 Composer::passthrough(),
826+ tonemap::Preset::default(),
803 )827 )
804 .expect("open");828 .expect("open");
805 // Nothing is ever received: two frames fill the channel and the next829 // Nothing is ever received: two frames fill the channel and the next
crates/engine/src/edith.rsmodified+125 -26
@@ -1,10 +1,11 @@
1 //! The project file: a line of text per thing, and nothing else.1 //! The project file: a line of text per thing, and nothing else.
2 //!2 //!
3 //! ```text3 //! ```text
4-//! edith 104+//! edith 11
5 //! playhead 905 //! playhead 90
6 //! resolution 1920 10806 //! resolution 1920 1080
7 //! fps 30.07 //! fps 30.0
8+//! tonemap vivid
8 //! limiter -1.0 on9 //! limiter -1.0 on
9 //! source 0 test_av.mp410 //! source 0 test_av.mp4
10 //! source 1 /elsewhere/test_av2.mp411 //! source 1 /elsewhere/test_av2.mp4
@@ -37,6 +38,12 @@
37 //! since the save comes back listed and refused by name rather than dropped,38 //! since the save comes back listed and refused by name rather than dropped,
38 //! which is what keeps a re-save from losing it.39 //! which is what keeps a re-save from losing it.
39 //!40 //!
41+//! The `tonemap` line is which HDR-to-SDR rendition the project is watched and
42+//! exported in ([`crate::tonemap::Preset`]), spelled `reference`, `standard` or
43+//! `vivid`. Left out when it is the default, which is `reference` -- so a
44+//! project holding no HDR media, and one whose owner never picked, are the bytes
45+//! they were.
46+//!
40 //! The `limiter` line is the master limiter over the whole mix47 //! The `limiter` line is the master limiter over the whole mix
41 //! ([`crate::limiter`]): its ceiling in dBFS and whether it is in circuit,48 //! ([`crate::limiter`]): its ceiling in dBFS and whether it is in circuit,
42 //! spelled `on` or `off`. Left out when it is the default, which is off.49 //! spelled `on` or `off`. Left out when it is the default, which is off.
@@ -93,7 +100,9 @@
93 //! is the only way an empty lane could still be there on the way back. A lane100 //! is the only way an empty lane could still be there on the way back. A lane
94 //! number may not skip one of its kind.101 //! number may not skip one of its kind.
95 //!102 //!
96-//! **Version 9** was this without the `subtitle` lines: such a project shows no103+//! **Version 10** was this without the `tonemap` line: such a project is shown
104+//! in the reference rendition, which is the only one there was.
105+//! **Version 9** was that without the `subtitle` lines: such a project shows no
97 //! subtitles, which is all any project could do.106 //! subtitles, which is all any project could do.
98 //! **Version 8** was that without the `fps` and `limiter` lines and without107 //! **Version 8** was that without the `fps` and `limiter` lines and without
99 //! the `gain` ones: such a project mixes every lane at unity, limits nothing,108 //! the `gain` ones: such a project mixes every lane at unity, limits nothing,
@@ -113,8 +122,9 @@
113 //! cumulatively and copied onto both lanes as one group each, which is exactly122 //! cumulatively and copied onto both lanes as one group each, which is exactly
114 //! what a v1 timeline meant, and an older file simply equalizes and grades123 //! what a v1 timeline meant, and an older file simply equalizes and grades
115 //! nothing, and an older one plays everything at real time, and an older one124 //! nothing, and an older one plays everything at real time, and an older one
116-//! mixes flat, and an older one shows no subtitles -- and saving any of them125+//! mixes flat, and an older one shows no subtitles, and an older one is shown
117-//! writes v10. An older reader refuses a newer file by name.126+//! in the reference rendition -- and saving any of them writes v11. An older
127+//! reader refuses a newer file by name.
118 //!128 //!
119 //! Text because an edit list is a few integers and a path, and a path is129 //! Text because an edit list is a few integers and a path, and a path is
120 //! *bytes* on this platform -- a JSON string would have to lossily decode one.130 //! *bytes* on this platform -- a JSON string would have to lossily decode one.
@@ -149,7 +159,8 @@ use crate::subtitle::SubtitleTrack;
149 159
150 /// What [`save`] writes. Read support goes back to `edith 1`; see the module160 /// What [`save`] writes. Read support goes back to `edith 1`; see the module
151 /// docs for what those dialects looked like.161 /// docs for what those dialects looked like.
152-const MAGIC: &[u8] = b"edith 10";162+const MAGIC: &[u8] = b"edith 11";
163+const MAGIC_V10: &[u8] = b"edith 10";
153 const MAGIC_V9: &[u8] = b"edith 9";164 const MAGIC_V9: &[u8] = b"edith 9";
154 const MAGIC_V8: &[u8] = b"edith 8";165 const MAGIC_V8: &[u8] = b"edith 8";
155 const MAGIC_V7: &[u8] = b"edith 7";166 const MAGIC_V7: &[u8] = b"edith 7";
@@ -198,6 +209,11 @@ pub struct Document {
198 /// songs has no answer for (see209 /// songs has no answer for (see
199 /// [`crate::PlaybackSession::open_project`]).210 /// [`crate::PlaybackSession::open_project`]).
200 pub fps: Option<f64>,211 pub fps: Option<f64>,
212+ /// The HDR-to-SDR rendition every clip on an HDR curve is shown in.
213+ /// [`crate::tonemap::Preset::Reference`] for every dialect before v11 and
214+ /// for a v11 file that leaves the line out, which both mean the published
215+ /// conversion -- the only one those projects had.
216+ pub tone: crate::tonemap::Preset,
201 pub playhead: u32,217 pub playhead: u32,
202 }218 }
203 219
@@ -216,6 +232,7 @@ pub fn save(
216 color: &[ColorParams],232 color: &[ColorParams],
217 resolution: (u32, u32),233 resolution: (u32, u32),
218 fps: Option<f64>,234 fps: Option<f64>,
235+ tone: crate::tonemap::Preset,
219 limiter: Limiter,236 limiter: Limiter,
220 playhead: u32,237 playhead: u32,
221 ) -> crate::Result<()> {238 ) -> crate::Result<()> {
@@ -230,8 +247,8 @@ pub fn save(
230 let result = std::fs::File::create(&part)247 let result = std::fs::File::create(&part)
231 .and_then(|mut f| {248 .and_then(|mut f| {
232 f.write_all(&emit(249 f.write_all(&emit(
233- &dir, sources, lanes, gains, subtitles, eq, color, resolution, fps, limiter,250+ &dir, sources, lanes, gains, subtitles, eq, color, resolution, fps, tone,
234- playhead,251+ limiter, playhead,
235 ))?;252 ))?;
236 f.sync_all()253 f.sync_all()
237 })254 })
@@ -273,6 +290,7 @@ fn emit(
273 color: &[ColorParams],290 color: &[ColorParams],
274 resolution: (u32, u32),291 resolution: (u32, u32),
275 fps: Option<f64>,292 fps: Option<f64>,
293+ tone: crate::tonemap::Preset,
276 limiter: Limiter,294 limiter: Limiter,
277 playhead: u32,295 playhead: u32,
278 ) -> Vec<u8> {296 ) -> Vec<u8> {
@@ -286,6 +304,12 @@ fn emit(
286 if let Some(fps) = fps.filter(|f| f.is_finite() && *f > 0.0) {304 if let Some(fps) = fps.filter(|f| f.is_finite() && *f > 0.0) {
287 out.extend_from_slice(format!("fps {fps:?}\n").as_bytes());305 out.extend_from_slice(format!("fps {fps:?}\n").as_bytes());
288 }306 }
307+ // Beside the rate, and written only when it is not the default: a project
308+ // holding no HDR media has nothing to say here, and saying nothing is what
309+ // a v10 file already said.
310+ if tone != crate::tonemap::Preset::default() {
311+ out.extend_from_slice(format!("tonemap {}\n", tone.name()).as_bytes());
312+ }
289 // Written only when it is not the default, so a project nobody has limited313 // Written only when it is not the default, so a project nobody has limited
290 // is the same bytes it was in v8 bar the version line.314 // is the same bytes it was in v8 bar the version line.
291 if limiter != Limiter::default() {315 if limiter != Limiter::default() {
@@ -415,8 +439,10 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> {
415 // The dialects that wrote a source line without its stream field. Reading439 // The dialects that wrote a source line without its stream field. Reading
416 // one is the whole of what "an old project still opens" means here.440 // one is the whole of what "an old project still opens" means here.
417 let streamless = v1 || first == MAGIC_V2;441 let streamless = v1 || first == MAGIC_V2;
418- // The one that carries subtitle tracks...442+ // The one that carries an HDR rendition...
419- let v10 = first == MAGIC;443+ let v11 = first == MAGIC;
444+ // ...the ones that carry subtitle tracks...
445+ let v10 = v11 || first == MAGIC_V10;
420 // ...the ones that carry the mix -- lane volumes, the master limiter and446 // ...the ones that carry the mix -- lane volumes, the master limiter and
421 // the rate the timeline was cut at...447 // the rate the timeline was cut at...
422 let v9 = v10 || first == MAGIC_V9;448 let v9 = v10 || first == MAGIC_V9;
@@ -456,9 +482,11 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> {
456 // ...and nothing before v9 carries a mix or a rate: every lane at unity,482 // ...and nothing before v9 carries a mix or a rate: every lane at unity,
457 // no limiter, and the rate inferred from the scaffold as it always was.483 // no limiter, and the rate inferred from the scaffold as it always was.
458 gains: Vec::new(),484 gains: Vec::new(),
459- // Nothing before v10 shows a subtitle.485+ // Nothing before v10 shows a subtitle, and nothing before v11 was shown
486+ // in any rendition but the published one.
460 subtitles: Vec::new(),487 subtitles: Vec::new(),
461 limiter: Limiter::default(),488 limiter: Limiter::default(),
489+ tone: crate::tonemap::Preset::default(),
462 fps: None,490 fps: None,
463 playhead: 0,491 playhead: 0,
464 };492 };
@@ -515,6 +543,20 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> {
515 })?;543 })?;
516 doc.fps = Some(fps);544 doc.fps = Some(fps);
517 }545 }
546+ b"tonemap" if v11 => {
547+ if !doc.sources.is_empty() {
548+ return Err(
549+ format!("line {n}: tonemap belongs once, before the sources").into(),
550+ );
551+ }
552+ let f = fields(rest, 1, "tonemap", n)?;
553+ doc.tone = crate::tonemap::Preset::from_name(f[0]).ok_or_else(|| {
554+ format!(
555+ "line {n}: {:?} is not a tone map",
556+ String::from_utf8_lossy(f[0])
557+ )
558+ })?;
559+ }
518 b"limiter" if v9 => {560 b"limiter" if v9 => {
519 if !doc.sources.is_empty() {561 if !doc.sources.is_empty() {
520 return Err(562 return Err(
@@ -1033,6 +1075,7 @@ mod tests {
1033 color,1075 color,
1034 resolution,1076 resolution,
1035 None,1077 None,
1078+ crate::tonemap::Preset::default(),
1036 Limiter::default(),1079 Limiter::default(),
1037 playhead,1080 playhead,
1038 )1081 )
@@ -1073,6 +1116,7 @@ mod tests {
1073 &[],1116 &[],
1074 (1280, 720),1117 (1280, 720),
1075 None,1118 None,
1119+ crate::tonemap::Preset::default(),
1076 Limiter::default(),1120 Limiter::default(),
1077 0,1121 0,
1078 );1122 );
@@ -1101,7 +1145,7 @@ mod tests {
1101 video 1 0 0 30 0 - - - fit 1000\n";1145 video 1 0 0 30 0 - - - fit 1000\n";
1102 let old = parse(v9, &dir).expect("v9 still loads");1146 let old = parse(v9, &dir).expect("v9 still loads");
1103 assert_eq!(old.subtitles, Vec::new());1147 assert_eq!(old.subtitles, Vec::new());
1104- assert!(flat(&dir, &old.sources, &old.lanes, old.playhead).starts_with(b"edith 10\n"));1148+ assert!(flat(&dir, &old.sources, &old.lanes, old.playhead).starts_with(b"edith 11\n"));
1105 // ...and the line itself is not a v9 line: a dialect may not be mixed.1149 // ...and the line itself is not a v9 line: a dialect may not be mixed.
1106 let mixed = parse(b"edith 9\nsource 0 a.mp4\nsubtitle - subs.srt\n", &dir)1150 let mixed = parse(b"edith 9\nsource 0 a.mp4\nsubtitle - subs.srt\n", &dir)
1107 .unwrap_err()1151 .unwrap_err()
@@ -1117,6 +1161,59 @@ mod tests {
1117 }1161 }
1118 }1162 }
1119 1163
1164+ /// The v11 line: the HDR rendition, written by name, read back as the very
1165+ /// preset -- and the dialect before it, which had no way to say one and
1166+ /// meant the published conversion.
1167+ #[test]
1168+ fn the_tone_map_round_trips_by_name_and_a_v10_file_is_the_reference_one() {
1169+ let dir = PathBuf::from("/proj");
1170+ let (_, sources, lanes) = doc();
1171+ for preset in crate::tonemap::Preset::ALL {
1172+ let bytes = super::emit(
1173+ &dir,
1174+ &sources,
1175+ &lanes,
1176+ &[],
1177+ &[],
1178+ &[],
1179+ &[],
1180+ (1280, 720),
1181+ None,
1182+ preset,
1183+ Limiter::default(),
1184+ 0,
1185+ );
1186+ let text = String::from_utf8_lossy(&bytes).to_string();
1187+ assert_eq!(
1188+ text.contains(&format!("tonemap {}\n", preset.name())),
1189+ preset != crate::tonemap::Preset::default(),
1190+ "the default is the line left out: {text}"
1191+ );
1192+ assert_eq!(parse(&bytes, &dir).expect("v11 parses").tone, preset);
1193+ }
1194+
1195+ // A v10 file is a project shown the published way, and re-saving it
1196+ // writes v11 with nothing more in it.
1197+ let v10 = b"edith 10\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
1198+ video 1 0 0 30 0 - - - fit 1000\n";
1199+ let old = parse(v10, &dir).expect("v10 still loads");
1200+ assert_eq!(old.tone, crate::tonemap::Preset::Reference);
1201+ // ...and the line itself is not a v10 line: a dialect may not be mixed.
1202+ let mixed = parse(b"edith 10\nsource 0 a.mp4\ntonemap vivid\n", &dir)
1203+ .unwrap_err()
1204+ .to_string();
1205+ assert_eq!(mixed, "line 3: unknown keyword \"tonemap\"");
1206+ // A rendition nobody wrote is a corrupt line, by name -- not a silent
1207+ // fall back to another picture.
1208+ for line in ["tonemap\n", "tonemap bright\n", "tonemap Vivid\n"] {
1209+ let file = format!("edith 11\nsource 0 a.mp4\n{line}");
1210+ assert!(
1211+ parse(file.as_bytes(), &dir).is_err(),
1212+ "{line:?} is not a tonemap line"
1213+ );
1214+ }
1215+ }
1216+
1120 fn clip(start: u32, in_frame: u32, out_frame: u32, source: usize, link: Option<u32>) -> Clip {1217 fn clip(start: u32, in_frame: u32, out_frame: u32, source: usize, link: Option<u32>) -> Clip {
1121 Clip {1218 Clip {
1122 start,1219 start,
@@ -1177,7 +1274,7 @@ mod tests {
1177 let bytes = flat(&dir, &sources, &lanes, 12);1274 let bytes = flat(&dir, &sources, &lanes, 12);
1178 assert_eq!(1275 assert_eq!(
1179 String::from_utf8_lossy(&bytes),1276 String::from_utf8_lossy(&bytes),
1180- "edith 10\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\1277+ "edith 11\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\
1181 source 2 /elsewhere/b.mp4\n\1278 source 2 /elsewhere/b.mp4\n\
1182 video 1 0 0 30 0 0 - - fit 1000\nvideo 1 30 10 20 1 1 - - fit 1000\n\1279 video 1 0 0 30 0 0 - - fit 1000\nvideo 1 30 10 20 1 1 - - fit 1000\n\
1183 audio 1 0 0 30 0 0 - - fit 1000\n",1280 audio 1 0 0 30 0 0 - - fit 1000\n",
@@ -1214,7 +1311,7 @@ mod tests {
1214 let bytes = flat(&dir, &sources, &lanes, 7);1311 let bytes = flat(&dir, &sources, &lanes, 7);
1215 assert_eq!(1312 assert_eq!(
1216 String::from_utf8_lossy(&bytes),1313 String::from_utf8_lossy(&bytes),
1217- "edith 10\nplayhead 7\nresolution 1280 720\nsource 0 a.mp4\n\1314+ "edith 11\nplayhead 7\nresolution 1280 720\nsource 0 a.mp4\n\
1218 video 1 0 0 30 0 4 - - fit 1000\naudio 1\n\1315 video 1 0 0 30 0 4 - - fit 1000\naudio 1\n\
1219 video 2 40 0 10 0 - - - fit 1000\naudio 2 0 0 30 0 4 - - fit 1000\n",1316 video 2 40 0 10 0 - - - fit 1000\naudio 2 0 0 30 0 4 - - fit 1000\n",
1220 "an empty lane is a line of its own; everything else is its clips"1317 "an empty lane is a line of its own; everything else is its clips"
@@ -1322,7 +1419,7 @@ mod tests {
1322 let bytes = emit(&dir, &sources, &lanes, &eq, &[], (1280, 720), 0);1419 let bytes = emit(&dir, &sources, &lanes, &eq, &[], (1280, 720), 0);
1323 assert_eq!(1420 assert_eq!(
1324 String::from_utf8_lossy(&bytes),1421 String::from_utf8_lossy(&bytes),
1325- "edith 10\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\1422+ "edith 11\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
1326 eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk\n\1423 eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk\n\
1327 eq 16777215.0:-0.1:3.918315e-39:hs\n\1424 eq 16777215.0:-0.1:3.918315e-39:hs\n\
1328 eq\n\1425 eq\n\
@@ -1426,7 +1523,7 @@ mod tests {
1426 let bytes = emit(&dir, &sources, &lanes, &[], &color, (1280, 720), 0);1523 let bytes = emit(&dir, &sources, &lanes, &[], &color, (1280, 720), 0);
1427 assert_eq!(1524 assert_eq!(
1428 String::from_utf8_lossy(&bytes),1525 String::from_utf8_lossy(&bytes),
1429- "edith 10\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\1526+ "edith 11\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
1430 color 0.1:1.2:0.9:-0.3\n\1527 color 0.1:1.2:0.9:-0.3\n\
1431 color -1e-7:16777215.0:3.918315e-39:-0.0\n\1528 color -1e-7:16777215.0:3.918315e-39:-0.0\n\
1432 color 0.0:1.0:1.0:0.0\n\1529 color 0.0:1.0:1.0:0.0\n\
@@ -1491,7 +1588,7 @@ mod tests {
1491 (1280, 720),1588 (1280, 720),
1492 old.playhead1589 old.playhead
1493 )),1590 )),
1494- "edith 10\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\1591+ "edith 11\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\
1495 eq 80.0:-3.0:0.707:ls\n\1592 eq 80.0:-3.0:0.707:ls\n\
1496 video 1 0 0 30 0 0 0 - fit 1000\naudio 1 0 0 30 0 0 - - fit 1000\n"1593 video 1 0 0 30 0 0 0 - fit 1000\naudio 1 0 0 30 0 0 - - fit 1000\n"
1497 );1594 );
@@ -1529,7 +1626,7 @@ mod tests {
1529 let bytes = emit(&dir, &sources, &lanes, &[], &[], (1280, 720), 0);1626 let bytes = emit(&dir, &sources, &lanes, &[], &[], (1280, 720), 0);
1530 assert_eq!(1627 assert_eq!(
1531 String::from_utf8_lossy(&bytes),1628 String::from_utf8_lossy(&bytes),
1532- "edith 10\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\1629+ "edith 11\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
1533 video 1 0 0 30 0 - - - fit 2000\nvideo 1 15 30 40 0 - - - fit 250\n\1630 video 1 0 0 30 0 - - - fit 2000\nvideo 1 15 30 40 0 - - - fit 250\n\
1534 audio 1 0 0 30 0 - - - fit 2000\n",1631 audio 1 0 0 30 0 - - - fit 2000\n",
1535 "the rate is the clip line's last field, in thousandths"1632 "the rate is the clip line's last field, in thousandths"
@@ -1558,7 +1655,7 @@ mod tests {
1558 (1280, 720),1655 (1280, 720),
1559 old.playhead1656 old.playhead
1560 )),1657 )),
1561- "edith 10\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\1658+ "edith 11\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\
1562 video 1 0 0 30 0 0 - - fit 1000\naudio 1 0 0 30 0 0 - - fit 1000\n"1659 video 1 0 0 30 0 0 - - fit 1000\naudio 1 0 0 30 0 0 - - fit 1000\n"
1563 );1660 );
1564 // A rate outside what the editor can set is a corrupt line, by name.1661 // A rate outside what the editor can set is a corrupt line, by name.
@@ -1598,12 +1695,13 @@ mod tests {
1598 &[],1695 &[],
1599 (1280, 720),1696 (1280, 720),
1600 Some(23.976023976023978),1697 Some(23.976023976023978),
1698+ crate::tonemap::Preset::default(),
1601 limiter,1699 limiter,
1602 0,1700 0,
1603 );1701 );
1604 assert_eq!(1702 assert_eq!(
1605 String::from_utf8_lossy(&bytes),1703 String::from_utf8_lossy(&bytes),
1606- "edith 10\nplayhead 0\nresolution 1280 720\nfps 23.976023976023978\n\1704+ "edith 11\nplayhead 0\nresolution 1280 720\nfps 23.976023976023978\n\
1607 limiter -1.5 on\nsource 0 a.mp4\n\1705 limiter -1.5 on\nsource 0 a.mp4\n\
1608 video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n\1706 video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n\
1609 audio 2 0 0 30 0 - - - fit 1000\n\1707 audio 2 0 0 30 0 - - - fit 1000\n\
@@ -1635,7 +1733,7 @@ mod tests {
1635 (1280, 720),1733 (1280, 720),
1636 old.playhead1734 old.playhead
1637 )),1735 )),
1638- "edith 10\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\1736+ "edith 11\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\
1639 video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n"1737 video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n"
1640 );1738 );
1641 1739
@@ -1799,7 +1897,7 @@ mod tests {
1799 assert!(old.eq.is_empty(), "nothing before v5 equalizes anything");1897 assert!(old.eq.is_empty(), "nothing before v5 equalizes anything");
1800 assert_eq!(1898 assert_eq!(
1801 String::from_utf8_lossy(&flat(&dir, &old.sources, &old.lanes, old.playhead)),1899 String::from_utf8_lossy(&flat(&dir, &old.sources, &old.lanes, old.playhead)),
1802- "edith 10\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\1900+ "edith 11\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\
1803 source 2 /elsewhere/b.mp4\n\1901 source 2 /elsewhere/b.mp4\n\
1804 video 1 0 0 30 0 0 - - fit 1000\nvideo 1 30 10 20 1 1 - - fit 1000\n\1902 video 1 0 0 30 0 0 - - fit 1000\nvideo 1 30 10 20 1 1 - - fit 1000\n\
1805 audio 1 0 0 30 0 0 - - fit 1000\n"1903 audio 1 0 0 30 0 0 - - fit 1000\n"
@@ -1852,7 +1950,7 @@ mod tests {
1852 let v5 = flat(&dir, &back.sources, &back.lanes, back.playhead);1950 let v5 = flat(&dir, &back.sources, &back.lanes, back.playhead);
1853 assert_eq!(1951 assert_eq!(
1854 String::from_utf8_lossy(&v5),1952 String::from_utf8_lossy(&v5),
1855- "edith 10\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\1953+ "edith 11\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\
1856 source 0 /elsewhere/b.mp4\n\1954 source 0 /elsewhere/b.mp4\n\
1857 video 1 0 0 30 0 0 - - fit 1000\nvideo 1 30 10 20 1 1 - - fit 1000\n\1955 video 1 0 0 30 0 0 - - fit 1000\nvideo 1 30 10 20 1 1 - - fit 1000\n\
1858 audio 1 0 0 30 0 0 - - fit 1000\n",1956 audio 1 0 0 30 0 0 - - fit 1000\n",
@@ -1884,7 +1982,7 @@ mod tests {
1884 // Saved again it is the current version, which round-trips to the1982 // Saved again it is the current version, which round-trips to the
1885 // same document.1983 // same document.
1886 let v5 = flat(&dir, &back.sources, &back.lanes, back.playhead);1984 let v5 = flat(&dir, &back.sources, &back.lanes, back.playhead);
1887- assert!(v5.starts_with(b"edith 10\n"));1985+ assert!(v5.starts_with(b"edith 11\n"));
1888 let again = parse(&v5, &dir).expect("v5 parses");1986 let again = parse(&v5, &dir).expect("v5 parses");
1889 assert_eq!(again.lanes, back.lanes);1987 assert_eq!(again.lanes, back.lanes);
1890 // A dialect may not be mixed: lane lines under v1, `clip` under v2.1988 // A dialect may not be mixed: lane lines under v1, `clip` under v2.
@@ -1981,6 +2079,7 @@ mod tests {
1981 &[],2079 &[],
1982 (1280, 720),2080 (1280, 720),
1983 None,2081 None,
2082+ crate::tonemap::Preset::default(),
1984 Limiter::default(),2083 Limiter::default(),
1985 0,2084 0,
1986 )2085 )
@@ -1988,7 +2087,7 @@ mod tests {
1988 let bytes = std::fs::read(&path).expect("read back");2087 let bytes = std::fs::read(&path).expect("read back");
1989 assert_eq!(2088 assert_eq!(
1990 String::from_utf8_lossy(&bytes),2089 String::from_utf8_lossy(&bytes),
1991- "edith 10\nplayhead 0\nresolution 1280 720\nsource 1 a.mp4\n\2090+ "edith 11\nplayhead 0\nresolution 1280 720\nsource 1 a.mp4\n\
1992 video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n"2091 video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n"
1993 );2092 );
1994 // Loading rejoins the *given* directory, so the file is reached by the2093 // Loading rejoins the *given* directory, so the file is reached by the
@@ -2033,10 +2132,10 @@ mod tests {
2033 #[test]2132 #[test]
2034 fn a_wrong_first_line_is_refused_by_name() {2133 fn a_wrong_first_line_is_refused_by_name() {
2035 let dir = PathBuf::from("/proj");2134 let dir = PathBuf::from("/proj");
2036- let err = parse(b"edith 11\nsource 0 a.mp4\nvideo 0 0 5 0 -\n", &dir)2135+ let err = parse(b"edith 12\nsource 0 a.mp4\nvideo 0 0 5 0 -\n", &dir)
2037 .unwrap_err()2136 .unwrap_err()
2038 .to_string();2137 .to_string();
2039- assert_eq!(err, "line 1: unsupported version 11");2138+ assert_eq!(err, "line 1: unsupported version 12");
2040 for junk in [&b""[..], b"{}\n", b"source a.mp4\n"] {2139 for junk in [&b""[..], b"{}\n", b"source a.mp4\n"] {
2041 assert_eq!(2140 assert_eq!(
2042 parse(junk, &dir).unwrap_err().to_string(),2141 parse(junk, &dir).unwrap_err().to_string(),
crates/engine/src/export.rsmodified+8 -2
@@ -969,12 +969,18 @@ fn run(
969 // span reopens its file, so building it here rather than in the loop below969 // 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 SDR970 // 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.971 // source -- the whole of an ordinary project -- builds no table at all.
972+ //
973+ // Through the project's own preset ([`tonemap::Preset`]), which is the same
974+ // one playback's decode funnel builds its tables with: preview and export
975+ // are the same rendition of the same film because they are told the same
976+ // thing, not because two numbers happen to agree.
977+ let preset = project.tone();
972 let tone: Vec<Option<ToneMapper>> = rates978 let tone: Vec<Option<ToneMapper>> = rates
973 .iter()979 .iter()
974 .map(|(_, color)| match color.transfer {980 .map(|(_, color)| match color.transfer {
975 Transfer::Sdr => None,981 Transfer::Sdr => None,
976- Transfer::Pq => Some(ToneMapper::new(tonemap::Transfer::Pq)),982+ Transfer::Pq => Some(ToneMapper::new(tonemap::Transfer::Pq, preset)),
977- Transfer::Hlg => Some(ToneMapper::new(tonemap::Transfer::Hlg)),983+ Transfer::Hlg => Some(ToneMapper::new(tonemap::Transfer::Hlg, preset)),
978 })984 })
979 .collect();985 .collect();
980 // ...and the one space they are all written in, the same rule a reader with986 // ...and the one space they are all written in, the same rule a reader with
crates/engine/src/playback.rsmodified+46 -0
@@ -320,6 +320,9 @@ impl PlaybackSession {
320 u32::MAX,320 u32::MAX,
321 ColorParams::default(),321 ColorParams::default(),
322 Composer::passthrough(),322 Composer::passthrough(),
323+ // The default rendition: a file just opened is a project nobody has
324+ // picked one for, exactly as it is a project nobody has graded.
325+ crate::tonemap::Preset::default(),
323 )?;326 )?;
324 // A file is opened on its first audio stream, like `Project::single`327 // A file is opened on its first audio stream, like `Project::single`
325 // names it: nothing has picked one yet.328 // names it: nothing has picked one yet.
@@ -647,6 +650,10 @@ impl PlaybackSession {
647 u32::MAX,650 u32::MAX,
648 ColorParams::default(),651 ColorParams::default(),
649 Composer::passthrough(),652 Composer::passthrough(),
653+ // The saved rendition, from the document rather than from the
654+ // project (which is built below): this placeholder is what the
655+ // window shows until the `seek` at the end reopens the span.
656+ doc.tone,
650 )657 )
651 .map_err(|e| format!("source {}: {e}", first.path.display()))?,658 .map_err(|e| format!("source {}: {e}", first.path.display()))?,
652 };659 };
@@ -784,6 +791,7 @@ impl PlaybackSession {
784 .collect();791 .collect();
785 let project = Project::from_parts(doc.sources, doc.lanes, doc.eq, doc.color)?792 let project = Project::from_parts(doc.sources, doc.lanes, doc.eq, doc.color)?
786 .with_mix(&doc.gains, doc.limiter)793 .with_mix(&doc.gains, doc.limiter)
794+ .with_tone(doc.tone)
787 .with_subtitles(subtitles);795 .with_subtitles(subtitles);
788 let span = project.composite_span_at(0);796 let span = project.composite_span_at(0);
789 // Last, because it is the one thing here that cannot be taken back: the797 // Last, because it is the one thing here that cannot be taken back: the
@@ -978,6 +986,10 @@ impl PlaybackSession {
978 // says: a timeline of stills and songs used to come back at986 // says: a timeline of stills and songs used to come back at
979 // whatever its scaffold implied (`open_project`).987 // whatever its scaffold implied (`open_project`).
980 Some(self.meta.frame_rate),988 Some(self.meta.frame_rate),
989+ // ...and which rendition its HDR media is watched in, for the same
990+ // reason: a picked look that vanished on a reload is a look nobody
991+ // could keep.
992+ self.project.tone(),
981 self.project.limiter(),993 self.project.limiter(),
982 playhead,994 playhead,
983 )995 )
@@ -1160,6 +1172,10 @@ impl PlaybackSession {
1160 self.meta.height,1172 self.meta.height,
1161 self.project.composite_fit_at(start),1173 self.project.composite_fit_at(start),
1162 ),1174 ),
1175+ // ...and the rendition an HDR source among them is mapped to,
1176+ // the project's own and constant across the span for that reason
1177+ // too.
1178+ self.project.tone(),
1163 )1179 )
1164 .map(|(_, stream)| stream)1180 .map(|(_, stream)| stream)
1165 .inspect_err(|e| eprintln!("timeline frame {start}: video open failed: {e}")),1181 .inspect_err(|e| eprintln!("timeline frame {start}: video open failed: {e}")),
@@ -1648,6 +1664,33 @@ impl PlaybackSession {
1648 true1664 true
1649 }1665 }
1650 1666
1667+ /// Which HDR-to-SDR rendition this project is watched and exported in
1668+ /// ([`crate::tonemap::Preset`]) -- the reference one until somebody picks
1669+ /// another, and a setting on the project rather than on any clip.
1670+ pub fn tone(&self) -> crate::tonemap::Preset {
1671+ self.project.tone()
1672+ }
1673+
1674+ /// Picks one. Rebuilds the **picture** where the playhead is, exactly as
1675+ /// [`set_resolution`](Self::set_resolution) does -- the frame on screen is
1676+ /// remapped at once, paused or playing, and the sound is not touched: a
1677+ /// rendition is not something a sample can carry. `false` for the rendition
1678+ /// already in force.
1679+ ///
1680+ /// An SDR project is unmoved by this by construction: no clip of it builds a
1681+ /// tone map at all ([`crate::tonemap`]), so the reseek recomposes the very
1682+ /// same bytes.
1683+ ///
1684+ /// ponytail: not an undo step, for the reason the resolution is not
1685+ /// ([`Project::set_tone`]).
1686+ pub fn set_tone(&mut self, preset: crate::tonemap::Preset) -> bool {
1687+ if !self.project.set_tone(preset) {
1688+ return false;
1689+ }
1690+ self.invalidate(Dirty::Picture);
1691+ true
1692+ }
1693+
1651 /// The scaffolding source's own frame rate -- what the project rate started1694 /// The scaffolding source's own frame rate -- what the project rate started
1652 /// as, and the one rate a caller offering a list of them must not leave out1695 /// as, and the one rate a caller offering a list of them must not leave out
1653 /// ([`native_resolution`](Self::native_resolution)'s reason).1696 /// ([`native_resolution`](Self::native_resolution)'s reason).
@@ -2447,6 +2490,9 @@ fn matches_timeline(
2447 0,2490 0,
2448 ColorParams::default(),2491 ColorParams::default(),
2449 Composer::passthrough(),2492 Composer::passthrough(),
2493+ // A zero-length range decodes nothing, so no table is built and the
2494+ // rendition cannot matter here.
2495+ crate::tonemap::Preset::default(),
2450 )?;2496 )?;
2451 // The frame rate is *not* a refusal any more: a file shot at another rate is2497 // The frame rate is *not* a refusal any more: a file shot at another rate is
2452 // placed for the seconds it lasts and read through [`Rate`] at the2498 // placed for the seconds it lasts and read through [`Rate`] at the
crates/engine/src/project.rsmodified+35 -0
@@ -648,6 +648,10 @@ pub struct Project {
648 /// project's resolution is a setting on the picture, and neither is an undo648 /// project's resolution is a setting on the picture, and neither is an undo
649 /// step.649 /// step.
650 limiter: Limiter,650 limiter: Limiter,
651+ /// Which HDR-to-SDR rendition every clip on an HDR curve is shown and
652+ /// exported in ([`crate::tonemap::Preset`]). A setting on the picture, like
653+ /// the resolution, and not in the lane snapshots for the same reason.
654+ tone: crate::tonemap::Preset,
651 }655 }
652 656
653 impl Project {657 impl Project {
@@ -678,6 +682,7 @@ impl Project {
678 next_link: 1,682 next_link: 1,
679 subtitles: Vec::new(),683 subtitles: Vec::new(),
680 limiter: Limiter::default(),684 limiter: Limiter::default(),
685+ tone: crate::tonemap::Preset::default(),
681 }686 }
682 }687 }
683 688
@@ -787,6 +792,7 @@ impl Project {
787 next_link,792 next_link,
788 subtitles: Vec::new(),793 subtitles: Vec::new(),
789 limiter: Limiter::default(),794 limiter: Limiter::default(),
795+ tone: crate::tonemap::Preset::default(),
790 })796 })
791 }797 }
792 798
@@ -1154,6 +1160,35 @@ impl Project {
1154 self1160 self
1155 }1161 }
1156 1162
1163+ /// The HDR rendition a *load* puts back -- the same door
1164+ /// [`with_mix`](Project::with_mix) is, and no undo step for the same reason.
1165+ pub fn with_tone(mut self, preset: crate::tonemap::Preset) -> Self {
1166+ self.tone = preset;
1167+ self
1168+ }
1169+
1170+ /// Which HDR-to-SDR rendition this project is watched and exported in. A
1171+ /// project setting, not a clip's: one picture, one look
1172+ /// ([`crate::tonemap::Preset`]).
1173+ pub fn tone(&self) -> crate::tonemap::Preset {
1174+ self.tone
1175+ }
1176+
1177+ /// Sets it. `false` for the one already in force, which is what keeps a
1178+ /// re-pick of the current rendition from costing a reseek.
1179+ ///
1180+ /// ponytail: not an undo step, for the reason the limiter and the project
1181+ /// resolution are not -- it is not in the lane list the history snapshots.
1182+ /// Upgrade path is the same one: a history entry holding the project's own
1183+ /// settings beside the lanes.
1184+ pub fn set_tone(&mut self, preset: crate::tonemap::Preset) -> bool {
1185+ if self.tone == preset {
1186+ return false;
1187+ }
1188+ self.tone = preset;
1189+ true
1190+ }
1191+
1157 /// The subtitle tracks a *load* puts back, in the order they were saved --1192 /// The subtitle tracks a *load* puts back, in the order they were saved --
1158 /// the same door [`with_mix`](Project::with_mix) is, and no undo step for1193 /// the same door [`with_mix`](Project::with_mix) is, and no undo step for
1159 /// the same reason.1194 /// the same reason.
crates/engine/src/tonemap.rsmodified+237 -87
@@ -17,7 +17,8 @@
17 //! 2. the transfer's EOTF -> display light in cd/m^2 (PQ per ST 2084, HLG per17 //! 2. the transfer's EOTF -> display light in cd/m^2 (PQ per ST 2084, HLG per
18 //! BT.2100 including its OOTF, which is why HLG costs almost nothing extra:18 //! BT.2100 including its OOTF, which is why HLG costs almost nothing extra:
19 //! it is one more EOTF feeding the same pipe),19 //! it is one more EOTF feeding the same pipe),
20-//! 3. normalise by [`MASTER_NITS`] and take the 1/2.4 root -- Method A does its20+//! 3. normalise by the assumed mastering peak ([`Preset`]) and take the 1/2.4
21+//! root -- Method A does its
21 //! work in a gamma-2.4 domain, not in linear light,22 //! work in a gamma-2.4 domain, not in linear light,
22 //! 4. BT.2020 luma + colour differences in that domain,23 //! 4. BT.2020 luma + colour differences in that domain,
23 //! 5. the tone curve: a logarithmic lift keyed on the HDR peak, a three-piece24 //! 5. the tone curve: a logarithmic lift keyed on the HDR peak, a three-piece
@@ -35,9 +36,12 @@
35 //! Method A is conservative on mid-tones by construction: told the standard36 //! Method A is conservative on mid-tones by construction: told the standard
36 //! 1000 cd/m^2 mastering peak it puts 203-nit HDR diffuse white near SDR code37 //! 1000 cd/m^2 mastering peak it puts 203-nit HDR diffuse white near SDR code
37 //! 166 (about 40 cd/m^2), not at SDR white -- a picture a viewer reads as dark.38 //! 166 (about 40 cd/m^2), not at SDR white -- a picture a viewer reads as dark.
38-//! [`MASTER_NITS`] is the exposure knob that answers it: a lower assumed peak39+//! The assumed peak is the exposure knob that answers it -- a lower one lifts
39-//! lifts everything, and it is a constant here because this module is handed40+//! everything -- and *which* answer a project wants is a matter of taste, not of
40-//! pixels, never the stream metadata that would carry the real one.41+//! correctness: a reference rendition and a vivid one are both honest pictures
42+//! of the same film. So it is a [`Preset`] the viewer picks rather than a
43+//! constant, and never the stream's own metadata, which this module is never
44+//! handed (it is given pixels).
41 //!45 //!
42 //! # Why a 3D LUT46 //! # Why a 3D LUT
43 //!47 //!
@@ -71,13 +75,6 @@
71 //! pixels is mapped in the same visit, sharing the block's bilinear chroma75 //! pixels is mapped in the same visit, sharing the block's bilinear chroma
72 //! weights, which is what keeps a 4K frame inside a frame's time budget.76 //! weights, which is what keeps a 4K frame inside a frame's time budget.
73 77
74-/// The mastering peak Method A is told to assume, cd/m^2. Not the 1000 an HDR10
75-/// grade is mastered to and not BT.2446's own worked example: the goal here is
76-/// what a *viewer* sees on an SDR screen next to mpv, and told 1000 the method
77-/// lands 203-nit diffuse white on code 166, which reads as broadcast-dark.
78-/// Told 400 it lands near 205 -- display-referred, the brightness a player
79-/// shows -- which is what this constant buys. See the module note.
80-const MASTER_NITS: f32 = 400.0;
81 /// The SDR display peak Method A targets, cd/m^2.78 /// The SDR display peak Method A targets, cd/m^2.
82 const SDR_NITS: f32 = 100.0;79 const SDR_NITS: f32 = 100.0;
83 /// Method A's working gamma. Not a display curve here -- it is the domain the80 /// Method A's working gamma. Not a display curve here -- it is the domain the
@@ -99,6 +96,72 @@ const CHROMA_STEP: u32 = 4;
99 /// `1 << CHROMA_STEP`.96 /// `1 << CHROMA_STEP`.
100 const CHROMA_FRAC: u32 = 16;97 const CHROMA_FRAC: u32 = 16;
101 98
99+/// Which rendition of the same conversion a project is watching: two numbers,
100+/// the assumed mastering peak and a chroma gain, and *only* those two -- every
101+/// preset runs the very same BT.2446 Method A stages, so the hue relationships
102+/// the method is chosen for hold whichever one is picked.
103+///
104+/// The peak is Method A's exposure knob (see the module note): told the 1000
105+/// cd/m^2 an HDR10 grade is really mastered to, the published conversion lands
106+/// 203-nit diffuse white on code 166 -- broadcast-faithful, and darker than a
107+/// player looks; told a lower one it lifts the whole picture. The gain is
108+/// applied *after* the map, on the SDR colour differences, so it enriches the
109+/// picture a viewer is shown rather than bending a stage of the standard.
110+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
111+pub enum Preset {
112+ /// The published conversion, at the mastering peak the content really has.
113+ /// The default: what the document says, and what a second reference can be
114+ /// checked against.
115+ #[default]
116+ Reference,
117+ /// Display-referred: the peak lowered to 400 so diffuse white lands near SDR
118+ /// white and the picture reads as bright as a player shows it.
119+ Standard,
120+ /// Brighter again, and slightly richer -- the colour differences scaled up a
121+ /// tenth after the map.
122+ Vivid,
123+}
124+
125+impl Preset {
126+ /// Every preset, in the order a list offers them: reference first, brightest
127+ /// last.
128+ pub const ALL: [Preset; 3] = [Preset::Reference, Preset::Standard, Preset::Vivid];
129+
130+ /// The mastering peak Method A is told to assume, cd/m^2.
131+ pub fn master_nits(self) -> f32 {
132+ match self {
133+ Preset::Reference => 1000.0,
134+ Preset::Standard => 400.0,
135+ Preset::Vivid => 250.0,
136+ }
137+ }
138+
139+ /// What the SDR colour differences are multiplied by after the map. `1.0`
140+ /// leaves the method's own output untouched, byte for byte.
141+ pub fn chroma_gain(self) -> f32 {
142+ match self {
143+ Preset::Reference | Preset::Standard => 1.0,
144+ Preset::Vivid => 1.10,
145+ }
146+ }
147+
148+ /// The name a project file carries ([`crate::edith`]) -- lower case, one
149+ /// word, and the inverse of [`from_name`](Preset::from_name).
150+ pub fn name(self) -> &'static str {
151+ match self {
152+ Preset::Reference => "reference",
153+ Preset::Standard => "standard",
154+ Preset::Vivid => "vivid",
155+ }
156+ }
157+
158+ /// Reads one back. `None` for anything else, which a project file refuses by
159+ /// name rather than silently rendering another way.
160+ pub fn from_name(name: &[u8]) -> Option<Self> {
161+ Preset::ALL.into_iter().find(|p| p.name().as_bytes() == name)
162+ }
163+}
164+
102 /// Which HDR transfer the incoming codes carry. Both feed the same Method A165 /// Which HDR transfer the incoming codes carry. Both feed the same Method A
103 /// pipeline; they differ only in how a code becomes display light.166 /// pipeline; they differ only in how a code becomes display light.
104 #[derive(Debug, Clone, Copy, PartialEq, Eq)]167 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -126,7 +189,7 @@ pub struct ToneMapper {
126 }189 }
127 190
128 impl ToneMapper {191 impl ToneMapper {
129- pub fn new(transfer: Transfer) -> Self {192+ pub fn new(transfer: Transfer, preset: Preset) -> Self {
130 let cells = LUMA_NODES * CHROMA_NODES * CHROMA_NODES;193 let cells = LUMA_NODES * CHROMA_NODES * CHROMA_NODES;
131 let (mut y_node, mut uv_node) = (vec![0u8; cells], vec![[0u8; 2]; cells]);194 let (mut y_node, mut uv_node) = (vec![0u8; cells], vec![[0u8; 2]; cells]);
132 for kv in 0..CHROMA_NODES {195 for kv in 0..CHROMA_NODES {
@@ -138,6 +201,7 @@ impl ToneMapper {
138 // own.201 // own.
139 let out = map_code(202 let out = map_code(
140 transfer,203 transfer,
204+ preset,
141 (iy << LUMA_STEP) as f32,205 (iy << LUMA_STEP) as f32,
142 (ju << CHROMA_STEP) as f32,206 (ju << CHROMA_STEP) as f32,
143 (kv << CHROMA_STEP) as f32,207 (kv << CHROMA_STEP) as f32,
@@ -282,7 +346,8 @@ fn byte(value: f32) -> u8 {
282 /// The whole float pipeline, from one triple of input codes to one triple of346 /// The whole float pipeline, from one triple of input codes to one triple of
283 /// BT.709 limited-range output codes. Runs at build time only; the module note347 /// BT.709 limited-range output codes. Runs at build time only; the module note
284 /// walks the stages.348 /// walks the stages.
285-fn map_code(transfer: Transfer, yc: f32, uc: f32, vc: f32) -> [f32; 3] {349+fn map_code(transfer: Transfer, preset: Preset, yc: f32, uc: f32, vc: f32) -> [f32; 3] {
350+ let master_nits = preset.master_nits();
286 // 1. limited-range BT.2020 Y'C'bC'r -> R'G'B' signal.351 // 1. limited-range BT.2020 Y'C'bC'r -> R'G'B' signal.
287 let luma = (yc - 16.0) / 219.0;352 let luma = (yc - 16.0) / 219.0;
288 let cb = (uc - 128.0) / 224.0;353 let cb = (uc - 128.0) / 224.0;
@@ -303,14 +368,15 @@ fn map_code(transfer: Transfer, yc: f32, uc: f32, vc: f32) -> [f32; 3] {
303 // Clamping instead walks a too-bright pixel toward white, which is what a368 // Clamping instead walks a too-bright pixel toward white, which is what a
304 // highlight past the display's reach should do.369 // highlight past the display's reach should do.
305 //370 //
306- // ponytail: the ceiling is that MASTER_NITS is an exposure choice, not a371+ // ponytail: the ceiling is that the assumed peak is an exposure *choice*
307- // measurement. Everything the content masters above it -- which at 400 is372+ // (now the viewer's, [`Preset`]), not a measurement. Everything the content
308- // most of an HDR10 grade's highlight range -- walks to white here. The373+ // masters above it -- which at 400 is most of an HDR10 grade's highlight
309- // upgrade is the stream's own MaxCLL/mastering-display metadata reaching374+ // range -- walks to white here. The upgrade is the stream's own
310- // this module as a `new` argument, with 400 as the fallback: nothing else375+ // MaxCLL/mastering-display metadata reaching this module beside the preset,
311- // in the pipeline changes.376+ // as the measured ceiling the picked one is read against: nothing else in
312- let lin = display_light(transfer, [r, g, b]);377+ // the pipeline changes.
313- let gam = lin.map(|c| (c / MASTER_NITS).clamp(0.0, 1.0).powf(1.0 / GAMMA));378+ let lin = display_light(transfer, preset, [r, g, b]);
379+ let gam = lin.map(|c| (c / master_nits).clamp(0.0, 1.0).powf(1.0 / GAMMA));
314 380
315 // 4. BT.2020 luma and colour differences, in that domain.381 // 4. BT.2020 luma and colour differences, in that domain.
316 let y_hdr = 0.2627 * gam[0] + 0.6780 * gam[1] + 0.0593 * gam[2];382 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] {
318 let cr_hdr = (gam[0] - y_hdr) / 1.4746;384 let cr_hdr = (gam[0] - y_hdr) / 1.4746;
319 385
320 // 5/6. the curve, then colour-difference scaling and its luma payback.386 // 5/6. the curve, then colour-difference scaling and its luma payback.
321- let y_sdr = tone_curve(y_hdr);387+ let y_sdr = tone_curve(y_hdr, master_nits);
322 let scale = if y_hdr > 1e-6 {388 let scale = if y_hdr > 1e-6 {
323 y_sdr / (1.075 * y_hdr)389 y_sdr / (1.075 * y_hdr)
324 } else {390 } else {
@@ -342,29 +408,49 @@ fn map_code(transfer: Transfer, yc: f32, uc: f32, vc: f32) -> [f32; 3] {
342 let b709 = (-0.0182 * r - 0.1006 * g + 1.1187 * b).clamp(0.0, 1.0);408 let b709 = (-0.0182 * r - 0.1006 * g + 1.1187 * b).clamp(0.0, 1.0);
343 let [r, g, b] = [r709, g709, b709].map(|c| c.powf(1.0 / GAMMA));409 let [r, g, b] = [r709, g709, b709].map(|c| c.powf(1.0 / GAMMA));
344 410
345- // 8. BT.709 limited-range codes.411+ // 8. BT.709 limited-range codes, the preset's chroma gain on the two colour
412+ // differences.
413+ //
414+ // A *scale* about 128 and never a shift, applied here and nowhere earlier:
415+ // 128 is neutral, so a grey stays exactly grey at any gain (`128 - 128` is
416+ // zero however it is multiplied) and only a pixel that already had colour
417+ // gets more of it. Clamped to the legal 16..240 chroma range, which at gain
418+ // 1.0 is a clamp the maths above cannot reach -- the untouched presets come
419+ // out byte for byte what Method A produced.
346 let luma = 0.2126 * r + 0.7152 * g + 0.0722 * b;420 let luma = 0.2126 * r + 0.7152 * g + 0.0722 * b;
421+ let gain = preset.chroma_gain();
347 [422 [
348 16.0 + 219.0 * luma,423 16.0 + 219.0 * luma,
349- 128.0 + 224.0 * (b - luma) / 1.8556,424+ (128.0 + gain * 224.0 * (b - luma) / 1.8556).clamp(16.0, 240.0),
350- 128.0 + 224.0 * (r - luma) / 1.5748,425+ (128.0 + gain * 224.0 * (r - luma) / 1.5748).clamp(16.0, 240.0),
351 ]426 ]
352 }427 }
353 428
354 /// Signal -> display light in cd/m^2.429 /// Signal -> display light in cd/m^2.
355-fn display_light(transfer: Transfer, rgb: [f32; 3]) -> [f32; 3] {430+fn display_light(transfer: Transfer, preset: Preset, rgb: [f32; 3]) -> [f32; 3] {
356 match transfer {431 match transfer {
357 Transfer::Pq => rgb.map(pq_eotf),432 Transfer::Pq => rgb.map(pq_eotf),
358 Transfer::Hlg => {433 Transfer::Hlg => {
359 // BT.2100: inverse OETF to scene light, then the OOTF, whose system434 // BT.2100: inverse OETF to scene light, then the OOTF, whose system
360 // gamma is 1.2 at a 1000 cd/m^2 display and follows the display435 // gamma is 1.2 at a 1000 cd/m^2 display and follows the display
361- // peak from there by the standard's own log term -- so the peak436+ // peak from there by the standard's own log term -- so the peak the
362- // [`MASTER_NITS`] names is the peak the OOTF is built for, rather437+ // preset names is the peak the OOTF is built for, rather than a
363- // than a number the constant silently invalidates.438+ // number the choice silently invalidates.
439+ let master_nits = preset.master_nits();
364 let scene = rgb.map(hlg_scene);440 let scene = rgb.map(hlg_scene);
365 let ys = 0.2627 * scene[0] + 0.6780 * scene[1] + 0.0593 * scene[2];441 let ys = 0.2627 * scene[0] + 0.6780 * scene[1] + 0.0593 * scene[2];
366- let gamma = 1.2 + 0.42 * (MASTER_NITS / 1000.0).log10();442+ let gamma = 1.2 + 0.42 * (master_nits / 1000.0).log10();
367- let gain = MASTER_NITS * ys.max(0.0).powf(gamma - 1.0);443+ // Black is black, said outright rather than left to the arithmetic:
444+ // below a 1000 cd/m^2 peak the system gamma is *under* 1, so the
445+ // `ys^(gamma - 1)` term diverges as the scene goes black and the
446+ // `0 * inf` that follows is a NaN -- which byte-casts to 0 and puts
447+ // a hole where black belongs (measured: HLG black rendered code 0
448+ // under the vivid preset before this line).
449+ let ys = ys.max(0.0);
450+ let gain = match ys > 0.0 {
451+ true => master_nits * ys.powf(gamma - 1.0),
452+ false => 0.0,
453+ };
368 scene.map(|c| gain * c)454 scene.map(|c| gain * c)
369 }455 }
370 }456 }
@@ -401,8 +487,8 @@ fn hlg_scene(e: f32) -> f32 {
401 /// BT.2446 Method A's tone curve, in the gamma-2.4 domain: 1 in is 1 out (HDR487 /// BT.2446 Method A's tone curve, in the gamma-2.4 domain: 1 in is 1 out (HDR
402 /// peak to SDR peak) and 0 in is 0 out, which is what pins the two `p` terms488 /// peak to SDR peak) and 0 in is 0 out, which is what pins the two `p` terms
403 /// and the three-piece polynomial between them.489 /// and the three-piece polynomial between them.
404-fn tone_curve(y_hdr: f32) -> f32 {490+fn tone_curve(y_hdr: f32, master_nits: f32) -> f32 {
405- let p_hdr = 1.0 + 32.0 * (MASTER_NITS / 10000.0).powf(1.0 / GAMMA);491+ let p_hdr = 1.0 + 32.0 * (master_nits / 10000.0).powf(1.0 / GAMMA);
406 let p_sdr = 1.0 + 32.0 * (SDR_NITS / 10000.0).powf(1.0 / GAMMA);492 let p_sdr = 1.0 + 32.0 * (SDR_NITS / 10000.0).powf(1.0 / GAMMA);
407 let yp = (1.0 + (p_hdr - 1.0) * y_hdr.max(0.0)).ln() / p_hdr.ln();493 let yp = (1.0 + (p_hdr - 1.0) * y_hdr.max(0.0)).ln() / p_hdr.ln();
408 let yc = if yp <= 0.7399 {494 let yc = if yp <= 0.7399 {
@@ -445,49 +531,89 @@ mod tests {
445 }531 }
446 532
447 /// The anchors, in cd/m^2, against the codes the stages in the module note533 /// The anchors, in cd/m^2, against the codes the stages in the module note
448- /// give for [`MASTER_NITS`]. Black is pinned by the curve (0 in, 0 out);534+ /// give for each preset's assumed peak. Black is pinned by the curve (0 in,
449- /// [`MASTER_NITS`] itself is the assumed peak and must reach SDR white;535+ /// 0 out); the assumed peak itself must reach SDR white; 203 nits is BT.2408
450- /// 203 nits is BT.2408 diffuse white, and 205 is where a 400 cd/m^2 peak536+ /// diffuse white, and *where it lands is the whole difference between the
451- /// puts it -- a picture as bright as a player shows, which is the whole537+ /// presets* -- 166 at the published 1000 cd/m^2 (broadcast-faithful, and the
452- /// reason that constant is not 1000 (where the same maths gives 166). The538+ /// reason the reference rendition reads dark), 205 at 400, 226 at 250. The
453 /// day one of these moves, the transcription moved with it.539 /// day one of these moves, the transcription moved with it.
454 ///540 ///
455- /// 1000 nits is the ceiling the `map_code` ponytail names, asserted rather541+ /// The last row of each is the ceiling the `map_code` ponytail names,
456- /// than described: everything above the assumed peak is white.542+ /// asserted rather than described: everything above the assumed peak is
543+ /// white.
457 #[test]544 #[test]
458 fn pq_anchors_land_where_method_a_puts_them() {545 fn pq_anchors_land_where_method_a_puts_them() {
459- let mapper = ToneMapper::new(Transfer::Pq);546+ for (preset, diffuse) in [
460- for (nits, expected) in [547+ (Preset::Reference, 166u8),
461- (0.0, 16u8),548+ (Preset::Standard, 205),
462- (26.0, 108),549+ (Preset::Vivid, 226),
463- (203.0, 205),
464- (MASTER_NITS, 235),
465- (1000.0, 235),
466 ] {550 ] {
467- let code = byte(pq_code(nits));551+ let peak = preset.master_nits();
468- let (y, _, _) = mapped(&mapper, code, 128, 128);552+ let mapper = ToneMapper::new(Transfer::Pq, preset);
469- assert!(553+ for (nits, expected) in [(0.0, 16u8), (203.0, diffuse), (peak, 235), (10000.0, 235)] {
470- y.abs_diff(expected) <= 3,554+ let code = byte(pq_code(nits));
471- "{nits} cd/m^2 (code {code}) -> {y}, expected {expected}"555+ let (y, _, _) = mapped(&mapper, code, 128, 128);
472- );556+ assert!(
557+ y.abs_diff(expected) <= 3,
558+ "{preset:?}: {nits} cd/m^2 (code {code}) -> {y}, expected {expected}"
559+ );
560+ }
473 }561 }
474 }562 }
475 563
564+ /// What the presets are *for*, on one code: brighter is brighter, and the
565+ /// vivid one has more colour in it. A preset that renamed the same numbers
566+ /// would pass every other test in this module and fail this one.
567+ ///
568+ /// The chroma reading is the distance from neutral, which is the thing the
569+ /// gain scales; the grey beside it is the neutrality that must survive it,
570+ /// so "richer" cannot have been bought with a tint.
571+ #[test]
572+ fn a_brighter_preset_is_brighter_and_a_vivid_one_is_richer() {
573+ // BT.2408 diffuse white, and a saturated BT.2020 red beside it.
574+ let (diffuse, red) = (byte(pq_code(203.0)), (100u8, 90u8, 200u8));
575+ let luma = |preset| mapped(&ToneMapper::new(Transfer::Pq, preset), diffuse, 128, 128).0;
576+ let (reference, standard, vivid) = (
577+ luma(Preset::Reference),
578+ luma(Preset::Standard),
579+ luma(Preset::Vivid),
580+ );
581+ assert!(
582+ reference < standard && standard < vivid,
583+ "reference {reference}, standard {standard}, vivid {vivid}"
584+ );
585+ let colour = |preset| {
586+ let (_, u, v) = mapped(&ToneMapper::new(Transfer::Pq, preset), red.0, red.1, red.2);
587+ (u.abs_diff(128), v.abs_diff(128))
588+ };
589+ let (flat, rich) = (colour(Preset::Standard), colour(Preset::Vivid));
590+ // Both differences read together, and neither of them allowed to shrink:
591+ // this red is saturated enough that its V is already against the legal
592+ // 240 rail under both presets, so the gain has nowhere to take *that*
593+ // one -- which is the clamp doing its job, not the gain failing to.
594+ assert!(
595+ rich.0 + rich.1 > flat.0 + flat.1 && rich.0 >= flat.0 && rich.1 >= flat.1,
596+ "vivid's red {rich:?} is no further from neutral than standard's {flat:?}"
597+ );
598+ }
599+
476 /// On its nodes the grid is not an approximation at all: no interpolation600 /// On its nodes the grid is not an approximation at all: no interpolation
477 /// runs, so the byte a picture gets is the byte the float pipeline601 /// runs, so the byte a picture gets is the byte the float pipeline
478 /// computed. This is the half of the accuracy claim that is exact, and it602 /// computed. This is the half of the accuracy claim that is exact, and it
479 /// covers every node of every axis for both transfers.603 /// covers every node of every axis for both transfers.
480 #[test]604 #[test]
481 fn the_grid_is_the_pipeline_on_its_nodes() {605 fn the_grid_is_the_pipeline_on_its_nodes() {
482- for transfer in [Transfer::Pq, Transfer::Hlg] {606+ for preset in Preset::ALL {
483- let mapper = ToneMapper::new(transfer);607+ for transfer in [Transfer::Pq, Transfer::Hlg] {
484- for yc in (0..=248u8).step_by(1 << LUMA_STEP) {608+ let mapper = ToneMapper::new(transfer, preset);
485- for uc in (0..=240u8).step_by(1 << CHROMA_STEP) {609+ for yc in (0..=248u8).step_by(1 << LUMA_STEP) {
486- for vc in (0..=240u8).step_by(1 << CHROMA_STEP) {610+ for uc in (0..=240u8).step_by(1 << CHROMA_STEP) {
487- let got = mapped(&mapper, yc, uc, vc);611+ for vc in (0..=240u8).step_by(1 << CHROMA_STEP) {
488- let want = map_code(transfer, yc.into(), uc.into(), vc.into());612+ let got = mapped(&mapper, yc, uc, vc);
489- let want = (byte(want[0]), byte(want[1]), byte(want[2]));613+ let want = map_code(transfer, preset, yc.into(), uc.into(), vc.into());
490- assert_eq!(got, want, "{transfer:?} node {yc}/{uc}/{vc}");614+ let want = (byte(want[0]), byte(want[1]), byte(want[2]));
615+ assert_eq!(got, want, "{preset:?} {transfer:?} node {yc}/{uc}/{vc}");
616+ }
491 }617 }
492 }618 }
493 }619 }
@@ -507,8 +633,13 @@ mod tests {
507 /// pipeline steps.633 /// pipeline steps.
508 #[test]634 #[test]
509 fn between_nodes_the_grid_stays_inside_its_own_cell() {635 fn between_nodes_the_grid_stays_inside_its_own_cell() {
510- for transfer in [Transfer::Pq, Transfer::Hlg] {636+ // Every preset, since the vivid one's chroma gain is a stage the nodes
511- let mapper = ToneMapper::new(transfer);637+ // carry and the interpolation between them must not exaggerate.
638+ for (transfer, preset) in [Transfer::Pq, Transfer::Hlg]
639+ .into_iter()
640+ .flat_map(|t| Preset::ALL.map(|p| (t, p)))
641+ {
642+ let mapper = ToneMapper::new(transfer, preset);
512 for yc in (3..=255u8).step_by(23) {643 for yc in (3..=255u8).step_by(23) {
513 for uc in (5..=255u8).step_by(29) {644 for uc in (5..=255u8).step_by(29) {
514 for vc in (7..=255u8).step_by(31) {645 for vc in (7..=255u8).step_by(31) {
@@ -526,6 +657,7 @@ mod tests {
526 for dv in [0.0, f32::from(1u8 << CHROMA_STEP)] {657 for dv in [0.0, f32::from(1u8 << CHROMA_STEP)] {
527 let out = map_code(658 let out = map_code(
528 transfer,659 transfer,
660+ preset,
529 node(yc, LUMA_STEP) + dy,661 node(yc, LUMA_STEP) + dy,
530 node(uc, CHROMA_STEP) + du,662 node(uc, CHROMA_STEP) + du,
531 node(vc, CHROMA_STEP) + dv,663 node(vc, CHROMA_STEP) + dv,
@@ -542,7 +674,7 @@ mod tests {
542 // and the interpolation rounds once more.674 // and the interpolation rounds once more.
543 assert!(675 assert!(
544 got[i] + 1 >= lo[i] && got[i] <= hi[i] + 1,676 got[i] + 1 >= lo[i] && got[i] <= hi[i] + 1,
545- "{transfer:?} {name} at {yc}/{uc}/{vc}: {} outside {}..{}",677+ "{preset:?} {transfer:?} {name} at {yc}/{uc}/{vc}: {} outside {}..{}",
546 got[i],678 got[i],
547 lo[i],679 lo[i],
548 hi[i]680 hi[i]
@@ -559,14 +691,17 @@ mod tests {
559 /// grid or a truncating interpolation produces.691 /// grid or a truncating interpolation produces.
560 #[test]692 #[test]
561 fn a_grey_ramp_never_inverts() {693 fn a_grey_ramp_never_inverts() {
562- for transfer in [Transfer::Pq, Transfer::Hlg] {694+ for (transfer, preset) in [Transfer::Pq, Transfer::Hlg]
563- let mapper = ToneMapper::new(transfer);695+ .into_iter()
696+ .flat_map(|t| Preset::ALL.map(|p| (t, p)))
697+ {
698+ let mapper = ToneMapper::new(transfer, preset);
564 let mut last = 0u8;699 let mut last = 0u8;
565 for code in 0..=255u8 {700 for code in 0..=255u8 {
566 let (y, _, _) = mapped(&mapper, code, 128, 128);701 let (y, _, _) = mapped(&mapper, code, 128, 128);
567 assert!(702 assert!(
568 y >= last,703 y >= last,
569- "{transfer:?}: code {code} darkened to {y} < {last}"704+ "{preset:?} {transfer:?}: code {code} darkened to {y} < {last}"
570 );705 );
571 last = y;706 last = y;
572 }707 }
@@ -574,16 +709,21 @@ mod tests {
574 }709 }
575 710
576 /// Grey in, grey out: any chroma the pipeline invents on a neutral is a711 /// Grey in, grey out: any chroma the pipeline invents on a neutral is a
577- /// tint across the whole picture.712+ /// tint across the whole picture -- and a chroma *gain* that was written as
713+ /// a shift, or applied anywhere but about 128, is exactly that tint, which
714+ /// is why the vivid preset is in this loop.
578 #[test]715 #[test]
579 fn neutral_input_stays_neutral() {716 fn neutral_input_stays_neutral() {
580- for transfer in [Transfer::Pq, Transfer::Hlg] {717+ for (transfer, preset) in [Transfer::Pq, Transfer::Hlg]
581- let mapper = ToneMapper::new(transfer);718+ .into_iter()
719+ .flat_map(|t| Preset::ALL.map(|p| (t, p)))
720+ {
721+ let mapper = ToneMapper::new(transfer, preset);
582 for code in (16..=235u8).step_by(7) {722 for code in (16..=235u8).step_by(7) {
583 let (_, u, v) = mapped(&mapper, code, 128, 128);723 let (_, u, v) = mapped(&mapper, code, 128, 128);
584 assert!(724 assert!(
585 u.abs_diff(128) <= 2 && v.abs_diff(128) <= 2,725 u.abs_diff(128) <= 2 && v.abs_diff(128) <= 2,
586- "{transfer:?}: grey {code} tinted to U{u} V{v}"726+ "{preset:?} {transfer:?}: grey {code} tinted to U{u} V{v}"
587 );727 );
588 }728 }
589 }729 }
@@ -596,27 +736,37 @@ mod tests {
596 ///736 ///
597 /// BT.2408 HLG diffuse white is signal 0.75, and it does *not* land on the737 /// BT.2408 HLG diffuse white is signal 0.75, and it does *not* land on the
598 /// PQ side's 203-nit code: relative is the point of HLG, so 0.75 is 19% of738 /// PQ side's 203-nit code: relative is the point of HLG, so 0.75 is 19% of
599- /// whatever peak the display has -- 76 cd/m^2 of [`MASTER_NITS`]'s 400,739+ /// whatever peak the display has -- 76 cd/m^2 of the standard preset's 400,
600- /// against PQ's absolute 203 -- and it comes out darker, at 170. That is740+ /// against PQ's absolute 203 -- and it comes out darker. That is the
601- /// the standard's own behaviour and the number to watch: if the OOTF's741+ /// standard's own behaviour and the number to watch: if the OOTF's system
602- /// system gamma stops following the assumed peak, this is what moves.742+ /// gamma stops following the assumed peak, this is what moves, and it moves
743+ /// per preset because the peak is what a preset picks.
603 #[test]744 #[test]
604 fn hlg_anchors_are_sane() {745 fn hlg_anchors_are_sane() {
605- let mapper = ToneMapper::new(Transfer::Hlg);746+ for (preset, expected) in [
606- let code = |signal: f32| byte(16.0 + 219.0 * signal);747+ (Preset::Reference, 170u8),
607- let (black, _, _) = mapped(&mapper, code(0.0), 128, 128);748+ (Preset::Standard, 170),
608- let (diffuse, _, _) = mapped(&mapper, code(0.75), 128, 128);749+ (Preset::Vivid, 170),
609- let (white, _, _) = mapped(&mapper, code(1.0), 128, 128);750+ ] {
610- assert!(black.abs_diff(16) <= 3, "HLG black -> {black}");751+ let mapper = ToneMapper::new(Transfer::Hlg, preset);
611- assert!(white.abs_diff(235) <= 3, "HLG peak -> {white}");752+ let code = |signal: f32| byte(16.0 + 219.0 * signal);
612- assert!(diffuse.abs_diff(170) <= 3, "HLG diffuse white -> {diffuse}");753+ let (black, _, _) = mapped(&mapper, code(0.0), 128, 128);
754+ let (diffuse, _, _) = mapped(&mapper, code(0.75), 128, 128);
755+ let (white, _, _) = mapped(&mapper, code(1.0), 128, 128);
756+ assert!(black.abs_diff(16) <= 3, "{preset:?} HLG black -> {black}");
757+ assert!(white.abs_diff(235) <= 3, "{preset:?} HLG peak -> {white}");
758+ assert!(
759+ diffuse.abs_diff(expected) <= 3,
760+ "{preset:?} HLG diffuse white -> {diffuse}, expected {expected}"
761+ );
762+ }
613 }763 }
614 764
615 /// A short plane is left alone rather than half mapped, and a frame with no765 /// A short plane is left alone rather than half mapped, and a frame with no
616 /// size at all returns instead of panicking on a zero-length band.766 /// size at all returns instead of panicking on a zero-length band.
617 #[test]767 #[test]
618 fn a_frame_that_does_not_measure_up_is_untouched() {768 fn a_frame_that_does_not_measure_up_is_untouched() {
619- let mapper = ToneMapper::new(Transfer::Pq);769+ let mapper = ToneMapper::new(Transfer::Pq, Preset::default());
620 let mut y = vec![128u8; 8 * 8 - 1];770 let mut y = vec![128u8; 8 * 8 - 1];
621 let mut u = vec![128u8; 4 * 4];771 let mut u = vec![128u8; 4 * 4];
622 let mut v = vec![128u8; 4 * 4];772 let mut v = vec![128u8; 4 * 4];
@@ -631,7 +781,7 @@ mod tests {
631 /// off the end.781 /// off the end.
632 #[test]782 #[test]
633 fn odd_sizes_map_every_pixel() {783 fn odd_sizes_map_every_pixel() {
634- let mapper = ToneMapper::new(Transfer::Pq);784+ let mapper = ToneMapper::new(Transfer::Pq, Preset::default());
635 let (w, h) = (7usize, 5usize);785 let (w, h) = (7usize, 5usize);
636 let mut y = vec![200u8; w * h];786 let mut y = vec![200u8; w * h];
637 let mut u = vec![128u8; w.div_ceil(2) * h.div_ceil(2)];787 let mut u = vec![128u8; w.div_ceil(2) * h.div_ceil(2)];
@@ -653,7 +803,7 @@ mod tests {
653 /// time", and the reason a plain mean here would be a coin flip.803 /// time", and the reason a plain mean here would be a coin flip.
654 #[test]804 #[test]
655 fn perf_4k_and_1080p() {805 fn perf_4k_and_1080p() {
656- let mapper = ToneMapper::new(Transfer::Pq);806+ let mapper = ToneMapper::new(Transfer::Pq, Preset::default());
657 for (w, h, budget) in [(3840usize, 1600usize, 25.0f64), (1920, 1080, 8.0)] {807 for (w, h, budget) in [(3840usize, 1600usize, 25.0f64), (1920, 1080, 8.0)] {
658 let mut y: Vec<u8> = (0..w * h).map(|i| (i % 256) as u8).collect();808 let mut y: Vec<u8> = (0..w * h).map(|i| (i % 256) as u8).collect();
659 let mut u: Vec<u8> = (0..w / 2 * h / 2).map(|i| (i % 256) as u8).collect();809 let mut u: Vec<u8> = (0..w / 2 * h / 2).map(|i| (i % 256) as u8).collect();
crates/engine/tests/export_color.rsmodified+50 -39
@@ -422,46 +422,57 @@ fn an_hdr_clip_is_tone_mapped_before_it_is_graded() {
422 brightness: 0.25,422 brightness: 0.25,
423 ..Default::default()423 ..Default::default()
424 };424 };
425- let mut session = two_frames(&source);425+ // Under both the default rendition and a picked one: an export that built
426- assert!(426+ // its tables from anything but the project's own preset would sit on the
427- session.set_color(engine::project::Lane::V1, 0, Some(grade)),427+ // wrong reference for the second pass, which is the whole preview-equals-
428- "the grade went on the clip"428+ // export claim ([`tonemap::Preset`]).
429- );429+ for preset in [tonemap::Preset::default(), tonemap::Preset::Vivid] {
430- let out = out_path("hdr_order", "mp4");430+ let mut session = two_frames(&source);
431- export(&session, &out, Format::Mp4);431+ assert!(
432- let got = raw_yuv(&out).expect("ffmpeg read the export");432+ session.set_color(engine::project::Lane::V1, 0, Some(grade)),
433+ "the grade went on the clip"
434+ );
435+ assert_eq!(
436+ session.set_tone(preset),
437+ preset != tonemap::Preset::default(),
438+ "picking {preset:?}"
439+ );
440+ let out = out_path("hdr_order", "mp4");
441+ export(&session, &out, Format::Mp4);
442+ let got = raw_yuv(&out).expect("ffmpeg read the export");
433 443
434- let (width, height) = (1280usize, 720usize);444+ let (width, height) = (1280usize, 720usize);
435- let mapper = ToneMapper::new(tonemap::Transfer::Pq);445+ let mapper = ToneMapper::new(tonemap::Transfer::Pq, preset);
436- // The same bytes twice, through the two orders. Whichever way MASTER_NITS is446+ // The same bytes twice, through the two orders. Whichever preset is in
437- // set, both sides move with it -- what is asserted is which of them the447+ // force, both sides move with it -- what is asserted is which of them
438- // export sits on, not where either lands.448+ // the export sits on, not where either lands.
439- let both = [true, false].map(|tone_first| {449+ let both = [true, false].map(|tone_first| {
440- let mut planes = src.clone();450+ let mut planes = src.clone();
441- let (y, chroma) = planes.split_at_mut(width * height);451+ let (y, chroma) = planes.split_at_mut(width * height);
442- let (u, v) = chroma.split_at_mut(width * height / 4);452+ let (u, v) = chroma.split_at_mut(width * height / 4);
443- if tone_first {453+ if tone_first {
444- mapper.map(y, u, v, width, height);454+ mapper.map(y, u, v, width, height);
445- engine::color::apply_yuv(&grade, y, u, v);455+ engine::color::apply_yuv(&grade, y, u, v);
446- } else {456+ } else {
447- engine::color::apply_yuv(&grade, y, u, v);457+ engine::color::apply_yuv(&grade, y, u, v);
448- mapper.map(y, u, v, width, height);458+ mapper.map(y, u, v, width, height);
449- }459+ }
450- planes460+ planes
451- });461+ });
452- let [ordered, swapped] = both.map(|planes| mean_abs_diff(&got, &planes));462+ let [ordered, swapped] = both.map(|planes| mean_abs_diff(&got, &planes));
453- eprintln!(463+ eprintln!(
454- "HDR export: {ordered:.2} off tone-map-then-grade, {swapped:.2} off the swapped order"464+ "HDR export ({preset:?}): {ordered:.2} off tone-map-then-grade, {swapped:.2} off the swapped order"
455- );465+ );
456- assert!(466+ assert!(
457- ordered < 3.0,467+ ordered < 3.0,
458- "the export is {ordered:.2} codes from tone-map-then-grade"468+ "{preset:?}: the export is {ordered:.2} codes from tone-map-then-grade"
459- );469+ );
460- assert!(470+ assert!(
461- swapped > 3.0 * ordered,471+ swapped > 3.0 * ordered,
462- "ordered {ordered:.2} vs swapped {swapped:.2}: the two orders are not far enough apart to have measured anything"472+ "{preset:?}: ordered {ordered:.2} vs swapped {swapped:.2}: the two orders are not far enough apart to have measured anything"
463- );473+ );
464- std::fs::remove_file(&out).unwrap();474+ std::fs::remove_file(&out).unwrap();
475+ }
465 }476 }
466 477
467 /// The real thing, where this machine has it: five seconds of a 4K HDR10 film,478 /// The real thing, where this machine has it: five seconds of a 4K HDR10 film,
crates/engine/tests/hw_decode.rsmodified+1 -1
@@ -246,7 +246,7 @@ fn the_hdr_film_renders_tone_mapped() {
246 // The funnel's own budget at this size: the map plus the conversion, which246 // The funnel's own budget at this size: the map plus the conversion, which
247 // is what an HDR frame costs on top of the decode. Fastest of five, for the247 // is what an HDR frame costs on top of the decode. Fastest of five, for the
248 // reason `tonemap::perf_4k_and_1080p` documents.248 // reason `tonemap::perf_4k_and_1080p` documents.
249- let mapper = ToneMapper::new(Transfer::Pq);249+ let mapper = ToneMapper::new(Transfer::Pq, engine::tonemap::Preset::default());
250 let sdr = ColorDescription {250 let sdr = ColorDescription {
251 matrix: Matrix::Bt709,251 matrix: Matrix::Bt709,
252 transfer: engine::colorspace::Transfer::Sdr,252 transfer: engine::colorspace::Transfer::Sdr,
crates/engine/tests/saveload.rsmodified+48 -6
@@ -206,7 +206,7 @@ fn a_version_1_project_loads_fully_grouped_and_saves_as_version_7() {
206 let v2 = dir.join("new.edith");206 let v2 = dir.join("new.edith");
207 loaded.save_project(&v2).expect("save");207 loaded.save_project(&v2).expect("save");
208 let text = std::fs::read_to_string(&v2).expect("read back");208 let text = std::fs::read_to_string(&v2).expect("read back");
209- assert!(text.starts_with("edith 10\n"), "{text}");209+ assert!(text.starts_with("edith 11\n"), "{text}");
210 assert!(210 assert!(
211 text.contains("\nresolution 1280 720\n"),211 text.contains("\nresolution 1280 720\n"),
212 "a project with no resolution of its own is saved at source 0's: {text}"212 "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() {
294 loaded.save_project(&again).expect("save");294 loaded.save_project(&again).expect("save");
295 assert_eq!(295 assert_eq!(
296 std::fs::read_to_string(&again).expect("read back"),296 std::fs::read_to_string(&again).expect("read back"),
297- "edith 10\nplayhead 0\nresolution 1280 720\nfps 30.0\nsource 0 test_av.mp4\n\297+ "edith 11\nplayhead 0\nresolution 1280 720\nfps 30.0\nsource 0 test_av.mp4\n\
298 video 1 0 0 30 0 3 - - fit 1000\naudio 1\n\298 video 1 0 0 30 0 3 - - fit 1000\naudio 1\n\
299 video 2 40 0 20 0 - - - fit 1000\naudio 2 0 0 30 0 3 - - fit 1000\n",299 video 2 40 0 20 0 - - - fit 1000\naudio 2 0 0 30 0 3 - - fit 1000\n",
300 "a four-lane project is written as it was read, three versions on"300 "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() {
324 loaded.save_project(&again).expect("save");324 loaded.save_project(&again).expect("save");
325 assert_eq!(325 assert_eq!(
326 std::fs::read_to_string(&again).expect("read back"),326 std::fs::read_to_string(&again).expect("read back"),
327- "edith 10\nplayhead 0\nresolution 1280 720\nfps 30.0\nsource 0 test_av.mp4\n\327+ "edith 11\nplayhead 0\nresolution 1280 720\nfps 30.0\nsource 0 test_av.mp4\n\
328 eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk\n\328 eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk\n\
329 eq 12000.0:6.25:0.5:hs\n\329 eq 12000.0:6.25:0.5:hs\n\
330 video 1 0 0 30 0 - 0 - fit 1000\nvideo 1 30 30 60 0 - 1 - fit 1000\n\330 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() {
359 loaded.save_project(&again).expect("save");359 loaded.save_project(&again).expect("save");
360 assert_eq!(360 assert_eq!(
361 std::fs::read_to_string(&again).expect("read back"),361 std::fs::read_to_string(&again).expect("read back"),
362- "edith 10\nplayhead 0\nresolution 1280 720\nfps 30.0\nsource 0 test_av.mp4\n\362+ "edith 11\nplayhead 0\nresolution 1280 720\nfps 30.0\nsource 0 test_av.mp4\n\
363 eq 80.0:-3.0:0.707:ls\n\363 eq 80.0:-3.0:0.707:ls\n\
364 color 0.1:1.2:0.9:-0.3\n\364 color 0.1:1.2:0.9:-0.3\n\
365 color -0.25:1.0:0.0:0.5\n\365 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() {
409 loaded.save_project(&again).expect("save");409 loaded.save_project(&again).expect("save");
410 assert_eq!(410 assert_eq!(
411 std::fs::read_to_string(&again).expect("read back"),411 std::fs::read_to_string(&again).expect("read back"),
412- "edith 10\nplayhead 0\nresolution 960 720\nfps 30.0\nsource 0 test_av.mp4\n\412+ "edith 11\nplayhead 0\nresolution 960 720\nfps 30.0\nsource 0 test_av.mp4\n\
413 video 1 0 0 30 0 - - - fill 1000\nvideo 1 30 30 60 0 - - - center 1000\n\413 video 1 0 0 30 0 - - - fill 1000\nvideo 1 30 30 60 0 - - - center 1000\n\
414 audio 1 0 0 60 0 - - - fit 1000\n",414 audio 1 0 0 60 0 - - - fit 1000\n",
415 "a v7 project is written back as the v8 it now is: the same clips, each \415 "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() {
667 667
668 for (text, want) in [668 for (text, want) in [
669 (669 (
670- "edith 11\nsource 0 test_av.mp4\nvideo 1 0 0 30 0 - - - fit\n",670+ "edith 12\nsource 0 test_av.mp4\nvideo 1 0 0 30 0 - - - fit\n",
671 "line 1",671 "line 1",
672 ),672 ),
673 // An eq index the table does not hold, and a band shape there is none.673 // 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() {
793 );793 );
794 }794 }
795 795
796+/// The v11 bump's own round trip: the HDR rendition a project was left in comes
797+/// back with it, and a file written before there were any is the reference one.
798+/// A picked look that vanished on a reload would be a setting nobody could keep
799+/// -- the mix test's claim, for the picture.
800+#[test]
801+fn the_tone_map_preset_survives_a_save_and_an_open() {
802+ use engine::tonemap::Preset;
803+ let dir = scratch("tone");
804+ let source = copy_in(&dir, "test_av.mp4");
805+ let mut saved = PlaybackSession::open(&source).expect("open the fixture");
806+ assert_eq!(saved.tone(), Preset::Reference, "nobody has picked yet");
807+ assert!(saved.set_tone(Preset::Vivid));
808+ let path = dir.join("tone.edith");
809+ saved.save_project(&path).expect("save");
810+
811+ let mut loaded = PlaybackSession::open_project(&path).expect("open the project");
812+ assert_eq!(loaded.tone(), Preset::Vivid);
813+ assert!(!loaded.undo(), "a loaded rendition is not an undo step");
814+ // ...and saving it again is the same bytes, as the mix is.
815+ let again = dir.join("again.edith");
816+ loaded
817+ .save_project(&again)
818+ .expect("save the loaded project");
819+ assert_eq!(
820+ std::fs::read(&path).unwrap(),
821+ std::fs::read(&again).unwrap(),
822+ "save -> load -> save is not a fixed point"
823+ );
824+
825+ // A project written before v11 says nothing about a rendition, and means the
826+ // published one -- the picture it was always shown in.
827+ let old = dir.join("old.edith");
828+ std::fs::write(
829+ &old,
830+ "edith 10\nplayhead 0\nresolution 1920 1080\nsource 0 test_av.mp4\n\
831+ video 1 0 0 24 0 - - - fit 1000\naudio 1 0 0 24 0 - - - fit 1000\n",
832+ )
833+ .expect("write a v10 project");
834+ let older = PlaybackSession::open_project(&old).expect("open the v10 project");
835+ assert_eq!(older.tone(), Preset::Reference);
836+}
837+
796 /// The other half of the v9 bump, and the debt it pays: a timeline holding838 /// The other half of the v9 bump, and the debt it pays: a timeline holding
797 /// nothing but a song has no file to take a frame rate from, so it used to come839 /// nothing but a song has no file to take a frame rate from, so it used to come
798 /// back at the canvas rate whatever it was cut at. The written `fps` is now840 /// back at the canvas rate whatever it was cut at. The written `fps` is now
crates/engine/tests/silence.rsmodified+2 -1
@@ -370,13 +370,14 @@ fn scanning_a_clip_and_cutting_what_it_finds() {
370 &color,370 &color,
371 (1920, 1080),371 (1920, 1080),
372 None,372 None,
373+ p.tone(),
373 p.limiter(),374 p.limiter(),
374 0,375 0,
375 )376 )
376 .expect("save");377 .expect("save");
377 let text = std::fs::read_to_string(&file).expect("read it back");378 let text = std::fs::read_to_string(&file).expect("read it back");
378 assert!(379 assert!(
379- text.starts_with("edith 10"),380+ text.starts_with("edith 11"),
380 "{:?}",381 "{:?}",
381 &text[..16.min(text.len())]382 &text[..16.min(text.len())]
382 );383 );
crates/engine/tests/tonemap_render.rsmodified+63 -11
@@ -22,7 +22,7 @@ use engine::color::{ColorParams, apply_yuv};
22 use engine::colorspace::{ColorDescription, Matrix, Transfer};22 use engine::colorspace::{ColorDescription, Matrix, Transfer};
23 use engine::convert::i420_to_bgra;23 use engine::convert::i420_to_bgra;
24 use engine::project::Lane;24 use engine::project::Lane;
25-use engine::tonemap::{ToneMapper, Transfer as Hdr};25+use engine::tonemap::{Preset, ToneMapper, Transfer as Hdr};
26 26
27 /// The fixture's patches: the source codes, and where the centre of each one27 /// The fixture's patches: the source codes, and where the centre of each one
28 /// sits in the 320x240 picture.28 /// sits in the 320x240 picture.
@@ -99,7 +99,7 @@ fn spread(px: [u8; 3]) -> u8 {
99 /// to render it: tone-mapped first, then graded, then converted as BT.709 SDR.99 /// to render it: tone-mapped first, then graded, then converted as BT.709 SDR.
100 /// `grade` is applied in whichever domain `before` says -- which is the point of100 /// `grade` is applied in whichever domain `before` says -- which is the point of
101 /// [`the_grade_lands_after_the_tone_map`].101 /// [`the_grade_lands_after_the_tone_map`].
102-fn by_hand(codes: [u8; 3], grade: &ColorParams, before: bool) -> [u8; 3] {102+fn by_hand(codes: [u8; 3], grade: &ColorParams, before: bool, preset: Preset) -> [u8; 3] {
103 let (w, h) = (8usize, 8usize);103 let (w, h) = (8usize, 8usize);
104 let mut y = vec![codes[0]; w * h];104 let mut y = vec![codes[0]; w * h];
105 let mut u = vec![codes[1]; w / 2 * h / 2];105 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] {
107 if before {107 if before {
108 apply_yuv(grade, &mut y, &mut u, &mut v);108 apply_yuv(grade, &mut y, &mut u, &mut v);
109 }109 }
110- ToneMapper::new(Hdr::Pq).map(&mut y, &mut u, &mut v, w, h);110+ ToneMapper::new(Hdr::Pq, preset).map(&mut y, &mut u, &mut v, w, h);
111 if !before {111 if !before {
112 apply_yuv(grade, &mut y, &mut u, &mut v);112 apply_yuv(grade, &mut y, &mut u, &mut v);
113 }113 }
@@ -116,10 +116,12 @@ fn by_hand(codes: [u8; 3], grade: &ColorParams, before: bool) -> [u8; 3] {
116 }116 }
117 117
118 /// The claim itself: a PQ stream is shown as an SDR display can show it.118 /// The claim itself: a PQ stream is shown as an SDR display can show it.
119-/// Diffuse white lands where a viewer expects white-ish paper (~205, not the119+/// Diffuse white lands where BT.2446 Method A puts it at the mastering peak the
120-/// 144 an untouched code would convert to and not clipped white), the 1000120+/// content really has (~166, not the 144 an untouched code would convert to and
121-/// cd/m^2 highlight stays a highlight, and the saturated red is still red --121+/// not clipped white -- the reference rendition, which is what a project nobody
122-/// a grey wash is exactly what the missing map looked like.122+/// has picked for is shown in), the 1000 cd/m^2 highlight stays a highlight, and
123+/// the saturated red is still red -- a grey wash is exactly what the missing map
124+/// looked like.
123 #[test]125 #[test]
124 fn a_pq_stream_is_tone_mapped_on_its_way_to_the_window() {126 fn a_pq_stream_is_tone_mapped_on_its_way_to_the_window() {
125 let mut session = open("test_pq.mp4");127 let mut session = open("test_pq.mp4");
@@ -135,8 +137,8 @@ fn a_pq_stream_is_tone_mapped_on_its_way_to_the_window() {
135 137
136 let diffuse = luma_code(pixel(&frame, DIFFUSE.1));138 let diffuse = luma_code(pixel(&frame, DIFFUSE.1));
137 assert!(139 assert!(
138- (200..=210).contains(&diffuse),140+ (161..=171).contains(&diffuse),
139- "diffuse white (code {}) rendered at {diffuse}, wanted 200..=210",141+ "diffuse white (code {}) rendered at {diffuse}, wanted 161..=171",
140 DIFFUSE.0[0]142 DIFFUSE.0[0]
141 );143 );
142 let highlight = luma_code(pixel(&frame, HIGHLIGHT.1));144 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() {
151 );153 );
152 }154 }
153 155
156+/// The preset is a thing a viewer *sees*: picked on the running session, the
157+/// very next frame out of the funnel is the new rendition, and the three are in
158+/// the order their names promise -- reference darkest, vivid brightest and
159+/// richest. Measured on the rendered BGRA the window gets, so it covers the
160+/// whole chain (project setting -> reseek -> decode worker -> LUT), not the
161+/// table alone.
162+#[test]
163+fn picking_a_preset_changes_the_picture_the_window_shows() {
164+ let mut session = open("test_pq.mp4");
165+ assert_eq!(session.tone(), Preset::Reference, "nobody has picked yet");
166+ let mut shown = Vec::new();
167+ for preset in Preset::ALL {
168+ if preset != Preset::Reference {
169+ assert!(session.set_tone(preset), "pick {preset:?}");
170+ assert!(!session.set_tone(preset), "picking it again changes nothing");
171+ }
172+ let frame = next_frame(&mut session, "a preset");
173+ // Still a picture, not a wash: the fixture's saturated red has to stay
174+ // red under every rendition, which is what a mistuned preset breaks
175+ // first.
176+ assert!(spread(pixel(&frame, RED.1)) > 60, "{preset:?} washed the red out");
177+ shown.push(luma_code(pixel(&frame, DIFFUSE.1)));
178+ }
179+ let [reference, standard, vivid] = [shown[0], shown[1], shown[2]];
180+ assert!(
181+ reference < standard && standard < vivid,
182+ "diffuse white by preset: reference {reference}, standard {standard}, vivid {vivid}"
183+ );
184+ // The vivid preset's *chroma* gain is asserted on the codes rather than
185+ // here: this fixture's red is saturated enough that it clips to 255 in BGRA
186+ // under both presets, so a rendered patch cannot measure it
187+ // (`tonemap::tests::a_brighter_preset_is_brighter_and_a_vivid_one_is_richer`).
188+}
189+
190+/// ...and an SDR stream is not any of this: no clip of it builds a tone map at
191+/// all, so all three presets are the same bytes. The hash is the passthrough
192+/// branch's own, from the test below -- if a preset ever reached an SDR picture,
193+/// this is where it would show.
194+#[test]
195+fn an_sdr_stream_is_the_same_bytes_under_every_preset() {
196+ let mut session = open("test_h264.mkv");
197+ for preset in Preset::ALL {
198+ if preset != Preset::Reference {
199+ assert!(session.set_tone(preset), "pick {preset:?}");
200+ }
201+ let frame = next_frame(&mut session, "a preset");
202+ assert_eq!(fnv(&frame.bgra), SDR_PASSTHROUGH, "{preset:?} moved an SDR picture");
203+ }
204+}
205+
154 /// The other half: an SDR stream may not move by one byte for any of this.206 /// The other half: an SDR stream may not move by one byte for any of this.
155 /// Both branches of the funnel -- the fused passthrough conversion and the207 /// Both branches of the funnel -- the fused passthrough conversion and the
156 /// graded-then-placed one -- against hashes measured before the tone map was208 /// graded-then-placed one -- against hashes measured before the tone map was
@@ -204,8 +256,8 @@ fn the_grade_lands_after_the_tone_map() {
204 256
205 for (name, patch) in [("diffuse white", DIFFUSE), ("red", RED)] {257 for (name, patch) in [("diffuse white", DIFFUSE), ("red", RED)] {
206 let shown = pixel(&frame, patch.1);258 let shown = pixel(&frame, patch.1);
207- let after = by_hand(patch.0, &grade, false);259+ let after = by_hand(patch.0, &grade, false, Preset::default());
208- let before = by_hand(patch.0, &grade, true);260+ let before = by_hand(patch.0, &grade, true, Preset::default());
209 for (i, channel) in ["B", "G", "R"].iter().enumerate() {261 for (i, channel) in ["B", "G", "R"].iter().enumerate() {
210 assert!(262 assert!(
211 shown[i].abs_diff(after[i]) <= 2,263 shown[i].abs_diff(after[i]) <= 2,