forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'ec-hw-colour-meta'

Browse files at this commit

a5703e8d9ccab9c9af3cbb01506b6999f8ba5b2bAhmet Kaan GümüşParent: 665fede7669974
crates/ec-hw/src/dec/av1.rsmodified+2 -0
@@ -115,6 +115,7 @@ impl Av1Decoder {
115 (header.render_width, header.render_height),115 (header.render_width, header.render_height),
116 session.coded_size,116 session.coded_size,
117 session.bit_depth,117 session.bit_depth,
118+ None,
118 ));119 ));
119 // 7.21: showing a KEY frame again refreshes every reference slot with120 // 7.21: showing a KEY frame again refreshes every reference slot with
120 // it, which the reference *surfaces* have to follow too.121 // it, which the reference *surfaces* have to follow too.
@@ -183,6 +184,7 @@ impl Av1Decoder {
183 (header.render_width, header.render_height),184 (header.render_width, header.render_height),
184 session.coded_size,185 session.coded_size,
185 session.bit_depth,186 session.bit_depth,
187+ None,
186 ));188 ));
187 }189 }
188 Ok(())190 Ok(())
crates/ec-hw/src/dec/h264.rsmodified+40 -1
@@ -2,6 +2,7 @@
2 2
3 use std::sync::Arc;3 use std::sync::Arc;
4 4
5+use ec_core::color::{ColorDescription, ContentLight, Tags};
5 use ec_h264_syntax::{6 use ec_h264_syntax::{
6 AnnexBIter, DecRefPicMarking, NalHeader, NalUnitType, Pps, PredWeightTable, SliceHeader,7 AnnexBIter, DecRefPicMarking, NalHeader, NalUnitType, Pps, PredWeightTable, SliceHeader,
7 SliceType, Sps, unescape_rbsp,8 SliceType, Sps, unescape_rbsp,
@@ -12,7 +13,7 @@ use ec_va::{Buffer, Display, sys};
12 use super::dpb264::{Dpb, Mark, PicInfo, Picture, Poc, RefList};13 use super::dpb264::{Dpb, Mark, PicInfo, Picture, Poc, RefList};
13 use super::{ReadyFrames, Session, StreamInfo};14 use super::{ReadyFrames, Session, StreamInfo};
14 use crate::error::{Error, Result};15 use crate::error::{Error, Result};
15-use crate::frame::Frame;16+use crate::frame::{Colour, Frame};
16 use crate::params::h264::{17 use crate::params::h264::{
17 IQMatrixBufferH264, PICTURE_LONG_TERM_REFERENCE, PICTURE_SHORT_TERM_REFERENCE,18 IQMatrixBufferH264, PICTURE_LONG_TERM_REFERENCE, PICTURE_SHORT_TERM_REFERENCE,
18 PictureParameterBufferH264, SliceParameterBufferH264, VAPictureH264,19 PictureParameterBufferH264, SliceParameterBufferH264, VAPictureH264,
@@ -62,6 +63,8 @@ pub struct H264Decoder {
62 /// predicts from something never decoded since the seek and must not63 /// predicts from something never decoded since the seek and must not
63 /// reach the caller.64 /// reach the caller.
64 recovery_poc: Option<i32>,65 recovery_poc: Option<i32>,
66+ /// The most recent SPS's VUI colour tags, sticky across pictures.
67+ colour_tags: Tags,
65 }68 }
66 69
67 impl H264Decoder {70 impl H264Decoder {
@@ -79,6 +82,7 @@ impl H264Decoder {
79 rbsp: Vec::new(),82 rbsp: Vec::new(),
80 gap_frames: 0,83 gap_frames: 0,
81 recovery_poc: None,84 recovery_poc: None,
85+ colour_tags: Tags::default(),
82 }86 }
83 }87 }
84 88
@@ -97,6 +101,7 @@ impl H264Decoder {
97 self.rbsp = rbsp;101 self.rbsp = rbsp;
98 let sps = sps?;102 let sps = sps?;
99 self.dpb.configure(&sps);103 self.dpb.configure(&sps);
104+ self.colour_tags = vui_colour_tags(&sps);
100 let id = usize::from(sps.id);105 let id = usize::from(sps.id);
101 self.sps_map[id] = Some(sps);106 self.sps_map[id] = Some(sps);
102 }107 }
@@ -414,11 +419,45 @@ impl H264Decoder {
414 session.display_size,419 session.display_size,
415 session.coded_size,420 session.coded_size,
416 session.bit_depth,421 session.bit_depth,
422+ self.colour(),
417 );423 );
418 self.ready.push(frame);424 self.ready.push(frame);
419 self.dpb.released(idx);425 self.dpb.released(idx);
420 }426 }
421 }427 }
428+
429+ /// This stream's colour metadata, once its first SPS has been seen. No SEI
430+ /// here — H.264's mastering-display/content-light-level SEI is not parsed
431+ /// by this family today, so this is VUI-only.
432+ pub fn colour(&self) -> Option<Colour> {
433+ let session = self.session.as_ref()?;
434+ Some(Colour {
435+ description: ColorDescription::resolve(
436+ Tags::default(),
437+ self.colour_tags,
438+ session.display_size.1,
439+ ),
440+ light: ContentLight::default(),
441+ })
442+ }
443+}
444+
445+/// An SPS's VUI `colour_description` and range flag, as [`Tags`] for
446+/// [`ColorDescription::resolve`]. [`Tags::default()`] when the VUI has no
447+/// `video_signal_type` at all.
448+fn vui_colour_tags(sps: &Sps) -> Tags {
449+ let Some(vui) = &sps.vui else {
450+ return Tags::default();
451+ };
452+ if vui.video_format.is_none() {
453+ return Tags::default();
454+ }
455+ let (_primaries, transfer, matrix) = vui.colour_description.unwrap_or((0, 0, 0));
456+ Tags::from_codes(
457+ u64::from(matrix),
458+ u64::from(transfer),
459+ if vui.video_full_range { 2 } else { 1 },
460+ )
422 }461 }
423 462
424 /// The `pic_parameter_set_id` of a slice header, which is the second syntax463 /// The `pic_parameter_set_id` of a slice header, which is the second syntax
crates/ec-hw/src/dec/hevc.rsmodified+59 -3
@@ -9,6 +9,7 @@
9 9
10 use std::sync::Arc;10 use std::sync::Arc;
11 11
12+use ec_core::color::{ColorDescription, ContentLight, Tags};
12 use ec_h265_syntax::{13 use ec_h265_syntax::{
13 NalUnitType, ParsePositions, Pps, SliceHeader, SliceType, Sps, Vps, split_annex_b,14 NalUnitType, ParsePositions, Pps, SliceHeader, SliceType, Sps, Vps, split_annex_b,
14 unescape_rbsp,15 unescape_rbsp,
@@ -18,7 +19,7 @@ use ec_va::{Buffer, Display, sys};
18 19
19 use super::{ReadyFrames, Session, StreamInfo};20 use super::{ReadyFrames, Session, StreamInfo};
20 use crate::error::{Error, Result};21 use crate::error::{Error, Result};
21-use crate::frame::Frame;22+use crate::frame::{Colour, Frame};
22 use crate::params::hevc::{23 use crate::params::hevc::{
23 IQMatrixBufferHEVC, PICTURE_INVALID, PICTURE_LONG_TERM_REFERENCE, PICTURE_RPS_LT_CURR,24 IQMatrixBufferHEVC, PICTURE_INVALID, PICTURE_LONG_TERM_REFERENCE, PICTURE_RPS_LT_CURR,
24 PICTURE_RPS_ST_CURR_AFTER, PICTURE_RPS_ST_CURR_BEFORE, PictureParameterBufferHEVC,25 PICTURE_RPS_ST_CURR_AFTER, PICTURE_RPS_ST_CURR_BEFORE, PictureParameterBufferHEVC,
@@ -100,6 +101,11 @@ pub struct HevcDecoder {
100 no_rasl_output: bool,101 no_rasl_output: bool,
101 max_reorder: usize,102 max_reorder: usize,
102 max_dec_pic_buffering: usize,103 max_dec_pic_buffering: usize,
104+ /// The most recent SPS's VUI colour tags, sticky across pictures.
105+ colour_tags: Tags,
106+ /// The prefix SEI HDR peak seen so far, merged so a later access unit that
107+ /// says nothing does not erase what an earlier IRAP declared.
108+ colour_light: ContentLight,
103 }109 }
104 110
105 impl HevcDecoder {111 impl HevcDecoder {
@@ -119,6 +125,8 @@ impl HevcDecoder {
119 no_rasl_output: false,125 no_rasl_output: false,
120 max_reorder: 1,126 max_reorder: 1,
121 max_dec_pic_buffering: 6,127 max_dec_pic_buffering: 6,
128+ colour_tags: Tags::default(),
129+ colour_light: ContentLight::default(),
122 }130 }
123 }131 }
124 132
@@ -137,6 +145,7 @@ impl HevcDecoder {
137 let sps = Sps::parse(&nal.rbsp())?;145 let sps = Sps::parse(&nal.rbsp())?;
138 self.max_reorder = sps.max_num_reorder_pics as usize;146 self.max_reorder = sps.max_num_reorder_pics as usize;
139 self.max_dec_pic_buffering = sps.max_dec_pic_buffering_minus1 as usize + 1;147 self.max_dec_pic_buffering = sps.max_dec_pic_buffering_minus1 as usize + 1;
148+ self.colour_tags = vui_colour_tags(&sps);
140 let id = sps.id as usize;149 let id = sps.id as usize;
141 if id < self.sps_map.len() {150 if id < self.sps_map.len() {
142 self.sps_map[id] = Some(sps);151 self.sps_map[id] = Some(sps);
@@ -155,10 +164,33 @@ impl HevcDecoder {
155 _ => {}164 _ => {}
156 }165 }
157 }166 }
167+ // The HDR SEI messages (mastering display, content light level) live
168+ // outside the slice loop above and are read on the whole access unit:
169+ // an encoder writes them once, ahead of the IRAP they describe, and
170+ // they otherwise say nothing (`ContentLight::default()`), so a later
171+ // access unit that carries neither never overwrites what an earlier
172+ // one declared.
173+ let light = ec_core::color::hevc_sei_light(data);
174+ if light != ContentLight::default() {
175+ self.colour_light = light.over(self.colour_light);
176+ }
158 self.finish_picture()?;177 self.finish_picture()?;
159 Ok(())178 Ok(())
160 }179 }
161 180
181+ /// This stream's colour metadata, once its first SPS has been seen.
182+ pub fn colour(&self) -> Option<Colour> {
183+ let session = self.session.as_ref()?;
184+ Some(Colour {
185+ description: ColorDescription::resolve(
186+ Tags::default(),
187+ self.colour_tags,
188+ session.display_size.1,
189+ ),
190+ light: self.colour_light,
191+ })
192+ }
193+
162 /// The next frame in output order.194 /// The next frame in output order.
163 pub fn next_frame(&mut self) -> Option<Frame> {195 pub fn next_frame(&mut self) -> Option<Frame> {
164 self.ready.pop()196 self.ready.pop()
@@ -274,8 +306,7 @@ impl HevcDecoder {
274 // 8.1.3: 1 for an IDR, a BLA, or the first picture of a coded306 // 8.1.3: 1 for an IDR, a BLA, or the first picture of a coded
275 // video sequence — which a mid-stream start's first IRAP always307 // video sequence — which a mid-stream start's first IRAP always
276 // is, `self.started` still being false at that point.308 // is, `self.started` still being false at that point.
277- self.no_rasl_output =309+ self.no_rasl_output = nal_type.is_idr() || is_bla_picture(nal_type) || !self.started;
278- nal_type.is_idr() || is_bla_picture(nal_type) || !self.started;
279 }310 }
280 311
281 let poc = self.picture_order_count(sps, sh, nal_type);312 let poc = self.picture_order_count(sps, sh, nal_type);
@@ -638,6 +669,7 @@ impl HevcDecoder {
638 session.display_size,669 session.display_size,
639 session.coded_size,670 session.coded_size,
640 session.bit_depth,671 session.bit_depth,
672+ self.colour(),
641 ));673 ));
642 self.dpb[idx].output = false;674 self.dpb[idx].output = false;
643 self.dpb.retain(|p| p.stored());675 self.dpb.retain(|p| p.stored());
@@ -658,6 +690,30 @@ fn is_leading_picture(nal_type: NalUnitType) -> bool {
658 (6..=9).contains(&nal_type.code())690 (6..=9).contains(&nal_type.code())
659 }691 }
660 692
693+/// An SPS's VUI `colour_description` and range flag, as [`Tags`] for
694+/// [`ColorDescription::resolve`]. [`Tags::default()`] when the VUI has no
695+/// `video_signal_type` at all.
696+fn vui_colour_tags(sps: &Sps) -> Tags {
697+ let Some(vst) = sps.vui.as_ref().and_then(|vui| vui.video_signal_type) else {
698+ return Tags::default();
699+ };
700+ let (_primaries, transfer, matrix) = vst
701+ .colour_description
702+ .map(|cd| {
703+ (
704+ cd.colour_primaries,
705+ cd.transfer_characteristics,
706+ cd.matrix_coeffs,
707+ )
708+ })
709+ .unwrap_or((0, 0, 0));
710+ Tags::from_codes(
711+ u64::from(matrix),
712+ u64::from(transfer),
713+ if vst.video_full_range_flag { 2 } else { 1 },
714+ )
715+}
716+
661 /// RASL_N and RASL_R (8, 9): leading pictures dropped whole when their IRAP's717 /// RASL_N and RASL_R (8, 9): leading pictures dropped whole when their IRAP's
662 /// `NoRaslOutputFlag` is 1 (8.1.3).718 /// `NoRaslOutputFlag` is 1 (8.1.3).
663 fn is_rasl_picture(nal_type: NalUnitType) -> bool {719 fn is_rasl_picture(nal_type: NalUnitType) -> bool {
crates/ec-hw/src/dec/mod.rsmodified+11 -0
@@ -154,6 +154,17 @@ impl Decoder {
154 Inner::Av1(d) => d.stream_info(),154 Inner::Av1(d) => d.stream_info(),
155 }155 }
156 }156 }
157+
158+ /// This stream's colour metadata, once a session exists. [`None`] for VP9
159+ /// and AV1: neither's sequence header colour config is parsed by this
160+ /// family yet.
161+ pub fn colour(&self) -> Option<crate::frame::Colour> {
162+ match &self.inner {
163+ Inner::H264(d) => d.colour(),
164+ Inner::H265(d) => d.colour(),
165+ Inner::Vp9(_) | Inner::Av1(_) => None,
166+ }
167+ }
157 }168 }
158 169
159 /// Frames waiting to be collected, oldest first.170 /// Frames waiting to be collected, oldest first.
crates/ec-hw/src/dec/vp9.rsmodified+2 -0
@@ -98,6 +98,7 @@ impl Vp9Decoder {
98 (header.width, header.height),98 (header.width, header.height),
99 session.coded_size,99 session.coded_size,
100 session.bit_depth,100 session.bit_depth,
101+ None,
101 ));102 ));
102 return Ok(());103 return Ok(());
103 }104 }
@@ -137,6 +138,7 @@ impl Vp9Decoder {
137 (header.width, header.height),138 (header.width, header.height),
138 session.coded_size,139 session.coded_size,
139 session.bit_depth,140 session.bit_depth,
141+ None,
140 ));142 ));
141 }143 }
142 Ok(())144 Ok(())
crates/ec-hw/src/enc/mod.rsmodified+7 -1
@@ -138,7 +138,13 @@ impl EncoderConfig {
138 }138 }
139 139
140 /// Set the VUI colour description; H.265 E.2.1 / H.264 E.1.1 code points.140 /// Set the VUI colour description; H.265 E.2.1 / H.264 E.1.1 code points.
141- pub fn colour(mut self, primaries: u8, transfer: u8, matrix: u8, full_range: bool) -> EncoderConfig {141+ pub fn colour(
142+ mut self,
143+ primaries: u8,
144+ transfer: u8,
145+ matrix: u8,
146+ full_range: bool,
147+ ) -> EncoderConfig {
142 self.colour = Some(Colour {148 self.colour = Some(Colour {
143 primaries,149 primaries,
144 transfer,150 transfer,
crates/ec-hw/src/frame.rsmodified+24 -0
@@ -3,12 +3,27 @@
3 3
4 use std::sync::{Arc, Mutex};4 use std::sync::{Arc, Mutex};
5 5
6+use ec_core::color::{ColorDescription, ContentLight};
6 use ec_va::sys::{VA_FOURCC_NV12, VA_FOURCC_P010};7 use ec_va::sys::{VA_FOURCC_NV12, VA_FOURCC_P010};
7 use ec_va::{Image, MappedImage, PrimeSurface, Surface};8 use ec_va::{Image, MappedImage, PrimeSurface, Surface};
8 9
9 use crate::error::{Error, Result};10 use crate::error::{Error, Result};
10 use crate::pool::PooledSurface;11 use crate::pool::PooledSurface;
11 12
13+/// A stream's colour metadata, resolved from its own headers: VUI tags for the
14+/// primaries/transfer/matrix triplet, and — for HEVC — the two HDR prefix SEI
15+/// messages for the peak the mastering grade and the content itself declared.
16+/// No container tier here: ec-hw only ever sees the elementary stream, so a
17+/// caller that also holds the container's tags resolves those over this.
18+#[derive(Debug, Clone, Copy, PartialEq)]
19+pub struct Colour {
20+ /// Matrix/transfer/range, resolved from the bitstream's own VUI.
21+ pub description: ColorDescription,
22+ /// HDR peak: MaxCLL/MaxFALL and the mastering display's luminance, when
23+ /// the stream carried them (HEVC prefix SEI only).
24+ pub light: ContentLight,
25+}
26+
12 /// The readback image a decoder reuses across frames.27 /// The readback image a decoder reuses across frames.
13 ///28 ///
14 /// One `vaCreateImage`/`vaDestroyImage` pair per frame costs ~20 ms at 1080p on29 /// One `vaCreateImage`/`vaDestroyImage` pair per frame costs ~20 ms at 1080p on
@@ -33,6 +48,8 @@ pub struct Frame {
33 pub coded_size: (u32, u32),48 pub coded_size: (u32, u32),
34 /// Luma bit depth: 8 for NV12 surfaces, 10 for P010.49 /// Luma bit depth: 8 for NV12 surfaces, 10 for P010.
35 pub bit_depth: u8,50 pub bit_depth: u8,
51+ /// This stream's colour metadata, when the codec's decoder resolves one.
52+ pub colour: Option<Colour>,
36 }53 }
37 54
38 /// 8-bit planar 4:2:0, the currency edith's software path speaks.55 /// 8-bit planar 4:2:0, the currency edith's software path speaks.
@@ -73,6 +90,7 @@ impl Frame {
73 display_size: (u32, u32),90 display_size: (u32, u32),
74 coded_size: (u32, u32),91 coded_size: (u32, u32),
75 bit_depth: u8,92 bit_depth: u8,
93+ colour: Option<Colour>,
76 ) -> Frame {94 ) -> Frame {
77 Frame {95 Frame {
78 surface,96 surface,
@@ -81,6 +99,7 @@ impl Frame {
81 display_size,99 display_size,
82 coded_size,100 coded_size,
83 bit_depth,101 bit_depth,
102+ colour,
84 }103 }
85 }104 }
86 105
@@ -89,6 +108,11 @@ impl Frame {
89 &self.surface108 &self.surface
90 }109 }
91 110
111+ /// This frame's colour metadata, when the codec's decoder resolves one.
112+ pub fn colour(&self) -> Option<Colour> {
113+ self.colour
114+ }
115+
92 /// Export the surface as DRM PRIME file descriptors.116 /// Export the surface as DRM PRIME file descriptors.
93 ///117 ///
94 /// This is the path edith's `engine-hw` takes: the fds are imported into118 /// This is the path edith's `engine-hw` takes: the fds are imported into
crates/ec-hw/src/lib.rsmodified+1 -1
@@ -56,5 +56,5 @@ pub use enc::{
56 CodedFrame, EncCodec, Encoder, EncoderConfig, FrameMetadata, RateControlMode, Tunings,56 CodedFrame, EncCodec, Encoder, EncoderConfig, FrameMetadata, RateControlMode, Tunings,
57 };57 };
58 pub use error::{Error, Result};58 pub use error::{Error, Result};
59-pub use frame::{Frame, I420, I420_16, i420_to_nv12, nv12_to_i420};59+pub use frame::{Colour, Frame, I420, I420_16, i420_to_nv12, nv12_to_i420};
60 pub use pool::{PooledSurface, SurfacePool};60 pub use pool::{PooledSurface, SurfacePool};
crates/ec-hw/tests/gpu.rsmodified+124 -12
@@ -72,7 +72,15 @@ impl Reference {
72 // pictures on a film whose real cadence differs — which shows up72 // pictures on a film whose real cadence differs — which shows up
73 // here as everything being one frame out from some point onward.73 // here as everything being one frame out from some point onward.
74 .args([74 .args([
75- "-map", "0:v:0", "-fps_mode", "passthrough", "-pix_fmt", pix, "-f", "rawvideo", "-",75+ "-map",
76+ "0:v:0",
77+ "-fps_mode",
78+ "passthrough",
79+ "-pix_fmt",
80+ pix,
81+ "-f",
82+ "rawvideo",
83+ "-",
76 ])84 ])
77 .stdout(Stdio::piped())85 .stdout(Stdio::piped())
78 .stderr(Stdio::null())86 .stderr(Stdio::null())
@@ -708,7 +716,10 @@ fn encode_frame_zero_copy_matches_the_cpu_path() {
708 count += 1;716 count += 1;
709 })717 })
710 .expect("decode");718 .expect("decode");
711- assert_eq!(count as usize, frames, "{target:?}: decoded {count} of {frames}");719+ assert_eq!(
720+ count as usize, frames,
721+ "{target:?}: decoded {count} of {frames}"
722+ );
712 723
713 let ext = match target {724 let ext = match target {
714 EncCodec::H264 => "264",725 EncCodec::H264 => "264",
@@ -733,8 +744,16 @@ fn encode_frame_zero_copy_matches_the_cpu_path() {
733 cpu_frames.push(Planes::from_8bit(&f.to_i420().expect("readback")))744 cpu_frames.push(Planes::from_8bit(&f.to_i420().expect("readback")))
734 })745 })
735 .expect("decode CPU-path stream");746 .expect("decode CPU-path stream");
736- assert_eq!(zc_frames.len(), frames, "{target:?}: zero-copy stream frame count");747+ assert_eq!(
737- assert_eq!(cpu_frames.len(), frames, "{target:?}: CPU-path stream frame count");748+ zc_frames.len(),
749+ frames,
750+ "{target:?}: zero-copy stream frame count"
751+ );
752+ assert_eq!(
753+ cpu_frames.len(),
754+ frames,
755+ "{target:?}: CPU-path stream frame count"
756+ );
738 757
739 let worst = zc_frames758 let worst = zc_frames
740 .iter()759 .iter()
@@ -742,7 +761,10 @@ fn encode_frame_zero_copy_matches_the_cpu_path() {
742 .map(|(a, b)| psnr(a, b))761 .map(|(a, b)| psnr(a, b))
743 .fold(f64::INFINITY, f64::min);762 .fold(f64::INFINITY, f64::min);
744 println!("{target:?} encode_frame vs CPU path: worst {worst:.1} dB");763 println!("{target:?} encode_frame vs CPU path: worst {worst:.1} dB");
745- assert!(worst >= 35.0, "{target:?}: worst {worst:.1} dB vs the CPU path");764+ assert!(
765+ worst >= 35.0,
766+ "{target:?}: worst {worst:.1} dB vs the CPU path"
767+ );
746 }768 }
747 }769 }
748 770
@@ -815,7 +837,10 @@ fn colour_description_reaches_the_vui() {
815 // ffprobe's csv reorders these as color_space,color_transfer,color_primaries837 // ffprobe's csv reorders these as color_space,color_transfer,color_primaries
816 // regardless of the -show_entries order given above.838 // regardless of the -show_entries order given above.
817 let got = probe(&bt2020_path);839 let got = probe(&bt2020_path);
818- assert_eq!(got, "bt2020nc,smpte2084,bt2020", "ffprobe on the BT.2020 stream");840+ assert_eq!(
841+ got, "bt2020nc,smpte2084,bt2020",
842+ "ffprobe on the BT.2020 stream"
843+ );
819 }844 }
820 845
821 /// AV1 encoding is opt-in, and this test does not turn it on.846 /// AV1 encoding is opt-in, and this test does not turn it on.
@@ -1244,7 +1269,8 @@ fn ten_bit_4k_chroma_is_not_grey() {
1244 let mut compared = 0usize;1269 let mut compared = 0usize;
1245 decode_stream(&mut decoder, Codec::H265, &data, frames, |frame| {1270 decode_stream(&mut decoder, Codec::H265, &data, frames, |frame| {
1246 let (w, h) = frame.display_size;1271 let (w, h) = frame.display_size;
1247- let ref10 = ref10.get_or_insert_with(|| Reference::open(path, w, h, true).expect("ffmpeg runs"));1272+ let ref10 =
1273+ ref10.get_or_insert_with(|| Reference::open(path, w, h, true).expect("ffmpeg runs"));
1248 let want10 = ref10.next(w, h).expect("ffmpeg has a frame");1274 let want10 = ref10.next(w, h).expect("ffmpeg has a frame");
1249 let got16 = Planes::from_16bit(&frame.to_i420_16().expect("readback"));1275 let got16 = Planes::from_16bit(&frame.to_i420_16().expect("readback"));
1250 let y_db = plane_psnr(&got16.y, &want10.y, 1023.0);1276 let y_db = plane_psnr(&got16.y, &want10.y, 1023.0);
@@ -1254,13 +1280,17 @@ fn ten_bit_4k_chroma_is_not_grey() {
1254 1023.0,1280 1023.0,
1255 );1281 );
1256 println!("frame {compared} to_i420_16 vs yuv420p10le: Y {y_db:.1} dB, UV {uv_db:.1} dB");1282 println!("frame {compared} to_i420_16 vs yuv420p10le: Y {y_db:.1} dB, UV {uv_db:.1} dB");
1257- assert!(y_db >= 50.0, "frame {compared}: Y PSNR collapsed to {y_db:.1} dB");1283+ assert!(
1284+ y_db >= 50.0,
1285+ "frame {compared}: Y PSNR collapsed to {y_db:.1} dB"
1286+ );
1258 assert!(1287 assert!(
1259 uv_db >= 50.0,1288 uv_db >= 50.0,
1260 "frame {compared}: chroma PSNR collapsed to {uv_db:.1} dB (grey frame)"1289 "frame {compared}: chroma PSNR collapsed to {uv_db:.1} dB (grey frame)"
1261 );1290 );
1262 1291
1263- let ref8 = ref8.get_or_insert_with(|| Reference::open(path, w, h, false).expect("ffmpeg runs"));1292+ let ref8 =
1293+ ref8.get_or_insert_with(|| Reference::open(path, w, h, false).expect("ffmpeg runs"));
1264 let want8 = ref8.next(w, h).expect("ffmpeg has a frame");1294 let want8 = ref8.next(w, h).expect("ffmpeg has a frame");
1265 let got8 = Planes::from_8bit(&frame.to_i420().expect("readback"));1295 let got8 = Planes::from_8bit(&frame.to_i420().expect("readback"));
1266 let y_db8 = plane_psnr(&got8.y, &want8.y, 255.0);1296 let y_db8 = plane_psnr(&got8.y, &want8.y, 255.0);
@@ -1273,7 +1303,10 @@ fn ten_bit_4k_chroma_is_not_grey() {
1273 // ffmpeg dithers its 8-bit downconversion; this crate truncates. Both1303 // ffmpeg dithers its 8-bit downconversion; this crate truncates. Both
1274 // are legitimate 10-to-8 roundings, so the floor here is the1304 // are legitimate 10-to-8 roundings, so the floor here is the
1275 // dithering noise floor, not the lossless bound above.1305 // dithering noise floor, not the lossless bound above.
1276- assert!(y_db8 >= 30.0, "frame {compared}: 8-bit Y PSNR {y_db8:.1} dB");1306+ assert!(
1307+ y_db8 >= 30.0,
1308+ "frame {compared}: 8-bit Y PSNR {y_db8:.1} dB"
1309+ );
1277 assert!(1310 assert!(
1278 uv_db8 >= 30.0,1311 uv_db8 >= 30.0,
1279 "frame {compared}: 8-bit chroma PSNR collapsed to {uv_db8:.1} dB (grey frame)"1312 "frame {compared}: 8-bit chroma PSNR collapsed to {uv_db8:.1} dB (grey frame)"
@@ -1284,6 +1317,80 @@ fn ten_bit_4k_chroma_is_not_grey() {
1284 assert_eq!(compared, frames, "not all frames were compared");1317 assert_eq!(compared, frames, "not all frames were compared");
1285 }1318 }
1286 1319
1320+/// The HEVC HDR peak (`content_light_level_information` and
1321+/// `mastering_display_colour_volume` prefix SEI), on the one real file that
1322+/// only carries it there: the Matroska `Colour` element itself has no MaxCLL/
1323+/// MaxFALL for this rip (verified separately against `ffprobe`), so a decoder
1324+/// that does not read the SEI reports none at all. Numbers match what
1325+/// `ffprobe -show_frames -read_intervals %+#1 -show_entries
1326+/// frame_side_data_list` reports for this file.
1327+#[test]
1328+fn hdr_film_light_level_sei_is_exposed() {
1329+ let Some(display) = display() else { return };
1330+ let path = Path::new(
1331+ "/home/user/Downloads/reeld\
1332+ /reeld.mkv",
1333+ );
1334+ if !path.exists() {
1335+ eprintln!("skipped: film not present");
1336+ return;
1337+ }
1338+ let frames = 2usize;
1339+ let Some(data) = elementary(path, Codec::H265, frames) else {
1340+ eprintln!("skipped: no elementary stream");
1341+ return;
1342+ };
1343+ let mut decoder = Decoder::new(&display, Codec::H265).expect("decoder opens");
1344+ let mut seen = 0usize;
1345+ decode_stream(&mut decoder, Codec::H265, &data, frames, |frame| {
1346+ seen += 1;
1347+ let colour = frame
1348+ .colour()
1349+ .expect("HEVC decoder resolves colour metadata");
1350+ assert_eq!(
1351+ colour.description.codes(),
1352+ (9, 16, 9),
1353+ "primaries/transfer/matrix (BT.2020 / PQ / BT.2020 NCL)"
1354+ );
1355+ assert_eq!(colour.light.max_cll, Some(1230.0), "MaxCLL");
1356+ assert_eq!(colour.light.max_fall, Some(419.0), "MaxFALL");
1357+ assert!(
1358+ colour.light.mastering_max.is_some(),
1359+ "mastering display peak missing"
1360+ );
1361+ })
1362+ .expect("decode");
1363+ assert_eq!(seen, frames, "not all frames were compared");
1364+}
1365+
1366+/// An SDR H.264 stream, which carries no HDR SEI at all: `Frame::colour`
1367+/// either resolves from the VUI or answers [`None`], but never panics.
1368+#[test]
1369+fn sdr_h264_colour_never_panics() {
1370+ let Some(display) = display() else { return };
1371+ let paths = fixtures(".264");
1372+ if paths.is_empty() {
1373+ eprintln!("skipped: no H.264 fixtures generated");
1374+ return;
1375+ }
1376+ let path = &paths[0];
1377+ let Some(data) = std::fs::read(path).ok() else {
1378+ eprintln!("skipped: fixture unreadable");
1379+ return;
1380+ };
1381+ let mut decoder = Decoder::new(&display, Codec::H264).expect("decoder opens");
1382+ let mut seen = 0usize;
1383+ decode_stream(&mut decoder, Codec::H264, &data, 2, |frame| {
1384+ seen += 1;
1385+ // No SEI parsing on this codec: content light is always absent.
1386+ if let Some(colour) = frame.colour() {
1387+ assert_eq!(colour.light.max_cll, None);
1388+ }
1389+ })
1390+ .expect("decode");
1391+ assert!(seen > 0, "{}: nothing decoded", short(path));
1392+}
1393+
1287 /// Per-frame cost of the 4K 10-bit read-back path, isolated from decode1394 /// Per-frame cost of the 4K 10-bit read-back path, isolated from decode
1288 /// submission itself.1395 /// submission itself.
1289 ///1396 ///
@@ -1309,7 +1416,10 @@ fn ten_bit_4k_frame_path_is_realtime() {
1309 return;1416 return;
1310 };1417 };
1311 let units = split_access_units(&data, Codec::H265);1418 let units = split_access_units(&data, Codec::H265);
1312- assert!(units.len() > limit, "film clip too short for {limit} frames");1419+ assert!(
1420+ units.len() > limit,
1421+ "film clip too short for {limit} frames"
1422+ );
1313 1423
1314 #[derive(Clone, Copy)]1424 #[derive(Clone, Copy)]
1315 enum Op {1425 enum Op {
@@ -1444,7 +1554,9 @@ fn hevc_seek_matches_linear_mkv() {
1444 // caller to: decode the leading VPS/SPS/PPS (their IDR picture is thrown1554 // caller to: decode the leading VPS/SPS/PPS (their IDR picture is thrown
1445 // away) and reset picture state before feeding the seek target.1555 // away) and reset picture state before feeding the seek target.
1446 let mut seek_decoder = Decoder::new(&display, Codec::H265).expect("decoder opens");1556 let mut seek_decoder = Decoder::new(&display, Codec::H265).expect("decoder opens");
1447- seek_decoder.decode(units[0], 0).expect("prime parameter sets");1557+ seek_decoder
1558+ .decode(units[0], 0)
1559+ .expect("prime parameter sets");
1448 seek_decoder.reset();1560 seek_decoder.reset();
1449 let mut seeked_frame = None;1561 let mut seeked_frame = None;
1450 for (i, unit) in units[cra_at..].iter().enumerate() {1562 for (i, unit) in units[cra_at..].iter().enumerate() {