forge
Explore
Log in

Don't you dare go Hollow

A film's real peak brightness is parsed, not assumed

Browse files at this commit

5726307a96be4b8cc94c56f3a3509d7ba645c16bAhmet Kaan GümüşParent: 7744ff1
  • feat
    • a film's real peak brightness is parsed, not assumed
Show full message
✨ feat(demux): a film's real peak brightness is parsed, not assumed

MaxCLL/MaxFALL and the mastering display's luminances, off all three
places they live: a Matroska Colour element (0x55BC/0x55BD and the
MasteringMetadata floats behind 0x55D0), an mp4 sample entry's clli and
mdcv boxes, and -- for the web rips where the container carries none of
it -- the HEVC SEI messages of the same names in the first access unit.

Carried on Demuxer::light() as ContentLight, whose peak() prefers the
measured content light over the display the grade was approved on.
Nothing reads it yet: wiring it into the tone map, which today assumes a
constant, is its own change.
crates/engine/src/colorspace.rsmodified+331 -0
@@ -131,6 +131,148 @@ impl ColorDescription {
131 }131 }
132 }132 }
133 133
134+/// How bright a stream's pictures actually get, in cd/m^2 ("nits"), as the grade
135+/// declared them. Absent from everything but HDR, which is why every field is an
136+/// [`Option`] and why [`Default`] is all-[`None`]: an SDR file says nothing here
137+/// and a tone map handed nothing must fall back to its assumed constant rather
138+/// than to a zero.
139+///
140+/// Two different claims, which is why there are four numbers. `max_cll`/
141+/// `max_fall` measure the *content* -- the brightest pixel anywhere in the
142+/// stream, and the brightest frame average -- while the mastering pair describes
143+/// the *display the grade was approved on*, which is a ceiling the film may
144+/// never come near.
145+///
146+/// Parsed at open by both demuxers ([`crate::demux::Demuxer::light`]); nothing
147+/// reads it yet. [`crate::tonemap`] is where it belongs, and wiring it there is
148+/// its own change.
149+#[derive(Debug, Clone, Copy, PartialEq, Default)]
150+pub struct ContentLight {
151+ /// MaxCLL: the brightest single pixel in the whole stream.
152+ pub max_cll: Option<f32>,
153+ /// MaxFALL: the brightest frame-average light level in the whole stream.
154+ pub max_fall: Option<f32>,
155+ /// The mastering display's peak white.
156+ pub mastering_max: Option<f32>,
157+ /// The mastering display's black, which is a hundredth of a nit or less on
158+ /// the displays these grades are approved on.
159+ pub mastering_min: Option<f32>,
160+}
161+
162+impl ContentLight {
163+ /// The peak a tone map should roll off from, or [`None`] for a file that
164+ /// declared neither and has to be assumed at.
165+ ///
166+ /// MaxCLL first, and the order matters: it is the brightest pixel *in this
167+ /// film*, measured over the finished encode. The mastering display's peak is
168+ /// only the brightest thing the colourist *could* have used -- a film graded
169+ /// on a 4000 nit display whose own brightest pixel is 600 comes out crushed
170+ /// if that ceiling is believed instead of the measurement.
171+ pub fn peak(self) -> Option<f32> {
172+ self.max_cll.or(self.mastering_max)
173+ }
174+
175+ /// Field-wise fallback, as [`Tags::over`] is for the colour tags: `self` is
176+ /// the container's word and `under` the bitstream's. Per field rather than
177+ /// per file because a remuxer that rewrote MaxCLL and dropped the mastering
178+ /// block is a file that exists.
179+ pub fn over(self, under: Self) -> Self {
180+ Self {
181+ max_cll: self.max_cll.or(under.max_cll),
182+ max_fall: self.max_fall.or(under.max_fall),
183+ mastering_max: self.mastering_max.or(under.mastering_max),
184+ mastering_min: self.mastering_min.or(under.mastering_min),
185+ }
186+ }
187+}
188+
189+/// A `MasteringDisplayColourVolume` payload: eight 16-bit chromaticities (green,
190+/// blue, red -- that order -- then the white point) and the two luminances, in
191+/// ten-thousandths of a nit. An mp4 `mdcv` box and an HEVC
192+/// `mastering_display_colour_volume` SEI are these same 24 bytes, so one reader
193+/// serves both; Matroska writes the same numbers as EBML floats instead and is
194+/// read where it is walked.
195+///
196+/// The chromaticities are read past: what a tone map wants is the luminance
197+/// pair, and the display's gamut is not something this engine can act on.
198+/// A zero luminance is "not stated", which is what ffmpeg writes when it has
199+/// nothing -- believing it would tell a tone map the film peaks at black.
200+pub(crate) fn mdcv(payload: &[u8]) -> ContentLight {
201+ let luminance = |at: usize| -> Option<f32> {
202+ let raw = u32::from_be_bytes(payload.get(at..at + 4)?.try_into().ok()?);
203+ Some(raw as f32 * 1e-4).filter(|v| *v > 0.0)
204+ };
205+ ContentLight {
206+ mastering_max: luminance(16),
207+ mastering_min: luminance(20),
208+ ..ContentLight::default()
209+ }
210+}
211+
212+/// A `ContentLightLevel` payload: MaxCLL then MaxFALL, whole nits, 16 bits each.
213+/// An mp4 `clli` box and an HEVC `content_light_level_info` SEI, again the same
214+/// four bytes. Zero is "not stated" here too.
215+pub(crate) fn clli(payload: &[u8]) -> ContentLight {
216+ let level = |at: usize| -> Option<f32> {
217+ let raw = u16::from_be_bytes(payload.get(at..at + 2)?.try_into().ok()?);
218+ Some(f32::from(raw)).filter(|v| *v > 0.0)
219+ };
220+ ContentLight {
221+ max_cll: level(0),
222+ max_fall: level(2),
223+ ..ContentLight::default()
224+ }
225+}
226+
227+/// The two HDR SEI messages of one Annex-B access unit. The tier below the
228+/// container, and for a web rip the *only* tier: the encoder writes these ahead
229+/// of every keyframe, and a muxer that never carried them into `Colour`/`mdcv`
230+/// leaves them as the one place the film's real peak still exists (which is
231+/// exactly what the 2160p HEVC rips this was read against do).
232+pub fn hevc_sei_light(annex_b: &[u8]) -> ContentLight {
233+ let mut light = ContentLight::default();
234+ for nal in nal_units(annex_b) {
235+ // 39 prefix SEI, 40 suffix SEI, and the HEVC NAL header is two bytes.
236+ if nal.len() <= 2 || !matches!((nal[0] >> 1) & 0x3f, 39 | 40) {
237+ continue;
238+ }
239+ let sei = rbsp(&nal[2..]);
240+ let mut at = 0;
241+ // sei_message() (H.265 §7.3.5): payload type and size are each a run of
242+ // 0xff bytes plus a final smaller one. The trailing 0x80 of the RBSP
243+ // reads as a type with no size behind it, which ends the walk.
244+ while let (Some(kind), Some(size)) = (sei_value(&sei, &mut at), sei_value(&sei, &mut at)) {
245+ let Some(payload) = sei.get(at..at + size) else {
246+ break;
247+ };
248+ at += size;
249+ match kind {
250+ 137 => light = light.over(mdcv(payload)),
251+ 144 => light = light.over(clli(payload)),
252+ _ => {}
253+ }
254+ }
255+ }
256+ light
257+}
258+
259+/// One `ff`-extended SEI count, advancing `at` past it. [`None`] at the end of
260+/// the message and for a run long enough to be garbage rather than a value.
261+fn sei_value(sei: &[u8], at: &mut usize) -> Option<usize> {
262+ let mut value = 0usize;
263+ loop {
264+ let &byte = sei.get(*at)?;
265+ *at += 1;
266+ value += usize::from(byte);
267+ if byte != 0xff {
268+ return Some(value);
269+ }
270+ if value > 1 << 16 {
271+ return None;
272+ }
273+ }
274+}
275+
134 /// Rewrites planar 4:2:0 samples coded against `from` as the same picture coded276 /// Rewrites planar 4:2:0 samples coded against `from` as the same picture coded
135 /// against `to`, in place. Both spaces here are limited range with the same277 /// against `to`, in place. Both spaces here are limited range with the same
136 /// primaries, so this is the matrix and nothing else: no gamut mapping, no range278 /// primaries, so this is the matrix and nothing else: no gamut mapping, no range
@@ -1267,4 +1409,193 @@ mod tests {
1267 assert!(worst(&u, &ru) <= 2, "cb drifted by {}", worst(&u, &ru));1409 assert!(worst(&u, &ru) <= 2, "cb drifted by {}", worst(&u, &ru));
1268 assert!(worst(&v, &rv) <= 2, "cr drifted by {}", worst(&v, &rv));1410 assert!(worst(&v, &rv) <= 2, "cr drifted by {}", worst(&v, &rv));
1269 }1411 }
1412+
1413+ /// The grade `scripts/gen_fixtures.sh` writes into all three HDR fixtures:
1414+ /// MaxCLL 1000, MaxFALL 400, a 1000 nit mastering display down to 0.005.
1415+ const GRADE: ContentLight = ContentLight {
1416+ max_cll: Some(1000.0),
1417+ max_fall: Some(400.0),
1418+ mastering_max: Some(1000.0),
1419+ mastering_min: Some(0.005),
1420+ };
1421+
1422+ /// Nits, compared the way three different encodings of them allow: Matroska
1423+ /// writes 0.005 as a double and both mp4 and the SEI write 50 ten-thousandths
1424+ /// of a nit, and those do not land on the same `f32`.
1425+ #[track_caller]
1426+ fn same_light(got: ContentLight, want: ContentLight) {
1427+ let close = |a: Option<f32>, b: Option<f32>| match (a, b) {
1428+ (Some(a), Some(b)) => (a - b).abs() <= b.abs() * 1e-4,
1429+ (a, b) => a == b,
1430+ };
1431+ assert!(
1432+ close(got.max_cll, want.max_cll)
1433+ && close(got.max_fall, want.max_fall)
1434+ && close(got.mastering_max, want.mastering_max)
1435+ && close(got.mastering_min, want.mastering_min),
1436+ "{got:?} is not {want:?}"
1437+ );
1438+ }
1439+
1440+ fn light_of(name: &str) -> ContentLight {
1441+ let (_, demuxer) =
1442+ Demuxer::open(&asset(name)).unwrap_or_else(|e| panic!("open {name}: {e}"));
1443+ demuxer.light()
1444+ }
1445+
1446+ /// The container tier, both containers: Matroska's `MaxCLL`/`MaxFALL` beside
1447+ /// its `MasteringMetadata` floats, and an mp4's `clli`/`mdcv` beside its
1448+ /// `colr`. Same grade in, same four numbers out.
1449+ #[test]
1450+ fn the_containers_carry_the_grades_brightness() {
1451+ same_light(light_of("test_hdr_meta.mkv"), GRADE);
1452+ same_light(light_of("test_hdr_meta.mp4"), GRADE);
1453+ assert_eq!(light_of("test_hdr_meta.mkv").peak(), Some(1000.0));
1454+ }
1455+
1456+ /// The bitstream tier, which is the only one a web rip has: test_hdr_sei.mkv
1457+ /// is the x265 encode before the transcode that gave the other two their
1458+ /// container elements -- its `Colour` element stops at the code points, and
1459+ /// every one of these numbers comes out of the first access unit's SEI.
1460+ #[test]
1461+ fn an_sei_answers_for_a_container_that_says_nothing() {
1462+ same_light(light_of("test_hdr_sei.mkv"), GRADE);
1463+ }
1464+
1465+ /// ...and a file that carries neither tier says so, rather than reporting a
1466+ /// zero peak that would tell a tone map the picture never leaves black.
1467+ #[test]
1468+ fn an_sdr_file_declares_no_brightness_at_all() {
1469+ assert_eq!(light_of("test_av.mp4"), ContentLight::default());
1470+ assert_eq!(light_of("test_av1.mkv"), ContentLight::default());
1471+ assert_eq!(ContentLight::default().peak(), None);
1472+ }
1473+
1474+ /// The number a tone map will ask for. MaxCLL is the film's own measured
1475+ /// peak and wins; the mastering display is the fallback, and a grade that
1476+ /// stated only the display is still worth more than an assumed constant.
1477+ #[test]
1478+ fn the_peak_is_the_measured_light_before_the_display_it_was_graded_on() {
1479+ assert_eq!(GRADE.peak(), Some(1000.0));
1480+ let display_only = ContentLight {
1481+ max_cll: None,
1482+ ..GRADE
1483+ };
1484+ assert_eq!(display_only.peak(), Some(1000.0), "the mastering display");
1485+ let measured = ContentLight {
1486+ max_cll: Some(600.0),
1487+ mastering_max: Some(4000.0),
1488+ ..ContentLight::default()
1489+ };
1490+ assert_eq!(
1491+ measured.peak(),
1492+ Some(600.0),
1493+ "600 nits of content, not 4000"
1494+ );
1495+ // The tier fallback: field by field, container over bitstream.
1496+ let container = ContentLight {
1497+ max_cll: Some(1200.0),
1498+ ..ContentLight::default()
1499+ };
1500+ assert_eq!(
1501+ container.over(measured),
1502+ ContentLight {
1503+ max_cll: Some(1200.0),
1504+ mastering_max: Some(4000.0),
1505+ ..ContentLight::default()
1506+ }
1507+ );
1508+ }
1509+
1510+ /// The SEI walk on bytes rather than on a file: a `mastering_display_colour_volume`
1511+ /// (137) and a `content_light_level_info` (144) in one prefix SEI NAL, with
1512+ /// an emulation-prevention byte inside the mastering payload -- which is not
1513+ /// hypothetical, a 0.005 nit minimum *is* `00 00 00 32` before escaping.
1514+ #[test]
1515+ fn the_sei_walk_reads_past_an_emulation_prevention_byte() {
1516+ let mut mastering = Vec::new();
1517+ for coordinate in [8500u16, 39850, 6550, 2300, 35400, 14600, 15635, 16450] {
1518+ mastering.extend_from_slice(&coordinate.to_be_bytes());
1519+ }
1520+ mastering.extend_from_slice(&10_000_000u32.to_be_bytes()); // 1000 nits
1521+ mastering.extend_from_slice(&50u32.to_be_bytes()); // 0.005 nits
1522+ let mut nal = vec![39 << 1, 1]; // prefix SEI, temporal id 1
1523+ nal.extend_from_slice(&[137, 24]);
1524+ // 00 00 00 32 is escaped into 00 00 03 00 32 by any encoder that writes
1525+ // it, and the reader has to undo that or the luminances land a byte out.
1526+ let mut escaped = Vec::new();
1527+ let mut zeros = 0;
1528+ for &byte in &mastering {
1529+ if zeros == 2 && byte <= 3 {
1530+ escaped.push(3);
1531+ zeros = 0;
1532+ }
1533+ zeros = if byte == 0 { zeros + 1 } else { 0 };
1534+ escaped.push(byte);
1535+ }
1536+ assert!(
1537+ escaped.len() > mastering.len(),
1538+ "the payload needed escaping"
1539+ );
1540+ nal.extend_from_slice(&escaped);
1541+ nal.extend_from_slice(&[144, 4, 0x03, 0xe8, 0x01, 0x90]); // 1000 / 400
1542+ nal.push(0x80); // rbsp_trailing_bits
1543+ let mut annex_b = vec![0, 0, 0, 1];
1544+ annex_b.extend_from_slice(&nal);
1545+ same_light(hevc_sei_light(&annex_b), GRADE);
1546+
1547+ // Nothing to find is not a failure: a keyframe with no SEI at all, and a
1548+ // truncated message, both come back empty rather than reading garbage.
1549+ assert_eq!(
1550+ hevc_sei_light(&[0, 0, 0, 1, 0x26, 0x01, 0xAA]),
1551+ ContentLight::default()
1552+ );
1553+ assert_eq!(
1554+ hevc_sei_light(&[0, 0, 0, 1, 39 << 1, 1, 144, 4, 0x03]),
1555+ ContentLight::default()
1556+ );
1557+ }
1558+
1559+ /// Zero is what a muxer writes for "I was not told", in every one of the
1560+ /// three encodings -- and it must not read back as a film that peaks at
1561+ /// black.
1562+ #[test]
1563+ fn an_unstated_brightness_is_absent_and_not_a_zero() {
1564+ assert_eq!(clli(&[0, 0, 0, 0]), ContentLight::default());
1565+ assert_eq!(mdcv(&[0u8; 24]), ContentLight::default());
1566+ // ...and a box shorter than its own syntax is absent too.
1567+ assert_eq!(clli(&[0x03]), ContentLight::default());
1568+ assert_eq!(mdcv(&[0u8; 16]), ContentLight::default());
1569+ }
1570+
1571+ /// The real thing: a 4K HDR10 web rip, whose grade lives *only* in the
1572+ /// bitstream -- its `Colour` element is four code points and stops. The
1573+ /// numbers are what ffprobe reports for the same file (`Content light level
1574+ /// metadata` 1759/202, `Mastering display metadata` 10000000/10000 down to
1575+ /// 50/10000). Skipped, loudly, on a machine without the film.
1576+ #[test]
1577+ fn a_real_hdr_film_reports_the_peak_ffprobe_reports() {
1578+ let film = Path::new(
1579+ "/path/to/a-real-4k-hdr10-film.mkv",
1580+ );
1581+ if !film.exists() {
1582+ eprintln!("skipped: {} is not on this machine", film.display());
1583+ return;
1584+ }
1585+ let (_, demuxer) = Demuxer::open(film).expect("open the film");
1586+ same_light(
1587+ demuxer.light(),
1588+ ContentLight {
1589+ max_cll: Some(1759.0),
1590+ max_fall: Some(202.0),
1591+ mastering_max: Some(1000.0),
1592+ mastering_min: Some(0.005),
1593+ },
1594+ );
1595+ assert_eq!(
1596+ demuxer.light().peak(),
1597+ Some(1759.0),
1598+ "the film's own peak, not the 1000 nit display it was graded on"
1599+ );
1600+ }
1270 }1601 }
crates/engine/src/demux.rsmodified+152 -13
@@ -19,7 +19,7 @@ use std::path::Path;
19 use mp4::{MediaType, Mp4Reader, Mp4Track, TrackType};19 use mp4::{MediaType, Mp4Reader, Mp4Track, TrackType};
20 20
21 use crate::audio::{edit_media_time, packet_at, stts_pairs};21 use crate::audio::{edit_media_time, packet_at, stts_pairs};
22-use crate::colorspace::{ColorDescription, Tags, bitstream_tags};22+use crate::colorspace::{ColorDescription, ContentLight, Tags, bitstream_tags};
23 23
24 const START_CODE: [u8; 4] = [0, 0, 0, 1];24 const START_CODE: [u8; 4] = [0, 0, 0, 1];
25 25
@@ -80,12 +80,58 @@ pub enum Demuxer {
80 80
81 impl Demuxer {81 impl Demuxer {
82 pub fn open(path: &Path) -> crate::Result<(VideoMeta, Self)> {82 pub fn open(path: &Path) -> crate::Result<(VideoMeta, Self)> {
83- if is_matroska(path) {83+ let (meta, mut demuxer) = if is_matroska(path) {
84 let (meta, mkv) = MkvDemuxer::open(path)?;84 let (meta, mkv) = MkvDemuxer::open(path)?;
85- return Ok((meta, Self::Mkv(mkv)));85+ (meta, Self::Mkv(mkv))
86+ } else {
87+ let (meta, mp4) = Mp4Demuxer::open(path)?;
88+ (meta, Self::Mp4(mp4))
89+ };
90+ demuxer.fill_sei_light();
91+ Ok((meta, demuxer))
92+ }
93+
94+ /// What the file says about how bright its pictures get, [`ContentLight`],
95+ /// read at open out of the container and -- for an HEVC stream whose
96+ /// container said nothing -- out of the first access unit's SEI.
97+ ///
98+ /// Not part of [`VideoMeta`] for the reason [`Self::bit_depth`] is not:
99+ /// nothing above reads it yet. [`crate::tonemap`] is where it goes, and that
100+ /// is a change of its own.
101+ pub fn light(&self) -> ContentLight {
102+ match self {
103+ Self::Mp4(d) => d.light,
104+ Self::Mkv(d) => d.light,
105+ }
106+ }
107+
108+ /// The bitstream tier of [`Self::light`]: an HEVC encoder writes the film's
109+ /// peak into an SEI ahead of every keyframe, and a container that carried
110+ /// none of it -- a web rip's Matroska, which tags the curve and stops there
111+ /// -- leaves that SEI as the only place the grade still exists.
112+ ///
113+ /// One access unit is read for it and the cursor put back where it opened,
114+ /// and only when the container said nothing at all: a file that spoke is
115+ /// believed whole rather than half-read, which is what keeps this off the
116+ /// cost of every open.
117+ fn fill_sei_light(&mut self) {
118+ let (codec, light) = match self {
119+ Self::Mp4(d) => (d.codec, d.light),
120+ Self::Mkv(d) => (d.codec, d.light),
121+ };
122+ if codec != Codec::Hevc || light != ContentLight::default() {
123+ return;
124+ }
125+ let first = self.next_access_unit();
126+ self.seek_to_sync_at_or_before(0);
127+ let Ok(Some(au)) = first else {
128+ return;
129+ };
130+ let found = light.over(crate::colorspace::hevc_sei_light(&au));
131+ match self {
132+ Self::Mp4(d) => d.light = found,
133+ Self::Mkv(d) => d.light = found,
86 }134 }
87- let (meta, mp4) = Mp4Demuxer::open(path)?;
88- Ok((meta, Self::Mp4(mp4)))
89 }135 }
90 136
91 /// Next access unit in decode order, `None` at end of track.137 /// Next access unit in decode order, `None` at end of track.
@@ -153,6 +199,8 @@ pub struct Mp4Demuxer {
153 next_sample: u32,199 next_sample: u32,
154 /// Bits per luma sample; see [`Demuxer::bit_depth`].200 /// Bits per luma sample; see [`Demuxer::bit_depth`].
155 bit_depth: u8,201 bit_depth: u8,
202+ /// How bright the track says it gets; see [`Demuxer::light`].
203+ light: ContentLight,
156 }204 }
157 205
158 impl Mp4Demuxer {206 impl Mp4Demuxer {
@@ -287,6 +335,7 @@ impl Mp4Demuxer {
287 sync_samples,335 sync_samples,
288 next_sample,336 next_sample,
289 bit_depth,337 bit_depth,
338+ light: mp4_light(path, track_id),
290 },339 },
291 ))340 ))
292 }341 }
@@ -382,6 +431,8 @@ pub struct MkvDemuxer {
382 nal_length: usize,431 nal_length: usize,
383 /// Bits per luma sample; see [`Demuxer::bit_depth`].432 /// Bits per luma sample; see [`Demuxer::bit_depth`].
384 bit_depth: u8,433 bit_depth: u8,
434+ /// How bright the track says it gets; see [`Demuxer::light`].
435+ light: ContentLight,
385 /// One block's bytes, reused across access units: a 4K HEVC keyframe is a436 /// One block's bytes, reused across access units: a 4K HEVC keyframe is a
386 /// megabyte and it is reframed, not handed over, so the read needs a437 /// megabyte and it is reframed, not handed over, so the read needs a
387 /// landing place of its own.438 /// landing place of its own.
@@ -472,6 +523,7 @@ impl MkvDemuxer {
472 config: video.config,523 config: video.config,
473 nal_length: video.nal_length,524 nal_length: video.nal_length,
474 bit_depth: video.bit_depth,525 bit_depth: video.bit_depth,
526+ light: video.light,
475 scratch: Vec::new(),527 scratch: Vec::new(),
476 next: 0,528 next: 0,
477 unpack: video.unpack,529 unpack: video.unpack,
@@ -533,7 +585,10 @@ impl MkvDemuxer {
533 /// by symphonia, or by the Dolby decoder where it is AC-3 ([`MkvAudio`]), and585 /// by symphonia, or by the Dolby decoder where it is AC-3 ([`MkvAudio`]), and
534 /// this exists to say which codec neither of them took.586 /// this exists to say which codec neither of them took.
535 pub fn matroska_audio_codec(path: &Path) -> crate::Result<Option<String>> {587 pub fn matroska_audio_codec(path: &Path) -> crate::Result<Option<String>> {
536- Ok(matroska_audio_tracks(path)?.into_iter().next().map(|t| t.codec))588+ Ok(matroska_audio_tracks(path)?
589+ .into_iter()
590+ .next()
591+ .map(|t| t.codec))
537 }592 }
538 593
539 /// One audio `TrackEntry` of a Matroska file, as the header describes it.594 /// One audio `TrackEntry` of a Matroska file, as the header describes it.
@@ -690,6 +745,9 @@ struct MkvVideo {
690 height: u32,745 height: u32,
691 /// What the track's `Colour` element declared, empty when it has none.746 /// What the track's `Colour` element declared, empty when it has none.
692 tags: Tags,747 tags: Tags,
748+ /// What that same element said about brightness (MaxCLL and the mastering
749+ /// display), likewise empty when it said nothing.
750+ light: ContentLight,
693 default_duration: Option<u64>,751 default_duration: Option<u64>,
694 timestamp_scale: u64,752 timestamp_scale: u64,
695 codec: Codec,753 codec: Codec,
@@ -831,6 +889,15 @@ const COLOUR: u32 = 0x55B0;
831 const MATRIX_COEFFICIENTS: u32 = 0x55B1;889 const MATRIX_COEFFICIENTS: u32 = 0x55B1;
832 const RANGE: u32 = 0x55B9;890 const RANGE: u32 = 0x55B9;
833 const TRANSFER_CHARACTERISTICS: u32 = 0x55BA;891 const TRANSFER_CHARACTERISTICS: u32 = 0x55BA;
892+// ...and how bright it says its pictures get: two whole-nit integers beside the
893+// code points, and a `MasteringMetadata` container whose ten children are EBML
894+// *floats* -- eight chromaticities nothing here reads and the two luminances it
895+// does. Byte-verified the same way, against an ffmpeg-written HDR fixture.
896+const MAX_CLL: u32 = 0x55BC;
897+const MAX_FALL: u32 = 0x55BD;
898+const MASTERING_METADATA: u32 = 0x55D0;
899+const LUMINANCE_MAX: u32 = 0x55D9;
900+const LUMINANCE_MIN: u32 = 0x55DA;
834 const TRACK_LANGUAGE: u32 = 0x22B59C;901 const TRACK_LANGUAGE: u32 = 0x22B59C;
835 const TRACK_NAME: u32 = 0x536E;902 const TRACK_NAME: u32 = 0x536E;
836 const CONTENT_ENCODINGS: u32 = 0x6D80;903 const CONTENT_ENCODINGS: u32 = 0x6D80;
@@ -934,6 +1001,7 @@ fn mkv_track_entry(
934 let (mut width, mut height, mut config) = (0, 0, Vec::new());1001 let (mut width, mut height, mut config) = (0, 0, Vec::new());
935 let (mut language, mut name) = (String::new(), String::new());1002 let (mut language, mut name) = (String::new(), String::new());
936 let mut tags = Tags::default();1003 let mut tags = Tags::default();
1004+ let mut light = ContentLight::default();
937 let mut unpack = Unpack::None;1005 let mut unpack = Unpack::None;
938 let mut at = body;1006 let mut at = body;
939 while let Some((id, body, stop)) = ebml_element(file, at, end)? {1007 while let Some((id, body, stop)) = ebml_element(file, at, end)? {
@@ -971,6 +1039,33 @@ fn mkv_track_entry(
971 transfer = ebml_uint(file, c.1, c.2)?1039 transfer = ebml_uint(file, c.1, c.2)?
972 }1040 }
973 RANGE => range = ebml_uint(file, c.1, c.2)?,1041 RANGE => range = ebml_uint(file, c.1, c.2)?,
1042+ MAX_CLL => {
1043+ light.max_cll = nits(ebml_uint(file, c.1, c.2)? as f64)
1044+ }
1045+ MAX_FALL => {
1046+ light.max_fall = nits(ebml_uint(file, c.1, c.2)? as f64)
1047+ }
1048+ MASTERING_METADATA => {
1049+ let mut at = c.1;
1050+ while let Some(m) = ebml_element(file, at, c.2)? {
1051+ match m.0 {
1052+ LUMINANCE_MAX => {
1053+ light.mastering_max =
1054+ nits(ebml_float(file, m.1, m.2)?)
1055+ }
1056+ LUMINANCE_MIN => {
1057+ light.mastering_min =
1058+ nits(ebml_float(file, m.1, m.2)?)
1059+ }
1060+ // The eight chromaticities: the
1061+ // display's gamut, which this
1062+ // engine cannot act on. Walked
1063+ // past, never refused.
1064+ _ => {}
1065+ }
1066+ at = m.2;
1067+ }
1068+ }
974 _ => {}1069 _ => {}
975 }1070 }
976 at = c.2;1071 at = c.2;
@@ -1029,6 +1124,7 @@ fn mkv_track_entry(
1029 width,1124 width,
1030 height,1125 height,
1031 tags,1126 tags,
1127+ light,
1032 default_duration,1128 default_duration,
1033 timestamp_scale,1129 timestamp_scale,
1034 codec,1130 codec,
@@ -1241,7 +1337,11 @@ fn mkv_lace(file: &mut File, block: &BlockHeader) -> crate::Result<Vec<(u64, usi
1241 let head_len = (1 + 256 * 9).min(block.len);1337 let head_len = (1 + 256 * 9).min(block.len);
1242 let mut head = vec![0u8; head_len];1338 let mut head = vec![0u8; head_len];
1243 read_exact_at(file, block.at, &mut head)?;1339 read_exact_at(file, block.at, &mut head)?;
1244- let count = usize::from(*head.first().ok_or("a laced Matroska block with no frames")?) + 1;1340+ let count = usize::from(
1341+ *head
1342+ .first()
1343+ .ok_or("a laced Matroska block with no frames")?,
1344+ ) + 1;
1245 let short = || crate::Error::from("a Matroska lace header past the end of its block");1345 let short = || crate::Error::from("a Matroska lace header past the end of its block");
1246 // The cursor into the lace header, which is where the frames start once the1346 // The cursor into the lace header, which is where the frames start once the
1247 // sizes have been read.1347 // sizes have been read.
@@ -1293,9 +1393,10 @@ fn mkv_lace(file: &mut File, block: &BlockHeader) -> crate::Result<Vec<(u64, usi
1293 let mut frames = Vec::with_capacity(count);1393 let mut frames = Vec::with_capacity(count);
1294 let mut off = block.at + at as u64;1394 let mut off = block.at + at as u64;
1295 for size in sizes {1395 for size in sizes {
1296- let stop = off.checked_add(size as u64).filter(|&s| s <= end).ok_or(1396+ let stop = off
1297- "a Matroska lace whose frame sizes run past the end of its block",1397+ .checked_add(size as u64)
1298- )?;1398+ .filter(|&s| s <= end)
1399+ .ok_or("a Matroska lace whose frame sizes run past the end of its block")?;
1299 frames.push((off, size));1400 frames.push((off, size));
1300 off = stop;1401 off = stop;
1301 }1402 }
@@ -1392,6 +1493,25 @@ fn ebml_uint(file: &mut File, body: u64, stop: u64) -> crate::Result<u64> {
1392 .fold(0u64, |acc, &b| (acc << 8) | u64::from(b)))1493 .fold(0u64, |acc, &b| (acc << 8) | u64::from(b)))
1393 }1494 }
1394 1495
1496+/// An EBML float element: IEEE big-endian, 4 or 8 bytes wide (a Matroska muxer
1497+/// writes the luminances as doubles). Zero for any other width, which is what an
1498+/// absent one is by spec and what [`nits`] then reads as "not stated".
1499+fn ebml_float(file: &mut File, body: u64, stop: u64) -> crate::Result<f64> {
1500+ let bytes = ebml_bytes(file, body, stop)?;
1501+ Ok(match bytes.len() {
1502+ 4 => f64::from(f32::from_be_bytes(bytes[..4].try_into().unwrap())),
1503+ 8 => f64::from_be_bytes(bytes[..8].try_into().unwrap()),
1504+ _ => 0.0,
1505+ })
1506+}
1507+
1508+/// A brightness a container stated, or [`None`] when it stated zero -- which is
1509+/// what a muxer writes for "unknown" and what a tone map must not read as a film
1510+/// that peaks at black.
1511+fn nits(value: f64) -> Option<f32> {
1512+ (value > 0.0).then_some(value as f32)
1513+}
1514+
1395 /// The payload of an element, which is only ever a header field here -- 8 bytes1515 /// The payload of an element, which is only ever a header field here -- 8 bytes
1396 /// for an integer, a few hundred for a `CodecPrivate`.1516 /// for an integer, a few hundred for a `CodecPrivate`.
1397 fn ebml_bytes(file: &mut File, body: u64, stop: u64) -> crate::Result<Vec<u8>> {1517 fn ebml_bytes(file: &mut File, body: u64, stop: u64) -> crate::Result<Vec<u8>> {
@@ -1558,6 +1678,27 @@ fn colr_tags(path: &Path, track_id: u32) -> Option<Tags> {
1558 Some(Tags::from_codes(code(8)?, code(6)?, range))1678 Some(Tags::from_codes(code(8)?, code(6)?, range))
1559 }1679 }
1560 1680
1681+/// The `clli` and `mdcv` boxes of `track_id`'s sample entry: what an mp4 says
1682+/// about how bright its pictures get, beside the `colr` that says what their
1683+/// numbers mean. Neither is a FullBox -- their payloads are the HEVC SEI
1684+/// messages of the same names, byte for byte, and are read by the same pair of
1685+/// readers ([`crate::colorspace::clli`], [`crate::colorspace::mdcv`]).
1686+///
1687+/// Empty rather than an error for the files that carry neither, which is every
1688+/// SDR mp4 there is.
1689+fn mp4_light(path: &Path, track_id: u32) -> ContentLight {
1690+ let Ok((_, entry)) = sample_entry(path, track_id) else {
1691+ return ContentLight::default();
1692+ };
1693+ // Behind the same fixed 78-byte VisualSampleEntry header `colr` sits behind.
1694+ let entry = entry.get(78..).unwrap_or_default();
1695+ let levels = child(entry, b"clli").map(crate::colorspace::clli);
1696+ let mastering = child(entry, b"mdcv").map(crate::colorspace::mdcv);
1697+ levels
1698+ .unwrap_or_default()
1699+ .over(mastering.unwrap_or_default())
1700+}
1701+
1561 /// The four-character code of `track_id`'s first `stsd` sample entry and that1702 /// The four-character code of `track_id`'s first `stsd` sample entry and that
1562 /// entry's payload. Read by hand for the same reason the record above is: the1703 /// entry's payload. Read by hand for the same reason the record above is: the
1563 /// crate keeps no fourcc for a sample entry it does not recognise, so this is1704 /// 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<Vec<MkvSubtitle>> {
1800 // The tracks something reads: see `MkvSubtitle::cues`.1941 // The tracks something reads: see `MkvSubtitle::cues`.
1801 let wanted: Vec<u64> = tracks1942 let wanted: Vec<u64> = tracks
1802 .iter()1943 .iter()
1803- .filter(|t| {1944+ .filter(|t| (t.codec.starts_with("S_TEXT") || t.codec == PGS) && t.unsupported.is_none())
1804- (t.codec.starts_with("S_TEXT") || t.codec == PGS) && t.unsupported.is_none()
1805- })
1806 .map(|t| t.number)1945 .map(|t| t.number)
1807 .collect();1946 .collect();
1808 if !wanted.is_empty() {1947 if !wanted.is_empty() {
scripts/gen_fixtures.shmodified+21 -0
@@ -266,6 +266,27 @@ ffmpeg -y -f lavfi -i testsrc2=size=640x480:rate=30:duration=1 \
266 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" \266 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" \
267 -c:v libx264 -profile:v high -qp 1 -pix_fmt yuv420p \267 -c:v libx264 -profile:v high -qp 1 -pix_fmt yuv420p \
268 assets/test_pq.mp4268 assets/test_pq.mp4
269+# The HDR *metadata* fixtures: the same grade written three ways, so the three
270+# places a film's real peak brightness can live each have a file with known
271+# numbers in it. MaxCLL 1000, MaxFALL 400, mastering display 1000 nits down to
272+# 0.005 (which is what x265's `L(10000000,50)` means: ten-thousandths of a nit).
273+#
274+# Two passes, and the second one is not optional: `-x265-params master-display`
275+# only writes the SEI messages *inside the bitstream*, and ffmpeg's muxers write
276+# a container's own MaxCLL/`mdcv` off stream side data, which exists only once a
277+# decode has extracted those SEIs. Remuxing with `-c copy` does not do it --
278+# verified, the `Colour` element comes back out with the code points and nothing
279+# else. So: encode HEVC with the SEIs, then transcode into each container, which
280+# is also what leaves test_hdr_sei.mkv carrying the SEI tier *alone* (H.264
281+# writes no such SEI, so the transcoded pair carry the container tier alone).
282+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" \
283+ -c:v libx265 -pix_fmt yuv420p10le \
284+ -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" \
285+ assets/test_hdr_sei.mkv
286+ffmpeg -y -i assets/test_hdr_sei.mkv -c:v libx264 -qp 20 -pix_fmt yuv420p \
287+ assets/test_hdr_meta.mkv
288+ffmpeg -y -i assets/test_hdr_sei.mkv -c:v libx264 -qp 20 -pix_fmt yuv420p \
289+ assets/test_hdr_meta.mp4
269 # Sync fixture: one flash and one beep, at the same instant. Black picture with290 # Sync fixture: one flash and one beep, at the same instant. Black picture with
270 # a white frame from t=1.0 to t=1.1, silence with a 1 kHz tone over exactly that291 # a white frame from t=1.0 to t=1.1, silence with a 1 kHz tone over exactly that
271 # stretch — so a test can find each of them and say how far apart they came out.292 # stretch — so a test can find each of them and say how far apart they came out.