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

weirdnet-media

crates.io docs.rs

Media processing for Weirdnet clients and nodes: the audio and video work apps do before sending media to a model and after getting speech back. Pure Rust where it can be (WAV, PCM, resampling, chunking, plans, subtitles), and a hardened ffmpeg / ffprobe runner for everything else, with a fake so tests never need ffmpeg. Part of Weirdnet by Weird Brains.

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) and refuse, naming the missing setting, when it is absent. Nothing is fetched: inputs are files the caller already chose or bytes it holds.

Audio

  • probe: wav_header / wav_file read WAV headers in Rust (PCM 8/16/24/32-bit, float 32/64, extensible headers, streamed sizes); probe::probe reads a WAV in Rust and anything else through ffprobe into a MediaInfo (container, duration, first video and audio stream).
  • pcm: Pcm (interleaved 16-bit), decode_wav, encode_wav, normalize_wav (16 kHz mono), Pcm::to_mono, Pcm::resample (windowed sinc, low-passed going down), Pcm::slice_ms, crossfade (equal power), concat with Join::{Cut, Crossfade, Pause} (every piece must share rate and channels), tone for fixtures.
  • vad: silence_cuts(pcm, max_ms): 30 ms RMS frames, each cut at the quietest frame in the last fifth of its window, no overlap; frame_rms and cuts_from_rms for energy measured elsewhere.
  • transcribe: plan(pcm, &TranscribeLimits) sends a clip whole when it fits, cuts it at silences when it is longer than audio_max_seconds (narrowed by max_request_bytes), and refuses a clip over the request limit when no audio_max_seconds is known. prompt_from gives the next piece's prompt (the last 200 characters). realign shifts each piece's segments onto the clip; a piece without segments becomes one coarse segment.
  • speak: TextPlan splits narration or a script (SpeechText::Script of ScriptTurns) into pieces that fit max_input_chars: paragraph, then sentence, then clause, then word, never inside a word, never mixing speakers. Without max_input_chars it refuses text over 4 000 characters. TextPlan::joins gives a 10 ms crossfade inside a paragraph and a 300 ms pause between paragraphs and turns, for pcm::concat.
  • subtitles: srt and vtt from segments (coarse cues get a NOTE in WebVTT).
  • audio: normalize / normalize_pcm (WAV in Rust, anything else through ffmpeg), extract (the first audio stream of an audio or video file, -vn, a range, bounded output) and encode to AudioFormat::{Wav, Mp3, Opus, Flac}.
  • waveform: Waveform, an immutable interleaved f32 buffer whose clones share the samples (so it can be handed to an audio thread), for editing and mixing where Pcm's 16 bits would round every step. Gain (linear and dB), fades (FadeCurve::{Linear, EqualPower} 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 convert to and from Pcm; 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); to_wav(WavFormat) writes 16-bit, 24-bit or 32-bit float.

Video

  • video::FrameSource: probe, frame_at(ms, w, h), scenes(threshold), keyframes(), audio(start, len). FfmpegSource implements it over any Exec; FakeSource generates frames for tests; phone decoders can implement it too.
  • plan_frames(Mode, range, n, &Marks) with Mode::{Uniform, Scene, Hybrid, Keyframes, Every { ms }}: sorted, unique, inside the range, never more than n.
  • extract_frames(source, &FrameRequest) (count, longest edge, mode, range, byte bound), thumbnail, soundtrack, clip (stream copy to fragmented MP4, Matroska or WebM, bounded), fit, label, clip_range, parse_scenes, parse_keyframes, is_video_path.

The hardened runner

ffmpeg::Runner runs one Job at a time (an Input, options before and after it, an output bound) and never through a shell:

  • -nostdin -hide_banner -loglevel error -protocol_whitelist file,pipe and a demuxer allowlist (-format_whitelist: WAV, MP3, FLAC, Ogg, AAC, MP4/MOV, Matroska/WebM, AVI). Playlists, concat, image sequences and lavfi are refused, and so are URLs and protocol prefixes in any job option.
  • Input only as file:<canonical path> (a regular file under Limits::max_input_bytes) or bytes on pipe:0; output only to pipe:1, read with a bound, the child killed past it.
  • Limits: wall time (120 s), address space on Unix (1 GiB), niceness (10), decoder threads (2), and on Linux a new network namespace when unprivileged user namespaces allow it.
  • stderr is kept only on failure, truncated to 2 KiB. Nothing is logged.
  • PrivateDir: a 0700 temp dir removed on drop.

ffmpeg::Exec is the seam. FakeRunner validates jobs the same way, records them, and answers from rules or a FakeMedia description (probe JSON, frames, WAV of the right length, scenes, keyframes). Binaries::locate(Some("YOUR_APP_FFMPEG")) finds ffmpeg from an environment variable, beside the executable (or a macOS bundle's Helpers), then PATH.

Example

[dependencies]
weirdnet-media = "0.2"
use weirdnet_media::audio;
use weirdnet_media::ffmpeg::{Input, Runner};
use weirdnet_media::subtitles::srt;
use weirdnet_media::transcribe::{self, PieceTranscript, TranscribeLimits};

let runner = Runner::locate(Some("MYAPP_FFMPEG"))?;
let pcm = audio::normalize_pcm(&runner, &Input::file("talk.mp4"), 4 * 3600 * 1000)?;
let plan = transcribe::plan(&pcm, &TranscribeLimits::new(Some(30), Some(32 << 20)))?;
let mut results = Vec::new();
let mut prompt = String::new();
for i in 0..plan.pieces.len() {
    let wav = plan.piece_wav(&pcm, i).unwrap();
    let piece: PieceTranscript = send_to_transcriber(wav, &prompt)?; // your client
    prompt = transcribe::prompt_from(&piece.text);
    results.push(piece);
}
let transcript = transcribe::realign(&plan, &results)?;
std::fs::write("talk.srt", srt(&transcript.segments))?;

Long narration:

use weirdnet_media::pcm::{concat, decode_wav, encode_wav};
use weirdnet_media::speak::TextPlan;

let plan = TextPlan::text(&chapter, profile.max_input_chars)?;
let pieces = plan.pieces.iter().map(|p| decode_wav(&synthesize(&p.text)?)).collect::<Result<Vec<_>, _>>()?;
let audio = concat(&pieces, &plan.default_joins())?;
std::fs::write("chapter.wav", encode_wav(&audio))?;

Mixing without losing level, then writing a 32-bit float WAV:

use weirdnet_media::waveform::{FadeCurve, MixSource, WavFormat, Waveform, mix};

let kick = Waveform::tone(48_000, 60.0, 4_800, 0.8)?.fade_out(2_400, FadeCurve::EqualPower);
let hat = Waveform::tone(48_000, 8_000.0, 1_200, 0.3)?;
let bar = mix(&[MixSource::new(&kick), MixSource::new(&hat).with_gain(0.5).at(2_400)])?;
std::fs::write("bar.wav", bar.normalize_peak(-1.0)?.to_wav(WavFormat::Float32))?;

Frames for a vision model:

use weirdnet_media::ffmpeg::{Input, Runner};
use weirdnet_media::video::{FfmpegSource, FrameRequest, Mode, extract_frames};

let runner = Runner::locate(None)?;
let source = FfmpegSource::new(&runner, Input::file("clip.mp4"));
// count and edge come from the model's reported limits
let (probe, frames) = extract_frames(&source, &FrameRequest::new(count).max_edge(edge).mode(Mode::Hybrid))?;

Testing

cargo test runs everything against FakeRunner and generated WAV fixtures. The tests in tests/real_ffmpeg.rs run when ffmpeg and ffprobe are installed (or WEIRDNET_MEDIA_FFMPEG names an ffmpeg binary with ffprobe beside it) and return early otherwise. They include hostile files: a text file named .wav, an ffconcat list, an HLS playlist pointing at a URL, an SDP file, a truncated FLAC, and a long clip under a short output bound and time limit.

License

BSD-3-Clause, Copyright (c) 2026, Weird Brains LLC.