whisper-nvidia-cli 0.1.0

One-shot agent-native local NVIDIA GPU speech-to-text CLI powered by whisper.cpp
Documentation
//! The external media helper: locating it, asking it, and outliving it safely.
//!
//! Everything this product does through another process lives here. It was
//! carved out of `audio.rs`, which had grown to about three times the median
//! module and mixed six unrelated jobs — probing, native decoding, resampling,
//! filtering, energy-based cutting and this. The split is a move, not a
//! rewrite: no behaviour changed with it.
//!
//! The shared rule of this module is that a child process is never left behind.
//! Every spawn goes through [`crate::signal::spawn_tracked`], so a signal or a
//! blown deadline can reach the whole tree, and every wait polls instead of
//! blocking, because a blocking wait cannot be interrupted.

use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::OnceLock;

use crate::error::Error;

/// Resolve a media helper: the configured path first, then `ffmpeg` on PATH.
///
/// The configured path wins so a deliberate choice is never second-guessed.
/// The PATH lookup exists because `inspect` is the verb an agent calls BEFORE
/// committing to a transcription, and refusing to measure a video merely
/// because no helper was persisted yet makes the cheap verb useless exactly
/// when it is most useful.
///
/// This reads the operating system's `PATH`, never a product variable: the
/// product still has none, and FR-023 is about the CUDA variable, not this.
pub fn resolve_helper(configured: &str) -> Option<String> {
    let trimmed = configured.trim();
    if !trimmed.is_empty() && Path::new(trimmed).is_file() {
        return Some(trimmed.to_string());
    }
    let path = std::env::var_os("PATH")?;
    std::env::split_paths(&path)
        .map(|dir| dir.join("ffmpeg"))
        .find(|candidate| candidate.is_file())
        .map(|candidate| candidate.display().to_string())
}

/// Ask the helper to describe a container, without decoding it.
///
/// `ffmpeg -i FILE` with no output file prints the stream layout on stderr and
/// exits non-zero by design, so the exit status is deliberately ignored and the
/// stderr text is the result. Nothing is written to disk and no model is
/// loaded, which is what FR-014 means by "sem ouvir".
fn describe_with_helper(
    helper: &str,
    input: &Path,
    deadline: Option<std::time::Instant>,
) -> Result<String, Error> {
    let mut cmd = std::process::Command::new(helper);
    cmd.args(["-hide_banner", "-i", &input.display().to_string()])
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::piped());
    let (id, child) =
        crate::signal::spawn_tracked(&mut cmd).map_err(|e| Error::HelperFailed(e.to_string()))?;
    let mut captured = String::new();
    {
        let mut guard = child.lock().unwrap_or_else(|e| e.into_inner());
        if let Some(mut err) = guard.stderr.take() {
            use std::io::Read;
            let _ = err.read_to_string(&mut captured);
        }
    }
    // The description is short and the pipe is already drained, so the wait
    // below returns almost immediately; it still honours the deadline, because
    // a wedged container is exactly the input that hangs a decoder.
    let outcome = loop {
        let polled = {
            let mut guard = child.lock().unwrap_or_else(|e| e.into_inner());
            guard
                .try_wait()
                .map_err(|e| Error::HelperFailed(e.to_string()))?
        };
        if polled.is_some() {
            break Ok(());
        }
        let stop = if deadline
            .map(|d| std::time::Instant::now() > d)
            .unwrap_or(false)
        {
            Some(Error::Timeout)
        } else if crate::signal::is_shutdown_requested() {
            Some(crate::signal::shutdown_error().unwrap_or(Error::Interrupted))
        } else {
            None
        };
        if let Some(err) = stop {
            let mut guard = child.lock().unwrap_or_else(|e| e.into_inner());
            crate::signal::kill_child_tree(&mut guard);
            break Err(err);
        }
        std::thread::sleep(helper_poll());
    };
    crate::signal::release_child(id);
    outcome.map(|()| captured)
}

/// Measure a video container: duration in seconds, sample rate, channel count.
///
/// This is the module's whole public answer about a file, and the parsing
/// helpers below stay private behind it. `audio::inspect_file` used to reach
/// for four separate pieces — resolve, describe, parse duration, parse layout —
/// which meant the caller had to know the shape of the helper's output to use
/// it correctly. One function that returns the measurement keeps the ffmpeg
/// text an implementation detail of this module.
///
/// `helper_hint` is the configured path; an empty one falls back to `ffmpeg` on
/// PATH. `Error::HelperMissing` means the container cannot be measured on this
/// host, which is the same 69 the transcription route answers for video.
pub fn probe_video(
    helper_hint: &str,
    input: &Path,
    deadline: Option<std::time::Instant>,
) -> Result<(f64, u32, usize), Error> {
    let Some(helper) = resolve_helper(helper_hint) else {
        return Err(Error::HelperMissing);
    };
    let description = describe_with_helper(&helper, input, deadline)?;
    let Some(duration) = parse_duration(&description) else {
        return Err(Error::VideoExtractionFailed {
            path: input.display().to_string(),
        });
    };
    let (rate, channels) = parse_audio_layout(&description);
    Ok((duration, rate, channels))
}

/// Read `Duration: HH:MM:SS.ss` out of a helper description.
fn parse_duration(description: &str) -> Option<f64> {
    let tail = description.split("Duration:").nth(1)?;
    let stamp = tail.split(',').next()?.trim();
    if stamp.starts_with("N/A") {
        return None;
    }
    let mut parts = stamp.split(':');
    let hours: f64 = parts.next()?.trim().parse().ok()?;
    let minutes: f64 = parts.next()?.trim().parse().ok()?;
    let seconds: f64 = parts.next()?.trim().parse().ok()?;
    Some(hours * 3600.0 + minutes * 60.0 + seconds)
}

/// Read sample rate and channel count from the first audio stream.
///
/// Returns zeros when the container carries no audio track at all, which is a
/// real answer about a real file and not a measurement failure.
fn parse_audio_layout(description: &str) -> (u32, usize) {
    let Some(line) = description
        .lines()
        .find(|l| l.contains("Stream #") && l.contains("Audio:"))
    else {
        return (0, 0);
    };
    let mut rate = 0u32;
    let mut channels = 0usize;
    for field in line.split(',') {
        let field = field.trim();
        if let Some(hz) = field.strip_suffix(" Hz") {
            if let Ok(parsed) = hz.trim().parse::<u32>() {
                rate = parsed;
            }
        }
        channels = match field {
            "mono" => 1,
            "stereo" => 2,
            "5.1" | "5.1(side)" => 6,
            "7.1" => 8,
            _ => channels,
        };
    }
    (rate, channels)
}

/// The compiled-in poll interval, in milliseconds.
const DEFAULT_HELPER_POLL_MS: u64 = 25;

/// How often the helper is checked for exit, shutdown, and the deadline, in
/// milliseconds.
///
/// This reads the same operator key the GPU probe reads. Both are this
/// product's "wait on a child process" loop, and an operator who lowers the
/// reaction latency of one has no reason to expect the other to stay slow.
/// The initial value is the same 25 ms the literal used.
static HELPER_POLL_MS: AtomicU64 = AtomicU64::new(DEFAULT_HELPER_POLL_MS);

/// Publish the operator's helper poll interval, in milliseconds.
///
/// Zero keeps the default rather than disabling the sleep: a poll of zero is a
/// busy loop, and this knob exists to lower the cost of the wait, not to raise
/// it to a full core.
pub fn publish_helper_poll_ms(ms: u64) {
    HELPER_POLL_MS.store(ms, Ordering::SeqCst);
}

/// The interval a helper wait sleeps for between checks.
fn helper_poll() -> std::time::Duration {
    let ms = HELPER_POLL_MS.load(Ordering::SeqCst);
    std::time::Duration::from_millis(if ms == 0 { DEFAULT_HELPER_POLL_MS } else { ms })
}

/// Extra arguments the operator hands the decode helper.
static HELPER_ARGS: OnceLock<Vec<String>> = OnceLock::new();

/// Publish the operator's extra helper arguments.
///
/// Without this, adding `-threads`, `-nostdin` or a gain filter meant replacing
/// the helper binary with a wrapper script — a whole extra moving part to carry
/// two flags.
///
/// The first publish of an invocation wins, and it happens before any decode.
pub fn publish_helper_args(args: Vec<String>) {
    let _ = HELPER_ARGS.set(args);
}

/// Build the decode argv: engine contract, operator extras, then the output.
///
/// `-ac 1`, `-ar 16000` and `-f wav` are deliberately NOT configurable. The
/// engine accepts 16 kHz mono and nothing else, so those three describe the
/// thing being fed rather than a preference of the operator; making them
/// settable would only offer a way to produce audio the decoder must reject.
///
/// The extras land after them and before the output path, which is where
/// ffmpeg reads output options such as `-threads` or a filter.
fn decode_args(input: &Path, out: &Path, extra: &[String]) -> Vec<String> {
    let mut args = vec![
        "-y".to_string(),
        "-i".to_string(),
        input.display().to_string(),
        "-ac".to_string(),
        "1".to_string(),
        "-ar".to_string(),
        "16000".to_string(),
        "-f".to_string(),
        "wav".to_string(),
    ];
    // An empty entry would reach ffmpeg as an empty argument and fail the
    // decode; a trailing separator in the configured list is not a request.
    args.extend(
        extra
            .iter()
            .filter(|a| !a.trim().is_empty())
            .map(|a| a.trim().to_string()),
    );
    args.push(out.display().to_string());
    args
}

/// Extract audio from video using the persisted helper path.
///
/// The child is spawned rather than waited on inline, and it is registered as
/// a process-owned resource. A blocking `status()` cannot be interrupted, so an
/// interrupt or a blown deadline used to exit this process and leave the helper
/// running: a one-shot invocation that outlives itself through its own child.
pub fn extract_with_helper(
    helper: &str,
    input: &Path,
    work: &Path,
    deadline: Option<std::time::Instant>,
) -> Result<PathBuf, Error> {
    if helper.trim().is_empty() {
        return Err(Error::HelperMissing);
    }
    let out = work.join("extract.wav");
    let mut cmd = std::process::Command::new(helper);
    cmd.args(decode_args(
        input,
        &out,
        HELPER_ARGS.get().map(Vec::as_slice).unwrap_or_default(),
    ))
    .stdout(std::process::Stdio::null())
    .stderr(std::process::Stdio::null());
    // Group membership and tracking both come from `spawn_tracked`, so the
    // helper and the GPU probe cannot drift apart on either.
    let (id, child) =
        crate::signal::spawn_tracked(&mut cmd).map_err(|e| Error::HelperFailed(e.to_string()))?;
    let result = await_helper(&child, input, deadline);
    crate::signal::release_child(id);
    result.map(|()| out)
}

/// Wait for the helper while staying interruptible.
///
/// The lock is released between polls so the signal thread can still reach the
/// same handle to kill it.
fn await_helper(
    child: &std::sync::Mutex<std::process::Child>,
    input: &Path,
    deadline: Option<std::time::Instant>,
) -> Result<(), Error> {
    loop {
        let polled = {
            let mut guard = child.lock().unwrap_or_else(|e| e.into_inner());
            guard
                .try_wait()
                .map_err(|e| Error::HelperFailed(e.to_string()))?
        };
        if let Some(status) = polled {
            return if status.success() {
                Ok(())
            } else {
                Err(Error::VideoExtractionFailed {
                    path: input.display().to_string(),
                })
            };
        }
        // Stop conditions are checked before sleeping again, and the helper is
        // killed here rather than left for the exit path, so a stopped decode
        // never keeps a transcoder alive while the batch unwinds.
        let stop = if deadline
            .map(|d| std::time::Instant::now() > d)
            .unwrap_or(false)
        {
            Some(Error::Timeout)
        } else if crate::signal::is_shutdown_requested() {
            Some(crate::signal::shutdown_error().unwrap_or(Error::Interrupted))
        } else {
            None
        };
        if let Some(err) = stop {
            let mut guard = child.lock().unwrap_or_else(|e| e.into_inner());
            // The whole tree, not just the helper: this is the path a first
            // signal and a blown deadline take, so it is where a surviving
            // grandchild is actually produced.
            crate::signal::kill_child_tree(&mut guard);
            return Err(err);
        }
        std::thread::sleep(helper_poll());
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn extras_land_after_the_engine_contract_and_before_the_output() {
        let args = decode_args(
            Path::new("in.mkv"),
            Path::new("out.wav"),
            &["-threads".to_string(), "2".to_string(), "  ".to_string()],
        );
        assert_eq!(
            args,
            vec![
                "-y", "-i", "in.mkv", "-ac", "1", "-ar", "16000", "-f", "wav", "-threads", "2",
                "out.wav",
            ]
        );
    }

    #[test]
    fn no_extras_keeps_the_argv_the_helper_always_got() {
        let args = decode_args(Path::new("in.mkv"), Path::new("out.wav"), &[]);
        assert_eq!(
            args,
            vec!["-y", "-i", "in.mkv", "-ac", "1", "-ar", "16000", "-f", "wav", "out.wav"]
        );
    }
}