mirror of
https://github.com/storytold/craft-libs.git
synced 2026-12-01 02:36:54 +01:00
The WAV reader takes an RF64 file's data size from the first ds64 chunk of 16 bytes or more. repair_wav skipped a first ds64 chunk under 28 bytes and wrote the sizes into a later one, so the frame count it returned differed from what decoding gave. It now returns Malformed for a first ds64 chunk of 16 to 27 bytes, before writing anything. repair_wav wrote the pad byte of odd-length data before the size fields. A write error after the pad left 8-bit mono data of even length with the old size, which a second repair refused. The pad byte is now written last.
414 lines
18 KiB
Rust
414 lines
18 KiB
Rust
//! Native WAV / BWF / RF64 writer (RIFF chunk layout per the Microsoft multimedia
|
||
//! specification, `bext` per EBU Tech 3285, `ds64` per EBU Tech 3306).
|
||
|
||
use super::pcm::{Quantizer, sample_format, validate_buffer, validate_layout, write_interleaved};
|
||
use crate::wav::{AMBISONIC_TAIL, GUID_TAIL, WAVE_FORMAT_EXTENSIBLE, WAVE_FORMAT_IEEE_FLOAT, WAVE_FORMAT_PCM};
|
||
use crate::{AudioBuffer, AudioError, BitDepth, BwfInfo, Result};
|
||
use std::io::{Cursor, ErrorKind, Read, Seek, SeekFrom, Write};
|
||
|
||
const BEXT_MIN_LEN: usize = 602;
|
||
|
||
/// Default speaker mask for a channel count (callers that know the layout pass their own): the
|
||
/// usual layout's mask, or the first `n` positions for counts with no usual layout, up to 18.
|
||
fn channel_mask(channels: usize) -> u32 {
|
||
match crate::ChannelLayout::default_for(crate::layout::count(channels)).mask() {
|
||
Some(mask) => mask,
|
||
None if channels <= 18 => (1u32 << channels) - 1,
|
||
None => 0,
|
||
}
|
||
}
|
||
|
||
/// `s` in a field of `len` bytes, cut at a character boundary so a reader finds valid UTF-8.
|
||
fn put_fixed_str(out: &mut Vec<u8>, s: &str, len: usize) {
|
||
let bytes = s.as_bytes();
|
||
let n = (0..=bytes.len().min(len)).rev().find(|&n| s.is_char_boundary(n)).unwrap_or(0);
|
||
out.extend_from_slice(bytes.get(..n).unwrap_or_default());
|
||
out.resize(out.len() + (len - n), 0);
|
||
}
|
||
|
||
fn bext_chunk(bwf: &BwfInfo) -> Vec<u8> {
|
||
let mut c = Vec::with_capacity(BEXT_MIN_LEN);
|
||
put_fixed_str(&mut c, &bwf.description, 256);
|
||
put_fixed_str(&mut c, &bwf.originator, 32);
|
||
put_fixed_str(&mut c, &bwf.originator_reference, 32);
|
||
put_fixed_str(&mut c, &bwf.origination_date, 10);
|
||
put_fixed_str(&mut c, &bwf.origination_time, 8);
|
||
c.extend_from_slice(&((bwf.time_reference & 0xFFFF_FFFF) as u32).to_le_bytes());
|
||
c.extend_from_slice(&((bwf.time_reference >> 32) as u32).to_le_bytes());
|
||
c.extend_from_slice(&1u16.to_le_bytes()); // version 1
|
||
c.resize(BEXT_MIN_LEN, 0); // UMID, loudness, reserved; no coding history
|
||
c
|
||
}
|
||
|
||
fn push_chunk(out: &mut Vec<u8>, id: &[u8; 4], body: &[u8]) {
|
||
out.extend_from_slice(id);
|
||
out.extend_from_slice(&u32::try_from(body.len()).unwrap_or(u32::MAX).to_le_bytes());
|
||
out.extend_from_slice(body);
|
||
if body.len() % 2 == 1 {
|
||
out.push(0);
|
||
}
|
||
}
|
||
|
||
/// A WAV written block by block: a placeholder header first, then the real one (the same length,
|
||
/// RF64 above 4 GiB, or always when `force_rf64`) written over it by [`Writer::finish`].
|
||
pub(crate) struct Writer<W> {
|
||
out: W,
|
||
start: u64,
|
||
channels: usize,
|
||
sample_rate: u32,
|
||
format: (u16, bool),
|
||
bwf: Option<BwfInfo>,
|
||
mask: Option<u32>,
|
||
force_rf64: bool,
|
||
quantizers: Vec<Quantizer>,
|
||
frames: u64,
|
||
bytes: Vec<u8>,
|
||
/// Set when a block write has failed: the sink may hold a prefix of that block while
|
||
/// `frames` does not count it, so the writer refuses every later call.
|
||
failed: bool,
|
||
}
|
||
|
||
/// The optional header parts of a WAV file: BWF metadata, speaker mask, and whether to force RF64.
|
||
#[derive(Clone, Copy)]
|
||
pub(crate) struct HeaderExtras<'a> {
|
||
pub(crate) bwf: Option<&'a BwfInfo>,
|
||
pub(crate) mask: Option<u32>,
|
||
pub(crate) force_rf64: bool,
|
||
}
|
||
|
||
impl<W: Write + Seek> Writer<W> {
|
||
pub(crate) fn new(mut out: W, channels: usize, sample_rate: u32, depth: BitDepth, dither: bool, extras: HeaderExtras<'_>) -> Result<Self> {
|
||
let HeaderExtras { bwf, mask, force_rf64 } = extras;
|
||
validate_layout(channels, sample_rate)?;
|
||
let format = sample_format(depth);
|
||
let start = out.stream_position()?;
|
||
out.write_all(&header(channels, sample_rate, format, bwf, mask, 0, force_rf64)?)?;
|
||
let quantizers = Quantizer::per_channel(u32::from(format.0), dither, channels);
|
||
Ok(Writer {
|
||
out,
|
||
start,
|
||
channels,
|
||
sample_rate,
|
||
format,
|
||
bwf: bwf.cloned(),
|
||
mask,
|
||
force_rf64,
|
||
quantizers,
|
||
frames: 0,
|
||
bytes: Vec::new(),
|
||
failed: false,
|
||
})
|
||
}
|
||
|
||
fn header(&self, frames: u64) -> Result<Vec<u8>> {
|
||
header(self.channels, self.sample_rate, self.format, self.bwf.as_ref(), self.mask, frames, self.force_rf64)
|
||
}
|
||
|
||
/// The frame count after `frames` more (RF64 has room for any bounce).
|
||
pub(crate) fn check_room(&self, frames: u64) -> Result<u64> {
|
||
let total = self.frames.saturating_add(frames);
|
||
self.header(total)?;
|
||
Ok(total)
|
||
}
|
||
|
||
/// Appends `frames` frames of planar audio (missing samples are silence).
|
||
pub(crate) fn write<C: AsRef<[f32]>>(&mut self, block: &[C], frames: usize) -> Result<()> {
|
||
if self.failed {
|
||
return Err(super::failed_write_error());
|
||
}
|
||
let total = self.check_room(frames as u64)?;
|
||
if let Err(e) = write_interleaved(&mut self.out, &mut self.bytes, block, frames, &mut self.quantizers, self.format, false) {
|
||
self.failed = true;
|
||
return Err(AudioError::from(e));
|
||
}
|
||
self.frames = total;
|
||
Ok(())
|
||
}
|
||
|
||
pub(crate) fn finish(mut self) -> Result<W> {
|
||
if self.failed {
|
||
return Err(super::failed_write_error());
|
||
}
|
||
let data_len = u64::from(self.format.0 / 8).saturating_mul(self.channels as u64).saturating_mul(self.frames);
|
||
if data_len % 2 == 1 {
|
||
self.out.write_all(&[0])?;
|
||
}
|
||
let head = self.header(self.frames)?;
|
||
self.out.seek(SeekFrom::Start(self.start))?;
|
||
self.out.write_all(&head)?;
|
||
self.out.seek(SeekFrom::End(0))?;
|
||
self.out.flush()?;
|
||
Ok(self.out)
|
||
}
|
||
}
|
||
|
||
/// Encode a WAV file. `force_rf64` writes the RF64 layout even for small files (for tests);
|
||
/// it is used automatically when the file would exceed 4 GiB.
|
||
/// `mask` overrides the speaker mask derived from the channel count.
|
||
pub(crate) fn encode(
|
||
buf: &AudioBuffer,
|
||
depth: BitDepth,
|
||
dither: bool,
|
||
bwf: Option<&BwfInfo>,
|
||
force_rf64: bool,
|
||
mask: Option<u32>,
|
||
) -> Result<Vec<u8>> {
|
||
validate_buffer(buf)?;
|
||
let channels = buf.channels.len();
|
||
let frames = buf.frames();
|
||
let format = sample_format(depth);
|
||
let head = header(channels, buf.sample_rate, format, bwf, mask, frames as u64, force_rf64)?;
|
||
let data_len = (usize::from(format.0 / 8) * channels).checked_mul(frames).ok_or_else(|| AudioError::TooLarge("data size overflow".into()))?;
|
||
let mut out = Vec::new();
|
||
out.try_reserve_exact(head.len().saturating_add(data_len).saturating_add(1))
|
||
.map_err(|_| AudioError::TooLarge(format!("cannot allocate {data_len} bytes for WAV output")))?;
|
||
let mut w = Writer::new(Cursor::new(out), channels, buf.sample_rate, depth, dither, HeaderExtras { bwf, mask, force_rf64 })?;
|
||
w.write(&buf.channels, frames)?;
|
||
Ok(w.finish()?.into_inner())
|
||
}
|
||
|
||
/// Everything before the sample data of a WAV holding `frames` frames.
|
||
pub(crate) fn header(
|
||
channels: usize,
|
||
sample_rate: u32,
|
||
(bits, is_float): (u16, bool),
|
||
bwf: Option<&BwfInfo>,
|
||
mask: Option<u32>,
|
||
frames: u64,
|
||
force_rf64: bool,
|
||
) -> Result<Vec<u8>> {
|
||
let block = usize::from(bits / 8).checked_mul(channels).ok_or_else(|| AudioError::TooLarge("block size overflow".into()))?;
|
||
let block_align = u16::try_from(block).map_err(|_| AudioError::Encode("too many channels for WAV".into()))?;
|
||
let data_len = u64::from(block_align).checked_mul(frames).ok_or_else(|| AudioError::TooLarge("data size overflow".into()))?;
|
||
let extensible = channels > 2 || bits > 16 || mask.is_some_and(|m| m != channel_mask(channels));
|
||
let fmt_tag = if is_float { WAVE_FORMAT_IEEE_FLOAT } else { WAVE_FORMAT_PCM };
|
||
|
||
let mut fmt = Vec::with_capacity(40);
|
||
fmt.extend_from_slice(&(if extensible { WAVE_FORMAT_EXTENSIBLE } else { fmt_tag }).to_le_bytes());
|
||
fmt.extend_from_slice(&(channels as u16).to_le_bytes());
|
||
fmt.extend_from_slice(&sample_rate.to_le_bytes());
|
||
let byte_rate = sample_rate
|
||
.checked_mul(u32::from(block_align))
|
||
.ok_or_else(|| AudioError::Encode("sample rate × block size overflows the WAV byte rate".into()))?;
|
||
fmt.extend_from_slice(&byte_rate.to_le_bytes());
|
||
fmt.extend_from_slice(&block_align.to_le_bytes());
|
||
fmt.extend_from_slice(&bits.to_le_bytes());
|
||
if extensible {
|
||
fmt.extend_from_slice(&22u16.to_le_bytes());
|
||
fmt.extend_from_slice(&bits.to_le_bytes());
|
||
fmt.extend_from_slice(&mask.unwrap_or_else(|| channel_mask(channels)).to_le_bytes());
|
||
fmt.extend_from_slice(&fmt_tag.to_le_bytes());
|
||
fmt.extend_from_slice(&GUID_TAIL);
|
||
}
|
||
|
||
let mut head = Vec::with_capacity(1024);
|
||
let rf64_body_len = 28usize;
|
||
// Reserve room for ds64 (as JUNK when not needed, so a later writer could upgrade in place).
|
||
let mut meta = Vec::new();
|
||
if let Some(bwf) = bwf {
|
||
push_chunk(&mut meta, b"bext", &bext_chunk(bwf));
|
||
}
|
||
push_chunk(&mut meta, b"fmt ", &fmt);
|
||
if is_float {
|
||
push_chunk(&mut meta, b"fact", &u32::try_from(frames).unwrap_or(u32::MAX).to_le_bytes());
|
||
}
|
||
let total = ((4 + (8 + rf64_body_len) + meta.len() + 8) as u64)
|
||
.checked_add(data_len)
|
||
.and_then(|t| t.checked_add(data_len & 1))
|
||
.ok_or_else(|| AudioError::TooLarge("WAV size overflow".into()))?;
|
||
let rf64 = force_rf64 || u32::try_from(total).is_err();
|
||
|
||
if rf64 {
|
||
head.extend_from_slice(b"RF64");
|
||
head.extend_from_slice(&u32::MAX.to_le_bytes());
|
||
head.extend_from_slice(b"WAVE");
|
||
let mut ds64 = Vec::with_capacity(rf64_body_len);
|
||
ds64.extend_from_slice(&total.to_le_bytes());
|
||
ds64.extend_from_slice(&data_len.to_le_bytes());
|
||
ds64.extend_from_slice(&frames.to_le_bytes());
|
||
ds64.extend_from_slice(&0u32.to_le_bytes());
|
||
push_chunk(&mut head, b"ds64", &ds64);
|
||
} else {
|
||
head.extend_from_slice(b"RIFF");
|
||
head.extend_from_slice(&(total as u32).to_le_bytes());
|
||
head.extend_from_slice(b"WAVE");
|
||
push_chunk(&mut head, b"JUNK", &[0u8; 28]);
|
||
}
|
||
head.extend_from_slice(&meta);
|
||
head.extend_from_slice(b"data");
|
||
head.extend_from_slice(&(if rf64 { u32::MAX } else { data_len as u32 }).to_le_bytes());
|
||
Ok(head)
|
||
}
|
||
|
||
/// Where the size fields of a WAV sit, from a walk of its chunks up to `data`.
|
||
struct Layout {
|
||
rf64: bool,
|
||
/// The body of the `ds64` chunk of an RF64 file, or in a RIFF file the body of the 28-byte
|
||
/// `JUNK` or `ds64` chunk right after `WAVE` that can become one.
|
||
ds64: Option<u64>,
|
||
junk: bool,
|
||
fact: Option<u64>,
|
||
block_align: u64,
|
||
data: u64,
|
||
}
|
||
|
||
fn read_at<F: Read + Seek>(file: &mut F, pos: u64, buf: &mut [u8]) -> Result<bool> {
|
||
file.seek(SeekFrom::Start(pos))?;
|
||
match file.read_exact(buf) {
|
||
Ok(()) => Ok(true),
|
||
Err(e) if e.kind() == ErrorKind::UnexpectedEof => Ok(false),
|
||
Err(e) => Err(e.into()),
|
||
}
|
||
}
|
||
|
||
fn write_at<F: Write + Seek>(file: &mut F, pos: u64, bytes: &[u8]) -> Result<()> {
|
||
file.seek(SeekFrom::Start(pos))?;
|
||
file.write_all(bytes)?;
|
||
Ok(())
|
||
}
|
||
|
||
/// The block size of a PCM or float `fmt ` chunk body at `pos` of `size` bytes.
|
||
fn pcm_block_align<F: Read + Seek>(file: &mut F, pos: u64, size: u32) -> Result<u64> {
|
||
let mut fmt = [0u8; 40];
|
||
let n = if size >= 40 { 40 } else { 16 };
|
||
if size < 16 || !read_at(file, pos, &mut fmt[..n])? {
|
||
return Err(AudioError::Malformed("WAV fmt chunk is cut short".into()));
|
||
}
|
||
let field = |at: usize| u16::from_le_bytes([fmt[at], fmt[at + 1]]);
|
||
let mut tag = field(0);
|
||
if tag == WAVE_FORMAT_EXTENSIBLE && n == 40 {
|
||
// The extensible fields the reader checks.
|
||
if field(16) < 22 || field(18) > field(14) {
|
||
return Err(AudioError::Malformed("WAVE_FORMAT_EXTENSIBLE fmt chunk has a cbSize below 22 or too many valid bits".into()));
|
||
}
|
||
if fmt[26..] == GUID_TAIL || fmt[26..] == AMBISONIC_TAIL {
|
||
tag = field(24);
|
||
}
|
||
}
|
||
if tag != WAVE_FORMAT_PCM && tag != WAVE_FORMAT_IEEE_FLOAT {
|
||
return Err(AudioError::Unsupported(format!("repairing a WAV of format tag {tag:#06x}")));
|
||
}
|
||
let (channels, align, bits) = (field(2), field(12), field(14));
|
||
if channels == 0 || bits == 0 || u32::from(align) != u32::from(channels) * u32::from(bits.div_ceil(8)) {
|
||
return Err(AudioError::Malformed(format!("WAV block size {align} does not fit {channels} channels of {bits} bits")));
|
||
}
|
||
// The widths the WAV reader decodes.
|
||
if !matches!((tag, bits), (WAVE_FORMAT_PCM, 1..=32) | (WAVE_FORMAT_IEEE_FLOAT, 32 | 64)) {
|
||
return Err(AudioError::Unsupported(format!("repairing a WAV of format tag {tag:#06x} with {bits} bits per sample")));
|
||
}
|
||
Ok(u64::from(align))
|
||
}
|
||
|
||
fn layout<F: Read + Seek>(file: &mut F, len: u64) -> Result<Layout> {
|
||
let mut riff = [0u8; 12];
|
||
if !read_at(file, 0, &mut riff)? || !(riff.starts_with(b"RIFF") || riff.starts_with(b"RF64")) || &riff[8..] != b"WAVE" {
|
||
return Err(AudioError::Malformed("not a WAV file".into()));
|
||
}
|
||
let rf64 = riff.starts_with(b"RF64");
|
||
let (mut ds64, mut junk, mut fact, mut block_align) = (None, false, None, None);
|
||
let mut pos = 12u64;
|
||
let mut chunk = [0u8; 8];
|
||
// The same bound as the reader's, so a file of tiny chunks can't spin forever.
|
||
for _ in 0..100_000 {
|
||
if pos >= len || !read_at(file, pos, &mut chunk)? {
|
||
break;
|
||
}
|
||
let size = u32::from_le_bytes([chunk[4], chunk[5], chunk[6], chunk[7]]);
|
||
let body = pos + 8;
|
||
match &chunk[..4] {
|
||
b"data" => {
|
||
let block_align = block_align.ok_or_else(|| AudioError::Malformed("WAV data chunk before its fmt chunk".into()))?;
|
||
return Ok(Layout { rf64, ds64, junk, fact, block_align, data: body });
|
||
}
|
||
// The first `ds64` and `fact` chunks take the sizes; later ones are left as they are.
|
||
// The WAV reader takes the data size from the first `ds64` chunk of 16 bytes or more.
|
||
b"ds64" if rf64 && size >= 16 && ds64.is_none() => {
|
||
if size < 28 {
|
||
return Err(AudioError::Malformed("RF64 ds64 chunk is shorter than 28 bytes".into()));
|
||
}
|
||
ds64 = Some(body);
|
||
}
|
||
// A `ds64` id here in a RIFF file is a promotion that stopped before the RF64 id.
|
||
b"JUNK" | b"ds64" if !rf64 && pos == 12 && size == 28 => (ds64, junk) = (Some(body), true),
|
||
b"fact" if size >= 4 && fact.is_none() => fact = Some(body),
|
||
b"fmt " => block_align = Some(pcm_block_align(file, body, size)?),
|
||
_ => {}
|
||
}
|
||
pos = body + u64::from(size) + u64::from(size & 1);
|
||
}
|
||
Err(AudioError::Malformed("WAV has no data chunk".into()))
|
||
}
|
||
|
||
/// The data size the header records: the `ds64` field of an RF64 file, else the data chunk's.
|
||
fn stored_data_len<F: Read + Seek>(file: &mut F, l: &Layout) -> Result<Option<u64>> {
|
||
let mut size = [0u8; 8];
|
||
Ok(match (l.rf64, l.ds64) {
|
||
(true, Some(at)) => read_at(file, at + 8, &mut size)?.then(|| u64::from_le_bytes(size)),
|
||
(true, None) => None,
|
||
(false, _) => read_at(file, l.data - 4, &mut size[..4])?
|
||
.then(|| u32::from_le_bytes([size[0], size[1], size[2], size[3]]))
|
||
.filter(|&s| s != u32::MAX)
|
||
.map(u64::from),
|
||
})
|
||
}
|
||
|
||
/// Rewrites the size fields of a WAV that ends in its data chunk for the whole frames it holds.
|
||
/// Returns the frame count and the length the file should have; bytes past it are a partial frame.
|
||
pub(crate) fn repair<F: Read + Write + Seek>(file: &mut F) -> Result<(u64, u64)> {
|
||
let len = file.seek(SeekFrom::End(0))?;
|
||
let l = layout(file, len)?;
|
||
let held = len.saturating_sub(l.data);
|
||
// A finished file's own size, which also tells its pad byte from a frame of one byte.
|
||
let stored = stored_data_len(file, &l)?.filter(|&s| s % l.block_align == 0 && s.checked_add(s & 1) == Some(held));
|
||
if stored.is_none() && l.block_align == 1 && held > 0 && held % 2 == 0 {
|
||
// The last byte may be a sample or the pad byte after an odd count of them.
|
||
return Err(AudioError::Unsupported("repairing 8-bit mono WAV data of even length: a pad byte reads as a sample".into()));
|
||
}
|
||
let frames = stored.unwrap_or(held) / l.block_align;
|
||
let data_len = frames * l.block_align;
|
||
let pad = data_len & 1;
|
||
let new_len = l.data + data_len + pad;
|
||
let riff_len = new_len - 8;
|
||
let rf64 = l.rf64 || u32::try_from(riff_len).is_err();
|
||
let ds64 = match (rf64, l.ds64) {
|
||
(false, _) => None,
|
||
(true, Some(at)) if l.rf64 || l.junk => Some(at),
|
||
(true, _) if l.rf64 => return Err(AudioError::Malformed("RF64 file has no ds64 chunk".into())),
|
||
(true, _) => return Err(AudioError::TooLarge("WAV past 4 GiB has no room for a ds64 chunk".into())),
|
||
};
|
||
if let Some(at) = l.fact {
|
||
write_at(file, at, &u32::try_from(frames).unwrap_or(u32::MAX).to_le_bytes())?;
|
||
}
|
||
match ds64 {
|
||
Some(at) => {
|
||
let mut body = Vec::with_capacity(28);
|
||
body.extend_from_slice(&riff_len.to_le_bytes());
|
||
body.extend_from_slice(&data_len.to_le_bytes());
|
||
body.extend_from_slice(&frames.to_le_bytes());
|
||
if !l.rf64 {
|
||
// The `JUNK` chunk's last 4 bytes become the table length: no table entries.
|
||
body.extend_from_slice(&0u32.to_le_bytes());
|
||
}
|
||
write_at(file, at, &body)?;
|
||
if !l.rf64 {
|
||
write_at(file, at - 8, b"ds64")?;
|
||
write_at(file, 0, b"RF64")?;
|
||
}
|
||
write_at(file, l.data - 4, &u32::MAX.to_le_bytes())?;
|
||
write_at(file, 4, &u32::MAX.to_le_bytes())?;
|
||
}
|
||
None => {
|
||
write_at(file, l.data - 4, &(data_len as u32).to_le_bytes())?;
|
||
write_at(file, 4, &(riff_len as u32).to_le_bytes())?;
|
||
}
|
||
}
|
||
// The pad byte goes last: until it is written, 8-bit mono data keeps an odd length that a
|
||
// repeated repair can count.
|
||
if pad == 1 {
|
||
write_at(file, l.data + data_len, &[0])?;
|
||
}
|
||
file.seek(SeekFrom::Start(new_len))?;
|
||
file.flush()?;
|
||
Ok((frames, new_len))
|
||
}
|