forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

sei.rs528 lines, 20.3 KiBHistoryRawDownload
1//! SEI messages: mastering display, content light level, decoded picture hash.
2//!
3//! Three messages, and each one is here because something downstream reads it.
4//! The two HDR messages are what a tone map finds when the container lost its
5//! metadata (see [`ec_core::color::hevc_sei_light`], which reads exactly these
6//! payloads back). The decoded picture hash is the encoder's own oracle: an MD5
7//! of the reconstructed picture, which any conformant decoder must reproduce, so
8//! a mismatch is a *bit-exactness* failure report rather than a mystery.
9//!
10//! [`parse_sei_rbsp`] is the reader: it returns the typed messages of one SEI
11//! RBSP, and refuses a malformed one rather than guessing.
12
13use crate::md5::Md5;
14use crate::nal::{NalHeader, NalUnitType};
15use crate::ps::rbsp_trailing_bits;
16use ec_core::bitio::BitWriter;
17use ec_core::color::ContentLight;
18use ec_core::error::{Error, Result};
19
20/// `payloadType` values written here.
21const PAYLOAD_MASTERING_DISPLAY: u32 = 137;
22const PAYLOAD_CONTENT_LIGHT_LEVEL: u32 = 144;
23const PAYLOAD_DECODED_PICTURE_HASH: u32 = 132;
24
25/// Build one SEI RBSP holding `messages`, each a `(payloadType, payload)` pair.
26///
27/// The `ff` byte run for sizes over 254 is written the way the spec spells it,
28/// even though nothing here comes close: a hash message is 49 bytes.
29fn sei_rbsp(messages: &[(u32, Vec<u8>)]) -> Vec<u8> {
30 let mut w = BitWriter::with_capacity(64);
31 for (payload_type, payload) in messages {
32 let mut left = *payload_type;
33 while left >= 255 {
34 w.write_bits(0xff, 8);
35 left -= 255;
36 }
37 w.write_bits(left, 8);
38 let mut size = payload.len() as u32;
39 while size >= 255 {
40 w.write_bits(0xff, 8);
41 size -= 255;
42 }
43 w.write_bits(size, 8);
44 w.write_bytes(payload);
45 }
46 rbsp_trailing_bits(&mut w);
47 w.into_bytes()
48}
49
50/// The prefix SEI RBSP describing HDR mastering metadata, or `None` when there
51/// is nothing to say.
52///
53/// Both messages are written whole or not at all: a `mastering_display_colour_volume`
54/// with a zero luminance pair is what the oracle writes when it knows nothing, and a
55/// tone map that believes it maps the film to black.
56pub fn hdr_metadata_rbsp(light: ContentLight) -> Option<Vec<u8>> {
57 hdr_metadata_rbsp_with(None, light)
58}
59
60/// [`hdr_metadata_rbsp`] with an explicit mastering display: when `display` is
61/// given it is written verbatim (chromaticities and luminances), and the mastering
62/// pair inside `light` is ignored. The content light level comes from `light`.
63pub fn hdr_metadata_rbsp_with(
64 display: Option<MasteringDisplay>,
65 light: ContentLight,
66) -> Option<Vec<u8>> {
67 let mut messages = Vec::new();
68 if let Some(d) = display {
69 let mut payload = Vec::with_capacity(24);
70 for (x, y) in d.display_primaries {
71 payload.extend_from_slice(&x.to_be_bytes());
72 payload.extend_from_slice(&y.to_be_bytes());
73 }
74 payload.extend_from_slice(&d.white_point.0.to_be_bytes());
75 payload.extend_from_slice(&d.white_point.1.to_be_bytes());
76 payload.extend_from_slice(&d.max_luminance.to_be_bytes());
77 payload.extend_from_slice(&d.min_luminance.to_be_bytes());
78 messages.push((PAYLOAD_MASTERING_DISPLAY, payload));
79 } else if let (Some(max), Some(min)) = (light.mastering_max, light.mastering_min) {
80 let mut payload = Vec::with_capacity(24);
81 // The chromaticities are not modelled by this family (the tone map wants
82 // the luminance pair), so BT.2020's are written: they are what an HDR
83 // grade is approved on, and a decoder that reads them gets a true answer
84 // rather than zeros.
85 const BT2020_PRIMARIES: [(u16, u16); 3] = [(8500, 39_850), (6550, 2300), (35_400, 14_600)];
86 const D65: (u16, u16) = (15_635, 16_450);
87 for (x, y) in BT2020_PRIMARIES {
88 payload.extend_from_slice(&x.to_be_bytes());
89 payload.extend_from_slice(&y.to_be_bytes());
90 }
91 payload.extend_from_slice(&D65.0.to_be_bytes());
92 payload.extend_from_slice(&D65.1.to_be_bytes());
93 payload.extend_from_slice(&((max * 10_000.0) as u32).to_be_bytes());
94 payload.extend_from_slice(&((min * 10_000.0) as u32).to_be_bytes());
95 messages.push((PAYLOAD_MASTERING_DISPLAY, payload));
96 }
97 if let (Some(cll), Some(fall)) = (light.max_cll, light.max_fall) {
98 let mut payload = Vec::with_capacity(4);
99 payload.extend_from_slice(&(cll as u16).to_be_bytes());
100 payload.extend_from_slice(&(fall as u16).to_be_bytes());
101 messages.push((PAYLOAD_CONTENT_LIGHT_LEVEL, payload));
102 }
103 if messages.is_empty() {
104 None
105 } else {
106 Some(sei_rbsp(&messages))
107 }
108}
109
110/// The suffix SEI RBSP carrying one MD5 per colour plane (D.2.20).
111///
112/// `planes` are the *reconstructed* planes in coding order, each as
113/// `(samples, stride, width, height)` over the whole coded picture — the
114/// conformance window is not applied, because the hash is defined over
115/// `pic_width_in_luma_samples`.
116pub fn decoded_picture_hash_rbsp(planes: &[(&[u8], usize, usize, usize)]) -> Vec<u8> {
117 let mut payload = Vec::with_capacity(1 + 16 * planes.len());
118 payload.push(0); // hash_type = MD5
119 for &(data, stride, width, height) in planes {
120 let mut md5 = Md5::new();
121 for y in 0..height {
122 md5.update(&data[y * stride..y * stride + width]);
123 }
124 payload.extend_from_slice(&md5.finish());
125 }
126 sei_rbsp(&[(PAYLOAD_DECODED_PICTURE_HASH, payload)])
127}
128
129/// The NAL header a prefix SEI travels under.
130pub fn prefix_sei_header() -> NalHeader {
131 NalHeader::new(NalUnitType::PrefixSei)
132}
133
134/// The NAL header a suffix SEI (the picture hash) travels under.
135pub fn suffix_sei_header() -> NalHeader {
136 NalHeader::new(NalUnitType::SuffixSei)
137}
138
139/// `payloadType` of the alternative transfer characteristics message (D.2.x).
140const PAYLOAD_ALTERNATIVE_TRANSFER: u32 = 147;
141
142/// `mastering_display_colour_volume` (D.2.28): what the grade was approved on.
143///
144/// Chromaticities are in increments of 0.00002 and luminances in increments of
145/// 0.0001 cd/m2, exactly as the message carries them.
146#[derive(Debug, Clone, Copy, PartialEq, Eq)]
147pub struct MasteringDisplay {
148 /// `display_primaries_x[c]`, `display_primaries_y[c]` for c = 0, 1, 2. The spec
149 /// order is green, blue, red.
150 pub display_primaries: [(u16, u16); 3],
151 /// `white_point_x`, `white_point_y`.
152 pub white_point: (u16, u16),
153 /// `max_display_mastering_luminance`, in 0.0001 cd/m2.
154 pub max_luminance: u32,
155 /// `min_display_mastering_luminance`, in 0.0001 cd/m2.
156 pub min_luminance: u32,
157}
158
159impl MasteringDisplay {
160 /// The peak white in cd/m2 (nits).
161 pub fn max_nits(&self) -> f32 {
162 self.max_luminance as f32 / 10_000.0
163 }
164
165 /// The black level in cd/m2 (nits).
166 pub fn min_nits(&self) -> f32 {
167 self.min_luminance as f32 / 10_000.0
168 }
169}
170
171/// `content_light_level_info` (D.2.35), in cd/m2.
172#[derive(Debug, Clone, Copy, PartialEq, Eq)]
173pub struct ContentLightLevel {
174 /// `max_content_light_level` (MaxCLL).
175 pub max_content_light_level: u16,
176 /// `max_pic_average_light_level` (MaxFALL).
177 pub max_pic_average_light_level: u16,
178}
179
180/// `decoded_picture_hash` (D.2.20): one digest per colour plane, in coding order.
181///
182/// The number of planes is one for 4:0:0 and three otherwise. The message carries no
183/// chroma format, so it is read from the payload size, and any other count is refused.
184#[derive(Debug, Clone, PartialEq, Eq)]
185pub enum PictureHash {
186 /// `hash_type` 0: an MD5 of each plane.
187 Md5(Vec<[u8; 16]>),
188 /// `hash_type` 1: a 16-bit CRC of each plane.
189 Crc(Vec<u16>),
190 /// `hash_type` 2: a 32-bit checksum of each plane.
191 Checksum(Vec<u32>),
192}
193
194/// One SEI message read from a prefix or suffix SEI RBSP.
195#[derive(Debug, Clone, PartialEq, Eq)]
196pub enum SeiMessage {
197 /// `mastering_display_colour_volume`, payloadType 137.
198 MasteringDisplay(MasteringDisplay),
199 /// `content_light_level_info`, payloadType 144.
200 ContentLightLevel(ContentLightLevel),
201 /// `decoded_picture_hash`, payloadType 132.
202 DecodedPictureHash(PictureHash),
203 /// `alternative_transfer_characteristics`, payloadType 147: the
204 /// `preferred_transfer_characteristics` code point.
205 AlternativeTransferCharacteristics(u8),
206 /// Any other payload type, carried verbatim.
207 Unknown {
208 /// `payloadType`.
209 payload_type: u32,
210 /// The payload bytes, without the type and size fields.
211 bytes: Vec<u8>,
212 },
213}
214
215/// Read every SEI message in one SEI RBSP (7.3.2.4 and 7.3.5).
216///
217/// The caller has already removed emulation prevention bytes. Each message is
218/// `payloadType` and `payloadSize`, each a run of `0xff` bytes plus a final byte,
219/// followed by the payload, and the RBSP ends with the trailing bits. A message
220/// whose known type has the wrong size, a payload that runs past the end, a
221/// missing trailing bit, or a picture hash with a plane count other than one or
222/// three is [`Error::corrupt`]; nothing here panics on any input.
223pub fn parse_sei_rbsp(rbsp: &[u8]) -> Result<Vec<SeiMessage>> {
224 // The stop bit is the last set bit of the RBSP; everything before it is messages.
225 let stop = rbsp
226 .iter()
227 .rposition(|&b| b != 0)
228 .ok_or_else(|| Error::corrupt("SEI: RBSP is all zero bytes"))?;
229 if rbsp[stop] != 0x80 {
230 return Err(Error::corrupt("SEI: RBSP has no trailing bits"));
231 }
232 let end = stop;
233 let mut at = 0usize;
234 let mut out = Vec::new();
235 while at < end {
236 let payload_type = read_ff_value(rbsp, &mut at, end)?;
237 let payload_type = u32::try_from(payload_type)
238 .map_err(|_| Error::corrupt("SEI: payloadType does not fit 32 bits"))?;
239 let size = read_ff_value(rbsp, &mut at, end)?;
240 if size > end - at {
241 return Err(Error::corrupt("SEI: payload runs past the end of the RBSP"));
242 }
243 let payload = &rbsp[at..at + size];
244 at += size;
245 out.push(message(payload_type, payload)?);
246 }
247 Ok(out)
248}
249
250/// One message from its type and payload.
251fn message(payload_type: u32, payload: &[u8]) -> Result<SeiMessage> {
252 Ok(match payload_type {
253 PAYLOAD_MASTERING_DISPLAY => {
254 if payload.len() != 24 {
255 return Err(Error::corrupt(format!(
256 "SEI: mastering display payload is {} bytes, not 24",
257 payload.len()
258 )));
259 }
260 let u16_at = |i: usize| u16::from_be_bytes([payload[i], payload[i + 1]]);
261 let u32_at = |i: usize| {
262 u32::from_be_bytes([payload[i], payload[i + 1], payload[i + 2], payload[i + 3]])
263 };
264 SeiMessage::MasteringDisplay(MasteringDisplay {
265 display_primaries: [
266 (u16_at(0), u16_at(2)),
267 (u16_at(4), u16_at(6)),
268 (u16_at(8), u16_at(10)),
269 ],
270 white_point: (u16_at(12), u16_at(14)),
271 max_luminance: u32_at(16),
272 min_luminance: u32_at(20),
273 })
274 }
275 PAYLOAD_CONTENT_LIGHT_LEVEL => {
276 if payload.len() != 4 {
277 return Err(Error::corrupt(format!(
278 "SEI: content light level payload is {} bytes, not 4",
279 payload.len()
280 )));
281 }
282 SeiMessage::ContentLightLevel(ContentLightLevel {
283 max_content_light_level: u16::from_be_bytes([payload[0], payload[1]]),
284 max_pic_average_light_level: u16::from_be_bytes([payload[2], payload[3]]),
285 })
286 }
287 PAYLOAD_DECODED_PICTURE_HASH => SeiMessage::DecodedPictureHash(picture_hash(payload)?),
288 PAYLOAD_ALTERNATIVE_TRANSFER => {
289 if payload.len() != 1 {
290 return Err(Error::corrupt(format!(
291 "SEI: alternative transfer payload is {} bytes, not 1",
292 payload.len()
293 )));
294 }
295 SeiMessage::AlternativeTransferCharacteristics(payload[0])
296 }
297 _ => SeiMessage::Unknown {
298 payload_type,
299 bytes: payload.to_vec(),
300 },
301 })
302}
303
304/// A `decoded_picture_hash` payload: `hash_type`, then one digest per plane.
305fn picture_hash(payload: &[u8]) -> Result<PictureHash> {
306 let Some((&hash_type, digests)) = payload.split_first() else {
307 return Err(Error::corrupt("SEI: empty decoded picture hash payload"));
308 };
309 let size = match hash_type {
310 0 => 16,
311 1 => 2,
312 2 => 4,
313 other => {
314 return Err(Error::corrupt(format!(
315 "SEI: decoded picture hash_type {other} is reserved"
316 )));
317 }
318 };
319 if digests.len() % size != 0 || !matches!(digests.len() / size, 1 | 3) {
320 return Err(Error::corrupt(format!(
321 "SEI: decoded picture hash carries {} bytes, not one or three planes of {size}",
322 digests.len()
323 )));
324 }
325 Ok(match hash_type {
326 0 => PictureHash::Md5(digests.as_chunks::<16>().0.to_vec()),
327 1 => PictureHash::Crc(
328 digests
329 .as_chunks::<2>()
330 .0
331 .iter()
332 .map(|c| u16::from_be_bytes(*c))
333 .collect(),
334 ),
335 _ => PictureHash::Checksum(
336 digests
337 .as_chunks::<4>()
338 .0
339 .iter()
340 .map(|c| u32::from_be_bytes(*c))
341 .collect(),
342 ),
343 })
344}
345
346/// A `payloadType` or `payloadSize`: a run of `0xff` bytes and one more. Stops at
347/// `end`, so a value that runs off the RBSP is an error.
348fn read_ff_value(rbsp: &[u8], at: &mut usize, end: usize) -> Result<usize> {
349 let mut value = 0usize;
350 loop {
351 if *at >= end {
352 return Err(Error::corrupt("SEI: message header runs past the RBSP"));
353 }
354 let byte = rbsp[*at];
355 *at += 1;
356 value += usize::from(byte);
357 if byte != 0xff {
358 return Ok(value);
359 }
360 }
361}
362
363#[cfg(test)]
364mod tests {
365 use super::*;
366
367 #[test]
368 fn hdr_sei_reads_back_through_ec_core() {
369 let light = ContentLight {
370 max_cll: Some(1000.0),
371 max_fall: Some(400.0),
372 mastering_max: Some(1000.0),
373 mastering_min: Some(0.005),
374 ..ContentLight::default()
375 };
376 let rbsp = hdr_metadata_rbsp(light).unwrap();
377 let mut annex_b = Vec::new();
378 crate::nal::write_annex_b(&mut annex_b, prefix_sei_header(), &rbsp, true);
379 // ec-core's reader is the consumer this exists for.
380 let read = ec_core::color::hevc_sei_light(&annex_b);
381 assert_eq!(read.max_cll, Some(1000.0));
382 assert_eq!(read.max_fall, Some(400.0));
383 assert_eq!(read.mastering_max, Some(1000.0));
384 assert_eq!(read.mastering_min, Some(0.005));
385 assert!(hdr_metadata_rbsp(ContentLight::default()).is_none());
386 }
387
388 #[test]
389 fn picture_hash_is_md5_of_each_plane() {
390 let luma = vec![7u8; 16 * 16];
391 let rbsp = decoded_picture_hash_rbsp(&[(&luma, 16, 16, 16)]);
392 // payloadType 132, payloadSize 17, hash_type 0, then the digest.
393 assert_eq!(rbsp[0], 132);
394 assert_eq!(rbsp[1], 17);
395 assert_eq!(rbsp[2], 0);
396 let mut md5 = Md5::new();
397 md5.update(&luma);
398 assert_eq!(&rbsp[3..19], &md5.finish()[..]);
399 }
400
401 /// The HDR10 mastering display of a 1000 nit, 0.0050 nit BT.2020 grade on D65.
402 fn hdr10_mdcv_payload() -> Vec<u8> {
403 let mut p = Vec::new();
404 for (x, y) in [(8500u16, 39_850u16), (6550, 2300), (35_400, 14_600)] {
405 p.extend_from_slice(&x.to_be_bytes());
406 p.extend_from_slice(&y.to_be_bytes());
407 }
408 p.extend_from_slice(&15_635u16.to_be_bytes());
409 p.extend_from_slice(&16_450u16.to_be_bytes());
410 p.extend_from_slice(&10_000_000u32.to_be_bytes());
411 p.extend_from_slice(&50u32.to_be_bytes());
412 p
413 }
414
415 #[test]
416 fn hdr10_mastering_display_example_reads_back() {
417 let rbsp = sei_rbsp(&[(137, hdr10_mdcv_payload())]);
418 let msgs = parse_sei_rbsp(&rbsp).unwrap();
419 assert_eq!(msgs.len(), 1);
420 let SeiMessage::MasteringDisplay(md) = msgs[0] else {
421 panic!("not a mastering display: {:?}", msgs[0]);
422 };
423 assert_eq!(md.display_primaries[0], (8500, 39_850)); // green
424 assert_eq!(md.display_primaries[1], (6550, 2300)); // blue
425 assert_eq!(md.display_primaries[2], (35_400, 14_600)); // red
426 assert_eq!(md.white_point, (15_635, 16_450)); // D65
427 assert_eq!(md.max_nits(), 1000.0);
428 assert!((md.min_nits() - 0.005).abs() < 1e-6);
429 }
430
431 #[test]
432 fn content_light_and_transfer_read_back_among_others() {
433 let mut cll = Vec::new();
434 cll.extend_from_slice(&1000u16.to_be_bytes());
435 cll.extend_from_slice(&400u16.to_be_bytes());
436 // payloadType 300 and a 260-byte payload: both need the ff extension.
437 let unknown = vec![0xab; 260];
438 let mut rbsp = Vec::new();
439 rbsp.extend_from_slice(&[0xff, 45, 0xff, 5]);
440 rbsp.extend_from_slice(&unknown);
441 rbsp.extend_from_slice(&[144, 4]);
442 rbsp.extend_from_slice(&cll);
443 rbsp.extend_from_slice(&[147, 1, 16]);
444 rbsp.push(0x80);
445 let msgs = parse_sei_rbsp(&rbsp).unwrap();
446 assert_eq!(
447 msgs,
448 vec![
449 SeiMessage::Unknown {
450 payload_type: 300,
451 bytes: unknown,
452 },
453 SeiMessage::ContentLightLevel(ContentLightLevel {
454 max_content_light_level: 1000,
455 max_pic_average_light_level: 400,
456 }),
457 SeiMessage::AlternativeTransferCharacteristics(16),
458 ]
459 );
460 }
461
462 #[test]
463 fn picture_hashes_read_back_for_each_hash_type() {
464 // MD5, three planes: one digest each, 1 + 48 bytes.
465 let mut md5 = vec![0u8];
466 md5.extend(1..=48u8);
467 // CRC, one plane.
468 let crc = [1u8, 0xbe, 0xef];
469 // Checksum, three planes.
470 let mut sum = vec![2u8];
471 sum.extend_from_slice(&1u32.to_be_bytes());
472 sum.extend_from_slice(&2u32.to_be_bytes());
473 sum.extend_from_slice(&3u32.to_be_bytes());
474 let rbsp = sei_rbsp(&[(132, md5.clone()), (132, crc.to_vec()), (132, sum)]);
475 let msgs = parse_sei_rbsp(&rbsp).unwrap();
476 let mut digests = [[0u8; 16]; 3];
477 for (i, d) in digests.iter_mut().enumerate() {
478 d.copy_from_slice(&md5[1 + 16 * i..1 + 16 * (i + 1)]);
479 }
480 assert_eq!(
481 msgs[0],
482 SeiMessage::DecodedPictureHash(PictureHash::Md5(digests.to_vec()))
483 );
484 assert_eq!(
485 msgs[1],
486 SeiMessage::DecodedPictureHash(PictureHash::Crc(vec![0xbeef]))
487 );
488 assert_eq!(
489 msgs[2],
490 SeiMessage::DecodedPictureHash(PictureHash::Checksum(vec![1, 2, 3]))
491 );
492 }
493
494 #[test]
495 fn malformed_sei_is_an_error_not_a_panic() {
496 let short_mdcv = sei_rbsp(&[(137, vec![0; 23])]);
497 let long_cll = sei_rbsp(&[(144, vec![0; 5])]);
498 let two_plane_md5 = sei_rbsp(&[(132, [vec![0u8], vec![0; 32]].concat())]);
499 let reserved_hash = sei_rbsp(&[(132, vec![3, 0, 0])]);
500 let bad_atc = sei_rbsp(&[(147, vec![1, 2])]);
501 let no_stop_bit = vec![5u8, 1, 0x00];
502 let all_zero = vec![0u8, 0];
503 let empty = Vec::new();
504 let unterminated_ff = vec![0xffu8, 0xff];
505 let past_end = vec![5u8, 9, 1, 2, 0x80];
506 let size_ff_past_end = vec![5u8, 0xff, 0xff, 0x80];
507 for (name, bad) in [
508 ("short mdcv", short_mdcv),
509 ("long cll", long_cll),
510 ("two-plane md5", two_plane_md5),
511 ("reserved hash type", reserved_hash),
512 ("bad atc", bad_atc),
513 ("no stop bit", no_stop_bit),
514 ("all zero", all_zero),
515 ("empty", empty),
516 ("unterminated ff", unterminated_ff),
517 ("payload past end", past_end),
518 ("size ff past end", size_ff_past_end),
519 ] {
520 assert!(parse_sei_rbsp(&bad).is_err(), "{name} should be refused");
521 }
522 // Every truncation of a valid message is refused or read, never a panic.
523 let good = sei_rbsp(&[(137, hdr10_mdcv_payload()), (144, vec![0, 1, 0, 2])]);
524 for n in 0..good.len() {
525 let _ = parse_sei_rbsp(&good[..n]);
526 }
527 }
528}