The pieces / weirdnet-media

weirdnet-medianew

Audio and video processing for clients and nodes: WAV and PCM in pure Rust, 16 kHz resampling, silence-aware chunking, long-audio transcription and long-text speech plans, SRT and WebVTT, video frame planning and extraction, and a hardened ffmpeg runner with a test fake.

v0.2.0 GitHub crates.io docs.rs weirdnet-media = "0.2.0"

What it brings

Use weirdnet-media when an app sends audio or video to a model or gets speech back: normalizing audio for a transcriber, cutting long recordings to the transcriber's window and stitching the transcript back together, splitting long text for a speech model and joining the audio it returns, writing subtitles, and turning a video into frames and a soundtrack for a model that reads images and audio. It runs on clients and, opt in, on nodes; untrusted media only reaches ffmpeg through the hardened runner.

What it is

The media work an app does before it sends audio or video to a model and after it gets speech back, in one place. WAV, PCM, resampling, chunking, plans and subtitles are pure Rust; everything else goes through ffmpeg and ffprobe in child processes behind a hardened runner, and a fake runner answers in tests so they never need ffmpeg.

There are no defaults that stand in for a model’s limits. Plans take what the model reports (audio_max_seconds, max_request_bytes, max_input_chars, frame counts and sizes, as weirdnet-agent catalogs carry them) and refuse, naming the missing setting, when it is absent. Nothing is fetched: inputs are files the caller chose or bytes it holds.

How it works

Limits come from the model

Nothing here guesses a model's limits. TranscribeLimits carries the transcriber's audio_max_seconds and max_request_bytes, TextLimits the speech profile's max_input_chars, and FrameRequest a frame count and edge the caller derived from the model's media limits. When a plan needs a limit that is absent, it refuses with a message naming the setting: a clip over the request limit with no audio_max_seconds, or text over 4 000 characters with no max_input_chars (a refusal threshold of the client, not a limit claimed for any model).

Long-audio transcription

audio::normalize_pcm turns any input into 16 kHz mono 16-bit PCM: a WAV is decoded and resampled in Rust (a windowed-sinc filter that low-passes when going down), anything else is decoded by ffmpeg. transcribe::plan keeps the clip whole when it fits; otherwise the window is audio_max_seconds, narrowed by what fits the request, and vad::silence_cuts places each cut at the quietest 30 ms frame in the last fifth of the window, so pieces never overlap and rarely split a word. Each piece's prompt is prompt_from the previous transcript (its last 200 characters, from a word). realign shifts every segment by its piece's start and clamps it to the piece; a backend that returns no segments gets one segment per piece, flagged coarse, and WebVTT output says so in a NOTE.

Long-text speech

TextPlan is pure and deterministic. It packs whole paragraphs into a piece while they fit, splits a paragraph that doesn't at sentence ends, a sentence at clause punctuation, and a clause between words; a single word longer than the limit is an error rather than a split. Scripts (SpeechText::Script) keep their turns: a piece never mixes speakers, and a long turn splits at sentences and keeps its speaker. Each piece records its paragraph and whether it starts one, and joins turns that into a 10 ms equal-power crossfade inside a paragraph and a 300 ms pause before a new paragraph or turn, for pcm::concat, which refuses pieces whose sample rate or channels differ. audio::encode writes WAV in Rust, or MP3, Opus or FLAC through ffmpeg.

Editing and mixing

From 0.2.0, waveform::Waveform holds interleaved f32 samples, immutable, with clones that share them (so one can be handed to an audio thread), for editing and mixing where Pcm's 16 bits would round every step. It has gain (linear and dB), fades (FadeCurve::Linear and EqualPower from weirdnet-dsp), peak and RMS normalise, a peak ceiling that reduces gain rather than clipping, constant-power pan, mono and stereo, and slicing. mix sums MixSources, each with a gain and a start offset, up to 20 minutes at 48 kHz. from_pcm and to_pcm convert to and from Pcm and every i16 value survives the round trip; from_wav reads 8, 16, 24 and 32-bit integer and 32 and 64-bit float WAV (extensible headers, any chunk order, streamed sizes, never allocating from a header's claim), and to_wav(WavFormat) writes 16-bit, 24-bit or 32-bit float.

Video

FrameSource is the decoder seam: probe, frame_at, scenes, keyframes and audio. FfmpegSource implements it over the runner (JPEG frames through image2pipe, scene scores from ffmpeg's select filter, keyframes from ffprobe packet flags, the soundtrack as 16 kHz mono WAV); phone decoders can implement it too, and FakeSource generates frames for tests. plan_frames picks times inside a range: uniform (the middle of equal slices), scene (the start and the strongest changes), hybrid (half uniform, half scene changes away from them), keyframes (the nearest keyframe to each slot) or every N milliseconds, always sorted, unique and never more than asked. extract_frames bounds the total bytes; clip stream-copies a range to fragmented MP4, Matroska or WebM for models that read video natively.

The hardened runner

Every call is a Job: one input, the options before and after it, an output bound. Runner runs it without a shell, adding -nostdin, -protocol_whitelist file,pipe and a demuxer allowlist (-format_whitelist: WAV, MP3, FLAC, Ogg, AAC, MP4/MOV, Matroska/WebM, AVI), so a playlist, concat list or URL inside a file can't be followed; jobs that name a URL, another protocol, an extra input or a disallowed input format are refused before anything starts. The input is a canonical regular file under the size limit or bytes on pipe:0; output goes only to pipe:1, read with a bound, and the child is killed when it passes it or the time limit (120 s by default). On Unix the child gets a 1 GiB address-space limit and a lower priority, and on Linux a new network namespace where unprivileged user namespaces allow it. stderr is kept only on failure, truncated to 2 KiB, and nothing is logged. PrivateDir is a 0700 temporary directory removed on drop. FakeRunner validates jobs exactly like the runner, records them and answers from rules or a FakeMedia description, so apps can test their media paths without ffmpeg.

Key types and modules

  • probe: WAV headers read in Rust (8 to 32-bit PCM, 32 and 64-bit float, extensible headers, streamed sizes); any other container through ffprobe into a MediaInfo.
  • pcm: decode and write WAV, mono mixing, windowed-sinc resampling to 16 kHz for transcribers, equal-power crossfade, and concat with crossfade, pause or cut joins (every piece must share rate and channels).
  • vad::silence_cuts: 30 ms RMS frames, each cut at the quietest frame in the last fifth of its window, no overlap.
  • transcribe: plan sends a clip whole when it fits and cuts it at silences when it is longer than audio_max_seconds; prompt_from carries the last 200 characters to the next piece; realign shifts segments onto the clip and marks pieces without segments as coarse.
  • speak::TextPlan: narration or a script split to fit max_input_chars at paragraph, sentence, clause, then word boundaries, never inside a word or mixing speakers, with the joins to stitch the audio (10 ms crossfade inside a paragraph, 300 ms pause between paragraphs and turns).
  • subtitles: SRT and WebVTT from segments.
  • audio: normalization to 16 kHz mono WAV, soundtrack extraction from audio or video, and encoding to WAV, MP3, Opus or FLAC.
  • video: FrameSource (FfmpegSource over the runner, FakeSource for tests), plan_frames (uniform, scene, hybrid, keyframes, fixed intervals), extract_frames, thumbnail, soundtrack and stream-copied clips.
  • waveform (from 0.2.0): Waveform, an immutable interleaved f32 buffer whose clones share the samples, for editing and mixing without rounding every step to 16 bits: gain (linear and dB), linear and equal-power fades (from weirdnet-dsp), peak and RMS normalise, a peak ceiling (gain reduction, not clipping), constant-power pan, mono and stereo, slicing, and mix of MixSources with a gain and a start offset (capped at 20 minutes at 48 kHz). from_pcm and to_pcm keep every i16; from_wav reads 8 to 32-bit integer and 32 and 64-bit float WAV, to_wav writes 16-bit, 24-bit or 32-bit float.
  • ffmpeg::Runner: protocol and demuxer allowlists, no URLs and no shell, input as a canonical file or on a pipe, bounded output, time, address-space and priority limits, a Linux network namespace when allowed. FakeRunner validates jobs the same way and answers from rules or a FakeMedia.

Feature flags

None: everything is on by default.

Usage

In Cargo.toml:

[dependencies]
weirdnet-media = "0.2.0"

Then (built and run against the published crate when this page was made):

// Narration split to fit a speech model and stitched back, and a long clip cut for a
// transcriber with its transcript as SRT. Synthesis and transcription are stand-ins here.
use weirdnet_media::pcm::{concat, encode_wav, tone};
use weirdnet_media::speak::TextPlan;
use weirdnet_media::subtitles::srt;
use weirdnet_media::transcribe::{self, PieceTranscript, Segment, TranscribeLimits};

fn main() -> weirdnet_media::Result<()> {
    let chapter = "The harbor was quiet that morning. Gulls circled the masts.\n\nMara walked to the end of the pier.";
    // max_input_chars comes from the model's speech profile.
    let plan = TextPlan::text(chapter, Some(40))?;
    for p in &plan.pieces {
        println!("piece {}: {:?}", p.index + 1, p.text);
    }
    // One tone per piece stands in for the synthesized speech.
    let pieces: Vec<_> = plan.pieces.iter().map(|p| tone(24_000, 220.0, 20 * p.chars as u64, 0.3)).collect();
    let audio = concat(&pieces, &plan.default_joins())?;
    println!("{} ms, {} bytes of WAV", audio.duration_ms(), encode_wav(&audio).len());

    // 70 s of audio for a transcriber that takes 30 s per request.
    let clip = tone(16_000, 220.0, 70_000, 0.3);
    let cut = transcribe::plan(&clip, &TranscribeLimits::new(Some(30), Some(32 << 20)))?;
    let results: Vec<PieceTranscript> = cut
        .pieces
        .iter()
        .map(|p| PieceTranscript::new(format!("piece {}", p.index + 1), vec![Segment::new(0, 1_000, format!("piece {}", p.index + 1))]))
        .collect();
    let transcript = transcribe::realign(&cut, &results)?;
    print!("{}", srt(&transcript.segments));
    Ok(())
}

Where it fits

  • Builds on weirdnet-dsp.
  • Extracted from Bragi’s video sampler.
  • License: BSD-3-Clause.
Version 0.2.0 is on crates.io (docs.rs, repository). Its only dependencies are serde, serde_json, weirdnet-dsp (for the waveform fades and level maths, from 0.2.0) and, on Unix, libc. The ffmpeg-backed tests run where ffmpeg is installed; the rest run against the fake runner.