diff --git a/Cargo.lock b/Cargo.lock index f829f299c..e811752b0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1352,6 +1352,7 @@ version = "0.1.0" dependencies = [ "craft-media", "craft-media-testkit", + "craft-xml", "log", "proptest", "rayon", diff --git a/crates/audio/Cargo.toml b/crates/audio/Cargo.toml index 8798272b3..c411a0357 100644 --- a/crates/audio/Cargo.toml +++ b/crates/audio/Cargo.toml @@ -19,7 +19,7 @@ workspace = true # ยต-law and free-format MP3 through symphonia. decode = ["decode-native", "symphonia"] # `decode` without symphonia: only the formats with a native decoder (others are Unsupported). -decode-native = ["aac-decode", "alac-decode", "opus-decode", "ac3-decode", "mpa-decode", "mp3-decode", "craft-media/isobmff", "craft-media/matroska", "craft-media/ogg", "dep:log"] +decode-native = ["aac-decode", "alac-decode", "opus-decode", "ac3-decode", "mpa-decode", "mp3-decode", "craft-media/isobmff", "craft-media/matroska", "craft-media/ogg", "dep:log", "dep:craft-xml"] # The symphonia fallback for the formats with no native decoder yet. symphonia = ["decode-native", "dep:symphonia"] # Every encoder: the lossless file writers and the AAC, ALAC, AC-3/E-AC-3, MP3 and Opus encoders. @@ -60,6 +60,7 @@ serde = ["dep:serde", "craft-media/serde"] [dependencies] craft-media = { workspace = true } +craft-xml = { workspace = true, optional = true } thiserror = { workspace = true } serde = { workspace = true, optional = true } log = { version = "0.4", optional = true } diff --git a/crates/audio/README.md b/crates/audio/README.md index 5a5df4f2f..63251db8d 100644 --- a/crates/audio/README.md +++ b/crates/audio/README.md @@ -761,3 +761,8 @@ The codec modules' public items keep their names, so apps can re-export them CAF. MP4 and Matroska files decode to presentation length. A packet that fails is concealed, not dropped. A failed source read is `AudioError::Io`. + +WAV timestamps use `bext` when present, including a zero timestamp. Otherwise a bounded iXML +`BWFXML/BEXT` time reference supplies the timestamp (two unsigned 32-bit words; an omitted high +word is zero). Only the first iXML chunk is considered. Invalid or oversized optional XML is +ignored without rejecting the audio. This works for byte-backed and streaming sources. diff --git a/crates/audio/src/read/wav.rs b/crates/audio/src/read/wav.rs index bd9c2301a..c1552d7e2 100644 --- a/crates/audio/src/read/wav.rs +++ b/crates/audio/src/read/wav.rs @@ -115,6 +115,50 @@ fn parse_bext(c: &[u8]) -> Option { }) } +/// Cap optional metadata independently of audio length, including on range-backed sources. +const IXML_MAX: usize = 1 << 20; + +/// iXML's BEXT mirror is a fallback only: a real `bext` always wins, including timestamp zero. +/// Read the two unsigned 32-bit words, not arbitrary text that merely contains their tag names. +fn ixml_time_reference(bytes: &[u8]) -> Option { + let options = craft_xml::Options { + doctype: craft_xml::Doctype::Reject, + ..craft_xml::Options::default().strict().with_limits(craft_xml::Limits { + max_input: IXML_MAX, + max_depth: 32, + max_nodes: 8192, + max_attrs: 64, + max_attrs_total: 8192, + ..craft_xml::Limits::default() + }) + }; + let root = options.parse(bytes).ok()?; + if root.name != "BWFXML" { + return None; + } + let mut bexts = root.children("BEXT"); + let bext = bexts.next()?; + if bexts.next().is_some() { + return None; + } + let word = |name: &str| -> Option> { + let mut fields = bext.children(name); + let Some(field) = fields.next() else { return Some(None) }; + if fields.next().is_some() || field.children.iter().any(|n| matches!(n, craft_xml::Node::El(_))) { + return None; + } + let text = field.text(); + let text = text.trim(); + if text.is_empty() || !text.bytes().all(|b| b.is_ascii_digit()) { + return None; + } + Some(Some(text.parse().ok()?)) + }; + let low = word("BWF_TIME_REFERENCE_LOW")??; + let high = word("BWF_TIME_REFERENCE_HIGH")?.unwrap_or(0); + Some((u64::from(high) << 32) | u64::from(low)) +} + /// Refuse the WAVE file at `at`, which symphonia reads (A-law, ADPCM, ...), if an INFO entry /// claims more bytes than the file holds: symphonia allocates each entry's length. Chunks are /// walked where symphonia reads them: after the bytes a chunk's parser used, not its length. @@ -239,7 +283,7 @@ fn pcm_layout(fmt: &Fmt) -> Result> { } /// Parse a WAV file's chunks: its format, `bext` metadata and where its samples are. Only chunk -/// headers and the small `fmt `, `bext` and `ds64` bodies are read. +/// headers, small `fmt `, `bext` and `ds64` bodies, and at most one 1 MiB iXML document are read. pub(crate) fn parse(src: &Src<'_>) -> Result { if !is_wav(&src.bytes_upto(0, 12)) { return Err(AudioError::Malformed("not a RIFF/RF64 WAVE file".into())); @@ -249,6 +293,8 @@ pub(crate) fn parse(src: &Src<'_>) -> Result { let mut ds64_data: Option = None; let mut fmt: Option = None; let mut bwf: Option = None; + let mut ixml_time = None; + let mut ixml_seen = false; let mut data: Option<(u64, u64)> = None; let mut pos: u64 = 12; @@ -288,7 +334,18 @@ pub(crate) fn parse(src: &Src<'_>) -> Result { let small = |n: u64| src.bytes(body, usize::try_from(declared.min(n)).unwrap_or(0)).unwrap_or_default(); match &id { b"fmt " => fmt = Some(parse_fmt(&small(256))?), - b"bext" => bwf = parse_bext(&small(4096)), + b"bext" => { + if let Some(info) = parse_bext(&small(4096)) { + bwf = Some(info); + } + } + b"iXML" if !ixml_seen => { + // Inspect at most one bounded document, not 100,000 individually bounded trees. + ixml_seen = true; + if declared <= IXML_MAX as u64 { + ixml_time = ixml_time_reference(&small(IXML_MAX as u64)); + } + } b"ds64" => ds64_data = le_u64(&small(64), 8), _ => {} } @@ -297,6 +354,9 @@ pub(crate) fn parse(src: &Src<'_>) -> Result { pos = next; } + if bwf.is_none() { + bwf = ixml_time.map(|time_reference| BwfInfo { time_reference, ..BwfInfo::default() }); + } let fmt = fmt.ok_or_else(|| AudioError::Malformed("WAV has no fmt chunk".into()))?; if fmt.channels == 0 { return Err(AudioError::Malformed("WAV declares zero channels".into())); diff --git a/crates/audio/tests/audio/main.rs b/crates/audio/tests/audio/main.rs index 8c37256d6..52e1d17f4 100644 --- a/crates/audio/tests/audio/main.rs +++ b/crates/audio/tests/audio/main.rs @@ -10,3 +10,4 @@ mod raw_pcm; mod roundtrip; mod stream; mod wav_empty_data; +mod wav_ixml; diff --git a/crates/audio/tests/audio/wav_ixml.rs b/crates/audio/tests/audio/wav_ixml.rs new file mode 100644 index 000000000..8bc975940 --- /dev/null +++ b/crates/audio/tests/audio/wav_ixml.rs @@ -0,0 +1,87 @@ +//! iXML timestamp parity with FilmCraft's streaming WAV reader, including hostile metadata. +use std::io::Cursor; + +use craft_audio::{DecodeOptions, Decoder}; +use craft_media::ReadSeekSource; + +fn chunk(id: &[u8; 4], body: &[u8]) -> Vec { + let mut out = id.to_vec(); + out.extend_from_slice(&(body.len() as u32).to_le_bytes()); + out.extend_from_slice(body); + if body.len() % 2 != 0 { + out.push(0); + } + out +} + +fn wav(metadata: &[Vec]) -> Vec { + let mut out = b"RIFF\0\0\0\0WAVE".to_vec(); + out.extend(chunk(b"fmt ", &[1, 0, 1, 0, 0x80, 0xbb, 0, 0, 0, 0x77, 1, 0, 2, 0, 16, 0])); + for m in metadata { + out.extend(m); + } + out.extend(chunk(b"data", &[0, 0, 1, 0])); + let len = (out.len() - 8) as u32; + out[4..8].copy_from_slice(&len.to_le_bytes()); + out +} + +fn xml(low: &str, high: Option<&str>) -> Vec { + let high = high.map(|v| format!("{v}")).unwrap_or_default(); + chunk(b"iXML", format!("{low}{high}").as_bytes()) +} + +fn check(file: Vec, expected: Option) { + let options = DecodeOptions::default(); + let mut bytes = Decoder::from_bytes(&file, Some("wav"), &options).unwrap(); + assert_eq!(bytes.info().bwf.as_ref().map(|b| b.time_reference), expected); + let source = ReadSeekSource::new(Cursor::new(file.clone())).unwrap(); + let mut stream = Decoder::open(source, Some("wav"), &options).unwrap(); + assert_eq!(stream.info().bwf.as_ref().map(|b| b.time_reference), expected); + assert_eq!(bytes.info().frames, 2); + assert_eq!(stream.next_block().unwrap().unwrap().frames(), 2); + assert_eq!(bytes.next_block().unwrap().unwrap().frames(), 2); +} + +#[test] +fn ixml_fallback_preserves_large_timestamps_and_optional_high_word() { + check(wav(&[xml(" 5 ", Some("1"))]), Some((1 << 32) + 5)); + check(wav(&[xml("0", None)]), Some(0)); + check(wav(&[xml("4294967295", Some("4294967295"))]), Some(u64::MAX)); +} + +#[test] +fn bext_wins_in_either_chunk_order_including_timestamp_zero() { + let bext = chunk(b"bext", &[0; 602]); + let ixml = xml("5", Some("1")); + check(wav(&[bext.clone(), ixml.clone()]), Some(0)); + check(wav(&[ixml.clone(), bext.clone()]), Some(0)); + check(wav(&[bext, chunk(b"bext", &[0; 12]), ixml.clone()]), Some(0)); + check(wav(&[chunk(b"bext", &[0; 12]), ixml]), Some((1 << 32) + 5)); +} + +#[test] +fn invalid_metadata_never_fabricates_a_timestamp_or_blocks_audio() { + for low in ["4294967296", "-1", "+1", "", "1.5", "5"] { + check(wav(&[xml(low, Some("0"))]), None); + } + for high in ["4294967296", "-1", "", "oops"] { + check(wav(&[xml("5", Some(high))]), None); + } + for text in [ + "5", + "", + "56", + "5", + ] { + check(wav(&[chunk(b"iXML", text.as_bytes())]), None); + } + check(wav(&[chunk(b"iXML", &vec![b' '; (1 << 20) + 1])]), None); + let deep = format!("{}{}", "".repeat(40), "".repeat(40)); + check(wav(&[chunk(b"iXML", deep.as_bytes())]), None); +} + +#[test] +fn only_first_ixml_document_is_considered() { + check(wav(&[xml("5", None), xml("6", None)]), Some(5)); +}