diff --git a/crates/engine/src/colorspace.rs b/crates/engine/src/colorspace.rs index f257a47..03f0366 100644 --- a/crates/engine/src/colorspace.rs +++ b/crates/engine/src/colorspace.rs @@ -131,6 +131,148 @@ impl ColorDescription { } } +/// How bright a stream's pictures actually get, in cd/m^2 ("nits"), as the grade +/// declared them. Absent from everything but HDR, which is why every field is an +/// [`Option`] and why [`Default`] is all-[`None`]: an SDR file says nothing here +/// and a tone map handed nothing must fall back to its assumed constant rather +/// than to a zero. +/// +/// Two different claims, which is why there are four numbers. `max_cll`/ +/// `max_fall` measure the *content* -- the brightest pixel anywhere in the +/// stream, and the brightest frame average -- while the mastering pair describes +/// the *display the grade was approved on*, which is a ceiling the film may +/// never come near. +/// +/// Parsed at open by both demuxers ([`crate::demux::Demuxer::light`]); nothing +/// reads it yet. [`crate::tonemap`] is where it belongs, and wiring it there is +/// its own change. +#[derive(Debug, Clone, Copy, PartialEq, Default)] +pub struct ContentLight { + /// MaxCLL: the brightest single pixel in the whole stream. + pub max_cll: Option, + /// MaxFALL: the brightest frame-average light level in the whole stream. + pub max_fall: Option, + /// The mastering display's peak white. + pub mastering_max: Option, + /// The mastering display's black, which is a hundredth of a nit or less on + /// the displays these grades are approved on. + pub mastering_min: Option, +} + +impl ContentLight { + /// The peak a tone map should roll off from, or [`None`] for a file that + /// declared neither and has to be assumed at. + /// + /// MaxCLL first, and the order matters: it is the brightest pixel *in this + /// film*, measured over the finished encode. The mastering display's peak is + /// only the brightest thing the colourist *could* have used -- a film graded + /// on a 4000 nit display whose own brightest pixel is 600 comes out crushed + /// if that ceiling is believed instead of the measurement. + pub fn peak(self) -> Option { + self.max_cll.or(self.mastering_max) + } + + /// Field-wise fallback, as [`Tags::over`] is for the colour tags: `self` is + /// the container's word and `under` the bitstream's. Per field rather than + /// per file because a remuxer that rewrote MaxCLL and dropped the mastering + /// block is a file that exists. + pub fn over(self, under: Self) -> Self { + Self { + max_cll: self.max_cll.or(under.max_cll), + max_fall: self.max_fall.or(under.max_fall), + mastering_max: self.mastering_max.or(under.mastering_max), + mastering_min: self.mastering_min.or(under.mastering_min), + } + } +} + +/// A `MasteringDisplayColourVolume` payload: eight 16-bit chromaticities (green, +/// blue, red -- that order -- then the white point) and the two luminances, in +/// ten-thousandths of a nit. An mp4 `mdcv` box and an HEVC +/// `mastering_display_colour_volume` SEI are these same 24 bytes, so one reader +/// serves both; Matroska writes the same numbers as EBML floats instead and is +/// read where it is walked. +/// +/// The chromaticities are read past: what a tone map wants is the luminance +/// pair, and the display's gamut is not something this engine can act on. +/// A zero luminance is "not stated", which is what ffmpeg writes when it has +/// nothing -- believing it would tell a tone map the film peaks at black. +pub(crate) fn mdcv(payload: &[u8]) -> ContentLight { + let luminance = |at: usize| -> Option { + let raw = u32::from_be_bytes(payload.get(at..at + 4)?.try_into().ok()?); + Some(raw as f32 * 1e-4).filter(|v| *v > 0.0) + }; + ContentLight { + mastering_max: luminance(16), + mastering_min: luminance(20), + ..ContentLight::default() + } +} + +/// A `ContentLightLevel` payload: MaxCLL then MaxFALL, whole nits, 16 bits each. +/// An mp4 `clli` box and an HEVC `content_light_level_info` SEI, again the same +/// four bytes. Zero is "not stated" here too. +pub(crate) fn clli(payload: &[u8]) -> ContentLight { + let level = |at: usize| -> Option { + let raw = u16::from_be_bytes(payload.get(at..at + 2)?.try_into().ok()?); + Some(f32::from(raw)).filter(|v| *v > 0.0) + }; + ContentLight { + max_cll: level(0), + max_fall: level(2), + ..ContentLight::default() + } +} + +/// The two HDR SEI messages of one Annex-B access unit. The tier below the +/// container, and for a web rip the *only* tier: the encoder writes these ahead +/// of every keyframe, and a muxer that never carried them into `Colour`/`mdcv` +/// leaves them as the one place the film's real peak still exists (which is +/// exactly what the 2160p HEVC rips this was read against do). +pub fn hevc_sei_light(annex_b: &[u8]) -> ContentLight { + let mut light = ContentLight::default(); + for nal in nal_units(annex_b) { + // 39 prefix SEI, 40 suffix SEI, and the HEVC NAL header is two bytes. + if nal.len() <= 2 || !matches!((nal[0] >> 1) & 0x3f, 39 | 40) { + continue; + } + let sei = rbsp(&nal[2..]); + let mut at = 0; + // sei_message() (H.265 §7.3.5): payload type and size are each a run of + // 0xff bytes plus a final smaller one. The trailing 0x80 of the RBSP + // reads as a type with no size behind it, which ends the walk. + while let (Some(kind), Some(size)) = (sei_value(&sei, &mut at), sei_value(&sei, &mut at)) { + let Some(payload) = sei.get(at..at + size) else { + break; + }; + at += size; + match kind { + 137 => light = light.over(mdcv(payload)), + 144 => light = light.over(clli(payload)), + _ => {} + } + } + } + light +} + +/// One `ff`-extended SEI count, advancing `at` past it. [`None`] at the end of +/// the message and for a run long enough to be garbage rather than a value. +fn sei_value(sei: &[u8], at: &mut usize) -> Option { + let mut value = 0usize; + loop { + let &byte = sei.get(*at)?; + *at += 1; + value += usize::from(byte); + if byte != 0xff { + return Some(value); + } + if value > 1 << 16 { + return None; + } + } +} + /// Rewrites planar 4:2:0 samples coded against `from` as the same picture coded /// against `to`, in place. Both spaces here are limited range with the same /// primaries, so this is the matrix and nothing else: no gamut mapping, no range @@ -1267,4 +1409,193 @@ mod tests { assert!(worst(&u, &ru) <= 2, "cb drifted by {}", worst(&u, &ru)); assert!(worst(&v, &rv) <= 2, "cr drifted by {}", worst(&v, &rv)); } + + /// The grade `scripts/gen_fixtures.sh` writes into all three HDR fixtures: + /// MaxCLL 1000, MaxFALL 400, a 1000 nit mastering display down to 0.005. + const GRADE: ContentLight = ContentLight { + max_cll: Some(1000.0), + max_fall: Some(400.0), + mastering_max: Some(1000.0), + mastering_min: Some(0.005), + }; + + /// Nits, compared the way three different encodings of them allow: Matroska + /// writes 0.005 as a double and both mp4 and the SEI write 50 ten-thousandths + /// of a nit, and those do not land on the same `f32`. + #[track_caller] + fn same_light(got: ContentLight, want: ContentLight) { + let close = |a: Option, b: Option| match (a, b) { + (Some(a), Some(b)) => (a - b).abs() <= b.abs() * 1e-4, + (a, b) => a == b, + }; + assert!( + close(got.max_cll, want.max_cll) + && close(got.max_fall, want.max_fall) + && close(got.mastering_max, want.mastering_max) + && close(got.mastering_min, want.mastering_min), + "{got:?} is not {want:?}" + ); + } + + fn light_of(name: &str) -> ContentLight { + let (_, demuxer) = + Demuxer::open(&asset(name)).unwrap_or_else(|e| panic!("open {name}: {e}")); + demuxer.light() + } + + /// The container tier, both containers: Matroska's `MaxCLL`/`MaxFALL` beside + /// its `MasteringMetadata` floats, and an mp4's `clli`/`mdcv` beside its + /// `colr`. Same grade in, same four numbers out. + #[test] + fn the_containers_carry_the_grades_brightness() { + same_light(light_of("test_hdr_meta.mkv"), GRADE); + same_light(light_of("test_hdr_meta.mp4"), GRADE); + assert_eq!(light_of("test_hdr_meta.mkv").peak(), Some(1000.0)); + } + + /// The bitstream tier, which is the only one a web rip has: test_hdr_sei.mkv + /// is the x265 encode before the transcode that gave the other two their + /// container elements -- its `Colour` element stops at the code points, and + /// every one of these numbers comes out of the first access unit's SEI. + #[test] + fn an_sei_answers_for_a_container_that_says_nothing() { + same_light(light_of("test_hdr_sei.mkv"), GRADE); + } + + /// ...and a file that carries neither tier says so, rather than reporting a + /// zero peak that would tell a tone map the picture never leaves black. + #[test] + fn an_sdr_file_declares_no_brightness_at_all() { + assert_eq!(light_of("test_av.mp4"), ContentLight::default()); + assert_eq!(light_of("test_av1.mkv"), ContentLight::default()); + assert_eq!(ContentLight::default().peak(), None); + } + + /// The number a tone map will ask for. MaxCLL is the film's own measured + /// peak and wins; the mastering display is the fallback, and a grade that + /// stated only the display is still worth more than an assumed constant. + #[test] + fn the_peak_is_the_measured_light_before_the_display_it_was_graded_on() { + assert_eq!(GRADE.peak(), Some(1000.0)); + let display_only = ContentLight { + max_cll: None, + ..GRADE + }; + assert_eq!(display_only.peak(), Some(1000.0), "the mastering display"); + let measured = ContentLight { + max_cll: Some(600.0), + mastering_max: Some(4000.0), + ..ContentLight::default() + }; + assert_eq!( + measured.peak(), + Some(600.0), + "600 nits of content, not 4000" + ); + // The tier fallback: field by field, container over bitstream. + let container = ContentLight { + max_cll: Some(1200.0), + ..ContentLight::default() + }; + assert_eq!( + container.over(measured), + ContentLight { + max_cll: Some(1200.0), + mastering_max: Some(4000.0), + ..ContentLight::default() + } + ); + } + + /// The SEI walk on bytes rather than on a file: a `mastering_display_colour_volume` + /// (137) and a `content_light_level_info` (144) in one prefix SEI NAL, with + /// an emulation-prevention byte inside the mastering payload -- which is not + /// hypothetical, a 0.005 nit minimum *is* `00 00 00 32` before escaping. + #[test] + fn the_sei_walk_reads_past_an_emulation_prevention_byte() { + let mut mastering = Vec::new(); + for coordinate in [8500u16, 39850, 6550, 2300, 35400, 14600, 15635, 16450] { + mastering.extend_from_slice(&coordinate.to_be_bytes()); + } + mastering.extend_from_slice(&10_000_000u32.to_be_bytes()); // 1000 nits + mastering.extend_from_slice(&50u32.to_be_bytes()); // 0.005 nits + let mut nal = vec![39 << 1, 1]; // prefix SEI, temporal id 1 + nal.extend_from_slice(&[137, 24]); + // 00 00 00 32 is escaped into 00 00 03 00 32 by any encoder that writes + // it, and the reader has to undo that or the luminances land a byte out. + let mut escaped = Vec::new(); + let mut zeros = 0; + for &byte in &mastering { + if zeros == 2 && byte <= 3 { + escaped.push(3); + zeros = 0; + } + zeros = if byte == 0 { zeros + 1 } else { 0 }; + escaped.push(byte); + } + assert!( + escaped.len() > mastering.len(), + "the payload needed escaping" + ); + nal.extend_from_slice(&escaped); + nal.extend_from_slice(&[144, 4, 0x03, 0xe8, 0x01, 0x90]); // 1000 / 400 + nal.push(0x80); // rbsp_trailing_bits + let mut annex_b = vec![0, 0, 0, 1]; + annex_b.extend_from_slice(&nal); + same_light(hevc_sei_light(&annex_b), GRADE); + + // Nothing to find is not a failure: a keyframe with no SEI at all, and a + // truncated message, both come back empty rather than reading garbage. + assert_eq!( + hevc_sei_light(&[0, 0, 0, 1, 0x26, 0x01, 0xAA]), + ContentLight::default() + ); + assert_eq!( + hevc_sei_light(&[0, 0, 0, 1, 39 << 1, 1, 144, 4, 0x03]), + ContentLight::default() + ); + } + + /// Zero is what a muxer writes for "I was not told", in every one of the + /// three encodings -- and it must not read back as a film that peaks at + /// black. + #[test] + fn an_unstated_brightness_is_absent_and_not_a_zero() { + assert_eq!(clli(&[0, 0, 0, 0]), ContentLight::default()); + assert_eq!(mdcv(&[0u8; 24]), ContentLight::default()); + // ...and a box shorter than its own syntax is absent too. + assert_eq!(clli(&[0x03]), ContentLight::default()); + assert_eq!(mdcv(&[0u8; 16]), ContentLight::default()); + } + + /// The real thing: a 4K HDR10 web rip, whose grade lives *only* in the + /// bitstream -- its `Colour` element is four code points and stops. The + /// numbers are what ffprobe reports for the same file (`Content light level + /// metadata` 1759/202, `Mastering display metadata` 10000000/10000 down to + /// 50/10000). Skipped, loudly, on a machine without the film. + #[test] + fn a_real_hdr_film_reports_the_peak_ffprobe_reports() { + let film = Path::new( + "/path/to/a-real-4k-hdr10-film.mkv", + ); + if !film.exists() { + eprintln!("skipped: {} is not on this machine", film.display()); + return; + } + let (_, demuxer) = Demuxer::open(film).expect("open the film"); + same_light( + demuxer.light(), + ContentLight { + max_cll: Some(1759.0), + max_fall: Some(202.0), + mastering_max: Some(1000.0), + mastering_min: Some(0.005), + }, + ); + assert_eq!( + demuxer.light().peak(), + Some(1759.0), + "the film's own peak, not the 1000 nit display it was graded on" + ); + } } diff --git a/crates/engine/src/demux.rs b/crates/engine/src/demux.rs index 8260e32..59c13e0 100644 --- a/crates/engine/src/demux.rs +++ b/crates/engine/src/demux.rs @@ -19,7 +19,7 @@ use std::path::Path; use mp4::{MediaType, Mp4Reader, Mp4Track, TrackType}; use crate::audio::{edit_media_time, packet_at, stts_pairs}; -use crate::colorspace::{ColorDescription, Tags, bitstream_tags}; +use crate::colorspace::{ColorDescription, ContentLight, Tags, bitstream_tags}; const START_CODE: [u8; 4] = [0, 0, 0, 1]; @@ -80,12 +80,58 @@ pub enum Demuxer { impl Demuxer { pub fn open(path: &Path) -> crate::Result<(VideoMeta, Self)> { - if is_matroska(path) { + let (meta, mut demuxer) = if is_matroska(path) { let (meta, mkv) = MkvDemuxer::open(path)?; - return Ok((meta, Self::Mkv(mkv))); + (meta, Self::Mkv(mkv)) + } else { + let (meta, mp4) = Mp4Demuxer::open(path)?; + (meta, Self::Mp4(mp4)) + }; + demuxer.fill_sei_light(); + Ok((meta, demuxer)) + } + + /// What the file says about how bright its pictures get, [`ContentLight`], + /// read at open out of the container and -- for an HEVC stream whose + /// container said nothing -- out of the first access unit's SEI. + /// + /// Not part of [`VideoMeta`] for the reason [`Self::bit_depth`] is not: + /// nothing above reads it yet. [`crate::tonemap`] is where it goes, and that + /// is a change of its own. + pub fn light(&self) -> ContentLight { + match self { + Self::Mp4(d) => d.light, + Self::Mkv(d) => d.light, + } + } + + /// The bitstream tier of [`Self::light`]: an HEVC encoder writes the film's + /// peak into an SEI ahead of every keyframe, and a container that carried + /// none of it -- a web rip's Matroska, which tags the curve and stops there + /// -- leaves that SEI as the only place the grade still exists. + /// + /// One access unit is read for it and the cursor put back where it opened, + /// and only when the container said nothing at all: a file that spoke is + /// believed whole rather than half-read, which is what keeps this off the + /// cost of every open. + fn fill_sei_light(&mut self) { + let (codec, light) = match self { + Self::Mp4(d) => (d.codec, d.light), + Self::Mkv(d) => (d.codec, d.light), + }; + if codec != Codec::Hevc || light != ContentLight::default() { + return; + } + let first = self.next_access_unit(); + self.seek_to_sync_at_or_before(0); + let Ok(Some(au)) = first else { + return; + }; + let found = light.over(crate::colorspace::hevc_sei_light(&au)); + match self { + Self::Mp4(d) => d.light = found, + Self::Mkv(d) => d.light = found, } - let (meta, mp4) = Mp4Demuxer::open(path)?; - Ok((meta, Self::Mp4(mp4))) } /// Next access unit in decode order, `None` at end of track. @@ -153,6 +199,8 @@ pub struct Mp4Demuxer { next_sample: u32, /// Bits per luma sample; see [`Demuxer::bit_depth`]. bit_depth: u8, + /// How bright the track says it gets; see [`Demuxer::light`]. + light: ContentLight, } impl Mp4Demuxer { @@ -287,6 +335,7 @@ impl Mp4Demuxer { sync_samples, next_sample, bit_depth, + light: mp4_light(path, track_id), }, )) } @@ -382,6 +431,8 @@ pub struct MkvDemuxer { nal_length: usize, /// Bits per luma sample; see [`Demuxer::bit_depth`]. bit_depth: u8, + /// How bright the track says it gets; see [`Demuxer::light`]. + light: ContentLight, /// One block's bytes, reused across access units: a 4K HEVC keyframe is a /// megabyte and it is reframed, not handed over, so the read needs a /// landing place of its own. @@ -472,6 +523,7 @@ impl MkvDemuxer { config: video.config, nal_length: video.nal_length, bit_depth: video.bit_depth, + light: video.light, scratch: Vec::new(), next: 0, unpack: video.unpack, @@ -533,7 +585,10 @@ impl MkvDemuxer { /// by symphonia, or by the Dolby decoder where it is AC-3 ([`MkvAudio`]), and /// this exists to say which codec neither of them took. pub fn matroska_audio_codec(path: &Path) -> crate::Result> { - Ok(matroska_audio_tracks(path)?.into_iter().next().map(|t| t.codec)) + Ok(matroska_audio_tracks(path)? + .into_iter() + .next() + .map(|t| t.codec)) } /// One audio `TrackEntry` of a Matroska file, as the header describes it. @@ -690,6 +745,9 @@ struct MkvVideo { height: u32, /// What the track's `Colour` element declared, empty when it has none. tags: Tags, + /// What that same element said about brightness (MaxCLL and the mastering + /// display), likewise empty when it said nothing. + light: ContentLight, default_duration: Option, timestamp_scale: u64, codec: Codec, @@ -831,6 +889,15 @@ const COLOUR: u32 = 0x55B0; const MATRIX_COEFFICIENTS: u32 = 0x55B1; const RANGE: u32 = 0x55B9; const TRANSFER_CHARACTERISTICS: u32 = 0x55BA; +// ...and how bright it says its pictures get: two whole-nit integers beside the +// code points, and a `MasteringMetadata` container whose ten children are EBML +// *floats* -- eight chromaticities nothing here reads and the two luminances it +// does. Byte-verified the same way, against an ffmpeg-written HDR fixture. +const MAX_CLL: u32 = 0x55BC; +const MAX_FALL: u32 = 0x55BD; +const MASTERING_METADATA: u32 = 0x55D0; +const LUMINANCE_MAX: u32 = 0x55D9; +const LUMINANCE_MIN: u32 = 0x55DA; const TRACK_LANGUAGE: u32 = 0x22B59C; const TRACK_NAME: u32 = 0x536E; const CONTENT_ENCODINGS: u32 = 0x6D80; @@ -934,6 +1001,7 @@ fn mkv_track_entry( let (mut width, mut height, mut config) = (0, 0, Vec::new()); let (mut language, mut name) = (String::new(), String::new()); let mut tags = Tags::default(); + let mut light = ContentLight::default(); let mut unpack = Unpack::None; let mut at = body; while let Some((id, body, stop)) = ebml_element(file, at, end)? { @@ -971,6 +1039,33 @@ fn mkv_track_entry( transfer = ebml_uint(file, c.1, c.2)? } RANGE => range = ebml_uint(file, c.1, c.2)?, + MAX_CLL => { + light.max_cll = nits(ebml_uint(file, c.1, c.2)? as f64) + } + MAX_FALL => { + light.max_fall = nits(ebml_uint(file, c.1, c.2)? as f64) + } + MASTERING_METADATA => { + let mut at = c.1; + while let Some(m) = ebml_element(file, at, c.2)? { + match m.0 { + LUMINANCE_MAX => { + light.mastering_max = + nits(ebml_float(file, m.1, m.2)?) + } + LUMINANCE_MIN => { + light.mastering_min = + nits(ebml_float(file, m.1, m.2)?) + } + // The eight chromaticities: the + // display's gamut, which this + // engine cannot act on. Walked + // past, never refused. + _ => {} + } + at = m.2; + } + } _ => {} } at = c.2; @@ -1029,6 +1124,7 @@ fn mkv_track_entry( width, height, tags, + light, default_duration, timestamp_scale, codec, @@ -1241,7 +1337,11 @@ fn mkv_lace(file: &mut File, block: &BlockHeader) -> crate::Result crate::Result crate::Result { .fold(0u64, |acc, &b| (acc << 8) | u64::from(b))) } +/// An EBML float element: IEEE big-endian, 4 or 8 bytes wide (a Matroska muxer +/// writes the luminances as doubles). Zero for any other width, which is what an +/// absent one is by spec and what [`nits`] then reads as "not stated". +fn ebml_float(file: &mut File, body: u64, stop: u64) -> crate::Result { + let bytes = ebml_bytes(file, body, stop)?; + Ok(match bytes.len() { + 4 => f64::from(f32::from_be_bytes(bytes[..4].try_into().unwrap())), + 8 => f64::from_be_bytes(bytes[..8].try_into().unwrap()), + _ => 0.0, + }) +} + +/// A brightness a container stated, or [`None`] when it stated zero -- which is +/// what a muxer writes for "unknown" and what a tone map must not read as a film +/// that peaks at black. +fn nits(value: f64) -> Option { + (value > 0.0).then_some(value as f32) +} + /// The payload of an element, which is only ever a header field here -- 8 bytes /// for an integer, a few hundred for a `CodecPrivate`. fn ebml_bytes(file: &mut File, body: u64, stop: u64) -> crate::Result> { @@ -1558,6 +1678,27 @@ fn colr_tags(path: &Path, track_id: u32) -> Option { Some(Tags::from_codes(code(8)?, code(6)?, range)) } +/// The `clli` and `mdcv` boxes of `track_id`'s sample entry: what an mp4 says +/// about how bright its pictures get, beside the `colr` that says what their +/// numbers mean. Neither is a FullBox -- their payloads are the HEVC SEI +/// messages of the same names, byte for byte, and are read by the same pair of +/// readers ([`crate::colorspace::clli`], [`crate::colorspace::mdcv`]). +/// +/// Empty rather than an error for the files that carry neither, which is every +/// SDR mp4 there is. +fn mp4_light(path: &Path, track_id: u32) -> ContentLight { + let Ok((_, entry)) = sample_entry(path, track_id) else { + return ContentLight::default(); + }; + // Behind the same fixed 78-byte VisualSampleEntry header `colr` sits behind. + let entry = entry.get(78..).unwrap_or_default(); + let levels = child(entry, b"clli").map(crate::colorspace::clli); + let mastering = child(entry, b"mdcv").map(crate::colorspace::mdcv); + levels + .unwrap_or_default() + .over(mastering.unwrap_or_default()) +} + /// The four-character code of `track_id`'s first `stsd` sample entry and that /// entry's payload. Read by hand for the same reason the record above is: the /// crate keeps no fourcc for a sample entry it does not recognise, so this is @@ -1800,9 +1941,7 @@ pub fn matroska_subtitles(path: &Path) -> crate::Result> { // The tracks something reads: see `MkvSubtitle::cues`. let wanted: Vec = tracks .iter() - .filter(|t| { - (t.codec.starts_with("S_TEXT") || t.codec == PGS) && t.unsupported.is_none() - }) + .filter(|t| (t.codec.starts_with("S_TEXT") || t.codec == PGS) && t.unsupported.is_none()) .map(|t| t.number) .collect(); if !wanted.is_empty() { diff --git a/scripts/gen_fixtures.sh b/scripts/gen_fixtures.sh index 4ae0b0b..27319ca 100755 --- a/scripts/gen_fixtures.sh +++ b/scripts/gen_fixtures.sh @@ -266,6 +266,27 @@ ffmpeg -y -f lavfi -i testsrc2=size=640x480:rate=30:duration=1 \ ffmpeg -y -f lavfi -i "color=c=black:s=320x240:rate=25:duration=1,format=yuv420p,geq=lum='if(lt(Y,H/2),if(lt(X,W/2),144,181),100)':cb='if(lt(Y,H/2),128,90)':cr='if(lt(Y,H/2),128,200)',setparams=color_primaries=bt2020:color_trc=smpte2084:colorspace=bt2020nc:range=tv" \ -c:v libx264 -profile:v high -qp 1 -pix_fmt yuv420p \ assets/test_pq.mp4 +# The HDR *metadata* fixtures: the same grade written three ways, so the three +# places a film's real peak brightness can live each have a file with known +# numbers in it. MaxCLL 1000, MaxFALL 400, mastering display 1000 nits down to +# 0.005 (which is what x265's `L(10000000,50)` means: ten-thousandths of a nit). +# +# Two passes, and the second one is not optional: `-x265-params master-display` +# only writes the SEI messages *inside the bitstream*, and ffmpeg's muxers write +# a container's own MaxCLL/`mdcv` off stream side data, which exists only once a +# decode has extracted those SEIs. Remuxing with `-c copy` does not do it -- +# verified, the `Colour` element comes back out with the code points and nothing +# else. So: encode HEVC with the SEIs, then transcode into each container, which +# is also what leaves test_hdr_sei.mkv carrying the SEI tier *alone* (H.264 +# writes no such SEI, so the transcoded pair carry the container tier alone). +ffmpeg -y -f lavfi -i "color=c=black:s=320x240:rate=25:duration=0.4,format=yuv420p10le,setparams=color_primaries=bt2020:color_trc=smpte2084:colorspace=bt2020nc:range=tv" \ + -c:v libx265 -pix_fmt yuv420p10le \ + -x265-params "log-level=error:master-display=G(8500,39850)B(6550,2300)R(35400,14600)WP(15635,16450)L(10000000,50):max-cll=1000,400" \ + assets/test_hdr_sei.mkv +ffmpeg -y -i assets/test_hdr_sei.mkv -c:v libx264 -qp 20 -pix_fmt yuv420p \ + assets/test_hdr_meta.mkv +ffmpeg -y -i assets/test_hdr_sei.mkv -c:v libx264 -qp 20 -pix_fmt yuv420p \ + assets/test_hdr_meta.mp4 # Sync fixture: one flash and one beep, at the same instant. Black picture with # a white frame from t=1.0 to t=1.1, silence with a 1 kHz tone over exactly that # stretch — so a test can find each of them and say how far apart they came out.