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
//! What a file holds: WAV headers read in pure Rust, anything else through `ffprobe` (hardened, in
//! [`crate::ffmpeg`]).

use std::io::Read as _;
use std::path::Path;

use serde::{Deserialize, Serialize};

use crate::error::{MediaError, Result};
use crate::ffmpeg::{Exec, Input, Job};

/// How a WAV stores its samples.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
#[non_exhaustive]
pub enum SampleFormat {
    /// Signed integers (unsigned for 8-bit), little-endian.
    Int,
    /// IEEE floats, little-endian.
    Float,
}

/// A WAV header.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct WavInfo {
    pub format: SampleFormat,
    pub sample_rate: u32,
    pub channels: u16,
    pub bits_per_sample: u16,
    /// Bytes per frame (all channels).
    pub block_align: u16,
    /// Where the samples start.
    pub data_offset: u64,
    /// How many bytes of samples there are. A streamed WAV (size 0 or `0xFFFFFFFF`, as ffmpeg writes
    /// to a pipe) or a header that claims more than the file holds counts what is there.
    pub data_len: u64,
}

impl WavInfo {
    /// Whole frames in the data.
    pub fn frames(&self) -> u64 {
        self.data_len / u64::from(self.block_align.max(1))
    }

    /// The length, in milliseconds (rounded down).
    pub fn duration_ms(&self) -> u64 {
        if self.sample_rate == 0 {
            return 0;
        }
        (u128::from(self.frames()) * 1000 / u128::from(self.sample_rate)) as u64
    }
}

/// Whether `head` starts like a RIFF/WAVE file.
pub fn looks_like_wav(head: &[u8]) -> bool {
    head.len() >= 12 && &head[0..4] == b"RIFF" && &head[8..12] == b"WAVE"
}

fn u16_at(b: &[u8], at: usize) -> u16 {
    u16::from_le_bytes([b[at], b[at + 1]])
}

fn u32_at(b: &[u8], at: usize) -> u32 {
    u32::from_le_bytes([b[at], b[at + 1], b[at + 2], b[at + 3]])
}

/// Reads the WAV header in `bytes` (the whole file, or at least its header when `total_len` says
/// how long the whole file is).
pub fn wav_header(bytes: &[u8], total_len: Option<u64>) -> Result<WavInfo> {
    let total = total_len.unwrap_or(bytes.len() as u64);
    if !looks_like_wav(bytes) {
        return Err(MediaError::invalid("not a RIFF/WAVE file"));
    }
    let mut at = 12usize;
    let mut fmt: Option<(SampleFormat, u16, u32, u16, u16)> = None;
    while at + 8 <= bytes.len() {
        let id = &bytes[at..at + 4];
        let size = u32_at(bytes, at + 4);
        let body = at + 8;
        if id == b"fmt " {
            if size < 16 || body + 16 > bytes.len() {
                return Err(MediaError::invalid("WAV fmt chunk is too short"));
            }
            let tag = u16_at(bytes, body);
            let channels = u16_at(bytes, body + 2);
            let rate = u32_at(bytes, body + 4);
            let align = u16_at(bytes, body + 12);
            let bits = u16_at(bytes, body + 14);
            let tag = if tag == 0xFFFE {
                // WAVE_FORMAT_EXTENSIBLE: the real tag is the first two bytes of the sub-format GUID.
                if size < 40 || body + 26 > bytes.len() {
                    return Err(MediaError::invalid("WAV extensible fmt chunk is too short"));
                }
                u16_at(bytes, body + 24)
            } else {
                tag
            };
            let format = match tag {
                1 => SampleFormat::Int,
                3 => SampleFormat::Float,
                other => return Err(MediaError::invalid(format!("WAV sample format {other:#06x} is not PCM or float"))),
            };
            let ok_bits = match format {
                SampleFormat::Int => matches!(bits, 8 | 16 | 24 | 32),
                SampleFormat::Float => matches!(bits, 32 | 64),
            };
            if !ok_bits {
                return Err(MediaError::invalid(format!("WAV with {bits}-bit samples is not supported")));
            }
            if channels == 0 || channels > 32 {
                return Err(MediaError::invalid(format!("WAV with {channels} channels")));
            }
            if rate == 0 || rate > 1_536_000 {
                return Err(MediaError::invalid(format!("WAV sample rate {rate}")));
            }
            if u32::from(align) != u32::from(channels) * u32::from(bits / 8) {
                return Err(MediaError::invalid("WAV block align does not match channels and sample size"));
            }
            fmt = Some((format, channels, rate, bits, align));
        } else if id == b"data" {
            let Some((format, channels, sample_rate, bits_per_sample, block_align)) = fmt else {
                return Err(MediaError::invalid("WAV data chunk before its fmt chunk"));
            };
            let offset = body as u64;
            let available = total.saturating_sub(offset);
            let data_len = if size == 0 || size == u32::MAX || u64::from(size) > available { available } else { u64::from(size) };
            return Ok(WavInfo { format, sample_rate, channels, bits_per_sample, block_align, data_offset: offset, data_len });
        }
        // Chunks are padded to an even size.
        let next = body as u64 + u64::from(size) + u64::from(size & 1);
        if next > bytes.len() as u64 {
            break;
        }
        at = next as usize;
    }
    Err(MediaError::invalid("WAV has no data chunk in its header"))
}

/// Reads the WAV header of the file at `path` (at most its first MiB).
pub fn wav_file(path: &Path) -> Result<WavInfo> {
    let file = std::fs::File::open(path)?;
    let total = file.metadata()?.len();
    let mut head = Vec::new();
    file.take(1 << 20).read_to_end(&mut head)?;
    wav_header(&head, Some(total))
}

/// One video stream.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct VideoStream {
    pub codec: String,
    pub width: u32,
    pub height: u32,
    /// Frames per second, when the container says.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub fps: Option<f32>,
}

/// One audio stream.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AudioStream {
    pub codec: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub sample_rate: Option<u32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub channels: Option<u16>,
}

/// What a probe found. Fields are absent when the container doesn't say.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct MediaInfo {
    /// The demuxer, as ffprobe names it (`wav`, `mov,mp4,m4a,3gp,3g2,mj2`, `matroska,webm`, ...).
    pub format: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub duration_ms: Option<u64>,
    /// The first video stream that is not cover art.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub video: Option<VideoStream>,
    /// The first audio stream.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub audio: Option<AudioStream>,
}

impl MediaInfo {
    /// A WAV header as a probe.
    pub fn from_wav(wav: &WavInfo) -> Self {
        let codec = match (wav.format, wav.bits_per_sample) {
            (SampleFormat::Float, b) => format!("pcm_f{b}le"),
            (_, 8) => "pcm_u8".to_string(),
            (_, b) => format!("pcm_s{b}le"),
        };
        MediaInfo {
            format: "wav".into(),
            duration_ms: Some(wav.duration_ms()),
            video: None,
            audio: Some(AudioStream { codec, sample_rate: Some(wav.sample_rate), channels: Some(wav.channels) }),
        }
    }
}

/// Containers that can point at other files or the network, or aren't media files; refused even
/// though the protocol and format allowlists would stop them first.
pub const REFUSED_FORMATS: &[&str] =
    &["concat", "hls", "dash", "tty", "lavfi", "ffmetadata", "sdp", "rtp", "rtsp", "image2", "txt", "srt", "webvtt", "data", "subviewer"];

/// A probe from `ffprobe -of json -show_format -show_streams` output. Refuses playlists, image
/// sequences and other non-media containers.
pub fn parse_ffprobe(json: &[u8]) -> Result<MediaInfo> {
    let unreadable = || MediaError::invalid("ffprobe output is not a media probe");
    let v: serde_json::Value = serde_json::from_slice(json).map_err(|_| unreadable())?;
    let format = v.get("format").ok_or_else(unreadable)?;
    let names = format.get("format_name").and_then(|n| n.as_str()).unwrap_or("").to_string();
    if names.is_empty() {
        return Err(unreadable());
    }
    if names.split(',').any(|n| REFUSED_FORMATS.contains(&n) || n.ends_with("_pipe")) {
        return Err(MediaError::refused(format!("container {names} is not an audio or video file")));
    }
    let streams = v.get("streams").and_then(|s| s.as_array()).cloned().unwrap_or_default();
    let num = |x: Option<&serde_json::Value>| -> Option<f64> {
        let x = x?;
        x.as_f64().or_else(|| x.as_str().and_then(|s| s.parse().ok()))
    };
    let text = |s: &serde_json::Value, k: &str| s.get(k).and_then(|t| t.as_str()).unwrap_or("").to_string();
    let kind = |s: &serde_json::Value| s.get("codec_type").and_then(|t| t.as_str()).map(str::to_string);
    let video = streams
        .iter()
        .find(|s| kind(s).as_deref() == Some("video") && s.get("disposition").and_then(|d| d.get("attached_pic")).and_then(|a| a.as_i64()) != Some(1))
        .and_then(|s| {
            let width = s.get("width").and_then(|w| w.as_u64()).unwrap_or(0) as u32;
            let height = s.get("height").and_then(|h| h.as_u64()).unwrap_or(0) as u32;
            if width == 0 || height == 0 {
                return None;
            }
            let fps = s.get("avg_frame_rate").and_then(|r| r.as_str()).and_then(parse_rate);
            Some(VideoStream { codec: text(s, "codec_name"), width, height, fps })
        });
    let audio = streams.iter().find(|s| kind(s).as_deref() == Some("audio")).map(|s| AudioStream {
        codec: text(s, "codec_name"),
        sample_rate: num(s.get("sample_rate")).filter(|r| *r > 0.0).map(|r| r as u32),
        channels: s.get("channels").and_then(|c| c.as_u64()).filter(|c| *c > 0).map(|c| c as u16),
    });
    let duration_ms = num(format.get("duration"))
        .or_else(|| streams.iter().find_map(|s| num(s.get("duration"))))
        .filter(|s| s.is_finite() && *s >= 0.0)
        .map(|s| (s * 1000.0).round() as u64);
    if video.is_none() && audio.is_none() {
        return Err(MediaError::invalid(format!("container {names} has no audio or video stream")));
    }
    Ok(MediaInfo { format: names, duration_ms, video, audio })
}

/// `"30000/1001"` as frames per second.
pub(crate) fn parse_rate(r: &str) -> Option<f32> {
    let (a, b) = r.split_once('/')?;
    let (a, b): (f32, f32) = (a.parse().ok()?, b.parse().ok()?);
    (b > 0.0 && a > 0.0).then_some(a / b)
}

/// Probes `input`: a WAV is read in Rust (no child process); anything else goes through `ffprobe`
/// on `exec`.
pub fn probe(exec: &dyn Exec, input: &Input) -> Result<MediaInfo> {
    let head = input.head(12)?;
    if looks_like_wav(&head) {
        let wav = match input {
            Input::File(path) => wav_file(path)?,
            Input::Bytes(bytes) => wav_header(bytes, None)?,
        };
        return Ok(MediaInfo::from_wav(&wav));
    }
    ffprobe(exec, input)
}

/// Probes `input` with `ffprobe` (format and streams as JSON), whatever it is.
pub fn ffprobe(exec: &dyn Exec, input: &Input) -> Result<MediaInfo> {
    let job = Job::ffprobe(input.clone()).args(["-of", "json", "-show_format", "-show_streams"]).max_output(4 << 20);
    parse_ffprobe(&exec.exec(&job)?)
}