forge
Explore
Log in

Don't you dare go Hollow

An nclc colr box states no range, and must not be read as one

Browse files at this commit

98eeb6c19f044c10962b95f759cce7eb9f26c0e1Ahmet Kaan GümüşParent: c2c209e
  • fix
    • an nclc colr box states no range, and must not be read as one
Show full message
fix(mp4): an nclc colr box states no range, and must not be read as one

`ColorInfo` has to answer `full_range` whether or not the file stated one, so
the ten-byte QuickTime `nclc` box -- which stops before the range byte -- was
coming back as a *declaration* of limited range. A host resolving its colour in
tiers then took that fabricated claim as the container tier and shadowed a
bitstream VUI that said full range: a full-range picture displayed as limited,
which is a visibly washed-out one.

`colr` now returns the triplet and the `Tags` that triplet really states, and
`Mp4Demuxer::color_tags(stream)` hands the second one over: an `nclx` states its
range (1 + the flag), an `nclc` and an `nclx` truncated before that byte state
none at all, and a track with no `colr` states nothing. `VideoParameters::color`
is unchanged for every file that really carries an `nclx`.

Latent rather than seen: no file in the scanned library carries an `nclc`.
Fixed as a class anyway -- the same shape sits in ec-matroska, whose `Range`
element is likewise absent-means-limited (`demux.rs:1214`).

cargo test -p ec-mp4: 17 unit + 10 integration passed.
crates/ec-mp4/src/demux.rsmodified+109 -16
@@ -5,7 +5,7 @@ use std::io::{Read, Seek};
55 use ec_core::{
66 AudioParameters, Buf, ChannelLayout, CodecId, CodecParameters, ColorInfo, Demuxer, Error,
77 MediaParameters, MediaType, Packet, PacketFlags, Result, Rounding, SeekMode, StreamInfo,
8- TimeBase, Timestamp, VideoParameters, color,
8+ TimeBase, Timestamp, VideoParameters, color, color::Tags,
99 };
1010
1111 use crate::boxes::{Boxes, FourCc, Src, be16, be32, be64, full};
@@ -47,6 +47,9 @@ pub struct Sample {
4747 /// One `trak`, as far as the packet loop cares about it.
4848 struct Trak {
4949 track_id: u32,
50+ /// What this track's `colr` box stated, tier by tier — empty for a track
51+ /// with no such box and for one that is not a picture.
52+ color_tags: Tags,
5053 /// Index in [`Mp4Demuxer::streams`], or [`None`] for a track whose sample
5154 /// entry this build has no [`CodecId`] for — its samples are walked past,
5255 /// never handed out as some other codec's.
@@ -221,6 +224,22 @@ impl<R: Read + Seek> Mp4Demuxer<R> {
221224 (duration > 0 && timescale > 0).then(|| duration as f64 / f64::from(timescale))
222225 }
223226
227+ /// What `stream`'s `colr` box **stated** about its colour, field by field:
228+ /// [`None`] wherever the box said nothing.
229+ ///
230+ /// Not the same answer as [`VideoParameters::color`], and the difference is
231+ /// the reason this exists. A `ColorInfo` has to fill in a `full_range` flag
232+ /// whether or not the file carried one, so a QuickTime `nclc` box — ten
233+ /// bytes, no range byte — reads there as a *declaration* of limited range
234+ /// and shadows a bitstream that said full. Here it is a matrix and a
235+ /// transfer and no range at all, which is what the file says.
236+ pub fn color_tags(&self, stream: u32) -> Tags {
237+ self.traks
238+ .iter()
239+ .find(|t| t.stream == Some(stream))
240+ .map_or(Tags::default(), |t| t.color_tags)
241+ }
242+
224243 /// Every sample of `stream`, in decode order: the index the file carries of
225244 /// itself. Empty for a stream that does not exist.
226245 pub fn samples(&self, stream: u32) -> &[Sample] {
@@ -391,6 +410,10 @@ impl<R: Read + Seek> Mp4Demuxer<R> {
391410 let table = SampleTable::read(stbl, self.src.len)?;
392411 let samples = table.build(shift)?;
393412 let track_language = language.clone();
413+ let color_tags = table
414+ .entry
415+ .as_ref()
416+ .map_or(Tags::default(), |e| e.color_tags);
394417 let stream = match table.entry {
395418 Some(entry) => {
396419 let media = match entry.codec.media_type() {
@@ -438,6 +461,7 @@ impl<R: Read + Seek> Mp4Demuxer<R> {
438461 });
439462 self.traks.push(Trak {
440463 track_id,
464+ color_tags,
441465 stream,
442466 time_base,
443467 samples,
@@ -879,6 +903,9 @@ struct Entry {
879903 extradata: Option<Buf>,
880904 video: Option<VideoParameters>,
881905 audio: Option<AudioParameters>,
906+ /// What the `colr` box *stated*, which is not what
907+ /// [`VideoParameters::color`] answers: see [`colr`].
908+ color_tags: Tags,
882909 }
883910
884911 /// What one `stsd` entry says its samples are, or [`None`] for a codec this
@@ -894,13 +921,15 @@ fn sample_entry(kind: &FourCc, payload: &[u8]) -> Result<Option<Entry>> {
894921 ..VideoParameters::default()
895922 };
896923 let mut extradata = None;
924+ let mut color_tags = Tags::default();
897925 for child in Boxes::new(payload.get(78..).unwrap_or(&[])) {
898926 let (kind, body) = child?;
899927 if &kind == config {
900928 extradata = Some(Buf::copy_from_slice(body));
901929 } else if &kind == b"colr" {
902- if let Some(info) = colr(body) {
930+ if let Some((info, tags)) = colr(body) {
903931 video.color = info;
932+ color_tags = tags;
904933 }
905934 } else if &kind == b"mdcv" {
906935 video.light = color::mdcv(body).over(video.light);
@@ -916,10 +945,12 @@ fn sample_entry(kind: &FourCc, payload: &[u8]) -> Result<Option<Entry>> {
916945 extradata,
917946 video: Some(video),
918947 audio: None,
948+ color_tags,
919949 }));
920950 }
921951 if kind == b"tx3g" {
922952 return Ok(Some(Entry {
953+ color_tags: Tags::default(),
923954 codec: CodecId::Tx3g,
924955 // The sample entry past its 8-byte header: the justification,
925956 // background colour and default style a renderer needs, which is
@@ -1021,6 +1052,7 @@ fn sample_entry(kind: &FourCc, payload: &[u8]) -> Result<Option<Entry>> {
10211052 extradata,
10221053 video: None,
10231054 audio: Some(audio),
1055+ color_tags: Tags::default(),
10241056 }))
10251057 }
10261058
@@ -1069,18 +1101,42 @@ fn video_codec(kind: &FourCc) -> Option<(CodecId, &'static FourCc)> {
10691101 }
10701102
10711103 /// A `ColourInformationBox`: the H.273 triplet, when it is the `nclx`/`nclc`
1072-/// kind rather than an ICC profile.
1073-fn colr(body: &[u8]) -> Option<ColorInfo> {
1104+/// kind rather than an ICC profile — as the raw triplet *and* as the tags that
1105+/// triplet really states.
1106+///
1107+/// The two are not the same claim, and the difference is a whole box: an `nclx`
1108+/// carries a range bit and a QuickTime `nclc` is ten bytes that stop before it.
1109+/// [`ColorInfo`] has to answer `full_range` either way, so a caller reading only
1110+/// that would take an `nclc` for a declaration of limited range and shadow a
1111+/// bitstream that said full. [`Tags`] can say *nothing*, so that is what an
1112+/// `nclc` — and an `nclx` truncated before its range byte — comes back as.
1113+fn colr(body: &[u8]) -> Option<(ColorInfo, Tags)> {
10741114 let kind = body.get(..4)?;
10751115 if kind != b"nclx" && kind != b"nclc" {
10761116 return None;
10771117 }
1078- Some(ColorInfo {
1079- primaries: be16(body, 4).ok()?.min(255) as u8,
1080- transfer: be16(body, 6).ok()?.min(255) as u8,
1081- matrix: be16(body, 8).ok()?.min(255) as u8,
1082- full_range: body.get(10).is_some_and(|b| b & 0x80 != 0),
1083- })
1118+ let (primaries, transfer, matrix) = (
1119+ be16(body, 4).ok()?,
1120+ be16(body, 6).ok()?,
1121+ be16(body, 8).ok()?,
1122+ );
1123+ // The Matroska `Range` coding [`Tags::from_codes`] takes: 0 says nothing,
1124+ // 1 limited, 2 full. A plain `video_full_range_flag` is `1 + flag`, and a
1125+ // box that never stated one is the 0.
1126+ let range = match kind == b"nclx" {
1127+ true => body.get(10).map_or(0, |b| 1 + u64::from(b >> 7)),
1128+ false => 0,
1129+ };
1130+ let info = ColorInfo {
1131+ primaries: primaries.min(255) as u8,
1132+ transfer: transfer.min(255) as u8,
1133+ matrix: matrix.min(255) as u8,
1134+ full_range: range == 2,
1135+ };
1136+ Some((
1137+ info,
1138+ Tags::from_codes(u64::from(matrix), u64::from(transfer), range),
1139+ ))
10841140 }
10851141
10861142 /// Frames per second off the sample table, as the rational it is.
@@ -1243,13 +1299,17 @@ mod tests {
12431299
12441300 #[test]
12451301 fn a_colr_box_is_the_h273_triplet() {
1246- let mut body = b"nclx".to_vec();
1247- body.extend_from_slice(&9u16.to_be_bytes());
1248- body.extend_from_slice(&16u16.to_be_bytes());
1249- body.extend_from_slice(&9u16.to_be_bytes());
1250- body.push(0x80);
1302+ let triplet = |kind: &[u8; 4]| {
1303+ let mut body = kind.to_vec();
1304+ body.extend_from_slice(&9u16.to_be_bytes());
1305+ body.extend_from_slice(&16u16.to_be_bytes());
1306+ body.extend_from_slice(&9u16.to_be_bytes());
1307+ body
1308+ };
1309+ let mut full = triplet(b"nclx");
1310+ full.push(0x80);
12511311 assert_eq!(
1252- colr(&body),
1312+ colr(&full).map(|(info, _)| info),
12531313 Some(ColorInfo {
12541314 primaries: 9,
12551315 transfer: 16,
@@ -1257,9 +1317,42 @@ mod tests {
12571317 full_range: true
12581318 })
12591319 );
1320+ assert_eq!(
1321+ colr(&full).map(|(_, tags)| tags.full_range),
1322+ Some(Some(true))
1323+ );
1324+ let mut limited = triplet(b"nclx");
1325+ limited.push(0x00);
1326+ assert_eq!(
1327+ colr(&limited).map(|(_, tags)| tags.full_range),
1328+ Some(Some(false)),
1329+ "an nclx that says limited is a claim, and stands"
1330+ );
12601331 assert_eq!(colr(b"prof\0\0"), None, "an ICC profile is not a triplet");
12611332 }
12621333
1334+ /// The box that has no range byte to read: QuickTime's `nclc`, and an `nclx`
1335+ /// truncated before its own last byte. Both state a matrix and a transfer
1336+ /// and **nothing** about range -- a fabricated `limited` here shadows a
1337+ /// bitstream that said full, and that is a green picture on screen.
1338+ #[test]
1339+ fn an_nclc_states_no_range_at_all() {
1340+ let mut body = b"nclc".to_vec();
1341+ body.extend_from_slice(&1u16.to_be_bytes());
1342+ body.extend_from_slice(&1u16.to_be_bytes());
1343+ body.extend_from_slice(&1u16.to_be_bytes());
1344+ assert_eq!(body.len(), 10, "an nclc payload stops at ten bytes");
1345+ let (info, tags) = colr(&body).expect("nclc is a triplet");
1346+ assert_eq!((info.primaries, info.transfer, info.matrix), (1, 1, 1));
1347+ assert_eq!(tags.matrix, Some(color::Matrix::Bt709));
1348+ assert_eq!(tags.transfer, Some(color::Transfer::Sdr));
1349+ assert_eq!(tags.full_range, None, "an nclc box states no range");
1350+ // ...and the same box with an nclx name but no range byte written.
1351+ let mut short = b"nclx".to_vec();
1352+ short.extend_from_slice(&body[4..]);
1353+ assert_eq!(colr(&short).expect("still a triplet").1.full_range, None);
1354+ }
1355+
12631356 #[test]
12641357 fn crafted_table_counts_are_refused_before_they_are_allocated() {
12651358 // An stco stating four billion chunks inside eight bytes.