transmux 0.25.5

Any-to-any media container muxing hub: demux TS, fMP4/CMAF, MPEG-PS, WebM, FLV, or RTMP into one neutral IR and mux to CMAF/fMP4, progressive MP4, TS, DASH, low-latency DASH, HLS, low-latency HLS, Smooth Streaming, or RTMP. CENC/CBCS encrypt+decrypt, SSAI splice, RTP/RTCP, and an fMP4/CMAF conformance validator; parses codec config headers only, samples stay opaque. no_std + alloc, except the XML manifest paths (DASH/Smooth/PlayReady), which need the std feature.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
//! Visual sample-entry extension boxes — ISO/IEC 14496-12:2015 §12.1.4–5.
//!
//! These boxes are optional children of `VisualSampleEntry` (avc1, hvc1, etc.)
//! and carry pixel aspect ratio, clean aperture, and colour information.
//!
//! # Types
//!
//! | Box  | Four-CC | Spec section | Description |
//! |------|---------|-------------|-------------|
//! | [`PixelAspectRatioBox`] | `pasp` | §12.1.4.2 | Pixel aspect ratio (hSpacing / vSpacing) |
//! | [`CleanApertureBox`] | `clap` | §12.1.4.2 | Clean aperture dimensions + offsets |
//! | [`ColourInformationBox`] | `colr` | §12.1.5.2 | Colour info (nclx / rICC / prof) |
//!
//! All types implement [`Parse`] + [`Serialize`] (round-trip symmetric).
//! `no_std` + `alloc`.

use alloc::vec::Vec;
use broadcast_common::{Parse, Serialize};

use crate::error::{Error, Result};

// ---------------------------------------------------------------------------
// PixelAspectRatioBox — pasp (§12.1.4.2)
// ---------------------------------------------------------------------------

/// Pixel Aspect Ratio Box (`pasp`) — ISO/IEC 14496-12:2015 §12.1.4.2.
///
/// Carries the relative width and height of a pixel. Only the ratio matters;
/// the units are unspecified. Both fields must be positive.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct PixelAspectRatioBox {
    pub h_spacing: u32,
    pub v_spacing: u32,
}

impl<'a> Parse<'a> for PixelAspectRatioBox {
    type Error = Error;

    fn parse(bytes: &'a [u8]) -> Result<Self> {
        if bytes.len() < 8 {
            return Err(Error::BufferTooShort {
                need: 8,
                have: bytes.len(),
                what: "pasp body",
            });
        }
        let h_spacing = u32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]);
        let v_spacing = u32::from_be_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]);
        Ok(Self {
            h_spacing,
            v_spacing,
        })
    }
}

impl Serialize for PixelAspectRatioBox {
    type Error = Error;

    fn serialized_len(&self) -> usize {
        8
    }

    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
        if buf.len() < 8 {
            return Err(Error::OutputBufferTooSmall {
                need: 8,
                have: buf.len(),
            });
        }
        buf[..4].copy_from_slice(&self.h_spacing.to_be_bytes());
        buf[4..8].copy_from_slice(&self.v_spacing.to_be_bytes());
        Ok(8)
    }
}

// ---------------------------------------------------------------------------
// CleanApertureBox — clap (§12.1.4.2)
// ---------------------------------------------------------------------------

/// Clean Aperture Box (`clap`) — ISO/IEC 14496-12:2015 §12.1.4.2.
///
/// Defines the clean aperture width, height, and offset as fractions (N/D).
/// For horizOff and vertOff, D must be positive and N may be positive or negative.
/// For cleanApertureWidth and cleanApertureHeight, both N and D must be positive.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct CleanApertureBox {
    pub clean_aperture_width_n: u32,
    pub clean_aperture_width_d: u32,
    pub clean_aperture_height_n: u32,
    pub clean_aperture_height_d: u32,
    pub horiz_off_n: u32,
    pub horiz_off_d: u32,
    pub vert_off_n: u32,
    pub vert_off_d: u32,
}

impl<'a> Parse<'a> for CleanApertureBox {
    type Error = Error;

    fn parse(bytes: &'a [u8]) -> Result<Self> {
        if bytes.len() < 32 {
            return Err(Error::BufferTooShort {
                need: 32,
                have: bytes.len(),
                what: "clap body",
            });
        }
        let clean_aperture_width_n = u32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]);
        let clean_aperture_width_d = u32::from_be_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]);
        let clean_aperture_height_n =
            u32::from_be_bytes([bytes[8], bytes[9], bytes[10], bytes[11]]);
        let clean_aperture_height_d =
            u32::from_be_bytes([bytes[12], bytes[13], bytes[14], bytes[15]]);
        let horiz_off_n = u32::from_be_bytes([bytes[16], bytes[17], bytes[18], bytes[19]]);
        let horiz_off_d = u32::from_be_bytes([bytes[20], bytes[21], bytes[22], bytes[23]]);
        let vert_off_n = u32::from_be_bytes([bytes[24], bytes[25], bytes[26], bytes[27]]);
        let vert_off_d = u32::from_be_bytes([bytes[28], bytes[29], bytes[30], bytes[31]]);
        Ok(Self {
            clean_aperture_width_n,
            clean_aperture_width_d,
            clean_aperture_height_n,
            clean_aperture_height_d,
            horiz_off_n,
            horiz_off_d,
            vert_off_n,
            vert_off_d,
        })
    }
}

impl Serialize for CleanApertureBox {
    type Error = Error;

    fn serialized_len(&self) -> usize {
        32
    }

    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
        if buf.len() < 32 {
            return Err(Error::OutputBufferTooSmall {
                need: 32,
                have: buf.len(),
            });
        }
        let mut c = 0usize;
        buf[c..c + 4].copy_from_slice(&self.clean_aperture_width_n.to_be_bytes());
        c += 4;
        buf[c..c + 4].copy_from_slice(&self.clean_aperture_width_d.to_be_bytes());
        c += 4;
        buf[c..c + 4].copy_from_slice(&self.clean_aperture_height_n.to_be_bytes());
        c += 4;
        buf[c..c + 4].copy_from_slice(&self.clean_aperture_height_d.to_be_bytes());
        c += 4;
        buf[c..c + 4].copy_from_slice(&self.horiz_off_n.to_be_bytes());
        c += 4;
        buf[c..c + 4].copy_from_slice(&self.horiz_off_d.to_be_bytes());
        c += 4;
        buf[c..c + 4].copy_from_slice(&self.vert_off_n.to_be_bytes());
        c += 4;
        buf[c..c + 4].copy_from_slice(&self.vert_off_d.to_be_bytes());
        Ok(32)
    }
}

// ---------------------------------------------------------------------------
// ColourInformationBox — colr (§12.1.5.2)
// ---------------------------------------------------------------------------

/// Colour type indicator inside [`ColourInformationBox`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub enum ColourType {
    Nclx,
    RIcc,
    Prof,
    Unknown([u8; 4]),
}

impl ColourType {
    /// Spec token for this `colour_type` FourCC (`"reserved"` for an
    /// unrecognised code — issue #204 convention).
    pub fn name(&self) -> &'static str {
        match self {
            ColourType::Nclx => "nclx",
            ColourType::RIcc => "rICC",
            ColourType::Prof => "prof",
            ColourType::Unknown(_) => "reserved",
        }
    }
}

// Hand-written rather than `impl_spec_display!` because the catch-all carries
// a 4-byte FourCC (not a single reserved byte the macro's `Reserved(u8)` form
// can format) — still losslessly renders the raw code, per the same
// convention.
impl core::fmt::Display for ColourType {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            ColourType::Unknown(code) => {
                write!(
                    f,
                    "{}(0x{:02X}{:02X}{:02X}{:02X})",
                    self.name(),
                    code[0],
                    code[1],
                    code[2],
                    code[3]
                )
            }
            other => f.write_str(other.name()),
        }
    }
}

/// Length of the `nclx` body after the 4-byte `colour_type` — ISO/IEC
/// 14496-12:2015 §12.1.5.2: `colour_primaries(16)`,
/// `transfer_characteristics(16)`, `matrix_coefficients(16)`,
/// `full_range_flag(1)` + `reserved(7)`.
const NCLX_PARAMS_LEN: usize = 7;

/// On-screen colour parameters for colour_type 'nclx' — ISO/IEC 14496-12:2015 §12.1.5.2.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct NclxColourInfo {
    pub colour_primaries: u16,
    pub transfer_characteristics: u16,
    pub matrix_coefficients: u16,
    pub full_range_flag: bool,
    /// The 7 `reserved` bits of the final byte, kept verbatim. The spec says
    /// they are zero, but preserving them keeps a `colr` byte-identical on a
    /// round trip instead of silently rewriting a sloppy writer's padding.
    pub reserved: u8,
}

/// Colour Information Box (`colr`) — ISO/IEC 14496-12:2015 §12.1.5.2.
///
/// Carries colour type info: `nclx` (on-screen), `rICC` (restricted ICC),
/// `prof` (unrestricted ICC), or unknown (opaque payload).
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct ColourInformationBox {
    pub colour_type: [u8; 4],
    pub nclx: Option<NclxColourInfo>,
    /// Every byte after the type-specific body. For `rICC`/`prof`/unknown that
    /// is the ICC profile or opaque payload; for `nclx` it is trailing padding
    /// some writers emit past the 7 spec'd bytes (`NCLX_PARAMS_LEN`), kept so
    /// the box round-trips byte-identically.
    pub icc_profile: Vec<u8>,
}

impl<'a> Parse<'a> for ColourInformationBox {
    type Error = Error;

    fn parse(bytes: &'a [u8]) -> Result<Self> {
        if bytes.len() < 4 {
            return Err(Error::BufferTooShort {
                need: 4,
                have: bytes.len(),
                what: "colr body",
            });
        }
        let colour_type = [bytes[0], bytes[1], bytes[2], bytes[3]];
        let rest = &bytes[4..];

        match &colour_type {
            b"nclx" => {
                if rest.len() < NCLX_PARAMS_LEN {
                    return Err(Error::BufferTooShort {
                        need: NCLX_PARAMS_LEN,
                        have: rest.len(),
                        what: "colr nclx params",
                    });
                }
                let colour_primaries = u16::from_be_bytes([rest[0], rest[1]]);
                let transfer_characteristics = u16::from_be_bytes([rest[2], rest[3]]);
                let matrix_coefficients = u16::from_be_bytes([rest[4], rest[5]]);
                let full_range_flag = (rest[6] >> 7) != 0;
                let reserved = rest[6] & 0x7F;
                Ok(Self {
                    colour_type,
                    nclx: Some(NclxColourInfo {
                        colour_primaries,
                        transfer_characteristics,
                        matrix_coefficients,
                        full_range_flag,
                        reserved,
                    }),
                    // Some writers pad an `nclx` body past the 7 spec'd bytes.
                    // Keep them verbatim so the box re-serializes byte-identically
                    // (r04-W39); the spec defines no other field here.
                    icc_profile: rest[NCLX_PARAMS_LEN..].to_vec(),
                })
            }
            b"rICC" | b"prof" => Ok(Self {
                colour_type,
                nclx: None,
                icc_profile: rest.to_vec(),
            }),
            _ => Ok(Self {
                colour_type,
                nclx: None,
                icc_profile: rest.to_vec(),
            }),
        }
    }
}

impl Serialize for ColourInformationBox {
    type Error = Error;

    fn serialized_len(&self) -> usize {
        // 4-byte `colour_type`, then either the 7 spec'd `nclx` bytes plus any
        // trailing pad, or the opaque payload.
        match &self.colour_type {
            b"nclx" => 4 + NCLX_PARAMS_LEN + self.icc_profile.len(),
            _ => 4 + self.icc_profile.len(),
        }
    }

    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
        let need = self.serialized_len();
        if buf.len() < need {
            return Err(Error::OutputBufferTooSmall {
                need,
                have: buf.len(),
            });
        }
        let mut c = 0usize;
        buf[c..c + 4].copy_from_slice(&self.colour_type);
        c += 4;
        if &self.colour_type == b"nclx" {
            // `serialized_len` always budgets the 7 `nclx` bytes for a `nclx`
            // colour type, so a missing `nclx` must be an error — otherwise the
            // box is written 7 bytes short of its declared length (r04-W39).
            let Some(nclx) = &self.nclx else {
                return Err(Error::InvalidValue {
                    field: "colr nclx",
                    value: 0,
                    reason: "colour_type is nclx but no nclx params are set",
                });
            };
            buf[c..c + 2].copy_from_slice(&nclx.colour_primaries.to_be_bytes());
            c += 2;
            buf[c..c + 2].copy_from_slice(&nclx.transfer_characteristics.to_be_bytes());
            c += 2;
            buf[c..c + 2].copy_from_slice(&nclx.matrix_coefficients.to_be_bytes());
            c += 2;
            buf[c] = ((nclx.full_range_flag as u8) << 7) | (nclx.reserved & 0x7F);
            c += 1;
        }
        // Trailing payload: the pad after an `nclx` body, or an ICC/opaque one.
        buf[c..c + self.icc_profile.len()].copy_from_slice(&self.icc_profile);
        c += self.icc_profile.len();
        Ok(c)
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use broadcast_common::Serialize;

    // ---- pasp ------------------------------------------------------------

    #[test]
    fn pasp_round_trip() {
        let body = [0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01]; // 1:1
        let pasp = PixelAspectRatioBox::parse(&body).unwrap();
        assert_eq!(pasp.h_spacing, 1);
        assert_eq!(pasp.v_spacing, 1);

        let bytes = pasp.to_bytes();
        assert_eq!(&bytes, &body);
    }

    #[test]
    fn pasp_mutate_proves_no_passthrough() {
        let body = [0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01];
        let pasp = PixelAspectRatioBox::parse(&body).unwrap();

        let pasp2 = PixelAspectRatioBox {
            h_spacing: 4,
            v_spacing: 3,
        };
        assert_ne!(pasp.to_bytes(), pasp2.to_bytes());
    }

    // ---- clap ------------------------------------------------------------

    #[test]
    fn clap_round_trip() {
        let body = [
            0x00, 0x00, 0x07, 0x80, // widthN = 1920
            0x00, 0x00, 0x00, 0x01, // widthD = 1
            0x00, 0x00, 0x04, 0x38, // heightN = 1080
            0x00, 0x00, 0x00, 0x01, // heightD = 1
            0x00, 0x00, 0x00, 0x00, // horizOffN = 0
            0x00, 0x00, 0x00, 0x01, // horizOffD = 1
            0x00, 0x00, 0x00, 0x00, // vertOffN = 0
            0x00, 0x00, 0x00, 0x01, // vertOffD = 1
        ];
        let clap = CleanApertureBox::parse(&body).unwrap();
        assert_eq!(clap.clean_aperture_width_n, 1920);
        assert_eq!(clap.clean_aperture_height_n, 1080);

        let bytes = clap.to_bytes();
        assert_eq!(&bytes, &body);
    }

    #[test]
    fn clap_mutate_proves_no_passthrough() {
        let body = [
            0x00, 0x00, 0x07, 0x80, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x04, 0x38, 0x00, 0x00,
            0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x01,
        ];
        let clap = CleanApertureBox::parse(&body).unwrap();

        let clap2 = CleanApertureBox {
            clean_aperture_width_n: 1280,
            ..clap
        };
        assert_ne!(clap.to_bytes(), clap2.to_bytes());
    }

    // ---- colr (nclx) -----------------------------------------------------

    /// Oracle: colr body from colr_hdr.mp4 (ffmpeg-generated BT.2020 HDR)
    const COLR_NCLX_ORACLE: [u8; 11] = [
        0x6E, 0x63, 0x6C, 0x78, // 'nclx'
        0x00, 0x02, // colour_primaries = 2 (unspecified)
        0x00, 0x02, // transfer_characteristics = 2 (unspecified)
        0x00, 0x09, // matrix_coefficients = 9 (BT.2020 non-constant)
        0x00, // full_range_flag=0, reserved=0
    ];

    #[test]
    fn colr_nclx_oracle_round_trip() {
        let colr = ColourInformationBox::parse(&COLR_NCLX_ORACLE).unwrap();
        assert_eq!(&colr.colour_type, b"nclx");

        let nclx = colr.nclx.as_ref().unwrap();
        assert_eq!(nclx.colour_primaries, 2);
        assert_eq!(nclx.transfer_characteristics, 2);
        assert_eq!(nclx.matrix_coefficients, 9);
        assert!(!nclx.full_range_flag);

        let bytes = colr.to_bytes();
        assert_eq!(&bytes, &COLR_NCLX_ORACLE);
    }

    #[test]
    fn colr_nclx_mutate_proves_no_passthrough() {
        let colr = ColourInformationBox::parse(&COLR_NCLX_ORACLE).unwrap();
        let mut colr2 = colr.clone();
        colr2.nclx.as_mut().unwrap().matrix_coefficients = 1;
        assert_ne!(colr.to_bytes(), colr2.to_bytes());
    }

    #[test]
    fn colr_nclx_full_range_round_trip() {
        let body = [
            0x6E, 0x63, 0x6C, 0x78, // 'nclx'
            0x00, 0x01, // bt709
            0x00, 0x01, // bt709
            0x00, 0x01, // bt709
            0x80, // full_range_flag=1
        ];
        let colr = ColourInformationBox::parse(&body).unwrap();
        assert!(colr.nclx.as_ref().unwrap().full_range_flag);
        assert_eq!(colr.to_bytes(), &body);
    }

    // ---- colr (opaque profiles) ------------------------------------------

    #[test]
    fn colr_ricc_opaque_round_trip() {
        let body = [b'r', b'I', b'C', b'C', 1, 2, 3, 4, 5];
        let colr = ColourInformationBox::parse(&body).unwrap();
        assert_eq!(colr.icc_profile, &[1, 2, 3, 4, 5]);
        assert_eq!(colr.to_bytes(), &body);
    }

    #[test]
    fn colr_prof_opaque_round_trip() {
        let body = [b'p', b'r', b'o', b'f', 0xAA, 0xBB];
        let colr = ColourInformationBox::parse(&body).unwrap();
        assert_eq!(colr.icc_profile, &[0xAA, 0xBB]);
        assert_eq!(colr.to_bytes(), &body);
    }

    /// r04-W39: the 7 `reserved` bits of the `nclx` flag byte are preserved, so
    /// a `colr` written with non-zero padding round-trips byte-identically
    /// instead of being silently rewritten.
    #[test]
    fn colr_nclx_reserved_bits_are_preserved() {
        let body = [
            0x6E, 0x63, 0x6C, 0x78, // 'nclx'
            0x00, 0x01, // bt709 primaries
            0x00, 0x01, // bt709 transfer
            0x00, 0x01, // bt709 matrix
            0xBF, // full_range_flag=1, reserved=0x3F (non-zero padding)
        ];
        let colr = ColourInformationBox::parse(&body).unwrap();
        let nclx = colr.nclx.as_ref().unwrap();
        assert!(nclx.full_range_flag);
        assert_eq!(nclx.reserved, 0x3F, "reserved bits kept, not zeroed");
        assert_eq!(colr.to_bytes(), body, "reserved bits must round-trip");

        // The spec's zero form still writes zero.
        let zero = [
            0x6E, 0x63, 0x6C, 0x78, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x80,
        ];
        let z = ColourInformationBox::parse(&zero).unwrap();
        assert_eq!(z.nclx.as_ref().unwrap().reserved, 0);
        assert_eq!(z.to_bytes(), zero);
    }

    /// r04-W39: a `nclx` body with trailing pad bytes must keep them, so the
    /// box re-serializes byte-identically. Unfixed, the extras were dropped and
    /// the output was shorter than the input.
    #[test]
    fn colr_nclx_trailing_bytes_are_preserved() {
        let mut body = COLR_NCLX_ORACLE.to_vec();
        body.extend_from_slice(&[0xDE, 0xAD]);
        let colr = ColourInformationBox::parse(&body).unwrap();
        assert_eq!(colr.colour_type, *b"nclx");
        assert_eq!(
            colr.icc_profile.as_slice(),
            &[0xDE, 0xAD],
            "trailing pad kept"
        );
        assert_eq!(colr.serialized_len(), body.len());
        assert_eq!(colr.to_bytes(), body);
    }

    /// r04-W39: `serialized_len` always budgets the 7 `nclx` bytes for a `nclx`
    /// colour type, so serializing one with no `nclx` params must error rather
    /// than write 7 bytes short of its declared length and return 4.
    #[test]
    fn colr_nclx_without_params_errors() {
        let colr = ColourInformationBox {
            colour_type: *b"nclx",
            nclx: None,
            icc_profile: Vec::new(),
        };
        assert_eq!(colr.serialized_len(), 4 + NCLX_PARAMS_LEN);
        let mut buf = vec![0u8; colr.serialized_len()];
        let err = colr.serialize_into(&mut buf).unwrap_err();
        assert!(
            matches!(
                err,
                Error::InvalidValue {
                    field: "colr nclx",
                    ..
                }
            ),
            "expected InvalidValue for the missing nclx params, got {err:?}"
        );
        // The opaque types are unaffected and still round-trip.
        let prof = ColourInformationBox {
            colour_type: *b"prof",
            nclx: None,
            icc_profile: vec![1, 2, 3],
        };
        assert_eq!(prof.serialized_len(), 7);
        assert_eq!(prof.to_bytes().len(), 7);
    }
}