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
//! Long-audio transcription: the chunking plan, the prompt carried from piece to piece, and the
//! re-alignment of each piece's segments onto the whole clip.
//!
//! The window comes from the transcriber's reported `audio_max_seconds` (or the operator's
//! setting). Without it, a clip that fits the request limit goes whole, and one that doesn't is
//! refused with the setting to fill in; nothing is guessed.

use serde::{Deserialize, Serialize};

use crate::error::{MediaError, Result};
use crate::pcm::{Pcm, encode_wav, wav_bytes};
use crate::vad::{CutConfig, silence_cuts_with};

/// Characters of the previous piece's transcript passed as the next piece's prompt.
pub const PROMPT_CHARS: usize = 200;

/// Bytes kept free in a request for everything but the audio.
pub const REQUEST_OVERHEAD: u64 = 64 * 1024;

/// What bounds one transcription request, as the model reports it or the user set it. Absent
/// when unknown.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct TranscribeLimits {
    /// The longest clip the transcriber takes (catalog/1 `audio_max_seconds`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub audio_max_seconds: Option<u32>,
    /// The largest request (catalog/1 `max_request_bytes`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_request_bytes: Option<u64>,
}

impl TranscribeLimits {
    /// Limits from the two values.
    pub fn new(audio_max_seconds: Option<u32>, max_request_bytes: Option<u64>) -> Self {
        TranscribeLimits { audio_max_seconds, max_request_bytes }
    }
}

/// One piece of the clip.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct Piece {
    pub index: usize,
    pub start_ms: u64,
    pub end_ms: u64,
}

impl Piece {
    /// The piece's length.
    pub fn len_ms(&self) -> u64 {
        self.end_ms - self.start_ms
    }
}

/// How a clip is sent: one piece, or several cut at silences.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Plan {
    pub duration_ms: u64,
    pub pieces: Vec<Piece>,
}

impl Plan {
    /// Whether the clip goes whole.
    pub fn is_whole(&self) -> bool {
        self.pieces.len() == 1
    }

    /// The PCM of piece `i`.
    pub fn piece_pcm(&self, pcm: &Pcm, i: usize) -> Option<Pcm> {
        self.pieces.get(i).map(|p| pcm.slice_ms(p.start_ms, p.end_ms))
    }

    /// Piece `i` as a 16-bit WAV.
    pub fn piece_wav(&self, pcm: &Pcm, i: usize) -> Option<Vec<u8>> {
        self.piece_pcm(pcm, i).map(|p| encode_wav(&p))
    }
}

/// The plan for `pcm` (normalize it first: [`Pcm::to_transcribe`]).
pub fn plan(pcm: &Pcm, limits: &TranscribeLimits) -> Result<Plan> {
    plan_with(pcm, limits, CutConfig::default())
}

/// [`plan`] with a [`CutConfig`].
pub fn plan_with(pcm: &Pcm, limits: &TranscribeLimits, cuts: CutConfig) -> Result<Plan> {
    let duration_ms = pcm.duration_ms();
    let whole = Plan { duration_ms, pieces: vec![Piece { index: 0, start_ms: 0, end_ms: duration_ms }] };
    let bytes = wav_bytes(pcm.sample_rate, pcm.channels, duration_ms);
    let fits_request = limits.max_request_bytes.is_none_or(|max| bytes + REQUEST_OVERHEAD <= max);
    let Some(max_s) = limits.audio_max_seconds.filter(|s| *s > 0) else {
        if fits_request {
            return Ok(whole);
        }
        return Err(MediaError::limit(format!(
            "the clip is {bytes} bytes, over the {}-byte request limit, and the transcriber reports no audio_max_seconds to cut it by; set audio_max_seconds for this model",
            limits.max_request_bytes.unwrap_or(0)
        )));
    };
    let mut window = u64::from(max_s) * 1000;
    if let Some(max) = limits.max_request_bytes {
        let per_ms = u64::from(pcm.sample_rate) * u64::from(pcm.channels.max(1)) * 2;
        let room = max.saturating_sub(REQUEST_OVERHEAD + 44);
        let by_bytes = (u128::from(room) * 1000 / u128::from(per_ms.max(1))) as u64;
        if by_bytes < 1000 {
            return Err(MediaError::limit(format!("a {max}-byte request limit leaves no room for audio")));
        }
        window = window.min(by_bytes);
    }
    if duration_ms <= window {
        return Ok(whole);
    }
    let mut bounds = vec![0];
    bounds.extend(silence_cuts_with(pcm, window, cuts));
    bounds.push(duration_ms);
    let pieces = bounds.windows(2).enumerate().map(|(index, w)| Piece { index, start_ms: w[0], end_ms: w[1] }).collect();
    Ok(Plan { duration_ms, pieces })
}

/// The prompt for the next piece: the last [`PROMPT_CHARS`] characters of `previous`, starting at
/// a word.
pub fn prompt_from(previous: &str) -> String {
    let text = previous.trim();
    let count = text.chars().count();
    if count <= PROMPT_CHARS {
        return text.to_string();
    }
    let start = text.char_indices().nth(count - PROMPT_CHARS).map(|(i, _)| i).unwrap_or(0);
    let tail = &text[start..];
    // Drop a leading partial word when there's a later word start.
    match tail.find(char::is_whitespace) {
        Some(sp) if !text[..start].ends_with(char::is_whitespace) => tail[sp..].trim_start().to_string(),
        _ => tail.to_string(),
    }
}

/// A timed piece of transcript.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Segment {
    pub start_ms: u64,
    pub end_ms: u64,
    pub text: String,
    /// The backend gave no segments for this piece, so this one spans the whole piece.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub coarse: bool,
}

impl Segment {
    /// A precise segment.
    pub fn new(start_ms: u64, end_ms: u64, text: impl Into<String>) -> Self {
        Segment { start_ms, end_ms, text: text.into(), coarse: false }
    }
}

/// What the transcriber returned for one piece, its times relative to the piece.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct PieceTranscript {
    pub text: String,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub segments: Vec<Segment>,
}

impl PieceTranscript {
    /// A transcript with its segments.
    pub fn new(text: impl Into<String>, segments: Vec<Segment>) -> Self {
        PieceTranscript { text: text.into(), segments }
    }
}

/// The whole clip's transcript.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Transcript {
    pub text: String,
    pub segments: Vec<Segment>,
    /// Some segments span a whole piece rather than what was said.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub coarse: bool,
}

/// Shifts each piece's segments by the piece's start (clamped to the piece) and joins the text.
/// A piece without segments becomes one [`Segment::coarse`] segment over the whole piece.
/// `results[i]` belongs to `plan.pieces[i]`.
pub fn realign(plan: &Plan, results: &[PieceTranscript]) -> Result<Transcript> {
    if results.len() != plan.pieces.len() {
        return Err(MediaError::invalid(format!("{} transcripts for {} pieces", results.len(), plan.pieces.len())));
    }
    let mut out = Transcript::default();
    let mut texts = Vec::new();
    for (piece, r) in plan.pieces.iter().zip(results) {
        let text = r.text.trim();
        if !text.is_empty() {
            texts.push(text.to_string());
        }
        if r.segments.is_empty() {
            if !text.is_empty() {
                out.segments.push(Segment { start_ms: piece.start_ms, end_ms: piece.end_ms, text: text.to_string(), coarse: true });
                out.coarse = true;
            }
            continue;
        }
        for s in &r.segments {
            let start = (piece.start_ms + s.start_ms).min(piece.end_ms);
            let end = (piece.start_ms + s.end_ms).clamp(start, piece.end_ms);
            out.coarse |= s.coarse;
            out.segments.push(Segment { start_ms: start, end_ms: end, text: s.text.trim().to_string(), coarse: s.coarse });
        }
    }
    out.text = texts.join(" ");
    Ok(out)
}