Merge pull request #1479 from storytold/fix/wav-ixml-parity

craft-audio: preserve WAV iXML time-reference fallback
This commit is contained in:
Dylan M. Taylor
2026-11-15 03:53:25 -05:00
committed by GitHub
6 changed files with 158 additions and 3 deletions
Generated
+1
View File
@@ -1352,6 +1352,7 @@ version = "0.1.0"
dependencies = [
"craft-media",
"craft-media-testkit",
"craft-xml",
"log",
"proptest",
"rayon",
+2 -1
View File
@@ -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 }
+5
View File
@@ -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.
+62 -2
View File
@@ -115,6 +115,50 @@ fn parse_bext(c: &[u8]) -> Option<BwfInfo> {
})
}
/// 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<u64> {
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<Option<u32>> {
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<Option<(PcmKind, SampleFormat)>> {
}
/// 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<WavParse> {
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<WavParse> {
let mut ds64_data: Option<u64> = None;
let mut fmt: Option<Fmt> = None;
let mut bwf: Option<BwfInfo> = 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<WavParse> {
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<WavParse> {
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()));
+1
View File
@@ -10,3 +10,4 @@ mod raw_pcm;
mod roundtrip;
mod stream;
mod wav_empty_data;
mod wav_ixml;
+87
View File
@@ -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<u8> {
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().is_multiple_of(2) {
out.push(0);
}
out
}
fn wav(metadata: &[Vec<u8>]) -> Vec<u8> {
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<u8> {
let high = high.map(|v| format!("<BWF_TIME_REFERENCE_HIGH>{v}</BWF_TIME_REFERENCE_HIGH>")).unwrap_or_default();
chunk(b"iXML", format!("<BWFXML><BEXT><BWF_TIME_REFERENCE_LOW>{low}</BWF_TIME_REFERENCE_LOW>{high}</BEXT></BWFXML>").as_bytes())
}
fn check(file: Vec<u8>, expected: Option<u64>) {
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", "<x>5</x>"] {
check(wav(&[xml(low, Some("0"))]), None);
}
for high in ["4294967296", "-1", "", "oops"] {
check(wav(&[xml("5", Some(high))]), None);
}
for text in [
"<BWFXML><BEXT><BWF_TIME_REFERENCE_LOW>5</BWF_TIME_REFERENCE_LOW>",
"<BWFXML><!-- <BWF_TIME_REFERENCE_LOW>5</BWF_TIME_REFERENCE_LOW> --></BWFXML>",
"<BWFXML><BEXT><BWF_TIME_REFERENCE_LOW>5</BWF_TIME_REFERENCE_LOW><BWF_TIME_REFERENCE_LOW>6</BWF_TIME_REFERENCE_LOW></BEXT></BWFXML>",
"<!DOCTYPE BWFXML><BWFXML><BEXT><BWF_TIME_REFERENCE_LOW>5</BWF_TIME_REFERENCE_LOW></BEXT></BWFXML>",
] {
check(wav(&[chunk(b"iXML", text.as_bytes())]), None);
}
check(wav(&[chunk(b"iXML", &vec![b' '; (1 << 20) + 1])]), None);
let deep = format!("<BWFXML>{}{}</BWFXML>", "<a>".repeat(40), "</a>".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));
}