1use crate::{Error, Result};
4
5#[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 #[must_use]
42 pub const fn primaries(&self) -> Option<ColorPrimaries> {
43 self.primaries
44 }
45
46 #[must_use]
49 pub const fn transfer(&self) -> Option<TransferFunction> {
50 self.transfer
51 }
52
53 #[must_use]
56 pub const fn matrix(&self) -> Option<YuvMatrix> {
57 self.matrix
58 }
59
60 #[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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
76#[non_exhaustive]
77pub enum ColorPrimaries {
78 Bt601,
80 Bt709,
82 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
110#[non_exhaustive]
111pub enum TransferFunction {
112 Bt601,
114 Bt709,
116 Bt2020,
118 Hlg,
120 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
162#[non_exhaustive]
163pub enum YuvMatrix {
164 Bt601,
166 Bt709,
168 Bt2020,
172}
173
174const ELEMENT: &[u8] = b"ndi_color_info";
176
177pub(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 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
202const QUOTED_LIMIT: usize = 40;
204
205pub(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
272fn 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
297fn 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 byte.is_ascii_control() || matches!(byte, b' ' | b'/' | b'>')
312}
313
314fn 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("e @ (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 _ => {}
410 }
411 }
412}
413
414fn 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
444fn 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 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 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
512fn 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
523fn find(haystack: &[u8], needle: &[u8]) -> Option<usize> {
525 haystack
526 .windows(needle.len())
527 .position(|window| window == needle)
528}
529
530fn 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 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 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_2020'\ntransfer=\"bt_2100_hlg\"\tmatrix='bt_709'/>",
683 "<ndi_color_info primaries='bt_2020' transfer=\"bt_2100_hlg\" matrix='bt_709' cam:label='ignored "extension"'/>",
684 "<ndi_color_info primaries='bt_2020' transfer='bt_2100_hlg' matrix='bt_709'/>",
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_709'/>",
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_7",
721 "bt_&#;09",
722 "bt_&#x;09",
723 "bt_709",
724 "bt_G;09",
725 "bt_&#x+37;09",
726 "bt_&#-55;09",
727 "bt_�09",
728 "bt_�09",
729 "bt_09",
730 "bt_�09",
731 "bt_�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_>09",
749 "bt_😀09",
750 "bt_	09",
751 "bt_709123456",
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 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}