diff --git a/crates/audio/Cargo.toml b/crates/audio/Cargo.toml index a0e46a7a5..ae633a05d 100644 --- a/crates/audio/Cargo.toml +++ b/crates/audio/Cargo.toml @@ -183,3 +183,7 @@ required-features = ["lossless-encode", "aac-encode"] [[test]] name = "dsd_bounds" required-features = ["dsd"] + +[[test]] +name = "dsd_metadata" +required-features = ["dsd"] diff --git a/crates/audio/src/dsd/dsdiff.rs b/crates/audio/src/dsd/dsdiff.rs index f1980d136..01a71b42e 100644 --- a/crates/audio/src/dsd/dsdiff.rs +++ b/crates/audio/src/dsd/dsdiff.rs @@ -38,6 +38,37 @@ fn channel_id_to_name(id: &[u8; 4]) -> String { } } +/// The text of a `DITI` or `DIAR` chunk: a four-byte big-endian character count, then that many +/// bytes. `None` when the count is missing or longer than the chunk. +fn diin_text(sub_data: &[u8]) -> Option { + let count = usize::try_from(u32::from_be_bytes(sub_data.get(..4)?.try_into().ok()?)).ok()?; + let text = sub_data.get(4..)?.get(..count)?; + Some(String::from_utf8_lossy(text).trim().to_string()) +} + +/// The channel identifiers DSDIFF 1.5 defines for a channel count (stereo, 5 and 5.1 channels); +/// other counts use the generic `C001`, `C002`, ... identifiers. +fn channel_ids(num_channels: usize) -> Vec<[u8; 4]> { + let named: &[&[u8; 4]] = match num_channels { + 1 => &[b"SLFT"], + 2 => &[b"SLFT", b"SRGT"], + 5 => &[b"MLFT", b"MRGT", b"C ", b"LS ", b"RS "], + 6 => &[b"MLFT", b"MRGT", b"C ", b"LFE ", b"LS ", b"RS "], + _ => &[], + }; + if !named.is_empty() { + return named.iter().map(|id| **id).collect(); + } + (1..=num_channels) + .map(|n| { + let s = format!("C{n:03}"); + let mut id = [b' '; 4]; + id.copy_from_slice(&s.as_bytes()[..4]); + id + }) + .collect() +} + /// Parses the metadata from a DSDIFF file. pub fn parse_dsdiff_header(bytes: &[u8]) -> Result<(Metadata, usize, usize), Error> { if bytes.len() < 16 { @@ -163,9 +194,9 @@ pub fn parse_dsdiff_header(bytes: &[u8]) -> Result<(Metadata, usize, usize), Err diin_pos = diin_pos.saturating_add(sub_size).saturating_add(sub_pad); if sub_id == b"DITI" && title.is_none() { - title = Some(String::from_utf8_lossy(sub_data).trim().to_string()); + title = diin_text(sub_data); } else if sub_id == b"DIAR" && artist.is_none() { - artist = Some(String::from_utf8_lossy(sub_data).trim().to_string()); + artist = diin_text(sub_data); } } } @@ -252,7 +283,9 @@ pub fn write_dsdiff(sample_rate: u32, channels: &[&[u8]], sample_count: u64) -> let bytes_per_ch = usize::try_from(sample_count.div_ceil(8)).map_err(|_| Error::MemoryLimitExceeded)?; let data_size = bytes_per_ch.checked_mul(num_channels).ok_or(Error::MemoryLimitExceeded)?; // Fixed headers plus four bytes for each channel identifier. - let file_size = super::encoded_size(data_size, 110 + 4 * num_channels)?; + // An odd-sized chunk payload is followed by a pad byte that its size field does not count. + let data_pad = data_size & 1; + let file_size = super::encoded_size(data_size + data_pad, 110 + 4 * num_channels)?; // Build PROP subchunks: // 1. 'FS ' (4 bytes + 12 chunk header) @@ -267,18 +300,8 @@ pub fn write_dsdiff(sample_rate: u32, channels: &[&[u8]], sample_count: u64) -> chnl_chunk.extend_from_slice(b"CHNL"); chnl_chunk.extend_from_slice(&(chnl_data_len as u64).to_be_bytes()); chnl_chunk.extend_from_slice(&(num_channels as u16).to_be_bytes()); - for c in 0..num_channels { - let code = match (num_channels, c) { - (1, 0) => b"SLFT", - (2, 0) => b"SLFT", - (2, 1) => b"SRGT", - (_, 0) => b"MLFT", - (_, 1) => b"MRGT", - (_, 2) => b"C ", - (_, 3) => b"LFE ", - _ => b"C ", - }; - chnl_chunk.extend_from_slice(code); + for id in channel_ids(num_channels) { + chnl_chunk.extend_from_slice(&id); } if !chnl_data_len.is_multiple_of(2) { chnl_chunk.push(0); @@ -330,6 +353,9 @@ pub fn write_dsdiff(sample_rate: u32, channels: &[&[u8]], sample_count: u64) -> out.push(byte); } } + if data_pad == 1 { + out.push(0); + } Ok(out) } diff --git a/crates/audio/src/dsd/dsf.rs b/crates/audio/src/dsd/dsf.rs index 34472001e..3a0946664 100644 --- a/crates/audio/src/dsd/dsf.rs +++ b/crates/audio/src/dsd/dsf.rs @@ -15,7 +15,7 @@ fn dsf_channel_names(channel_type: u32, channel_count: u16) -> Vec { 2 => vec!["Left".to_string(), "Right".to_string()], 3 => vec!["Left".to_string(), "Right".to_string(), "Center".to_string()], 4 => vec!["FrontLeft".to_string(), "FrontRight".to_string(), "BackLeft".to_string(), "BackRight".to_string()], - 5 => vec!["FrontLeft".to_string(), "FrontRight".to_string(), "Center".to_string(), "Surround".to_string()], + 5 => vec!["FrontLeft".to_string(), "FrontRight".to_string(), "Center".to_string(), "LFE".to_string()], 6 => vec!["FrontLeft".to_string(), "FrontRight".to_string(), "Center".to_string(), "BackLeft".to_string(), "BackRight".to_string()], 7 => vec![ "FrontLeft".to_string(), @@ -53,7 +53,16 @@ fn parse_id3v2(bytes: &[u8], offset: usize) -> (Option, Option) if frame_id[0] == 0 { break; } - let frame_size = u32::from_be_bytes([id3[pos + 4], id3[pos + 5], id3[pos + 6], id3[pos + 7]]) as usize; + let raw = [id3[pos + 4], id3[pos + 5], id3[pos + 6], id3[pos + 7]]; + // ID3v2.4 frame sizes are synchsafe; v2.3 ones are plain big-endian. + let frame_size = if id3[3] >= 4 { + if raw.iter().any(|b| b & 0x80 != 0) { + break; + } + ((raw[0] as usize) << 21) | ((raw[1] as usize) << 14) | ((raw[2] as usize) << 7) | raw[3] as usize + } else { + u32::from_be_bytes(raw) as usize + }; pos += 10; if frame_size > end.saturating_sub(pos) { break; @@ -78,23 +87,35 @@ fn parse_text_frame(data: &[u8]) -> Option { } let encoding = data[0]; let content = &data[1..]; - match encoding { - 0 | 3 => { - // ISO-8859-1 or UTF-8 - let s = String::from_utf8_lossy(content).trim_end_matches('\0').trim().to_string(); - if s.is_empty() { None } else { Some(s) } + let text = match encoding { + // ISO-8859-1: every byte is the code point of the same value. + 0 => content.iter().map(|&b| char::from(b)).collect::(), + 3 => String::from_utf8_lossy(content).into_owned(), + // UTF-16 with a byte order mark (which is removed); without one, assume big-endian. + 1 => { + let (big_endian, body) = match content { + [0xFE, 0xFF, rest @ ..] => (true, rest), + [0xFF, 0xFE, rest @ ..] => (false, rest), + _ => (true, content), + }; + utf16(body, big_endian) } - 1 | 2 => { - // UTF-16 with BOM or UTF-16BE - if content.len() < 2 { - return None; - } - let u16s: Vec = content.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes([c[0], c[1]])).collect(); - let s = String::from_utf16_lossy(&u16s).trim_end_matches('\0').trim().to_string(); - if s.is_empty() { None } else { Some(s) } - } - _ => None, - } + // UTF-16BE without a byte order mark. + 2 => utf16(content, true), + _ => return None, + }; + let s = text.trim_end_matches('\0').trim().to_string(); + if s.is_empty() { None } else { Some(s) } +} + +fn utf16(bytes: &[u8], big_endian: bool) -> String { + let units: Vec = bytes + .as_chunks::<2>() + .0 + .iter() + .map(|c| if big_endian { u16::from_be_bytes([c[0], c[1]]) } else { u16::from_le_bytes([c[0], c[1]]) }) + .collect(); + String::from_utf16_lossy(&units) } /// Parses DSF file metadata, returning the metadata, audio data offset, and block size per channel. @@ -264,6 +285,10 @@ pub fn parse_dsf(bytes: &[u8]) -> Result { Ok(RawAudio { metadata, bit_order: BitOrder::LsbFirst, channel_bytes }) } +fn unsupported_channel_layout() -> Result { + Err(Error::Unsupported("DSF has no channel type for this channel count (1 to 6 are supported)")) +} + /// Encodes 1-bit planar audio channels into a valid Sony DSF file. pub fn write_dsf(sample_rate: u32, channels: &[&[u8]], sample_count: u64, block_size: u32) -> Result, Error> { if channels.is_empty() || channels.len() > MAX_CHANNELS { @@ -299,7 +324,16 @@ pub fn write_dsf(sample_rate: u32, channels: &[&[u8]], sample_count: u64, block_ out.extend_from_slice(&52u64.to_le_bytes()); out.extend_from_slice(&1u32.to_le_bytes()); // format_version = 1 out.extend_from_slice(&0u32.to_le_bytes()); // format_id = 0 (raw DSD) - let channel_type = if num_channels == 1 { 1u32 } else { 2u32 }; + // DSF channel types: 1 mono, 2 stereo, 3 L R C, 4 quad, 6 five channels, 7 5.1. + let channel_type = match num_channels { + 1 => 1u32, + 2 => 2, + 3 => 3, + 4 => 4, + 5 => 6, + 6 => 7, + _ => unsupported_channel_layout()?, + }; out.extend_from_slice(&channel_type.to_le_bytes()); out.extend_from_slice(&(num_channels as u32).to_le_bytes()); out.extend_from_slice(&sample_rate.to_le_bytes()); diff --git a/crates/audio/src/dsd/filter.rs b/crates/audio/src/dsd/filter.rs index f7d934d3e..ec815afd1 100644 --- a/crates/audio/src/dsd/filter.rs +++ b/crates/audio/src/dsd/filter.rs @@ -156,6 +156,27 @@ pub(super) fn allocation_sizes(len: usize, factor: u32) -> Result<(usize, usize) Ok((working, output)) } +/// Unity-DC-gain low-pass taps for decimating by `ratio` (cutoff 0.45 / ratio cycles per sample). +fn decimation_taps(ratio: usize) -> Vec { + let n = 24 * ratio + 1; + let mid = (n / 2) as f64; + let fc = 0.45 / ratio as f64; + let mut taps: Vec = (0..n) + .map(|k| { + let x = k as f64 - mid; + let sinc = if x == 0.0 { 2.0 * fc } else { (2.0 * std::f64::consts::PI * fc * x).sin() / (std::f64::consts::PI * x) }; + let t = k as f64 / (n - 1) as f64; + let window = 0.42 - 0.5 * (2.0 * std::f64::consts::PI * t).cos() + 0.08 * (4.0 * std::f64::consts::PI * t).cos(); + sinc * window + }) + .collect(); + let sum: f64 = taps.iter().sum(); + for t in &mut taps { + *t /= sum; + } + taps.into_iter().map(|t| t as f32).collect() +} + /// Decimates 1-bit DSD audio bytes for a single channel to `f32` PCM. /// /// The default decimation factor is 8 (1 output float per input byte). @@ -209,16 +230,59 @@ pub fn decimate_channel(channel_bytes: &[u8], bit_order: BitOrder, factor: u32) return Ok(stage1); } - // Secondary downsampling by ratio = factor / 8 (2, 4, or 8). + // Secondary decimation by ratio = factor / 8 (2, 4, or 8). A plain average attenuates the band + // between the new Nyquist rate and the stage-1 rate too little (about -7.6 dB at 29.4 kHz for + // factor 64), so low-pass first: a Blackman-windowed sinc with its cutoff at 90% of the new + // Nyquist frequency, evaluated only at the kept samples. let ratio = (factor / 8) as usize; let out_len = stage1.len() / ratio; let mut out = Vec::new(); out.try_reserve_exact(out_len).map_err(|_| Error::MemoryLimitExceeded)?; - for chunk in stage1.chunks_exact(ratio) { - let sum: f32 = chunk.iter().sum(); - out.push(sum / ratio as f32); + let taps = decimation_taps(ratio); + let half = (taps.len() / 2) as isize; + let last = stage1.len() as isize - 1; + for i in 0..out_len { + let center = (i * ratio + ratio / 2) as isize; + let mut acc = 0.0_f32; + for (k, &w) in taps.iter().enumerate() { + let idx = (center + k as isize - half).clamp(0, last); + if let Some(&x) = stage1.get(idx as usize) { + acc += w * x; + } + } + out.push(acc); } Ok(out) } + +#[cfg(test)] +#[allow(clippy::unwrap_used)] +mod decimation_tests { + use super::*; + + /// A full-scale 29.4 kHz square wave in DSD64 (six bytes of ones, six of zeros) lies between + /// the output Nyquist frequency and the sampling rate of a 44.1 kHz result: it must be + /// attenuated well, not folded down at 0.42 of its amplitude. + #[test] + fn factor_64_attenuates_29_4_khz() { + let mut bytes = Vec::new(); + for _ in 0..2000 { + bytes.extend_from_slice(&[0xFF; 6]); + bytes.extend_from_slice(&[0x00; 6]); + } + let out = decimate_channel(&bytes, BitOrder::MsbFirst, 64).unwrap(); + let mid = &out[out.len() / 4..out.len() * 3 / 4]; + let peak = mid.iter().fold(0.0_f32, |m, v| m.max(v.abs())); + assert!(peak < 0.05, "peak {peak}"); + } + + #[test] + fn decimation_keeps_dc_level() { + let bytes = vec![0xFF; 4096]; + let out = decimate_channel(&bytes, BitOrder::MsbFirst, 64).unwrap(); + let mid = out[out.len() / 2]; + assert!((mid - 1.0).abs() < 0.05, "{mid}"); + } +} diff --git a/crates/audio/src/lib.rs b/crates/audio/src/lib.rs index 5ab2b8089..fcaf2897e 100644 --- a/crates/audio/src/lib.rs +++ b/crates/audio/src/lib.rs @@ -2,7 +2,7 @@ #![warn(missing_docs)] // The docs link items of every feature; built with fewer features, those links have no target. // CI and docs.rs build the docs with all features, where every link must resolve. -#![cfg_attr(not(all(feature = "decode", feature = "encode", feature = "peaks")), allow(rustdoc::broken_intra_doc_links))] +#![cfg_attr(not(all(feature = "decode", feature = "encode", feature = "peaks", feature = "dsd")), allow(rustdoc::broken_intra_doc_links))] //! Audio file I/O and codecs for the Craft apps. Input and output are byte slices or a //! [`craft_media::ByteSource`] (no filesystem access of its own); builds for //! `wasm32-unknown-unknown`. diff --git a/crates/audio/tests/dsd_bounds.rs b/crates/audio/tests/dsd_bounds.rs index c335c5d63..52f18730b 100644 --- a/crates/audio/tests/dsd_bounds.rs +++ b/crates/audio/tests/dsd_bounds.rs @@ -81,6 +81,11 @@ fn encoded_sizes_match_actual_bytes_for_odd_and_even_payloads() { let data = vec![0x69; len]; let planes = vec![data.as_slice(); channels]; for block in [0, 1, 3, 8] { + // DSF has channel types for 1 to 6 channels only. + if channels > 6 { + assert!(matches!(encode_dsf(2_822_400, &planes, len as u64 * 8, block), Err(Error::Unsupported(_)))); + continue; + } let dsf = encode_dsf(2_822_400, &planes, len as u64 * 8, block).unwrap(); assert_eq!(u64::from_le_bytes(dsf[12..20].try_into().unwrap()), dsf.len() as u64); assert_eq!(read_raw(&dsf).unwrap().channel_bytes, vec![data.clone(); channels]); diff --git a/crates/audio/tests/dsd_metadata.rs b/crates/audio/tests/dsd_metadata.rs new file mode 100644 index 000000000..6b076a0e7 --- /dev/null +++ b/crates/audio/tests/dsd_metadata.rs @@ -0,0 +1,153 @@ +//! Channel labels, text metadata and padding in the DSF and DSDIFF readers and writers. +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +use craft_audio::dsd::{encode_dsdiff, encode_dsf, read_metadata, read_raw}; + +const RATE: u32 = 2_822_400; + +fn planes(channels: usize, len: usize) -> Vec> { + vec![vec![0x69; len]; channels] +} + +fn refs(p: &[Vec]) -> Vec<&[u8]> { + p.iter().map(Vec::as_slice).collect() +} + +#[test] +fn dsdiff_names_surround_channels_by_layout() { + for (n, names) in [ + (5, vec!["Mono/Left", "Right", "Center", "LeftSurround", "RightSurround"]), + (6, vec!["Mono/Left", "Right", "Center", "LFE", "LeftSurround", "RightSurround"]), + ] { + let p = planes(n, 4); + let bytes = encode_dsdiff(RATE, &refs(&p), 32).unwrap(); + assert_eq!(read_metadata(&bytes).unwrap().channel_names, names, "{n} channels"); + } +} + +#[test] +fn dsdiff_odd_audio_is_padded_and_counted_in_the_file_size() { + let p = planes(1, 1); + let bytes = encode_dsdiff(RATE, &refs(&p), 8).unwrap(); + assert_eq!(bytes.len() % 2, 0); + assert_eq!(u64::from_be_bytes(bytes[4..12].try_into().unwrap()) + 12, bytes.len() as u64); + assert_eq!(*bytes.last().unwrap(), 0, "pad byte"); + assert_eq!(read_raw(&bytes).unwrap().channel_bytes, vec![vec![0x69]]); +} + +fn with_diin(mut bytes: Vec, sub: &[u8; 4], payload: &[u8]) -> Vec { + let mut sub_chunk = Vec::new(); + sub_chunk.extend_from_slice(sub); + sub_chunk.extend_from_slice(&(payload.len() as u64).to_be_bytes()); + sub_chunk.extend_from_slice(payload); + if payload.len() % 2 == 1 { + sub_chunk.push(0); + } + bytes.extend_from_slice(b"DIIN"); + bytes.extend_from_slice(&(sub_chunk.len() as u64).to_be_bytes()); + bytes.extend_from_slice(&sub_chunk); + let size = (bytes.len() - 12) as u64; + bytes[4..12].copy_from_slice(&size.to_be_bytes()); + bytes +} + +#[test] +fn dsdiff_title_and_artist_skip_the_character_count() { + let p = planes(2, 4); + let base = encode_dsdiff(RATE, &refs(&p), 32).unwrap(); + let mut payload = 4u32.to_be_bytes().to_vec(); + payload.extend_from_slice(b"Test"); + let bytes = with_diin(base.clone(), b"DITI", &payload); + assert_eq!(read_metadata(&bytes).unwrap().title.as_deref(), Some("Test")); + let bytes = with_diin(base.clone(), b"DIAR", &payload); + assert_eq!(read_metadata(&bytes).unwrap().artist.as_deref(), Some("Test")); + // A count longer than the chunk is not text. + let mut bad = 99u32.to_be_bytes().to_vec(); + bad.extend_from_slice(b"Test"); + assert_eq!(read_metadata(&with_diin(base, b"DITI", &bad)).unwrap().title, None); +} + +#[test] +fn dsf_channel_types_match_the_channel_count() { + for (n, expect) in [(1, 1), (2, 2), (3, 3), (4, 4), (5, 6), (6, 7)] { + let p = planes(n, 4); + let bytes = encode_dsf(RATE, &refs(&p), 32, 4096).unwrap(); + assert_eq!(u32::from_le_bytes(bytes[48..52].try_into().unwrap()), expect, "{n} channels"); + assert_eq!(read_metadata(&bytes).unwrap().channel_names.len(), n); + } + let p = planes(7, 4); + assert!(encode_dsf(RATE, &refs(&p), 32, 4096).is_err()); +} + +#[test] +fn dsf_type_5_names_the_fourth_channel_lfe() { + let p = planes(4, 4); + let mut bytes = encode_dsf(RATE, &refs(&p), 32, 4096).unwrap(); + bytes[48..52].copy_from_slice(&5u32.to_le_bytes()); + assert_eq!(read_metadata(&bytes).unwrap().channel_names, ["FrontLeft", "FrontRight", "Center", "LFE"]); +} + +fn id3(version: u8, frames: &[u8]) -> Vec { + let n = frames.len(); + let mut tag = vec![b'I', b'D', b'3', version, 0, 0]; + tag.extend_from_slice(&[(n >> 21) as u8 & 0x7F, (n >> 14) as u8 & 0x7F, (n >> 7) as u8 & 0x7F, n as u8 & 0x7F]); + tag.extend_from_slice(frames); + tag +} + +fn frame(version: u8, id: &[u8; 4], body: &[u8]) -> Vec { + let n = body.len(); + let mut f = id.to_vec(); + if version >= 4 { + f.extend_from_slice(&[(n >> 21) as u8 & 0x7F, (n >> 14) as u8 & 0x7F, (n >> 7) as u8 & 0x7F, n as u8 & 0x7F]); + } else { + f.extend_from_slice(&(n as u32).to_be_bytes()); + } + f.extend_from_slice(&[0, 0]); + f.extend_from_slice(body); + f +} + +fn dsf_with_tag(tag: &[u8]) -> Vec { + let p = planes(2, 4); + let mut bytes = encode_dsf(RATE, &refs(&p), 32, 4096).unwrap(); + let offset = bytes.len() as u64; + bytes[20..28].copy_from_slice(&offset.to_le_bytes()); + bytes.extend_from_slice(tag); + bytes +} + +#[test] +fn id3v24_frame_sizes_are_synchsafe() { + // A 128-byte frame has the synchsafe size 00 00 01 00; read as plain big-endian it is 256. + let mut frames = frame(4, b"APIC", &[0u8; 128]); + let mut title = vec![3]; + title.extend_from_slice(b"After art"); + frames.extend(frame(4, b"TIT2", &title)); + let m = read_metadata(&dsf_with_tag(&id3(4, &frames))).unwrap(); + assert_eq!(m.title.as_deref(), Some("After art")); +} + +#[test] +fn id3v23_frame_sizes_stay_big_endian() { + let mut frames = frame(3, b"APIC", &[0u8; 128]); + let mut title = vec![3]; + title.extend_from_slice(b"Three"); + frames.extend(frame(3, b"TIT2", &title)); + let m = read_metadata(&dsf_with_tag(&id3(3, &frames))).unwrap(); + assert_eq!(m.title.as_deref(), Some("Three")); +} + +#[test] +fn id3_text_encodings() { + let cases: [(&[u8], &str); 5] = [ + (b"\x00Caf\xe9", "Café"), + (b"\x03Caf\xc3\xa9", "Café"), + (b"\x02\x00A\x00B", "AB"), + (b"\x01\xFF\xFEA\x00B\x00", "AB"), + (b"\x01\xFE\xFF\x00A\x00B", "AB"), + ]; + for (body, expect) in cases { + let m = read_metadata(&dsf_with_tag(&id3(4, &frame(4, b"TIT2", body)))).unwrap(); + assert_eq!(m.title.as_deref(), Some(expect), "{body:?}"); + } +}