SPB Git

Repository Public

file.rs 24.4 KB 595 lines rust

1//! ORIX Sonata2//! File: crates/sonata-render/src/file.rs3//! Description: Audio files: WAV, AIFF/AIFC and FLAC writers with atomic replacement and4//! explicit overwrite, PCM conversion with optional TPDF dither, and strict readers.5//!6//! Author: Simon-Pierre Boucher7//! Contact: contact@spboucher.ai89use crate::flac;10use std::io::Write;11use std::path::{Path, PathBuf};1213/// Audio in memory: one `Vec<f32>` per channel, equal lengths, 1.0 = full scale.14#[derive(Clone, Debug, PartialEq)]15pub struct AudioData {16    pub sample_rate: u32,17    pub channels: Vec<Vec<f32>>,18}1920impl AudioData {21    pub fn stereo(sample_rate: u32, left: Vec<f32>, right: Vec<f32>) -> AudioData {22        AudioData { sample_rate, channels: vec![left, right] }23    }24    pub fn frames(&self) -> usize {25        self.channels.first().map(|c| c.len()).unwrap_or(0)26    }27    pub fn duration_sec(&self) -> f64 {28        self.frames() as f64 / self.sample_rate.max(1) as f6429    }30    fn validate(&self) -> Result<(), String> {31        if self.channels.is_empty() || self.channels.len() > 8 {32            return Err("audio must have 1 to 8 channels".into());33        }34        if self.channels.iter().any(|c| c.len() != self.channels[0].len()) {35            return Err("channels have different lengths".into());36        }37        if !(1..=768_000).contains(&self.sample_rate) {38            return Err(format!("invalid sample rate {}", self.sample_rate));39        }40        Ok(())41    }42}4344#[derive(Clone, Copy, Debug, PartialEq, Eq)]45pub enum FileFormat {46    Wav,47    /// AIFF for integer PCM, AIFF-C (`fl32` / `fl64`) for float.48    Aiff,49    Flac,50}5152impl FileFormat {53    pub fn from_extension(path: &Path) -> Option<FileFormat> {54        match path.extension()?.to_str()?.to_ascii_lowercase().as_str() {55            "wav" | "wave" => Some(FileFormat::Wav),56            "aif" | "aiff" | "aifc" => Some(FileFormat::Aiff),57            "flac" => Some(FileFormat::Flac),58            _ => None,59        }60    }61}6263#[derive(Clone, Copy, Debug, PartialEq, Eq)]64pub enum SampleFormat {65    Pcm16,66    Pcm24,67    Pcm32,68    Float32,69    Float64,70}7172impl SampleFormat {73    pub fn bits(self) -> u32 {74        match self {75            SampleFormat::Pcm16 => 16,76            SampleFormat::Pcm24 => 24,77            SampleFormat::Pcm32 | SampleFormat::Float32 => 32,78            SampleFormat::Float64 => 64,79        }80    }81    pub fn is_float(self) -> bool {82        matches!(self, SampleFormat::Float32 | SampleFormat::Float64)83    }84}8586#[derive(Clone, Copy, Debug, PartialEq, Eq)]87pub enum Dither {88    None,89    /// Triangular probability density, 2 LSB peak to peak, white. Applied only when converting90    /// to integer PCM; ignored for float formats.91    Tpdf,92}9394#[derive(Clone, Copy, Debug, PartialEq, Eq)]95pub struct FileSpec {96    pub format: FileFormat,97    pub samples: SampleFormat,98    pub dither: Dither,99    /// Replace an existing file. Without it, writing over an existing path is an error.100    pub overwrite: bool,101    /// Seed of the dither noise (same seed, same file).102    pub dither_seed: u64,103}104105impl FileSpec {106    pub fn new(format: FileFormat, samples: SampleFormat) -> FileSpec {107        FileSpec { format, samples, dither: Dither::None, overwrite: false, dither_seed: 0x5EED }108    }109}110111#[derive(Clone, Copy, Debug, PartialEq, Eq)]112pub struct WriteReport {113    pub bytes: u64,114    pub frames: u64,115    /// Samples beyond full scale that were clipped by the conversion to integer PCM.116    pub clipped_samples: u64,117    /// Non-finite samples written as silence.118    pub non_finite_samples: u64,119}120121/// Converts to integer PCM of `bits` bits: scale by 2^(bits-1), add dither, round to nearest122/// (ties away from zero), clamp to the representable range.123pub fn to_pcm(audio: &AudioData, bits: u32, dither: Dither, seed: u64) -> (Vec<Vec<i32>>, u64, u64) {124    let scale = (1u64 << (bits - 1)) as f64;125    let (lo, hi) = (-scale, scale - 1.0);126    let (mut clipped, mut bad) = (0u64, 0u64);127    let mut out = Vec::with_capacity(audio.channels.len());128    for (c, ch) in audio.channels.iter().enumerate() {129        let mut s = seed ^ (c as u64 + 1).wrapping_mul(0x9E37_79B9_7F4A_7C15);130        let mut uniform = move || {131            // SplitMix64, mapped to [-0.5, 0.5).132            s = s.wrapping_add(0x9E37_79B9_7F4A_7C15);133            let mut z = s;134            z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);135            z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);136            ((z ^ (z >> 31)) >> 11) as f64 / (1u64 << 53) as f64 - 0.5137        };138        out.push(139            ch.iter()140                .map(|&x| {141                    if !x.is_finite() {142                        bad += 1;143                        return 0;144                    }145                    let mut v = x as f64 * scale;146                    if dither == Dither::Tpdf {147                        v += uniform() + uniform();148                    }149                    let r = v.round();150                    if r < lo || r > hi {151                        clipped += 1;152                    }153                    r.clamp(lo, hi) as i32154                })155                .collect(),156        );157    }158    (out, clipped, bad)159}160161fn extended_80(rate: f64) -> [u8; 10] {162    let mut out = [0u8; 10];163    if rate <= 0.0 {164        return out;165    }166    let exp = rate.log2().floor() as i32;167    let mant = (rate / 2f64.powi(exp) * (1u64 << 63) as f64) as u64;168    out[..2].copy_from_slice(&((exp + 16_383) as u16).to_be_bytes());169    out[2..].copy_from_slice(&mant.to_be_bytes());170    out171}172173fn from_extended_80(b: &[u8]) -> f64 {174    let exp = (u16::from_be_bytes([b[0], b[1]]) & 0x7fff) as i32 - 16_383;175    let mant = u64::from_be_bytes([b[2], b[3], b[4], b[5], b[6], b[7], b[8], b[9]]);176    mant as f64 / (1u64 << 63) as f64 * 2f64.powi(exp)177}178179fn interleave(audio: &AudioData, spec: &FileSpec, big_endian: bool) -> (Vec<u8>, u64, u64) {180    let frames = audio.frames();181    let nch = audio.channels.len();182    let bytes = (spec.samples.bits() / 8) as usize;183    let mut data = Vec::with_capacity(frames * nch * bytes);184    let (mut clipped, mut bad) = (0, 0);185    if spec.samples.is_float() {186        for i in 0..frames {187            for ch in &audio.channels {188                let x = if ch[i].is_finite() {189                    ch[i]190                } else {191                    bad += 1;192                    0.0193                };194                match (spec.samples, big_endian) {195                    (SampleFormat::Float32, false) => data.extend_from_slice(&x.to_le_bytes()),196                    (SampleFormat::Float32, true) => data.extend_from_slice(&x.to_be_bytes()),197                    (_, false) => data.extend_from_slice(&(x as f64).to_le_bytes()),198                    (_, true) => data.extend_from_slice(&(x as f64).to_be_bytes()),199                }200            }201        }202    } else {203        let (pcm, c, b) = to_pcm(audio, spec.samples.bits(), spec.dither, spec.dither_seed);204        clipped = c;205        bad = b;206        for i in 0..frames {207            for ch in &pcm {208                let le = ch[i].to_le_bytes();209                if big_endian {210                    for k in (0..bytes).rev() {211                        data.push(le[k]);212                    }213                } else {214                    data.extend_from_slice(&le[..bytes]);215                }216            }217        }218    }219    (data, clipped, bad)220}221222fn encode_wav(audio: &AudioData, spec: &FileSpec) -> Result<(Vec<u8>, u64, u64), String> {223    let (data, clipped, bad) = interleave(audio, spec, false);224    let nch = audio.channels.len() as u16;225    let bits = spec.samples.bits() as u16;226    let block = nch * bits / 8;227    // Plain PCM header for 16-bit mono/stereo; WAVE_FORMAT_EXTENSIBLE for wider integers and228    // more than two channels; IEEE float (tag 3) with a fact chunk for float.229    let extensible = !spec.samples.is_float() && (bits > 16 || nch > 2);230    let mut fmt = Vec::new();231    let tag: u16 = if extensible {232        0xFFFE233    } else if spec.samples.is_float() {234        3235    } else {236        1237    };238    fmt.extend_from_slice(&tag.to_le_bytes());239    fmt.extend_from_slice(&nch.to_le_bytes());240    fmt.extend_from_slice(&audio.sample_rate.to_le_bytes());241    fmt.extend_from_slice(&(audio.sample_rate * block as u32).to_le_bytes());242    fmt.extend_from_slice(&block.to_le_bytes());243    fmt.extend_from_slice(&bits.to_le_bytes());244    if extensible {245        fmt.extend_from_slice(&22u16.to_le_bytes());246        fmt.extend_from_slice(&bits.to_le_bytes());247        let mask: u32 = match nch {248            1 => 0x4,249            2 => 0x3,250            _ => 0,251        };252        fmt.extend_from_slice(&mask.to_le_bytes());253        fmt.extend_from_slice(&[1, 0, 0, 0, 0, 0, 0x10, 0, 0x80, 0, 0, 0xAA, 0, 0x38, 0x9B, 0x71]);254    } else if spec.samples.is_float() {255        fmt.extend_from_slice(&0u16.to_le_bytes());256    }257    let fact = spec.samples.is_float();258    let total = 4 + 8 + fmt.len() + if fact { 12 } else { 0 } + 8 + data.len() + (data.len() & 1);259    if total > u32::MAX as usize {260        return Err("audio is too long for a WAV file (4 GiB limit); render a shorter range or use FLAC".into());261    }262    let mut out = Vec::with_capacity(total + 8);263    out.extend_from_slice(b"RIFF");264    out.extend_from_slice(&(total as u32).to_le_bytes());265    out.extend_from_slice(b"WAVEfmt ");266    out.extend_from_slice(&(fmt.len() as u32).to_le_bytes());267    out.extend_from_slice(&fmt);268    if fact {269        out.extend_from_slice(b"fact");270        out.extend_from_slice(&4u32.to_le_bytes());271        out.extend_from_slice(&(audio.frames() as u32).to_le_bytes());272    }273    out.extend_from_slice(b"data");274    out.extend_from_slice(&(data.len() as u32).to_le_bytes());275    out.extend_from_slice(&data);276    if data.len() & 1 == 1 {277        out.push(0);278    }279    Ok((out, clipped, bad))280}281282fn encode_aiff(audio: &AudioData, spec: &FileSpec) -> Result<(Vec<u8>, u64, u64), String> {283    let (data, clipped, bad) = interleave(audio, spec, true);284    let float = spec.samples.is_float();285    let mut comm = Vec::new();286    comm.extend_from_slice(&(audio.channels.len() as u16).to_be_bytes());287    comm.extend_from_slice(&(audio.frames() as u32).to_be_bytes());288    comm.extend_from_slice(&(spec.samples.bits() as u16).to_be_bytes());289    comm.extend_from_slice(&extended_80(audio.sample_rate as f64));290    if float {291        comm.extend_from_slice(if spec.samples == SampleFormat::Float32 { b"fl32" } else { b"fl64" });292        // Pascal string: length byte, text, padded to an even total.293        comm.extend_from_slice(&[0, 0]);294    }295    let total = 4 + if float { 12 } else { 0 } + 8 + comm.len() + 8 + 8 + data.len() + (data.len() & 1);296    if total > u32::MAX as usize || audio.frames() > u32::MAX as usize {297        return Err("audio is too long for an AIFF file (4 GiB limit)".into());298    }299    let mut out = Vec::with_capacity(total + 8);300    out.extend_from_slice(b"FORM");301    out.extend_from_slice(&(total as u32).to_be_bytes());302    out.extend_from_slice(if float { b"AIFC" } else { b"AIFF" });303    if float {304        out.extend_from_slice(b"FVER");305        out.extend_from_slice(&4u32.to_be_bytes());306        out.extend_from_slice(&0xA280_5140u32.to_be_bytes());307    }308    out.extend_from_slice(b"COMM");309    out.extend_from_slice(&(comm.len() as u32).to_be_bytes());310    out.extend_from_slice(&comm);311    out.extend_from_slice(b"SSND");312    out.extend_from_slice(&(data.len() as u32 + 8).to_be_bytes());313    out.extend_from_slice(&[0; 8]);314    out.extend_from_slice(&data);315    if data.len() & 1 == 1 {316        out.push(0);317    }318    Ok((out, clipped, bad))319}320321/// Encodes `audio` to the bytes of a file.322pub fn encode_audio(audio: &AudioData, spec: &FileSpec) -> Result<(Vec<u8>, WriteReport), String> {323    audio.validate()?;324    let (bytes, clipped, bad) = match spec.format {325        FileFormat::Wav => encode_wav(audio, spec)?,326        FileFormat::Aiff => encode_aiff(audio, spec)?,327        FileFormat::Flac => {328            let bits = match spec.samples {329                SampleFormat::Pcm16 => 16,330                SampleFormat::Pcm24 => 24,331                _ => return Err("FLAC export supports 16-bit and 24-bit PCM".into()),332            };333            let (pcm, clipped, bad) = to_pcm(audio, bits, spec.dither, spec.dither_seed);334            (flac::encode(&pcm, audio.sample_rate, bits)?, clipped, bad)335        }336    };337    let report = WriteReport { bytes: bytes.len() as u64, frames: audio.frames() as u64, clipped_samples: clipped, non_finite_samples: bad };338    Ok((bytes, report))339}340341/// Writes `bytes` to `path` atomically: the data goes to a temporary file in the same directory,342/// is flushed to disk, then renamed over the destination. An existing destination is an error343/// unless `overwrite`. On failure the temporary file is removed and the destination is untouched.344pub fn write_atomic(path: &Path, bytes: &[u8], overwrite: bool) -> Result<(), String> {345    if path.exists() {346        if !overwrite {347            return Err(format!("{} already exists (pass the overwrite option to replace it)", path.display()));348        }349        if path.is_dir() {350            return Err(format!("{} is a directory", path.display()));351        }352    }353    let dir = path.parent().filter(|p| !p.as_os_str().is_empty()).map(PathBuf::from).unwrap_or_else(|| PathBuf::from("."));354    let name = path.file_name().ok_or_else(|| format!("{} has no file name", path.display()))?.to_string_lossy().to_string();355    let tmp = dir.join(format!(".{name}.{}.{:x}.tmp", std::process::id(), bytes.len() as u64 ^ (bytes.as_ptr() as u64)));356    let result = (|| -> std::io::Result<()> {357        let mut f = std::fs::OpenOptions::new().write(true).create_new(true).open(&tmp)?;358        f.write_all(bytes)?;359        f.sync_all()?;360        if !overwrite {361            // Refuse to replace a file that appeared meanwhile: hard-link fails if the name exists.362            std::fs::hard_link(&tmp, path)?;363            std::fs::remove_file(&tmp)?;364        } else {365            std::fs::rename(&tmp, path)?;366        }367        Ok(())368    })();369    if let Err(e) = result {370        let _ = std::fs::remove_file(&tmp);371        return Err(format!("cannot write {}: {e}", path.display()));372    }373    Ok(())374}375376/// Encodes and writes an audio file atomically.377pub fn write_audio_file(path: &Path, audio: &AudioData, spec: &FileSpec) -> Result<WriteReport, String> {378    if path.exists() && !spec.overwrite {379        return Err(format!("{} already exists (pass the overwrite option to replace it)", path.display()));380    }381    let (bytes, report) = encode_audio(audio, spec)?;382    write_atomic(path, &bytes, spec.overwrite)?;383    Ok(report)384}385386/// Bounds applied when reading a file someone else produced.387#[derive(Clone, Copy, Debug, PartialEq, Eq)]388pub struct ReadLimits {389    pub max_file_bytes: u64,390    pub max_frames: u64,391    pub max_channels: usize,392}393394impl Default for ReadLimits {395    fn default() -> Self {396        ReadLimits { max_file_bytes: 2 << 30, max_frames: 192_000 * 3600 * 2, max_channels: 8 }397    }398}399400/// What a file contained, alongside the decoded audio.401#[derive(Clone, Debug, PartialEq)]402pub struct ReadInfo {403    pub format: FileFormat,404    pub bits: u32,405    pub float: bool,406}407408fn pcm_to_f32(bytes: &[u8], bits: u32, big_endian: bool, unsigned8: bool) -> f32 {409    let n = (bits / 8) as usize;410    let mut le = [0u8; 4];411    for k in 0..n {412        le[4 - n + k] = if big_endian { bytes[n - 1 - k] } else { bytes[k] };413    }414    if unsigned8 {415        return (bytes[0] as f32 - 128.0) / 128.0;416    }417    // The value sits in the top bytes: an arithmetic interpretation of the 32-bit word scales it.418    i32::from_le_bytes(le) as f32 / 2_147_483_648.0419}420421fn deinterleave(data: &[u8], nch: usize, bits: u32, float: bool, big_endian: bool, unsigned8: bool, limits: &ReadLimits) -> Result<Vec<Vec<f32>>, String> {422    let bytes = (bits / 8) as usize;423    let frame = bytes * nch;424    let frames = data.len() / frame;425    if frames as u64 > limits.max_frames {426        return Err(format!("file holds {frames} frames, more than the limit of {}", limits.max_frames));427    }428    let mut ch: Vec<Vec<f32>> = (0..nch).map(|_| Vec::with_capacity(frames)).collect();429    for f in 0..frames {430        for (c, out) in ch.iter_mut().enumerate() {431            let b = &data[f * frame + c * bytes..f * frame + (c + 1) * bytes];432            let v = if float {433                match (bits, big_endian) {434                    (32, false) => f32::from_le_bytes([b[0], b[1], b[2], b[3]]),435                    (32, true) => f32::from_be_bytes([b[0], b[1], b[2], b[3]]),436                    (_, false) => f64::from_le_bytes([b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7]]) as f32,437                    (_, true) => f64::from_be_bytes([b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7]]) as f32,438                }439            } else {440                pcm_to_f32(b, bits, big_endian, unsigned8)441            };442            // A file may carry anything: non-finite samples become silence.443            out.push(if v.is_finite() { v } else { 0.0 });444        }445    }446    Ok(ch)447}448449fn check_format(nch: usize, rate: u32, bits: u32, float: bool, limits: &ReadLimits) -> Result<(), String> {450    if nch == 0 || nch > limits.max_channels {451        return Err(format!("unsupported channel count {nch}"));452    }453    if !(1000..=768_000).contains(&rate) {454        return Err(format!("unsupported sample rate {rate} Hz"));455    }456    let ok = if float { bits == 32 || bits == 64 } else { matches!(bits, 8 | 16 | 24 | 32) };457    if !ok {458        return Err(format!("unsupported sample size: {bits}-bit {}", if float { "float" } else { "PCM" }));459    }460    Ok(())461}462463fn decode_wav(d: &[u8], limits: &ReadLimits) -> Result<(AudioData, ReadInfo), String> {464    let mut pos = 12;465    let mut fmt: Option<(usize, u32, u32, bool)> = None;466    while pos + 8 <= d.len() {467        let id = &d[pos..pos + 4];468        let len = u32::from_le_bytes([d[pos + 4], d[pos + 5], d[pos + 6], d[pos + 7]]) as usize;469        let body_start = pos + 8;470        if id == b"fmt " {471            let b = d.get(body_start..body_start + len).filter(|b| b.len() >= 16).ok_or("truncated WAV fmt chunk")?;472            let mut tag = u16::from_le_bytes([b[0], b[1]]);473            let nch = u16::from_le_bytes([b[2], b[3]]) as usize;474            let rate = u32::from_le_bytes([b[4], b[5], b[6], b[7]]);475            let block = u16::from_le_bytes([b[12], b[13]]) as usize;476            let bits = u16::from_le_bytes([b[14], b[15]]) as u32;477            if tag == 0xFFFE {478                let sub = b.get(24..26).ok_or("truncated WAVE_FORMAT_EXTENSIBLE header")?;479                tag = u16::from_le_bytes([sub[0], sub[1]]);480            }481            let float = match tag {482                1 => false,483                3 => true,484                t => return Err(format!("unsupported WAV encoding (format tag {t}); only PCM and IEEE float are read")),485            };486            check_format(nch, rate, bits, float, limits)?;487            if block != nch * (bits as usize / 8) {488                return Err("inconsistent WAV block alignment".into());489            }490            fmt = Some((nch, rate, bits, float));491        } else if id == b"data" {492            let (nch, rate, bits, float) = fmt.ok_or("WAV data chunk precedes the fmt chunk")?;493            // Streamed files may announce 0 or 0xFFFFFFFF: read what is actually there.494            let avail = d.len() - body_start;495            let len = if len == 0 || len > avail { avail } else { len };496            let frame = nch * bits as usize / 8;497            let data = &d[body_start..body_start + len - len % frame];498            let channels = deinterleave(data, nch, bits, float, false, bits == 8, limits)?;499            return Ok((AudioData { sample_rate: rate, channels }, ReadInfo { format: FileFormat::Wav, bits, float }));500        }501        pos = body_start.checked_add(len + (len & 1)).ok_or("corrupt WAV chunk size")?;502    }503    Err("WAV file has no data chunk".into())504}505506fn decode_aiff(d: &[u8], limits: &ReadLimits) -> Result<(AudioData, ReadInfo), String> {507    let aifc = &d[8..12] == b"AIFC";508    let mut pos = 12;509    let mut comm: Option<(usize, u64, u32, u32, bool, bool)> = None;510    let mut ssnd: Option<&[u8]> = None;511    while pos + 8 <= d.len() {512        let id = &d[pos..pos + 4];513        let len = u32::from_be_bytes([d[pos + 4], d[pos + 5], d[pos + 6], d[pos + 7]]) as usize;514        let body = d.get(pos + 8..(pos + 8).saturating_add(len).min(d.len())).ok_or("truncated AIFF chunk")?;515        if id == b"COMM" {516            if body.len() < 18 {517                return Err("truncated AIFF COMM chunk".into());518            }519            let nch = u16::from_be_bytes([body[0], body[1]]) as usize;520            let frames = u32::from_be_bytes([body[2], body[3], body[4], body[5]]) as u64;521            let bits = u16::from_be_bytes([body[6], body[7]]) as u32;522            let rate = from_extended_80(&body[8..18]);523            if !(rate.is_finite() && (1000.0..=768_000.0).contains(&rate)) {524                return Err("unsupported AIFF sample rate".into());525            }526            let (mut float, mut little) = (false, false);527            if aifc {528                match body.get(18..22).ok_or("truncated AIFF-C COMM chunk")? {529                    b"NONE" | b"twos" => {}530                    b"sowt" => little = true,531                    b"fl32" | b"FL32" | b"fl64" | b"FL64" => float = true,532                    other => return Err(format!("unsupported AIFF-C compression '{}'", String::from_utf8_lossy(other))),533                }534            }535            // AIFF stores odd bit depths in whole bytes, left-justified.536            let bits = bits.div_ceil(8) * 8;537            check_format(nch, rate.round() as u32, bits, float, limits)?;538            comm = Some((nch, frames, bits, rate.round() as u32, float, little));539        } else if id == b"SSND" {540            if body.len() < 8 {541                return Err("truncated AIFF SSND chunk".into());542            }543            let offset = u32::from_be_bytes([body[0], body[1], body[2], body[3]]) as usize;544            ssnd = Some(body.get(8 + offset..).ok_or("invalid AIFF sound data offset")?);545        }546        pos = (pos + 8).checked_add(len + (len & 1)).ok_or("corrupt AIFF chunk size")?;547    }548    let (nch, frames, bits, rate, float, little) = comm.ok_or("AIFF file has no COMM chunk")?;549    let data = ssnd.ok_or("AIFF file has no SSND chunk")?;550    let want = frames as usize * nch * bits as usize / 8;551    if data.len() < want {552        return Err("AIFF sound data is shorter than announced".into());553    }554    let channels = deinterleave(&data[..want], nch, bits, float, !little, false, limits)?;555    Ok((AudioData { sample_rate: rate, channels }, ReadInfo { format: FileFormat::Aiff, bits, float }))556}557558/// Decodes the bytes of a WAV, AIFF/AIFF-C or FLAC file. The container is recognised by its559/// signature, not by a file name.560pub fn decode_audio(d: &[u8], limits: &ReadLimits) -> Result<(AudioData, ReadInfo), String> {561    if d.len() as u64 > limits.max_file_bytes {562        return Err(format!("file is {} bytes, more than the limit of {}", d.len(), limits.max_file_bytes));563    }564    if d.len() >= 12 && &d[..4] == b"RIFF" && &d[8..12] == b"WAVE" {565        decode_wav(d, limits)566    } else if d.len() >= 12 && &d[..4] == b"FORM" && (&d[8..12] == b"AIFF" || &d[8..12] == b"AIFC") {567        decode_aiff(d, limits)568    } else if d.len() >= 4 && &d[..4] == b"fLaC" {569        let dec = flac::decode(d, limits.max_frames)?;570        if dec.channels.len() > limits.max_channels {571            return Err(format!("unsupported channel count {}", dec.channels.len()));572        }573        let scale = 1.0 / (1u64 << (dec.bits - 1)) as f32;574        let channels = dec.channels.iter().map(|c| c.iter().map(|v| *v as f32 * scale).collect()).collect();575        Ok((AudioData { sample_rate: dec.sample_rate, channels }, ReadInfo { format: FileFormat::Flac, bits: dec.bits, float: false }))576    } else if d.len() >= 4 && &d[..4] == b"RF64" {577        Err("RF64 files are not supported".into())578    } else {579        Err("unrecognised audio file (expected WAV, AIFF or FLAC)".into())580    }581}582583/// Reads and decodes an audio file, refusing files larger than the limits before reading them.584pub fn read_audio_file(path: &Path, limits: &ReadLimits) -> Result<(AudioData, ReadInfo), String> {585    let meta = std::fs::metadata(path).map_err(|e| format!("cannot read {}: {e}", path.display()))?;586    if !meta.is_file() {587        return Err(format!("{} is not a regular file", path.display()));588    }589    if meta.len() > limits.max_file_bytes {590        return Err(format!("{} is {} bytes, more than the limit of {}", path.display(), meta.len(), limits.max_file_bytes));591    }592    let bytes = std::fs::read(path).map_err(|e| format!("cannot read {}: {e}", path.display()))?;593    decode_audio(&bytes, limits).map_err(|e| format!("{}: {e}", path.display()))594}595
Files main
Menu

Theme