Cotton code
111 lines · 4.2 KB · RustRaw
//! Voice recording duration, read from the original Ogg/Opus stream.//! The serving Mac's engine job makes AAC m4a playback; the source remains untouched.pub const VOICE_RENDITION_CONTENT_TYPE: &str = "audio/mp4";pub const VOICE_RENDITION_EXT: &str = "m4a";const OPUS_RATE: u32 = 48_000;pub fn is_ogg_opus(content_type: &str) -> bool {    matches!(content_type.split(';').next().unwrap_or("").trim().to_ascii_lowercase().as_str(), "audio/ogg" | "audio/opus")}pub fn ogg_opus_duration_ms(ogg: &[u8]) -> Result<i64, String> {    let stream = read_ogg(ogg)?;    let mut packets = stream.packets.into_iter();    let head = packets.next().ok_or("the recording has no Opus header")?;    if head.len() < 19 || &head[..8] != b"OpusHead" {        return Err("the recording is not Opus".into());    }    let pre_skip = i64::from(u16::from_le_bytes([head[10], head[11]]));    if head[18] != 0 || !(1..=2).contains(&head[9]) {        return Err("the recording has more than two channels".into());    }    match packets.next() {        Some(tags) if tags.starts_with(b"OpusTags") => {}        _ => return Err("the recording has no Opus tags".into()),    }    let mut total = 0i64;    for packet in packets {        total += i64::from(opus_samples(&packet).ok_or("the recording holds a damaged Opus packet")?);    }    if total == 0 { return Err("the recording holds no sound".into()); }    let end = stream.last_granule.filter(|end| *end > 0 && *end <= total).unwrap_or(total);    Ok((end - pre_skip).max(0) * 1000 / i64::from(OPUS_RATE))}struct OggStream {    packets: Vec<Vec<u8>>,    last_granule: Option<i64>,}/// The packets of the FIRST logical stream in the file, in order.fn read_ogg(bytes: &[u8]) -> Result<OggStream, String> {    let mut at = 0usize;    let mut serial: Option<u32> = None;    let mut packets = Vec::new();    let mut partial: Vec<u8> = Vec::new();    let mut last_granule = None;    while at < bytes.len() {        if !bytes[at..].starts_with(b"OggS") {            return Err("the recording is not an Ogg file".into());        }        let header = bytes.get(at..at + 27).ok_or("the recording ends inside an Ogg page")?;        if &header[..4] != b"OggS" || header[4] != 0 {            return Err("the recording is not an Ogg file".into());        }        let granule = i64::from_le_bytes(header[6..14].try_into().expect("8 bytes"));        let page_serial = u32::from_le_bytes(header[14..18].try_into().expect("4 bytes"));        let segments = usize::from(header[26]);        let lacing = bytes            .get(at + 27..at + 27 + segments)            .ok_or("the recording ends inside an Ogg page")?;        let body_len: usize = lacing.iter().map(|value| usize::from(*value)).sum();        let body_at = at + 27 + segments;        let body = bytes            .get(body_at..body_at + body_len)            .ok_or("the recording ends inside an Ogg page")?;        at = body_at + body_len;        if *serial.get_or_insert(page_serial) != page_serial {            continue;        }        if granule != -1 {            last_granule = Some(granule);        }        let mut offset = 0usize;        for value in lacing {            let len = usize::from(*value);            partial.extend_from_slice(&body[offset..offset + len]);            offset += len;            if len < 255 {                packets.push(std::mem::take(&mut partial));            }        }    }    if packets.is_empty() {        return Err("the recording is empty".into());    }    Ok(OggStream { packets, last_granule })}/// Samples (at 48 kHz) one Opus packet decodes to, from its TOC byte (RFC 6716 §3.1).fn opus_samples(packet: &[u8]) -> Option<u32> {    let toc = *packet.first()?;    let config = toc >> 3;    let frame = match config {        0..=11 => [480, 960, 1920, 2880][usize::from(config % 4)],        12..=15 => [480, 960][usize::from(config % 2)],        _ => [120, 240, 480, 960][usize::from(config % 4)],    };    let count = match toc & 3 {        0 => 1,        1 | 2 => 2,        _ => u32::from(*packet.get(1)? & 0x3f),    };    let samples = frame * count;    // A packet longer than 120 ms is malformed.    (count > 0 && samples <= 5760).then_some(samples)}#[cfg(test)]#[path = "voice_rendition_tests.rs"]mod tests;