Skip to main content

grafton_ndi/
color_info.rs

1//! The `ndi_color_info` element of video frame metadata.
2
3use crate::{Error, Result};
4
5/// The color description a video frame carries in its `ndi_color_info`
6/// metadata.
7///
8/// NDI 6 describes a frame's colorimetry with one element in its metadata,
9/// standing alone or inside an `ndi_metadata_group`:
10///
11/// ```xml
12/// <ndi_color_info primaries="bt_2020" transfer="bt_2100_pq" matrix="bt_2020"/>
13/// ```
14///
15/// Each attribute may be missing, and its accessor then returns `None`. A
16/// missing `matrix` means BT.709 and a missing `transfer` means SDR, which is
17/// how image encoding reads them; missing `primaries` are unknown.
18/// Separate attributes with XML whitespace. Color values may contain decimal
19/// or hexadecimal character references. The reader recognizes predefined XML
20/// entities and reads color values without expanding custom entities.
21///
22/// Every video frame's `color_info` method reads it, for example
23/// [`VideoFrame::color_info`](crate::VideoFrame::color_info). That read refuses
24/// received metadata withheld as non-UTF-8 or unterminated text, including
25/// when its status was preserved on an owned copy. Measured with the
26/// 6.4 SDK, the SDK passes the element through unchanged to receivers in
27/// every color format, YUV and RGB, but does not apply it: it converts
28/// between YUV and RGB with BT.709 coefficients whatever the element says.
29///
30/// Document type declarations are skipped without expanding entities or
31/// loading external definitions.
32#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
33pub struct ColorInfo {
34    primaries: Option<ColorPrimaries>,
35    transfer: Option<TransferFunction>,
36    matrix: Option<YuvMatrix>,
37}
38
39impl ColorInfo {
40    /// The color primaries, or `None` when the element does not give them.
41    #[must_use]
42    pub const fn primaries(&self) -> Option<ColorPrimaries> {
43        self.primaries
44    }
45
46    /// The transfer function, or `None` when the element does not give one,
47    /// which means SDR.
48    #[must_use]
49    pub const fn transfer(&self) -> Option<TransferFunction> {
50        self.transfer
51    }
52
53    /// The YUV matrix, or `None` when the element does not give one, which
54    /// means BT.709.
55    #[must_use]
56    pub const fn matrix(&self) -> Option<YuvMatrix> {
57        self.matrix
58    }
59
60    /// Whether the transfer function is HDR: [`TransferFunction::Pq`] or
61    /// [`TransferFunction::Hlg`].
62    #[must_use]
63    pub const fn is_hdr(&self) -> bool {
64        match self.transfer {
65            Some(transfer) => transfer.is_hdr(),
66            None => false,
67        }
68    }
69}
70
71/// The color primaries of a [`ColorInfo`].
72///
73/// This enum is marked `#[non_exhaustive]` so that primaries a later SDK
74/// names can be added without a breaking change.
75#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
76#[non_exhaustive]
77pub enum ColorPrimaries {
78    /// ITU-R BT.601: `bt_601`.
79    Bt601,
80    /// ITU-R BT.709: `bt_709`.
81    Bt709,
82    /// ITU-R BT.2020: `bt_2020`, or `bt_2100`, whose primaries are the same.
83    Bt2020,
84}
85
86impl ColorPrimaries {
87    pub(crate) const fn name(self) -> &'static str {
88        match self {
89            Self::Bt601 => "BT.601",
90            Self::Bt709 => "BT.709",
91            Self::Bt2020 => "BT.2020",
92        }
93    }
94
95    #[cfg(feature = "image-encoding")]
96    pub(crate) const fn h273_code(self) -> u8 {
97        match self {
98            Self::Bt709 => 1,
99            Self::Bt601 => 6,
100            Self::Bt2020 => 9,
101        }
102    }
103}
104
105/// The transfer function of a [`ColorInfo`].
106///
107/// This enum is marked `#[non_exhaustive]` so that transfer functions a later
108/// SDK names can be added without a breaking change.
109#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
110#[non_exhaustive]
111pub enum TransferFunction {
112    /// The SDR transfer of ITU-R BT.601: `bt_601`.
113    Bt601,
114    /// The SDR transfer of ITU-R BT.709: `bt_709`.
115    Bt709,
116    /// The SDR transfer of ITU-R BT.2020: `bt_2020`.
117    Bt2020,
118    /// Hybrid log-gamma, ITU-R BT.2100: `bt_2100_hlg`.
119    Hlg,
120    /// Perceptual quantization, ITU-R BT.2100 and SMPTE ST 2084:
121    /// `bt_2100_pq`.
122    Pq,
123}
124
125impl TransferFunction {
126    pub(crate) const fn is_hdr(self) -> bool {
127        match self {
128            Self::Bt601 | Self::Bt709 | Self::Bt2020 => false,
129            Self::Hlg | Self::Pq => true,
130        }
131    }
132
133    #[cfg(feature = "image-encoding")]
134    pub(crate) const fn h273_code(self) -> u8 {
135        match self {
136            Self::Bt601 | Self::Bt709 | Self::Bt2020 => 1,
137            Self::Hlg => 18,
138            Self::Pq => 16,
139        }
140    }
141
142    pub(crate) const fn name(self) -> &'static str {
143        match self {
144            Self::Bt601 => "BT.601",
145            Self::Bt709 => "BT.709",
146            Self::Bt2020 => "BT.2020",
147            Self::Hlg => "HLG",
148            Self::Pq => "PQ",
149        }
150    }
151
152    #[cfg(all(test, feature = "image-encoding"))]
153    pub(crate) const ALL: [Self; 5] = [Self::Bt601, Self::Bt709, Self::Bt2020, Self::Hlg, Self::Pq];
154}
155
156/// The matrix that relates YCbCr to RGB, in a [`ColorInfo`] and in image
157/// encoding's color policy.
158///
159/// This enum is marked `#[non_exhaustive]` so that matrices a later SDK names
160/// can be added without a breaking change.
161#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
162#[non_exhaustive]
163pub enum YuvMatrix {
164    /// ITU-R BT.601: K<sub>R</sub> 0.299, K<sub>B</sub> 0.114. `bt_601`.
165    Bt601,
166    /// ITU-R BT.709: K<sub>R</sub> 0.2126, K<sub>B</sub> 0.0722. `bt_709`.
167    Bt709,
168    /// ITU-R BT.2020 non-constant luminance: K<sub>R</sub> 0.2627,
169    /// K<sub>B</sub> 0.0593. `bt_2020`, or `bt_2100`, which uses the same
170    /// matrix.
171    Bt2020,
172}
173
174/// The element's name, which every scanned start tag is compared with.
175const ELEMENT: &[u8] = b"ndi_color_info";
176
177/// The frame's one validated metadata observation, read lazily after an
178/// encoder has chosen its color policy.
179pub(crate) struct Metadata<'a>(crate::frames::FrameMetadataRef<'a>);
180
181impl<'a> Metadata<'a> {
182    pub(crate) fn new(metadata: crate::frames::FrameMetadataRef<'a>) -> Self {
183        Self(metadata)
184    }
185
186    /// Absent text has no color element; withheld text cannot establish that.
187    pub(crate) fn read(&self) -> Result<Option<ColorInfo>> {
188        use crate::frames::FrameMetadataRef;
189        match self.0 {
190            FrameMetadataRef::Absent => Ok(None),
191            FrameMetadataRef::Text(text) => parse(Some(text.as_str())),
192            FrameMetadataRef::Withheld(reason) => {
193                let status = FrameMetadataRef::Withheld(reason).status();
194                Err(Error::InvalidFrame(
195                    crate::FrameDefect::ColorMetadataWithheld { status },
196                ))
197            }
198        }
199    }
200}
201
202/// The most of an unreadable value an error message quotes.
203const QUOTED_LIMIT: usize = 40;
204
205/// Read the `ndi_color_info` element of a frame's metadata.
206///
207/// Returns `Ok(None)` when there is no metadata or no element, and the color
208/// description when every element in the text gives the same one. The
209/// element may stand anywhere in the text, alone or inside an
210/// `ndi_metadata_group`. Comments, CDATA sections, processing instructions
211/// and document type declarations are skipped. An unterminated one runs to
212/// the end of the text.
213///
214/// # Errors
215///
216/// [`Error::InvalidFrame`] naming the attribute and its value when an
217/// element is malformed or truncated, gives an attribute twice, gives a value
218/// outside the SDK's list, or differs from an earlier element.
219pub(crate) fn parse(metadata: Option<&str>) -> Result<Option<ColorInfo>> {
220    const DOCTYPE: &[u8] = b"<!DOCTYPE";
221    let Some(text) = metadata else {
222        return Ok(None);
223    };
224    let bytes = text.as_bytes();
225    let mut found = None;
226    let mut at = 0;
227    while let Some(offset) = bytes[at..].iter().position(|&byte| byte == b'<') {
228        let tag = &bytes[at + offset..];
229        at += offset
230            + if let Some(body) = tag.strip_prefix(b"<!--") {
231                match find(body, b"-->") {
232                    Some(end) => 4 + end + 3,
233                    None => break,
234                }
235            } else if let Some(body) = tag.strip_prefix(b"<![CDATA[") {
236                match find(body, b"]]>") {
237                    Some(end) => 9 + end + 3,
238                    None => break,
239                }
240            } else if let Some(body) = tag.strip_prefix(b"<?") {
241                match find(body, b"?>") {
242                    Some(end) => 2 + end + 2,
243                    None => break,
244                }
245            } else if let Some(body) = tag
246                .strip_prefix(DOCTYPE)
247                .filter(|body| matches!(body.first(), None | Some(b' ' | b'\t' | b'\r' | b'\n')))
248            {
249                match doctype_end(body) {
250                    Some(end) => DOCTYPE.len() + end,
251                    None => break,
252                }
253            } else if let Some(attributes) = start_tag(tag) {
254                let (info, len) = element(attributes)?;
255                if let Some(earlier) = found.filter(|&earlier| earlier != info) {
256                    return Err(Error::InvalidFrame(
257                        crate::FrameDefect::ConflictingColorMetadata {
258                            first: earlier,
259                            second: info,
260                        },
261                    ));
262                }
263                found = Some(info);
264                1 + ELEMENT.len() + len
265            } else {
266                1
267            };
268    }
269    Ok(found)
270}
271
272/// The offset past the declaration's closing `>`, measured from after
273/// `<!DOCTYPE`. End the declaration at a `>` outside the internal subset.
274/// Literals, comments and instructions may contain either delimiter.
275fn doctype_end(text: &[u8]) -> Option<usize> {
276    let mut in_subset = false;
277    let mut at = 0;
278    while let Some(&byte) = text.get(at) {
279        at += 1;
280        match byte {
281            b'\'' | b'"' => at += text[at..].iter().position(|&next| next == byte)? + 1,
282            b'<' if text[at..].starts_with(b"!--") => {
283                at += 3 + find(&text[at + 3..], b"-->")? + 3;
284            }
285            b'<' if text[at..].starts_with(b"?") => {
286                at += 1 + find(&text[at + 1..], b"?>")? + 2;
287            }
288            b'[' => in_subset = true,
289            b']' => in_subset = false,
290            b'>' if !in_subset => return Some(at),
291            _ => {}
292        }
293    }
294    None
295}
296
297/// The text after `<ndi_color_info` when `tag` starts that element's start
298/// tag: the name must end there, at whitespace, `/`, `>` or the end of a
299/// truncated text.
300fn start_tag(tag: &[u8]) -> Option<&[u8]> {
301    let after = tag.strip_prefix(b"<")?.strip_prefix(ELEMENT)?;
302    match after.first() {
303        Some(&byte) if !name_boundary(byte) => None,
304        _ => Some(after),
305    }
306}
307
308fn name_boundary(byte: u8) -> bool {
309    // Include invalid control bytes here so `element` can report them as
310    // syntax errors. Only `whitespace` consumes a separator.
311    byte.is_ascii_control() || matches!(byte, b' ' | b'/' | b'>')
312}
313
314/// Read one element's attributes, from just after its name, returning the
315/// description and the length read through the tag's closing `>`.
316fn element(text: &[u8]) -> Result<(ColorInfo, usize)> {
317    let mut info = ColorInfo {
318        primaries: None,
319        transfer: None,
320        matrix: None,
321    };
322    let mut at = 0;
323    loop {
324        let separator = whitespace(&text[at..]);
325        at += separator;
326        let rest = &text[at..];
327        if rest.starts_with(b"/>") {
328            return Ok((info, at + 2));
329        }
330        if rest.starts_with(b">") {
331            return Ok((info, at + 1));
332        }
333        if rest.is_empty() {
334            return Err(malformed(
335                crate::ColorMetadataDefect::UnclosedElement,
336                "is not closed",
337            ));
338        }
339        let name_len = rest
340            .iter()
341            .position(|&byte| name_boundary(byte) || byte == b'=')
342            .unwrap_or(rest.len());
343        if name_len == 0 {
344            return Err(malformed(
345                crate::ColorMetadataDefect::AttributeStart,
346                format!("has {} where an attribute should begin", quoted(&rest[..1])),
347            ));
348        }
349        let name = &rest[..name_len];
350        if separator == 0 {
351            return Err(malformed(
352                crate::ColorMetadataDefect::AttributeStart,
353                format!(
354                    "gives attribute {} without XML whitespace before it",
355                    quoted(name)
356                ),
357            ));
358        }
359        at += name_len;
360        at += whitespace(&text[at..]);
361        if text.get(at) != Some(&b'=') {
362            return Err(malformed(
363                crate::ColorMetadataDefect::MissingValue,
364                format!("gives attribute {} without a value", quoted(name)),
365            ));
366        }
367        at += 1;
368        at += whitespace(&text[at..]);
369        let quote = match text.get(at) {
370            Some(&quote @ (b'"' | b'\'')) => quote,
371            _ => {
372                return Err(malformed(
373                    crate::ColorMetadataDefect::UnquotedValue,
374                    format!("gives attribute {} an unquoted value", quoted(name)),
375                ))
376            }
377        };
378        at += 1;
379        let Some(value_len) = text[at..].iter().position(|&byte| byte == quote) else {
380            return Err(malformed(
381                crate::ColorMetadataDefect::UnclosedValue,
382                format!("does not close the value of attribute {}", quoted(name)),
383            ));
384        };
385        let value = &text[at..at + value_len];
386        at += value_len + 1;
387        match name {
388            b"primaries" => set(&mut info.primaries, name, value, |value| match value {
389                b"bt_601" => Some(ColorPrimaries::Bt601),
390                b"bt_709" => Some(ColorPrimaries::Bt709),
391                b"bt_2020" | b"bt_2100" => Some(ColorPrimaries::Bt2020),
392                _ => None,
393            })?,
394            b"transfer" => set(&mut info.transfer, name, value, |value| match value {
395                b"bt_601" => Some(TransferFunction::Bt601),
396                b"bt_709" => Some(TransferFunction::Bt709),
397                b"bt_2020" => Some(TransferFunction::Bt2020),
398                b"bt_2100_hlg" => Some(TransferFunction::Hlg),
399                b"bt_2100_pq" => Some(TransferFunction::Pq),
400                _ => None,
401            })?,
402            b"matrix" => set(&mut info.matrix, name, value, |value| match value {
403                b"bt_601" => Some(YuvMatrix::Bt601),
404                b"bt_709" => Some(YuvMatrix::Bt709),
405                b"bt_2020" | b"bt_2100" => Some(YuvMatrix::Bt2020),
406                _ => None,
407            })?,
408            // Attributes the SDK does not define are no concern of color.
409            _ => {}
410        }
411    }
412}
413
414/// Store an attribute's value, refusing a second one and a value outside the
415/// SDK's list.
416fn set<T>(
417    slot: &mut Option<T>,
418    name: &[u8],
419    value: &[u8],
420    read: impl FnOnce(&[u8]) -> Option<T>,
421) -> Result<()> {
422    if slot.is_some() {
423        return Err(malformed(
424            crate::ColorMetadataDefect::DuplicateAttribute,
425            format!("gives attribute {} twice", quoted(name)),
426        ));
427    }
428    let decoded = read_color_value(value, read).map_err(|()| {
429        malformed(
430            crate::ColorMetadataDefect::InvalidAttributeValue,
431            format!(
432                "gives attribute {} the invalid XML value {}",
433                quoted(name),
434                quoted(value)
435            ),
436        )
437    })?;
438    *slot = Some(decoded.ok_or_else(|| {
439        Error::InvalidFrame(crate::FrameDefect::ColorMetadata { issue: crate::ColorMetadataDefect::UndefinedValue, diagnostic: format!("The frame's ndi_color_info gives attribute {} the value {}, which is not one the NDI SDK defines", quoted(name), quoted(value)).into_boxed_str() })
440    })?);
441    Ok(())
442}
443
444/// Use the literal bytes directly. For escaped values, keep at most as many
445/// decoded bytes as the longest SDK token and validate the full input.
446fn read_color_value<T>(
447    mut value: &[u8],
448    read: impl FnOnce(&[u8]) -> Option<T>,
449) -> std::result::Result<Option<T>, ()> {
450    let invalid_literal = |byte| byte == b'<' || (byte < b' ' && !is_xml_whitespace(byte));
451    if !value
452        .iter()
453        .any(|&byte| byte == b'&' || invalid_literal(byte))
454    {
455        return Ok(read(value));
456    }
457
458    let mut decoded = [0; b"bt_2100_hlg".len()];
459    let mut len = 0;
460    while let Some((&first, rest)) = value.split_first() {
461        value = rest;
462        let byte = match first {
463            b'&' => {
464                let end = rest.iter().position(|&byte| byte == b';').ok_or(())?;
465                value = &rest[end + 1..];
466                let codepoint = reference_codepoint(&rest[..end]).ok_or(())?;
467                // Every SDK token is ASCII. Any non-ASCII byte makes this
468                // value undefined, so a wider codepoint can use a marker.
469                u8::try_from(codepoint).unwrap_or(u8::MAX)
470            }
471            byte if invalid_literal(byte) => return Err(()),
472            byte => byte,
473        };
474        if let Some(slot) = decoded.get_mut(len) {
475            *slot = byte;
476        }
477        len += 1;
478    }
479    Ok(decoded.get(..len).and_then(read))
480}
481
482fn reference_codepoint(reference: &[u8]) -> Option<u32> {
483    let (digits, radix) = match reference {
484        b"amp" => return Some(u32::from(b'&')),
485        b"apos" => return Some(u32::from(b'\'')),
486        b"gt" => return Some(u32::from(b'>')),
487        b"lt" => return Some(u32::from(b'<')),
488        b"quot" => return Some(u32::from(b'"')),
489        [b'#', b'x', digits @ ..] => (digits, 16),
490        [b'#', digits @ ..] => (digits, 10),
491        _ => return None,
492    };
493    // from_str_radix accepts a leading plus, which XML references forbid.
494    if digits.starts_with(b"+") {
495        return None;
496    }
497    let codepoint = u32::from_str_radix(std::str::from_utf8(digits).ok()?, radix).ok()?;
498    matches!(codepoint, 9 | 10 | 13 | 0x20..=0xd7ff | 0xe000..=0xfffd | 0x10000..=0x10ffff)
499        .then_some(codepoint)
500}
501
502fn malformed(issue: crate::ColorMetadataDefect, problem: impl std::fmt::Display) -> Error {
503    Error::InvalidFrame(crate::FrameDefect::ColorMetadata {
504        issue,
505        diagnostic: format!(
506            "The frame's ndi_color_info metadata cannot be read: the element {problem}"
507        )
508        .into_boxed_str(),
509    })
510}
511
512/// The length of the XML whitespace at the start of `text`.
513fn whitespace(text: &[u8]) -> usize {
514    text.iter()
515        .position(|&byte| !is_xml_whitespace(byte))
516        .unwrap_or(text.len())
517}
518
519fn is_xml_whitespace(byte: u8) -> bool {
520    matches!(byte, b' ' | b'\t' | b'\r' | b'\n')
521}
522
523/// The offset of the first `needle` in `haystack`.
524fn find(haystack: &[u8], needle: &[u8]) -> Option<usize> {
525    haystack
526        .windows(needle.len())
527        .position(|window| window == needle)
528}
529
530/// Metadata text for a message, quoted and cut short.
531fn quoted(text: &[u8]) -> String {
532    if text.len() > QUOTED_LIMIT {
533        format!(
534            "\"{}…\" ({} bytes)",
535            String::from_utf8_lossy(&text[..QUOTED_LIMIT]),
536            text.len()
537        )
538    } else {
539        format!("\"{}\"", String::from_utf8_lossy(text))
540    }
541}
542
543impl std::fmt::Display for TransferFunction {
544    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
545        f.write_str(self.name())
546    }
547}
548
549#[cfg(test)]
550mod tests {
551    use super::*;
552
553    fn read(text: &str) -> Result<Option<ColorInfo>> {
554        parse(Some(text))
555    }
556
557    fn info(
558        primaries: Option<ColorPrimaries>,
559        transfer: Option<TransferFunction>,
560        matrix: Option<YuvMatrix>,
561    ) -> ColorInfo {
562        ColorInfo {
563            primaries,
564            transfer,
565            matrix,
566        }
567    }
568
569    fn unreadable(text: &str) -> crate::FrameDefect {
570        match read(text) {
571            Err(Error::InvalidFrame(message)) => message,
572            other => panic!("{text:?} must be refused, got {other:?}"),
573        }
574    }
575
576    const HLG_2100: ColorInfo = ColorInfo {
577        primaries: Some(ColorPrimaries::Bt2020),
578        transfer: Some(TransferFunction::Hlg),
579        matrix: Some(YuvMatrix::Bt2020),
580    };
581
582    #[test]
583    fn no_metadata_or_no_element_is_none() {
584        assert_eq!(parse(None).unwrap(), None);
585        for text in [
586            "",
587            "<ndi_metadata_group/>",
588            "<ndi_color_infos primaries=\"x\"/>",
589            "<my_ndi_color_info primaries=\"bt_709\"/>",
590            "ndi_color_info primaries=\"bt_709\"",
591            "<!-- <ndi_color_info primaries=\"bt_9\"/> -->",
592            "<![CDATA[<ndi_color_info primaries=\"bt_9\"/>]]>",
593            "<!-- unterminated <ndi_color_info primaries=\"bt_9\"/>",
594            "<![CDATA[ unterminated <ndi_color_info primaries=\"bt_9\"/>",
595            "</ndi_color_info>",
596        ] {
597            assert_eq!(read(text).unwrap(), None, "{text:?}");
598        }
599    }
600
601    #[test]
602    fn processing_instruction_text_does_not_describe_the_frame() {
603        for text in [
604            "<?camera <ndi_color_info transfer='bt_2100_pq'/> ?>",
605            "<?camera <ndi_color_info matrix='unknown'/> ?>",
606            "<?camera <ndi_color_info transfer='bt_2100_pq'/>",
607        ] {
608            assert_eq!(read(text).unwrap(), None, "{text:?}");
609        }
610        let sdr = "<ndi_color_info transfer='bt_709'/>";
611        let instruction = "<?camera <ndi_color_info transfer='bt_2100_pq'/> ?>";
612        for text in [format!("{instruction}{sdr}"), format!("{sdr}{instruction}")] {
613            assert_eq!(read(&text).unwrap(), read(sdr).unwrap(), "{text:?}");
614        }
615        // XML ends an instruction at its first ?>, even inside quotes.
616        let text = format!("<?camera value='?>{sdr}");
617        assert_eq!(read(&text).unwrap(), read(sdr).unwrap());
618    }
619
620    #[test]
621    fn document_type_declarations_are_opaque_to_color_scanning() {
622        let element = "<ndi_color_info transfer='bt_709'/>";
623        for declaration in [
624            r#"<!DOCTYPE ndi_metadata_group [<!ENTITY label "<ndi_color_info transfer='bt_2100_pq'/>">]>"#,
625            r#"<!DOCTYPE ndi_metadata_group [
626                <!-- ] > <ndi_color_info matrix='unknown'/> -->
627                <?camera ] > ' <ndi_color_info/> ?>
628                <!ELEMENT ndi_metadata_group ANY>
629                <!ENTITY label '<ndi_color_info transfer="bt_2100_pq"/>'>
630                <!ENTITY other "text with ] >">
631            ]>"#,
632            r#"<!DOCTYPE ndi_metadata_group SYSTEM "camera]>v1.dtd">"#,
633            "<!DOCTYPE ndi_metadata_group>",
634        ] {
635            let empty = format!("{declaration}<ndi_metadata_group/>");
636            assert_eq!(read(&empty).unwrap(), None, "{declaration}");
637            let content =
638                format!("{declaration}<ndi_metadata_group>{element}</ndi_metadata_group>");
639            assert_eq!(
640                read(&content).unwrap(),
641                read(element).unwrap(),
642                "{declaration}"
643            );
644        }
645
646        for incomplete in [
647            r#"<!DOCTYPE ndi_metadata_group SYSTEM "<ndi_color_info/>"#,
648            r#"<!DOCTYPE ndi_metadata_group [<!ENTITY label "<ndi_color_info/>">"#,
649            "<!DOCTYPE ndi_metadata_group [<!-- ] > <ndi_color_info/>",
650            "<!DOCTYPE ndi_metadata_group [<?camera ] > <ndi_color_info/>",
651        ] {
652            assert_eq!(read(incomplete).unwrap(), None, "{incomplete}");
653        }
654    }
655
656    #[test]
657    fn the_sdk_example_reads_in_any_attribute_order_and_quote_style() {
658        // As the 6.4 SDK's HDR sender example writes it.
659        let sdk = "<ndi_color_info \t transfer=\"bt_2100_hlg\" \t matrix=\"bt_2100\" \t primaries=\"bt_2100\" /> ";
660        assert_eq!(read(sdk).unwrap(), Some(HLG_2100));
661        for text in [
662            "<ndi_color_info primaries='bt_2020' transfer='bt_2100_hlg' matrix='bt_2020'/>",
663            "<ndi_color_info matrix=\"bt_2020\" primaries='bt_2100' transfer=\"bt_2100_hlg\">",
664            "<ndi_color_info\nmatrix = \"bt_2020\"\r\n primaries\t=\t'bt_2020' transfer=\"bt_2100_hlg\"></ndi_color_info>",
665            "<ndi_metadata_group><ndi_color_info primaries=\"bt_2020\" transfer=\"bt_2100_hlg\" matrix=\"bt_2020\"/></ndi_metadata_group>",
666            "<!-- <ndi_color_info primaries=\"bt_601\"/> --><ndi_color_info primaries=\"bt_2020\" transfer=\"bt_2100_hlg\" matrix=\"bt_2020\" extra=\"ignored\"/>",
667            "<![CDATA[ <ndi_color_info/> ]]><ndi_color_info primaries=\"bt_2020\" transfer=\"bt_2100_hlg\" matrix=\"bt_2020\"/>",
668        ] {
669            assert_eq!(read(text).unwrap(), Some(HLG_2100), "{text:?}");
670        }
671    }
672
673    #[test]
674    fn color_attributes_decode_xml_character_references_without_allocating() {
675        let expected = Some(info(
676            Some(ColorPrimaries::Bt2020),
677            Some(TransferFunction::Hlg),
678            Some(YuvMatrix::Bt709),
679        ));
680        for text in [
681            "<ndi_color_info primaries='bt_2020' transfer='bt_2100_hlg' matrix='bt_709'/>",
682            "<ndi_color_info\rprimaries='bt_&#50;020'\ntransfer=\"bt_2100_&#104;lg\"\tmatrix='bt_&#55;09'/>",
683            "<ndi_color_info primaries='bt_&#x32;020' transfer=\"bt_2100_&#x68;lg\" matrix='&#x62;&#x74;&#x5F;&#x37;&#x30;&#x39;' cam:label='ignored &quot;extension&quot;'/>",
684            "<ndi_color_info primaries='bt_&#000050;020' transfer='bt_2100_&#x000068;lg' matrix='bt_&#x000037;09'/>",
685        ] {
686            let (parsed, allocations) = crate::test_alloc::allocation_count(|| read(text));
687            assert_eq!(parsed.unwrap(), expected, "{text:?}");
688            assert_eq!(allocations, 0, "{text:?}");
689        }
690    }
691
692    #[test]
693    fn color_attribute_syntax_errors_have_typed_diagnostics() {
694        use crate::ColorMetadataDefect::*;
695
696        for (text, expected) in [
697            (
698                "<ndi_color_info primaries='bt_709'transfer='bt_709'/>",
699                AttributeStart,
700            ),
701            (
702                "<ndi_color_info extension='value'matrix='bt_709'/>",
703                AttributeStart,
704            ),
705            ("<ndi_color_info\x0bmatrix='bt_709'/>", AttributeStart),
706            ("<ndi_color_info\x0cmatrix='bt_709'/>", AttributeStart),
707            ("<ndi_color_info matrix\x0c='bt_709'/>", MissingValue),
708            (
709                "<ndi_color_info matrix='bt_709' matrix='bt_&#55;09'/>",
710                DuplicateAttribute,
711            ),
712        ] {
713            assert!(
714                matches!(unreadable(text), crate::FrameDefect::ColorMetadata { issue, .. } if issue == expected),
715                "{text:?}"
716            );
717        }
718
719        for value in [
720            "bt_&#55",
721            "bt_&#;09",
722            "bt_&#x;09",
723            "bt_&#X37;09",
724            "bt_&#x3G;09",
725            "bt_&#x+37;09",
726            "bt_&#-55;09",
727            "bt_&#0;09",
728            "bt_&#xD800;09",
729            "bt_&#xFFFE;09",
730            "bt_&#x110000;09",
731            "bt_&#4294967296;09",
732            "bt_&digit;09",
733            "bt_&09",
734            "bt_<09",
735            "bt_\x01_09",
736            "greater_than_the_maximum_length&#xG;",
737        ] {
738            let text = format!("<ndi_color_info matrix='{value}'/>");
739            let crate::FrameDefect::ColorMetadata { issue, diagnostic } = unreadable(&text) else {
740                panic!("expected a color metadata diagnostic for {text:?}");
741            };
742            assert_eq!(issue, InvalidAttributeValue, "{text:?}");
743            assert!(diagnostic.contains("\"matrix\""), "{diagnostic}");
744            assert!(diagnostic.contains(value), "{diagnostic}");
745        }
746
747        for value in [
748            "bt_&gt;09",
749            "bt_&#x1F600;09",
750            "bt_&#9;09",
751            "bt_&#55;09123456",
752        ] {
753            let text = format!("<ndi_color_info matrix='{value}'/>");
754            assert!(
755                matches!(
756                    unreadable(&text),
757                    crate::FrameDefect::ColorMetadata {
758                        issue: UndefinedValue,
759                        ..
760                    }
761                ),
762                "{text:?}"
763            );
764        }
765    }
766
767    #[test]
768    fn every_sdk_value_reads_and_missing_attributes_are_none() {
769        for (value, primaries, matrix) in [
770            ("bt_601", ColorPrimaries::Bt601, YuvMatrix::Bt601),
771            ("bt_709", ColorPrimaries::Bt709, YuvMatrix::Bt709),
772            ("bt_2020", ColorPrimaries::Bt2020, YuvMatrix::Bt2020),
773            ("bt_2100", ColorPrimaries::Bt2020, YuvMatrix::Bt2020),
774        ] {
775            assert_eq!(
776                read(&format!("<ndi_color_info primaries=\"{value}\"/>")).unwrap(),
777                Some(info(Some(primaries), None, None))
778            );
779            assert_eq!(
780                read(&format!("<ndi_color_info matrix=\"{value}\"/>")).unwrap(),
781                Some(info(None, None, Some(matrix)))
782            );
783        }
784        for (value, transfer) in [
785            ("bt_601", TransferFunction::Bt601),
786            ("bt_709", TransferFunction::Bt709),
787            ("bt_2020", TransferFunction::Bt2020),
788            ("bt_2100_hlg", TransferFunction::Hlg),
789            ("bt_2100_pq", TransferFunction::Pq),
790        ] {
791            let read = read(&format!("<ndi_color_info transfer=\"{value}\"/>"))
792                .unwrap()
793                .unwrap();
794            assert_eq!(read, info(None, Some(transfer), None));
795            assert_eq!(
796                read.is_hdr(),
797                matches!(transfer, TransferFunction::Hlg | TransferFunction::Pq)
798            );
799        }
800        let empty = read("<ndi_color_info/>").unwrap().unwrap();
801        assert_eq!(empty, info(None, None, None));
802        assert!(!empty.is_hdr());
803    }
804
805    #[test]
806    fn repeats_must_agree() {
807        let same = "<ndi_color_info transfer=\"bt_2100_pq\"/><ndi_metadata_group><ndi_color_info transfer='bt_2100_pq'/></ndi_metadata_group>";
808        assert_eq!(
809            read(same).unwrap(),
810            Some(info(None, Some(TransferFunction::Pq), None))
811        );
812        for text in [
813            "<ndi_color_info transfer=\"bt_2100_pq\"/><ndi_color_info transfer=\"bt_2100_hlg\"/>",
814            "<ndi_color_info transfer=\"bt_2100_pq\"/><ndi_color_info transfer=\"bt_2100_pq\" primaries=\"bt_2020\"/>",
815        ] {
816            assert!(matches!(unreadable(text),crate::FrameDefect::ConflictingColorMetadata {..}), "{text:?}");
817        }
818    }
819
820    #[test]
821    fn unreadable_elements_are_refused_naming_the_attribute_and_value() {
822        for (text, needles) in [
823            (
824                "<ndi_color_info matrix=\"bt_2021\"/>",
825                &["\"matrix\"", "\"bt_2021\""][..],
826            ),
827            (
828                "<ndi_color_info transfer=\"BT_709\"/>",
829                &["\"transfer\"", "\"BT_709\""],
830            ),
831            (
832                "<ndi_color_info primaries=\"\"/>",
833                &["\"primaries\"", "\"\""],
834            ),
835            (
836                "<ndi_color_info transfer=\"bt_2100\"/>",
837                &["\"transfer\"", "\"bt_2100\""],
838            ),
839            (
840                "<ndi_color_info matrix=\"bt_709\" matrix=\"bt_709\"/>",
841                &["\"matrix\"", "twice"],
842            ),
843            (
844                "<ndi_color_info matrix=bt_709/>",
845                &["\"matrix\"", "unquoted"],
846            ),
847            (
848                "<ndi_color_info matrix/>",
849                &["\"matrix\"", "without a value"],
850            ),
851            (
852                "<ndi_color_info matrix=\"bt_709'/>",
853                &["\"matrix\"", "does not close"],
854            ),
855            ("<ndi_color_info matrix=\"bt_709\"", &["not closed"]),
856            (
857                "<ndi_color_info primaries=\"bt_20",
858                &["\"primaries\"", "does not close"],
859            ),
860            ("<ndi_color_info ", &["not closed"]),
861            ("<ndi_color_info\t", &["not closed"]),
862            ("<ndi_color_info", &["not closed"]),
863            (
864                "<ndi_color_info = \"bt_709\"/>",
865                &["\"=\"", "attribute should begin"],
866            ),
867            ("<ndi_color_info / >", &["\"/\"", "attribute should begin"]),
868        ] {
869            let cause = unreadable(text);
870            let expected_issue = match *needles.last().unwrap() {
871                "twice" => crate::ColorMetadataDefect::DuplicateAttribute,
872                "unquoted" => crate::ColorMetadataDefect::UnquotedValue,
873                "without a value" => crate::ColorMetadataDefect::MissingValue,
874                "does not close" => crate::ColorMetadataDefect::UnclosedValue,
875                "not closed" => crate::ColorMetadataDefect::UnclosedElement,
876                "attribute should begin" => crate::ColorMetadataDefect::AttributeStart,
877                _ => crate::ColorMetadataDefect::UndefinedValue,
878            };
879            let crate::FrameDefect::ColorMetadata { issue, diagnostic } = cause else {
880                panic!("{cause}")
881            };
882            assert_eq!(issue, expected_issue);
883            // The diagnostic still retains the attribute/value excerpt.
884            for needle in needles {
885                assert!(diagnostic.contains(needle), "{text:?}: {diagnostic}");
886            }
887        }
888        let long = format!("<ndi_color_info matrix=\"{}\"/>", "x".repeat(1000));
889        let cause = unreadable(&long);
890        let crate::FrameDefect::ColorMetadata { issue, diagnostic } = cause else {
891            panic!("{cause}")
892        };
893        assert_eq!(issue, crate::ColorMetadataDefect::UndefinedValue);
894        assert!(
895            diagnostic.contains("(1000 bytes)") && diagnostic.len() < 200,
896            "{diagnostic}"
897        );
898    }
899
900    #[test]
901    fn metadata_at_the_length_limit_reads_in_linear_time() {
902        let limit = crate::frames::MAX_METADATA_BYTES - 1;
903        let element = "<ndi_color_info transfer=\"bt_2100_pq\"/>";
904        for filler in ["<", "<!", "<!-", "<n", "<![CDATA", " "] {
905            let mut text = filler.repeat((limit - element.len()) / filler.len());
906            text.push_str(element);
907            let start = std::time::Instant::now();
908            assert_eq!(
909                read(&text).unwrap(),
910                Some(info(None, Some(TransferFunction::Pq), None)),
911                "{filler:?}"
912            );
913            assert!(
914                start.elapsed() < std::time::Duration::from_secs(5),
915                "{filler:?}"
916            );
917        }
918        for prefix in [
919            "<!--",
920            "<![CDATA[",
921            "<?camera ",
922            "<!DOCTYPE ndi_metadata_group [",
923        ] {
924            let unterminated = format!("{prefix}{}", "<ndi_color_info/>".repeat(limit / 20));
925            assert_eq!(read(&unterminated).unwrap(), None);
926        }
927    }
928
929    #[test]
930    fn mutated_metadata_never_panics() {
931        let valid = [
932            "<ndi_color_info transfer=\"bt_2100_hlg\" matrix=\"bt_2100\" primaries=\"bt_2100\"/>",
933            "<ndi_metadata_group><!-- c --><ndi_color_info primaries='bt_709'></ndi_color_info><![CDATA[x]]></ndi_metadata_group>",
934            "<ndi_color_info matrix=\"bt_601\" />é<ndi_color_info matrix=\"bt_601\"/>",
935            "<?camera <ndi_color_info matrix='unknown'/> ?>é<ndi_color_info matrix='bt_601'/>",
936            r#"<!DOCTYPE ndi_metadata_group [<!ENTITY label "<ndi_color_info transfer='bt_2100_pq'/>">]><ndi_metadata_group/>"#,
937        ];
938        let alphabet = "<>?/=\"' \t!-[]CDATAndi_color_infobt_2100_pqé";
939        let alphabet: Vec<char> = alphabet.chars().collect();
940        let mut seed = 0x2545_F491_4F6C_DD1Du64;
941        let mut next = move || {
942            seed ^= seed << 13;
943            seed ^= seed >> 7;
944            seed ^= seed << 17;
945            seed
946        };
947        for round in 0..20_000 {
948            let mut text: Vec<char> = valid[round % valid.len()].chars().collect();
949            for _ in 0..1 + next() % 4 {
950                let at = (next() as usize) % (text.len() + 1);
951                match next() % 3 {
952                    0 if at < text.len() => {
953                        text.remove(at);
954                    }
955                    1 => text.insert(at, alphabet[(next() as usize) % alphabet.len()]),
956                    _ => text.truncate(at),
957                }
958            }
959            let text: String = text.into_iter().collect();
960            let _ = read(&text);
961        }
962    }
963}