diff --git a/crates/ec-hw/src/dec/av1.rs b/crates/ec-hw/src/dec/av1.rs index 2c5ad2d3..961264ee 100644 --- a/crates/ec-hw/src/dec/av1.rs +++ b/crates/ec-hw/src/dec/av1.rs @@ -115,6 +115,7 @@ impl Av1Decoder { (header.render_width, header.render_height), session.coded_size, session.bit_depth, + None, )); // 7.21: showing a KEY frame again refreshes every reference slot with // it, which the reference *surfaces* have to follow too. @@ -183,6 +184,7 @@ impl Av1Decoder { (header.render_width, header.render_height), session.coded_size, session.bit_depth, + None, )); } Ok(()) diff --git a/crates/ec-hw/src/dec/h264.rs b/crates/ec-hw/src/dec/h264.rs index fdabb8ce..740f7fff 100644 --- a/crates/ec-hw/src/dec/h264.rs +++ b/crates/ec-hw/src/dec/h264.rs @@ -2,6 +2,7 @@ use std::sync::Arc; +use ec_core::color::{ColorDescription, ContentLight, Tags}; use ec_h264_syntax::{ AnnexBIter, DecRefPicMarking, NalHeader, NalUnitType, Pps, PredWeightTable, SliceHeader, SliceType, Sps, unescape_rbsp, @@ -12,7 +13,7 @@ use ec_va::{Buffer, Display, sys}; use super::dpb264::{Dpb, Mark, PicInfo, Picture, Poc, RefList}; use super::{ReadyFrames, Session, StreamInfo}; use crate::error::{Error, Result}; -use crate::frame::Frame; +use crate::frame::{Colour, Frame}; use crate::params::h264::{ IQMatrixBufferH264, PICTURE_LONG_TERM_REFERENCE, PICTURE_SHORT_TERM_REFERENCE, PictureParameterBufferH264, SliceParameterBufferH264, VAPictureH264, @@ -62,6 +63,8 @@ pub struct H264Decoder { /// predicts from something never decoded since the seek and must not /// reach the caller. recovery_poc: Option, + /// The most recent SPS's VUI colour tags, sticky across pictures. + colour_tags: Tags, } impl H264Decoder { @@ -79,6 +82,7 @@ impl H264Decoder { rbsp: Vec::new(), gap_frames: 0, recovery_poc: None, + colour_tags: Tags::default(), } } @@ -97,6 +101,7 @@ impl H264Decoder { self.rbsp = rbsp; let sps = sps?; self.dpb.configure(&sps); + self.colour_tags = vui_colour_tags(&sps); let id = usize::from(sps.id); self.sps_map[id] = Some(sps); } @@ -414,11 +419,45 @@ impl H264Decoder { session.display_size, session.coded_size, session.bit_depth, + self.colour(), ); self.ready.push(frame); self.dpb.released(idx); } } + + /// This stream's colour metadata, once its first SPS has been seen. No SEI + /// here — H.264's mastering-display/content-light-level SEI is not parsed + /// by this family today, so this is VUI-only. + pub fn colour(&self) -> Option { + let session = self.session.as_ref()?; + Some(Colour { + description: ColorDescription::resolve( + Tags::default(), + self.colour_tags, + session.display_size.1, + ), + light: ContentLight::default(), + }) + } +} + +/// An SPS's VUI `colour_description` and range flag, as [`Tags`] for +/// [`ColorDescription::resolve`]. [`Tags::default()`] when the VUI has no +/// `video_signal_type` at all. +fn vui_colour_tags(sps: &Sps) -> Tags { + let Some(vui) = &sps.vui else { + return Tags::default(); + }; + if vui.video_format.is_none() { + return Tags::default(); + } + let (_primaries, transfer, matrix) = vui.colour_description.unwrap_or((0, 0, 0)); + Tags::from_codes( + u64::from(matrix), + u64::from(transfer), + if vui.video_full_range { 2 } else { 1 }, + ) } /// The `pic_parameter_set_id` of a slice header, which is the second syntax diff --git a/crates/ec-hw/src/dec/hevc.rs b/crates/ec-hw/src/dec/hevc.rs index 03c7e9a1..13646cee 100644 --- a/crates/ec-hw/src/dec/hevc.rs +++ b/crates/ec-hw/src/dec/hevc.rs @@ -9,6 +9,7 @@ use std::sync::Arc; +use ec_core::color::{ColorDescription, ContentLight, Tags}; use ec_h265_syntax::{ NalUnitType, ParsePositions, Pps, SliceHeader, SliceType, Sps, Vps, split_annex_b, unescape_rbsp, @@ -18,7 +19,7 @@ use ec_va::{Buffer, Display, sys}; use super::{ReadyFrames, Session, StreamInfo}; use crate::error::{Error, Result}; -use crate::frame::Frame; +use crate::frame::{Colour, Frame}; use crate::params::hevc::{ IQMatrixBufferHEVC, PICTURE_INVALID, PICTURE_LONG_TERM_REFERENCE, PICTURE_RPS_LT_CURR, PICTURE_RPS_ST_CURR_AFTER, PICTURE_RPS_ST_CURR_BEFORE, PictureParameterBufferHEVC, @@ -100,6 +101,11 @@ pub struct HevcDecoder { no_rasl_output: bool, max_reorder: usize, max_dec_pic_buffering: usize, + /// The most recent SPS's VUI colour tags, sticky across pictures. + colour_tags: Tags, + /// The prefix SEI HDR peak seen so far, merged so a later access unit that + /// says nothing does not erase what an earlier IRAP declared. + colour_light: ContentLight, } impl HevcDecoder { @@ -119,6 +125,8 @@ impl HevcDecoder { no_rasl_output: false, max_reorder: 1, max_dec_pic_buffering: 6, + colour_tags: Tags::default(), + colour_light: ContentLight::default(), } } @@ -137,6 +145,7 @@ impl HevcDecoder { let sps = Sps::parse(&nal.rbsp())?; self.max_reorder = sps.max_num_reorder_pics as usize; self.max_dec_pic_buffering = sps.max_dec_pic_buffering_minus1 as usize + 1; + self.colour_tags = vui_colour_tags(&sps); let id = sps.id as usize; if id < self.sps_map.len() { self.sps_map[id] = Some(sps); @@ -155,10 +164,33 @@ impl HevcDecoder { _ => {} } } + // The HDR SEI messages (mastering display, content light level) live + // outside the slice loop above and are read on the whole access unit: + // an encoder writes them once, ahead of the IRAP they describe, and + // they otherwise say nothing (`ContentLight::default()`), so a later + // access unit that carries neither never overwrites what an earlier + // one declared. + let light = ec_core::color::hevc_sei_light(data); + if light != ContentLight::default() { + self.colour_light = light.over(self.colour_light); + } self.finish_picture()?; Ok(()) } + /// This stream's colour metadata, once its first SPS has been seen. + pub fn colour(&self) -> Option { + let session = self.session.as_ref()?; + Some(Colour { + description: ColorDescription::resolve( + Tags::default(), + self.colour_tags, + session.display_size.1, + ), + light: self.colour_light, + }) + } + /// The next frame in output order. pub fn next_frame(&mut self) -> Option { self.ready.pop() @@ -274,8 +306,7 @@ impl HevcDecoder { // 8.1.3: 1 for an IDR, a BLA, or the first picture of a coded // video sequence — which a mid-stream start's first IRAP always // is, `self.started` still being false at that point. - self.no_rasl_output = - nal_type.is_idr() || is_bla_picture(nal_type) || !self.started; + self.no_rasl_output = nal_type.is_idr() || is_bla_picture(nal_type) || !self.started; } let poc = self.picture_order_count(sps, sh, nal_type); @@ -638,6 +669,7 @@ impl HevcDecoder { session.display_size, session.coded_size, session.bit_depth, + self.colour(), )); self.dpb[idx].output = false; self.dpb.retain(|p| p.stored()); @@ -658,6 +690,30 @@ fn is_leading_picture(nal_type: NalUnitType) -> bool { (6..=9).contains(&nal_type.code()) } +/// An SPS's VUI `colour_description` and range flag, as [`Tags`] for +/// [`ColorDescription::resolve`]. [`Tags::default()`] when the VUI has no +/// `video_signal_type` at all. +fn vui_colour_tags(sps: &Sps) -> Tags { + let Some(vst) = sps.vui.as_ref().and_then(|vui| vui.video_signal_type) else { + return Tags::default(); + }; + let (_primaries, transfer, matrix) = vst + .colour_description + .map(|cd| { + ( + cd.colour_primaries, + cd.transfer_characteristics, + cd.matrix_coeffs, + ) + }) + .unwrap_or((0, 0, 0)); + Tags::from_codes( + u64::from(matrix), + u64::from(transfer), + if vst.video_full_range_flag { 2 } else { 1 }, + ) +} + /// RASL_N and RASL_R (8, 9): leading pictures dropped whole when their IRAP's /// `NoRaslOutputFlag` is 1 (8.1.3). fn is_rasl_picture(nal_type: NalUnitType) -> bool { diff --git a/crates/ec-hw/src/dec/mod.rs b/crates/ec-hw/src/dec/mod.rs index d152ba73..438a7a7c 100644 --- a/crates/ec-hw/src/dec/mod.rs +++ b/crates/ec-hw/src/dec/mod.rs @@ -154,6 +154,17 @@ impl Decoder { Inner::Av1(d) => d.stream_info(), } } + + /// This stream's colour metadata, once a session exists. [`None`] for VP9 + /// and AV1: neither's sequence header colour config is parsed by this + /// family yet. + pub fn colour(&self) -> Option { + match &self.inner { + Inner::H264(d) => d.colour(), + Inner::H265(d) => d.colour(), + Inner::Vp9(_) | Inner::Av1(_) => None, + } + } } /// Frames waiting to be collected, oldest first. diff --git a/crates/ec-hw/src/dec/vp9.rs b/crates/ec-hw/src/dec/vp9.rs index 15deb4d3..8310f237 100644 --- a/crates/ec-hw/src/dec/vp9.rs +++ b/crates/ec-hw/src/dec/vp9.rs @@ -98,6 +98,7 @@ impl Vp9Decoder { (header.width, header.height), session.coded_size, session.bit_depth, + None, )); return Ok(()); } @@ -137,6 +138,7 @@ impl Vp9Decoder { (header.width, header.height), session.coded_size, session.bit_depth, + None, )); } Ok(()) diff --git a/crates/ec-hw/src/enc/mod.rs b/crates/ec-hw/src/enc/mod.rs index 98b7c1b7..c71c6402 100644 --- a/crates/ec-hw/src/enc/mod.rs +++ b/crates/ec-hw/src/enc/mod.rs @@ -138,7 +138,13 @@ impl EncoderConfig { } /// Set the VUI colour description; H.265 E.2.1 / H.264 E.1.1 code points. - pub fn colour(mut self, primaries: u8, transfer: u8, matrix: u8, full_range: bool) -> EncoderConfig { + pub fn colour( + mut self, + primaries: u8, + transfer: u8, + matrix: u8, + full_range: bool, + ) -> EncoderConfig { self.colour = Some(Colour { primaries, transfer, diff --git a/crates/ec-hw/src/frame.rs b/crates/ec-hw/src/frame.rs index 3488e4c1..cc46ef06 100644 --- a/crates/ec-hw/src/frame.rs +++ b/crates/ec-hw/src/frame.rs @@ -3,12 +3,27 @@ use std::sync::{Arc, Mutex}; +use ec_core::color::{ColorDescription, ContentLight}; use ec_va::sys::{VA_FOURCC_NV12, VA_FOURCC_P010}; use ec_va::{Image, MappedImage, PrimeSurface, Surface}; use crate::error::{Error, Result}; use crate::pool::PooledSurface; +/// A stream's colour metadata, resolved from its own headers: VUI tags for the +/// primaries/transfer/matrix triplet, and — for HEVC — the two HDR prefix SEI +/// messages for the peak the mastering grade and the content itself declared. +/// No container tier here: ec-hw only ever sees the elementary stream, so a +/// caller that also holds the container's tags resolves those over this. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Colour { + /// Matrix/transfer/range, resolved from the bitstream's own VUI. + pub description: ColorDescription, + /// HDR peak: MaxCLL/MaxFALL and the mastering display's luminance, when + /// the stream carried them (HEVC prefix SEI only). + pub light: ContentLight, +} + /// The readback image a decoder reuses across frames. /// /// One `vaCreateImage`/`vaDestroyImage` pair per frame costs ~20 ms at 1080p on @@ -33,6 +48,8 @@ pub struct Frame { pub coded_size: (u32, u32), /// Luma bit depth: 8 for NV12 surfaces, 10 for P010. pub bit_depth: u8, + /// This stream's colour metadata, when the codec's decoder resolves one. + pub colour: Option, } /// 8-bit planar 4:2:0, the currency edith's software path speaks. @@ -73,6 +90,7 @@ impl Frame { display_size: (u32, u32), coded_size: (u32, u32), bit_depth: u8, + colour: Option, ) -> Frame { Frame { surface, @@ -81,6 +99,7 @@ impl Frame { display_size, coded_size, bit_depth, + colour, } } @@ -89,6 +108,11 @@ impl Frame { &self.surface } + /// This frame's colour metadata, when the codec's decoder resolves one. + pub fn colour(&self) -> Option { + self.colour + } + /// Export the surface as DRM PRIME file descriptors. /// /// This is the path edith's `engine-hw` takes: the fds are imported into diff --git a/crates/ec-hw/src/lib.rs b/crates/ec-hw/src/lib.rs index 8c759e27..24269672 100644 --- a/crates/ec-hw/src/lib.rs +++ b/crates/ec-hw/src/lib.rs @@ -56,5 +56,5 @@ pub use enc::{ CodedFrame, EncCodec, Encoder, EncoderConfig, FrameMetadata, RateControlMode, Tunings, }; pub use error::{Error, Result}; -pub use frame::{Frame, I420, I420_16, i420_to_nv12, nv12_to_i420}; +pub use frame::{Colour, Frame, I420, I420_16, i420_to_nv12, nv12_to_i420}; pub use pool::{PooledSurface, SurfacePool}; diff --git a/crates/ec-hw/tests/gpu.rs b/crates/ec-hw/tests/gpu.rs index 803e03b5..a6928ac4 100644 --- a/crates/ec-hw/tests/gpu.rs +++ b/crates/ec-hw/tests/gpu.rs @@ -72,7 +72,15 @@ impl Reference { // pictures on a film whose real cadence differs — which shows up // here as everything being one frame out from some point onward. .args([ - "-map", "0:v:0", "-fps_mode", "passthrough", "-pix_fmt", pix, "-f", "rawvideo", "-", + "-map", + "0:v:0", + "-fps_mode", + "passthrough", + "-pix_fmt", + pix, + "-f", + "rawvideo", + "-", ]) .stdout(Stdio::piped()) .stderr(Stdio::null()) @@ -708,7 +716,10 @@ fn encode_frame_zero_copy_matches_the_cpu_path() { count += 1; }) .expect("decode"); - assert_eq!(count as usize, frames, "{target:?}: decoded {count} of {frames}"); + assert_eq!( + count as usize, frames, + "{target:?}: decoded {count} of {frames}" + ); let ext = match target { EncCodec::H264 => "264", @@ -733,8 +744,16 @@ fn encode_frame_zero_copy_matches_the_cpu_path() { cpu_frames.push(Planes::from_8bit(&f.to_i420().expect("readback"))) }) .expect("decode CPU-path stream"); - assert_eq!(zc_frames.len(), frames, "{target:?}: zero-copy stream frame count"); - assert_eq!(cpu_frames.len(), frames, "{target:?}: CPU-path stream frame count"); + assert_eq!( + zc_frames.len(), + frames, + "{target:?}: zero-copy stream frame count" + ); + assert_eq!( + cpu_frames.len(), + frames, + "{target:?}: CPU-path stream frame count" + ); let worst = zc_frames .iter() @@ -742,7 +761,10 @@ fn encode_frame_zero_copy_matches_the_cpu_path() { .map(|(a, b)| psnr(a, b)) .fold(f64::INFINITY, f64::min); println!("{target:?} encode_frame vs CPU path: worst {worst:.1} dB"); - assert!(worst >= 35.0, "{target:?}: worst {worst:.1} dB vs the CPU path"); + assert!( + worst >= 35.0, + "{target:?}: worst {worst:.1} dB vs the CPU path" + ); } } @@ -815,7 +837,10 @@ fn colour_description_reaches_the_vui() { // ffprobe's csv reorders these as color_space,color_transfer,color_primaries // regardless of the -show_entries order given above. let got = probe(&bt2020_path); - assert_eq!(got, "bt2020nc,smpte2084,bt2020", "ffprobe on the BT.2020 stream"); + assert_eq!( + got, "bt2020nc,smpte2084,bt2020", + "ffprobe on the BT.2020 stream" + ); } /// 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() { let mut compared = 0usize; decode_stream(&mut decoder, Codec::H265, &data, frames, |frame| { let (w, h) = frame.display_size; - let ref10 = ref10.get_or_insert_with(|| Reference::open(path, w, h, true).expect("ffmpeg runs")); + let ref10 = + ref10.get_or_insert_with(|| Reference::open(path, w, h, true).expect("ffmpeg runs")); let want10 = ref10.next(w, h).expect("ffmpeg has a frame"); let got16 = Planes::from_16bit(&frame.to_i420_16().expect("readback")); let y_db = plane_psnr(&got16.y, &want10.y, 1023.0); @@ -1254,13 +1280,17 @@ fn ten_bit_4k_chroma_is_not_grey() { 1023.0, ); println!("frame {compared} to_i420_16 vs yuv420p10le: Y {y_db:.1} dB, UV {uv_db:.1} dB"); - assert!(y_db >= 50.0, "frame {compared}: Y PSNR collapsed to {y_db:.1} dB"); + assert!( + y_db >= 50.0, + "frame {compared}: Y PSNR collapsed to {y_db:.1} dB" + ); assert!( uv_db >= 50.0, "frame {compared}: chroma PSNR collapsed to {uv_db:.1} dB (grey frame)" ); - let ref8 = ref8.get_or_insert_with(|| Reference::open(path, w, h, false).expect("ffmpeg runs")); + let ref8 = + ref8.get_or_insert_with(|| Reference::open(path, w, h, false).expect("ffmpeg runs")); let want8 = ref8.next(w, h).expect("ffmpeg has a frame"); let got8 = Planes::from_8bit(&frame.to_i420().expect("readback")); let y_db8 = plane_psnr(&got8.y, &want8.y, 255.0); @@ -1273,7 +1303,10 @@ fn ten_bit_4k_chroma_is_not_grey() { // ffmpeg dithers its 8-bit downconversion; this crate truncates. Both // are legitimate 10-to-8 roundings, so the floor here is the // dithering noise floor, not the lossless bound above. - assert!(y_db8 >= 30.0, "frame {compared}: 8-bit Y PSNR {y_db8:.1} dB"); + assert!( + y_db8 >= 30.0, + "frame {compared}: 8-bit Y PSNR {y_db8:.1} dB" + ); assert!( uv_db8 >= 30.0, "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() { assert_eq!(compared, frames, "not all frames were compared"); } +/// The HEVC HDR peak (`content_light_level_information` and +/// `mastering_display_colour_volume` prefix SEI), on the one real file that +/// only carries it there: the Matroska `Colour` element itself has no MaxCLL/ +/// MaxFALL for this rip (verified separately against `ffprobe`), so a decoder +/// that does not read the SEI reports none at all. Numbers match what +/// `ffprobe -show_frames -read_intervals %+#1 -show_entries +/// frame_side_data_list` reports for this file. +#[test] +fn hdr_film_light_level_sei_is_exposed() { + let Some(display) = display() else { return }; + let path = Path::new( + "/home/user/Downloads/reeld\ + /reeld.mkv", + ); + if !path.exists() { + eprintln!("skipped: film not present"); + return; + } + let frames = 2usize; + let Some(data) = elementary(path, Codec::H265, frames) else { + eprintln!("skipped: no elementary stream"); + return; + }; + let mut decoder = Decoder::new(&display, Codec::H265).expect("decoder opens"); + let mut seen = 0usize; + decode_stream(&mut decoder, Codec::H265, &data, frames, |frame| { + seen += 1; + let colour = frame + .colour() + .expect("HEVC decoder resolves colour metadata"); + assert_eq!( + colour.description.codes(), + (9, 16, 9), + "primaries/transfer/matrix (BT.2020 / PQ / BT.2020 NCL)" + ); + assert_eq!(colour.light.max_cll, Some(1230.0), "MaxCLL"); + assert_eq!(colour.light.max_fall, Some(419.0), "MaxFALL"); + assert!( + colour.light.mastering_max.is_some(), + "mastering display peak missing" + ); + }) + .expect("decode"); + assert_eq!(seen, frames, "not all frames were compared"); +} + +/// An SDR H.264 stream, which carries no HDR SEI at all: `Frame::colour` +/// either resolves from the VUI or answers [`None`], but never panics. +#[test] +fn sdr_h264_colour_never_panics() { + let Some(display) = display() else { return }; + let paths = fixtures(".264"); + if paths.is_empty() { + eprintln!("skipped: no H.264 fixtures generated"); + return; + } + let path = &paths[0]; + let Some(data) = std::fs::read(path).ok() else { + eprintln!("skipped: fixture unreadable"); + return; + }; + let mut decoder = Decoder::new(&display, Codec::H264).expect("decoder opens"); + let mut seen = 0usize; + decode_stream(&mut decoder, Codec::H264, &data, 2, |frame| { + seen += 1; + // No SEI parsing on this codec: content light is always absent. + if let Some(colour) = frame.colour() { + assert_eq!(colour.light.max_cll, None); + } + }) + .expect("decode"); + assert!(seen > 0, "{}: nothing decoded", short(path)); +} + /// Per-frame cost of the 4K 10-bit read-back path, isolated from decode /// submission itself. /// @@ -1309,7 +1416,10 @@ fn ten_bit_4k_frame_path_is_realtime() { return; }; let units = split_access_units(&data, Codec::H265); - assert!(units.len() > limit, "film clip too short for {limit} frames"); + assert!( + units.len() > limit, + "film clip too short for {limit} frames" + ); #[derive(Clone, Copy)] enum Op { @@ -1444,7 +1554,9 @@ fn hevc_seek_matches_linear_mkv() { // caller to: decode the leading VPS/SPS/PPS (their IDR picture is thrown // away) and reset picture state before feeding the seek target. let mut seek_decoder = Decoder::new(&display, Codec::H265).expect("decoder opens"); - seek_decoder.decode(units[0], 0).expect("prime parameter sets"); + seek_decoder + .decode(units[0], 0) + .expect("prime parameter sets"); seek_decoder.reset(); let mut seeked_frame = None; for (i, unit) in units[cra_at..].iter().enumerate() {