fix(audio): stop DSF audio at the declared data chunk

This commit is contained in:
Dylan M. Taylor
2026-11-17 10:12:56 -05:00
parent cbbba064fd
commit 25a882c1ce
2 changed files with 32 additions and 3 deletions
+10 -3
View File
@@ -99,6 +99,11 @@ fn parse_text_frame(data: &[u8]) -> Option<String> {
/// Parses DSF file metadata, returning the metadata, audio data offset, and block size per channel.
pub fn parse_dsf_header(bytes: &[u8]) -> Result<(Metadata, usize, u32), Error> {
let (metadata, offset, _, block_size) = parse_dsf_header_bounded(bytes)?;
Ok((metadata, offset, block_size))
}
fn parse_dsf_header_bounded(bytes: &[u8]) -> Result<(Metadata, usize, usize, u32), Error> {
if bytes.len() < 28 + 52 + 12 {
return Err(Error::UnexpectedEof("DSF file header is truncated"));
}
@@ -189,12 +194,12 @@ pub fn parse_dsf_header(bytes: &[u8]) -> Result<(Metadata, usize, u32), Error> {
let metadata = Metadata { format: Format::Dsf, sample_rate, channels, sample_count, channel_names, title, artist };
Ok((metadata, payload_offset, block_size_per_channel))
Ok((metadata, payload_offset, payload_size, block_size_per_channel))
}
/// Parses a DSF file into raw 1-bit planar channel streams.
pub fn parse_dsf(bytes: &[u8]) -> Result<RawAudio, Error> {
let (metadata, payload_offset, block_size) = parse_dsf_header(bytes)?;
let (metadata, payload_offset, payload_size, block_size) = parse_dsf_header_bounded(bytes)?;
let block_size = block_size as usize;
let channels = metadata.channels as usize;
@@ -208,7 +213,9 @@ pub fn parse_dsf(bytes: &[u8]) -> Result<RawAudio, Error> {
return Err(Error::InvalidHeader("zero slice size"));
}
let payload = &bytes[payload_offset..];
// The header validated this range. Trailing ID3 or other bytes are not audio,
// even if sample_count asks for more samples than the data chunk contains.
let payload = &bytes[payload_offset..payload_offset + payload_size];
let num_slices = payload.len() / slice_size;
let mut channel_bytes: Vec<Vec<u8>> = Vec::with_capacity(channels);
+22
View File
@@ -91,3 +91,25 @@ fn encoded_sizes_match_actual_bytes_for_odd_and_even_payloads() {
}
}
}
#[test]
fn dsf_audio_stops_at_the_declared_data_chunk() {
for channels in 1..=2 {
let input = vec![&[0x33u8; 8][..]; channels];
let mut bytes = encode_dsf(2_822_400, &input, 64, 8).unwrap();
// Ask for an additional block without extending the data chunk.
bytes[64..72].copy_from_slice(&128u64.to_le_bytes());
let expected = read_raw(&bytes).unwrap();
for c in &expected.channel_bytes {
assert_eq!(&c[..8], &[0x33; 8]);
assert_eq!(&c[8..], &[0x69; 8]);
}
let metadata_offset = bytes.len() as u64;
bytes[20..28].copy_from_slice(&metadata_offset.to_le_bytes());
bytes.extend_from_slice(b"ID3\x04\x00\x00\x00\x00\x00\x00");
bytes.extend_from_slice(&[0xff; 32]);
let file_size = bytes.len() as u64;
bytes[12..20].copy_from_slice(&file_size.to_le_bytes());
assert_eq!(read_raw(&bytes).unwrap().channel_bytes, expected.channel_bytes);
}
}