weirdnet-media 0.2.0

Weirdnet media processing for clients and nodes: WAV probing and PCM in pure Rust, 16 kHz resampling, silence-aware chunking, long-audio transcription plans, long-text speech plans, SRT/VTT, video frame planning, and a hardened ffmpeg runner with a test fake.
Documentation
//! Audio through the hardened runner: normalization to 16 kHz mono WAV (WAV in Rust, anything
//! else through ffmpeg), soundtrack extraction from audio or video files, and encoding.

use serde::{Deserialize, Serialize};

use crate::error::{MediaError, Result};
use crate::ffmpeg::{Exec, Input, Job};
use crate::pcm::{Pcm, TRANSCRIBE_RATE, decode_wav, encode_wav, wav_bytes};
use crate::probe::looks_like_wav;

/// An output audio format.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
#[non_exhaustive]
pub enum AudioFormat {
    Wav,
    Mp3,
    /// Opus in an Ogg container (needs an ffmpeg with libopus).
    Opus,
    Flac,
}

impl AudioFormat {
    /// The MIME type.
    pub fn mime(self) -> &'static str {
        match self {
            AudioFormat::Wav => "audio/wav",
            AudioFormat::Mp3 => "audio/mpeg",
            AudioFormat::Opus => "audio/ogg",
            AudioFormat::Flac => "audio/flac",
        }
    }

    /// The file extension.
    pub fn extension(self) -> &'static str {
        match self {
            AudioFormat::Wav => "wav",
            AudioFormat::Mp3 => "mp3",
            AudioFormat::Opus => "opus",
            AudioFormat::Flac => "flac",
        }
    }

    /// The format for an extension or name (`wav`, `mp3`, `opus`/`ogg`, `flac`).
    pub fn from_name(name: &str) -> Option<AudioFormat> {
        match name.to_ascii_lowercase().as_str() {
            "wav" | "wave" => Some(AudioFormat::Wav),
            "mp3" | "mpeg" => Some(AudioFormat::Mp3),
            "opus" | "ogg" => Some(AudioFormat::Opus),
            "flac" => Some(AudioFormat::Flac),
            _ => None,
        }
    }
}

fn secs(ms: u64) -> String {
    format!("{}.{:03}", ms / 1000, ms % 1000)
}

/// What to take from a soundtrack.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Extract {
    /// Where to start; `None` for the beginning.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub start_ms: Option<u64>,
    /// How much; `None` for the rest.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub len_ms: Option<u64>,
    pub sample_rate: u32,
    pub channels: u16,
    /// The longest output, which bounds what is read (the clip's length when known).
    pub max_len_ms: u64,
}

impl Extract {
    /// 16 kHz mono, for a transcriber, at most `max_len_ms`.
    pub fn transcribe(max_len_ms: u64) -> Self {
        Extract { start_ms: None, len_ms: None, sample_rate: TRANSCRIBE_RATE, channels: 1, max_len_ms }
    }

    /// `rate` Hz with `channels` channels, at most `max_len_ms`.
    pub fn new(sample_rate: u32, channels: u16, max_len_ms: u64) -> Self {
        Extract { start_ms: None, len_ms: None, sample_rate, channels, max_len_ms }
    }

    /// Only `[start_ms, start_ms + len_ms)`.
    pub fn range(mut self, start_ms: u64, len_ms: u64) -> Self {
        self.start_ms = Some(start_ms);
        self.len_ms = Some(len_ms);
        self
    }
}

/// The first audio stream of `input` (audio or video) as a 16-bit WAV (`-vn -map 0:a:0`, metadata
/// dropped), as `what` says. The output is bounded by `what.max_len_ms`.
pub fn extract(exec: &dyn Exec, input: &Input, what: &Extract) -> Result<Vec<u8>> {
    let mut job = Job::ffmpeg(input.clone());
    if let Some(s) = what.start_ms.filter(|s| *s > 0) {
        job = job.before_input(["-ss".to_string(), secs(s)]);
    }
    if let Some(l) = what.len_ms {
        job = job.before_input(["-t".to_string(), secs(l)]);
    }
    let bound = what.len_ms.unwrap_or(what.max_len_ms).min(what.max_len_ms);
    let job = job
        .args(["-vn", "-sn", "-dn", "-map", "0:a:0", "-map_metadata", "-1", "-c:a", "pcm_s16le"])
        .args(["-ac".to_string(), what.channels.max(1).to_string(), "-ar".to_string(), what.sample_rate.to_string()])
        .args(["-f", "wav", "pipe:1"])
        .max_output(wav_bytes(what.sample_rate, what.channels.max(1), bound) + 4096);
    exec.exec(&job)
}

/// `input` as 16 kHz mono 16-bit PCM for a transcriber: a WAV is decoded and resampled in Rust; any
/// other container is decoded by ffmpeg. `max_len_ms` bounds what is read.
pub fn normalize_pcm(exec: &dyn Exec, input: &Input, max_len_ms: u64) -> Result<Pcm> {
    if looks_like_wav(&input.head(12)?) {
        let bytes = input.read_all(wav_bytes(192_000, 8, max_len_ms).saturating_mul(4))?;
        let pcm = decode_wav(&bytes)?;
        if pcm.duration_ms() > max_len_ms {
            return Err(MediaError::limit(format!("the audio is {} ms, over the {max_len_ms} ms limit", pcm.duration_ms())));
        }
        return Ok(pcm.to_transcribe());
    }
    let wav = extract(exec, input, &Extract::transcribe(max_len_ms))?;
    decode_wav(&wav)
}

/// [`normalize_pcm`] as WAV bytes.
pub fn normalize(exec: &dyn Exec, input: &Input, max_len_ms: u64) -> Result<Vec<u8>> {
    Ok(encode_wav(&normalize_pcm(exec, input, max_len_ms)?))
}

/// `pcm` encoded as `format`: WAV in Rust; MP3, Opus and FLAC through ffmpeg (fed WAV on
/// `pipe:0`). `max_bytes` bounds the output.
pub fn encode(exec: &dyn Exec, pcm: &Pcm, format: AudioFormat, max_bytes: u64) -> Result<Vec<u8>> {
    let wav = encode_wav(pcm);
    let (codec, muxer): (&[&str], &str) = match format {
        AudioFormat::Wav => {
            if wav.len() as u64 > max_bytes {
                return Err(MediaError::limit(format!("the WAV is {} bytes, over the {max_bytes}-byte bound", wav.len())));
            }
            return Ok(wav);
        }
        AudioFormat::Mp3 => (&["-c:a", "libmp3lame", "-q:a", "4"], "mp3"),
        AudioFormat::Opus => (&["-c:a", "libopus", "-b:a", "48k"], "ogg"),
        AudioFormat::Flac => (&["-c:a", "flac"], "flac"),
    };
    let job = Job::ffmpeg(Input::bytes(wav))
        .before_input(["-f", "wav"])
        .args(["-vn", "-map_metadata", "-1"])
        .args(codec.iter().copied())
        .args(["-f", muxer, "pipe:1"])
        .max_output(max_bytes);
    exec.exec(&job)
}