Skip to content

Effort free video editing!

26.7 KB
Raw Blame
import std/[json, os, sequtils, strformat, strutils, typedthreads]
import ./[av, ffmpeg, log]
import ./lib/[lang, pausecut, srttime]

type
  WhisperCtx = pointer
  WhisperSegmentCb = proc(user: pointer, text: cstring, t0ms, t1ms: int64) {.cdecl.}

when defined(whisper):
  {.emit: """
#include <whisper.h>
#include <parakeet.h>
#include <ggml.h>
#include <ggml-backend.h>

static void ae_quiet_log(enum ggml_log_level level, const char *text, void *user) {
    (void) level; (void) text; (void) user;
}

void *ae_whisper_init(const char *model_path, int use_gpu, int verbose) {
    if (!verbose) {
        whisper_log_set(ae_quiet_log, NULL);
        ggml_log_set(ae_quiet_log, NULL);
    }

    static int loaded = 0;
    if (!loaded) { ggml_backend_load_all(); loaded = 1; }

    struct whisper_context_params cp = whisper_context_default_params();
    cp.use_gpu = use_gpu != 0;
    cp.flash_attn = true;
    return whisper_init_from_file_with_params(model_path, cp);
}

#define AE_CARRY_TOKENS 64

// text is non-const char* to match Nim's cstring callback type (same TU now).
typedef void (*ae_seg_cb)(void *user, char *text, int64_t t0_ms, int64_t t1_ms);

// Transcribe one segment of mono f32 16kHz samples. on_segment is called once per
// resulting text segment, synchronously, on the caller's thread. t0/t1 are in ms,
// relative to the start of `samples`. Returns 0 on success.
int ae_whisper_run(void *ctx, const float *samples, int n_samples,
                   const char *language, int translate, int n_threads,
                   const char *initial_prompt, int max_len,
                   ae_seg_cb on_segment, void *user) {
    struct whisper_full_params p = whisper_full_default_params(WHISPER_SAMPLING_GREEDY);
    p.print_special = false;
    p.print_progress = false;
    p.print_realtime = false;
    p.print_timestamps = false;
    p.translate = translate != 0;
    p.language = language;
    p.n_threads = n_threads;
    // Carry the previous segment's text as context: reusing the same ctx across
    // calls conditions each utterance on the last, which keeps spelling and
    // script (kanji vs. kana) consistent. Only its last sentence or two: given
    // a full window of earlier transcript, the decoder starts copying lines
    // from it on a fixed 2 s timestamp grid instead of following the audio.
    p.no_context = false;
    p.n_max_text_ctx = AE_CARRY_TOKENS;
    if (initial_prompt && initial_prompt[0]) {
        // The prompt gets its own room on top, in every call, instead of
        // competing with the carried text for the same few tokens.
        int n = whisper_tokenize((struct whisper_context *) ctx, initial_prompt, NULL, 0);
        p.initial_prompt = initial_prompt;
        p.carry_initial_prompt = true;
        p.n_max_text_ctx += n < 0 ? -n : n;
    }
    if (max_len > 0) {
        p.max_len = max_len;
        p.token_timestamps = true;
        p.split_on_word = true;
    }

    if (whisper_full((struct whisper_context *) ctx, p, samples, n_samples) != 0)
        return -1;

    int n = whisper_full_n_segments((struct whisper_context *) ctx);
    for (int i = 0; i < n; i++) {
        const char *text = whisper_full_get_segment_text((struct whisper_context *) ctx, i);
        int64_t t0 = whisper_full_get_segment_t0((struct whisper_context *) ctx, i) * 10;
        int64_t t1 = whisper_full_get_segment_t1((struct whisper_context *) ctx, i) * 10;
        on_segment(user, (char *) text, t0, t1);
    }
    return 0;
}

void ae_whisper_free(void *ctx) {
    if (ctx) whisper_free((struct whisper_context *) ctx);
}

void *ae_parakeet_init(const char *model_path, int use_gpu, int verbose) {
    if (!verbose) {
        parakeet_log_set(ae_quiet_log, NULL);
        ggml_log_set(ae_quiet_log, NULL);
    }

    static int loaded = 0;
    if (!loaded) { ggml_backend_load_all(); loaded = 1; }

    struct parakeet_context_params cp = parakeet_context_default_params();
    cp.use_gpu = use_gpu != 0;
    return parakeet_init_from_file_with_params(model_path, cp);
}

// Same contract as ae_whisper_run. Parakeet has no language/translate/prompt
// knobs; each utterance is decoded independently. All t0/t1 are in 10ms mel
// frames, same scale as whisper's centiseconds. With split_words, one callback
// fires per word: tokens are grouped on is_word_start, with word times taken
// from the TDT token durations (punctuation has no word-start marker, so it
// attaches to the preceding word).
int ae_parakeet_run(void *ctx, const float *samples, int n_samples,
                    int n_threads, int split_words, ae_seg_cb on_segment, void *user) {
    struct parakeet_context *c = (struct parakeet_context *) ctx;
    struct parakeet_full_params p = parakeet_full_default_params(PARAKEET_SAMPLING_GREEDY);
    p.n_threads = n_threads;

    if (parakeet_full(c, p, samples, n_samples) != 0)
        return -1;

    int n = parakeet_full_n_segments(c);
    for (int i = 0; i < n; i++) {
        if (!split_words) {
            const char *text = parakeet_full_get_segment_text(c, i);
            int64_t t0 = parakeet_full_get_segment_t0(c, i) * 10;
            int64_t t1 = parakeet_full_get_segment_t1(c, i) * 10;
            on_segment(user, (char *) text, t0, t1);
            continue;
        }
        int nt = parakeet_full_n_tokens(c, i);
        char word[512]; int wlen = 0;
        int64_t t0 = 0, t1 = 0;
        for (int j = 0; j < nt; j++) {
            parakeet_token_data td = parakeet_full_get_token_data(c, i, j);
            if (td.is_word_start && wlen > 0) {
                on_segment(user, word, t0 * 10, t1 * 10);
                wlen = 0;
            }
            if (wlen == 0) t0 = td.t0;
            const char *ts = parakeet_token_to_str(c, td.id);
            wlen += parakeet_token_to_text(ts, wlen == 0, word + wlen, (int)sizeof(word) - wlen);
            if (wlen > (int)sizeof(word) - 1) wlen = (int)sizeof(word) - 1;
            t1 = td.t1;
        }
        if (wlen > 0)
            on_segment(user, word, t0 * 10, t1 * 10);
    }
    return 0;
}

void ae_parakeet_free(void *ctx) {
    if (ctx) parakeet_free((struct parakeet_context *) ctx);
}
""".}

  proc ae_whisper_init(modelPath: cstring, useGpu, verbose: cint): WhisperCtx {.
    importc, nodecl, cdecl.}
  proc ae_whisper_run(ctx: WhisperCtx, samples: ptr float32, nSamples: cint,
    language: cstring, translate: cint, nThreads: cint, initialPrompt: cstring,
    maxLen: cint, onSegment: WhisperSegmentCb, user: pointer):
    cint {.importc, nodecl, cdecl.}
  proc ae_whisper_free(ctx: WhisperCtx) {.importc, nodecl, cdecl.}
  proc whisper_lang_max_id(): cint {.importc, nodecl, cdecl.}
  proc whisper_lang_str(id: cint): cstring {.importc, nodecl, cdecl.}
  proc whisper_lang_str_full(id: cint): cstring {.importc, nodecl, cdecl.}
  proc ae_parakeet_init(modelPath: cstring, useGpu,
      verbose: cint): WhisperCtx {.importc, nodecl, cdecl.}
  proc ae_parakeet_run(ctx: WhisperCtx, samples: ptr float32, nSamples: cint,
    nThreads, splitWords: cint, onSegment: WhisperSegmentCb,
    user: pointer): cint {.importc, nodecl, cdecl.}
  proc ae_parakeet_free(ctx: WhisperCtx) {.importc, nodecl, cdecl.}
else:
  proc ae_whisper_init(modelPath: cstring, useGpu, verbose: cint): WhisperCtx = nil
  proc ae_whisper_run(ctx: WhisperCtx, samples: ptr float32, nSamples: cint,
    language: cstring, translate: cint, nThreads: cint, initialPrompt: cstring,
    maxLen: cint, onSegment: WhisperSegmentCb, user: pointer): cint = -1
  proc ae_whisper_free(ctx: WhisperCtx) = discard
  proc whisper_lang_max_id(): cint = -1
  proc whisper_lang_str(id: cint): cstring = nil
  proc whisper_lang_str_full(id: cint): cstring = nil
  proc ae_parakeet_init(modelPath: cstring, useGpu, verbose: cint): WhisperCtx = nil
  proc ae_parakeet_run(ctx: WhisperCtx, samples: ptr float32, nSamples: cint,
    nThreads, splitWords: cint, onSegment: WhisperSegmentCb,
    user: pointer): cint = -1
  proc ae_parakeet_free(ctx: WhisperCtx) = discard

# Whisper and parakeet GGUFs share the same ggml magic, and a failed
# whisper_init on a parakeet file leaks Metal buffers, so probing is not an
# option — go by the conventional model file name (ggml-parakeet-*).
proc whisperLanguage*(language: string): string =
  ## `language` as whisper names it: "auto", an ISO 639-1 code like "fr", or
  ## an English name like "french". ISO 639-2 codes and tags like "fr-CA"
  ## become the ISO 639-1 code.
  # whisper ignores a language it doesn't know and detects one instead.
  let lang = language.toLowerAscii
  if lang == "auto": return lang
  var known: seq[string]
  for id in 0.cint .. whisper_lang_max_id():
    known.add $whisper_lang_str(id)
    known.add $whisper_lang_str_full(id)
  if lang in known: return lang
  for two in toLang(lang).iso639_1Codes:
    if two in known: return two
  error &"Unknown language: {language}"

func isParakeetModel*(model: string): bool =
  "parakeet" in model.extractFilename.toLowerAscii

func isShortFormParakeet(model: string): bool =
  ## Whether `model` is the Japanese parakeet (parakeet-tdt_ctc-0.6b-ja). It
  ## was trained on short clips of unbroken speech: over a longer segment, or
  ## one with pauses in it, its decoder goes blank and whole sentences are
  ## lost. NVIDIA's own runtime does the same.
  isParakeetModel(model) and
    "ja" in model.extractFilename.toLowerAscii.split({'-', '_', '.'})

func defaultQueue*(model: string): int =
  ## The longest segment, in seconds, to hand `model` at once. Whisper reads
  ## 30 second windows; parakeet's encoder takes the whole segment, and fewer
  ## segments mean fewer cuts through running speech.
  if isShortFormParakeet(model): 8
  elif isParakeetModel(model): 120
  else: 30

# Apple SpeechAnalyzer backend (src/ae_speech.swift), selected with model "apple".
when defined(appleSpeech):
  proc ae_speech_init(locale: cstring): WhisperCtx {.importc, cdecl.}
  proc ae_speech_run(ctx: WhisperCtx, samples: ptr float32, nSamples: cint,
    splitWords: cint, onSegment: WhisperSegmentCb,
    user: pointer): cint {.importc, cdecl.}
  proc ae_speech_free(ctx: WhisperCtx) {.importc, cdecl.}
else:
  proc ae_speech_run(ctx: WhisperCtx, samples: ptr float32, nSamples: cint,
    splitWords: cint, onSegment: WhisperSegmentCb, user: pointer): cint = -1
  proc ae_speech_free(ctx: WhisperCtx) = discard

const
  Rate = 16000 # whisper's sample rate; the graph resamples to it
  WinSize = 480 # 30ms analysis window, matching auto-editor's chunking
  SilenceGap = Rate div 2 # 0.5s of trailing silence ends an utterance
  PrerollMax = Rate div 5 # keep 0.2s of pre-speech audio so onsets aren't clipped
  MinSpeech = Rate div 5 # ignore <0.2s blips (clicks, coughs)
  CutSearch = Rate * 5 # how far back a full segment looks for a pause to end on
  RepeatGapMs = 100 # a repeated cue this close to the last one continues it
  RetryPadMs = 100 # silence put before a segment to decode it a second way

type OutCtx = object
  f: File
  format: string
  splitWords: bool
  index: int
  pieces: seq[Piece] # where the segment being transcribed sits in the source
  segLen: int # its length in samples; models round a last cue's end past it
  # A whisper decoder stuck on a line emits it again in back-to-back cues, so
  # the latest cue is held back until the next one shows it isn't a repeat.
  mergeRepeats: bool
  held: bool
  heldText: string
  heldStartMs, heldEndMs: int64

proc writeCue(oc: ptr OutCtx, s: string, startMs, endMs: int64) =
  case oc.format
  of "srt":
    oc.index += 1
    oc.f.write(&"{oc.index}\n{srtTime(startMs)} --> {srtTime(endMs)}\n{s}\n\n")
  of "json":
    oc.f.write($(%*{"start": startMs, "end": endMs, "text": s}) & "\n")
  else:
    oc.f.write(s & "\n")
  oc.f.flushFile()

proc flushHeld(oc: ptr OutCtx) =
  if oc.held:
    oc.held = false
    writeCue(oc, oc.heldText, oc.heldStartMs, oc.heldEndMs)

type Cue = tuple[text: string, t0ms, t1ms: int64]

# Called per text segment on the thread that runs the model, so Nim GC is safe.
proc segCb(user: pointer, text: cstring, t0ms, t1ms: int64) {.cdecl.} =
  cast[ptr seq[Cue]](user)[].add ($text, t0ms, t1ms)

proc emit(oc: ptr OutCtx, text: string, t0ms, t1ms: int64) =
  var s = text.strip(leading = true, trailing = true)
  s = s.replace("[BLANK_AUDIO]", "").strip()
  if s.len == 0: return
  if oc.splitWords and s in ["[", "]", "BLANK", "_", "AUDIO"]: return

  # A cue that ends where a piece does ends with that piece's last sample,
  # not at the start of the next piece, which is a dropped silence later.
  let t0 = min(t0ms * Rate div 1000, oc.segLen)
  let t1 = clamp(t1ms * Rate div 1000, 1, max(oc.segLen, 1))
  let startMs = sourceSample(oc.pieces, t0) * 1000 div Rate
  let endMs = max(startMs, (sourceSample(oc.pieces, t1 - 1) + 1) * 1000 div Rate)
  if not oc.mergeRepeats:
    writeCue(oc, s, startMs, endMs)
  elif oc.held and s == oc.heldText and startMs - oc.heldEndMs <= RepeatGapMs:
    oc.heldEndMs = max(oc.heldEndMs, endMs)
  else:
    flushHeld(oc)
    oc.held = true
    oc.heldText = s
    oc.heldStartMs = startMs
    oc.heldEndMs = endMs

type
  Job = object
    samples: seq[float32] # mono f32 @16k; len 0 is the end-of-stream sentinel
    pieces: seq[Piece]
  WorkerArgs = object
    wctx: WhisperCtx
    apple: bool
    parakeet: bool
    oc: ptr OutCtx
    jobs: ptr Channel[Job]
    language: string
    translate: cint
    threads: cint
    prompt: string
    maxLen: cint
    debug: bool
    live: bool

const MaxPending = 16 # queued utterances before capture has to wait (back-pressure)

proc runWhisper(a: ptr WorkerArgs, samples: seq[float32], cues: var seq[Cue]): cint =
  ae_whisper_run(a.wctx, addr samples[0], samples.len.cint,
    a.language.cstring, a.translate, a.threads, a.prompt.cstring,
    a.maxLen, segCb, addr cues)

# Whisper runs here, off the capture thread, so a (multi-second) transcription
# never stalls av_read_frame and live mic audio isn't dropped. This thread alone
# drives the run-call sequence — preserving whisper's cross-call prompt context —
# and owns every output write (via emit); the capture thread only feeds it jobs.
proc whisperWorker(a: ptr WorkerArgs) {.thread.} =
  while true:
    var job = a.jobs[].recv()
    if job.samples.len == 0: break
    let startMs = sourceSample(job.pieces, 0) * 1000 div Rate
    a.oc.pieces = move job.pieces
    a.oc.segLen = job.samples.len
    if a.debug:
      stderr.writeLine(&"transcribing {job.samples.len} samples at {startMs} ms")
    var cues: seq[Cue]
    let rc =
      if a.apple:
        ae_speech_run(a.wctx, addr job.samples[0], job.samples.len.cint,
          a.maxLen, segCb, addr cues)
      elif a.parakeet:
        ae_parakeet_run(a.wctx, addr job.samples[0], job.samples.len.cint,
          a.threads, a.maxLen, segCb, addr cues)
      else:
        a.runWhisper(job.samples, cues)
    if not (a.apple or a.parakeet) and cues.anyIt(gaveUp(it.text.len, it.t1ms - it.t0ms)):
      # Whether whisper follows a segment or drops most of it can turn on a
      # few samples, so a second decode of slightly shifted audio often lands.
      var padded = newSeq[float32](RetryPadMs * Rate div 1000)
      padded.add job.samples
      var again: seq[Cue]
      if a.runWhisper(padded, again) == 0 and
          not again.anyIt(gaveUp(it.text.len, it.t1ms - it.t0ms)):
        if a.debug:
          stderr.writeLine(&"decoded the segment at {startMs} ms a second time")
        cues = again.mapIt((it.text, max(it.t0ms - RetryPadMs, 0),
          max(it.t1ms - RetryPadMs, 0)))
    for cue in cues:
      emit(a.oc, cue.text, cue.t0ms, cue.t1ms)
    if rc != 0:
      stderr.writeLine(&"transcription failed on segment at {startMs} ms; skipping")
    # Someone is watching a live transcript; don't sit on its latest line.
    if a.live: flushHeld(a.oc)

type PacketSource* = proc(pkt: ptr AVPacket): cint {.gcsafe.}
  ## Fills `pkt` like av_read_frame: 0 on success, AVERROR_EAGAIN to retry,
  ## any other negative value ends the stream.

proc fileSource*(fmtCtx: ptr AVFormatContext, stop: ptr bool): PacketSource =
  ## Packets of an open container; the stream ends early once `stop[]` is set.
  proc(pkt: ptr AVPacket): cint =
    if stop[]: AVERROR_EOF else: av_read_frame(fmtCtx, pkt)

proc run*(readPacket: PacketSource, audioStream: ptr AVStream,
    model, language: string, translate: bool, format, output: string,
    queue: int, threshold: float32, prompt: string, threads: cint,
    splitWords, debug: bool, heardMs: ptr int64 = nil, live = false) =
  ## Read `audioStream`'s packets from `readPacket` (a file or the live mic)
  ## until it ends, transcribing each detected speech segment. Output goes to
  ## `output` ("-" = stdout). `heardMs`, if given, follows how much audio has
  ## been read, for a progress display. `live` writes each segment's text as
  ## soon as it is transcribed.
  let useApple = model == "apple"
  let useParakeet = not useApple and isParakeetModel(model)
  var language = language
  var wctx: WhisperCtx
  if useApple:
    when defined(appleSpeech):
      # Blocks while downloading the system model on first use.
      if language == "auto":
        stderr.writeLine("Apple speech cannot auto-detect language; assuming en_US (set --language to override)")
      let locale = (if language == "auto": "en_US" else: language)
      wctx = ae_speech_init(locale.cstring)
      if wctx == nil:
        error &"Apple speech init failed. It needs macOS 26+ at runtime, a supported " &
          &"language (got: {locale}), and network access for the first-run model download"
    else:
      error "The 'apple' model needs a build made on macOS 26 or later"
  elif useParakeet:
    wctx = ae_parakeet_init(model.cstring, 1, (if debug: 1.cint else: 0.cint))
    if wctx == nil:
      when defined(whisper):
        error &"Could not load parakeet model: {model}"
      else:
        error "This build of auto-editor has no whisper support"
  else:
    language = whisperLanguage(language)
    wctx = ae_whisper_init(model.cstring, 1, (if debug: 1.cint else: 0.cint))
    if wctx == nil:
      when defined(whisper):
        error &"Could not load whisper model: {model}"
      else:
        error "This build of auto-editor has no whisper support"
  defer:
    if useApple: ae_speech_free(wctx)
    elif useParakeet: ae_parakeet_free(wctx)
    else: ae_whisper_free(wctx)

  let outFile =
    if output == "-": stdout
    else:
      try: open(output, fmWrite)
      except IOError: error &"Could not open output: {output}"
  defer: (if output != "-": outFile.close())

  # Resample whatever the device gives us to mono f32 @16k for whisper.
  var graph: ptr AVFilterGraph
  var srcCtx, sinkCtx: ptr AVFilterContext
  var inRate, inFmt: cint
  var inLayout: AVChannelLayout
  defer: avfilter_graph_free(addr graph)

  proc buildGraph(rate, fmt: cint, layout: ptr AVChannelLayout) =
    avfilter_graph_free(addr graph)
    inRate = rate
    inFmt = fmt
    discard av_channel_layout_copy(addr inLayout, layout)
    let fmtName = av_get_sample_fmt_name(fmt)
    let tb = audioStream.time_base
    let bufferArgs = &"sample_rate={rate}:sample_fmt={fmtName}:channel_layout={layout[]}:" &
      &"time_base={tb.num}/{tb.den}"

    graph = avfilter_graph_alloc()
    if graph == nil: error "out of memory"

    var resCtx, afmtCtx: ptr AVFilterContext
    var ret = avfilter_graph_create_filter(addr srcCtx,
      avfilter_get_by_name("abuffer"), nil, bufferArgs.cstring, nil, graph)
    if ret >= 0:
      ret = avfilter_graph_create_filter(addr resCtx,
        avfilter_get_by_name("aresample"), nil, "16000", nil, graph)
    if ret >= 0:
      ret = avfilter_graph_create_filter(addr afmtCtx,
        avfilter_get_by_name("aformat"), nil,
        "sample_fmts=flt:channel_layouts=mono:sample_rates=16000", nil, graph)
    if ret >= 0:
      ret = avfilter_graph_create_filter(addr sinkCtx,
        avfilter_get_by_name("abuffersink"), nil, nil, nil, graph)
    if ret < 0: error "Failed to create audio filters"
    if avfilter_link(srcCtx, 0, resCtx, 0) < 0 or
        avfilter_link(resCtx, 0, afmtCtx, 0) < 0 or
        avfilter_link(afmtCtx, 0, sinkCtx, 0) < 0:
      error "Failed to connect filters"
    graph.nb_threads = threads
    if avfilter_graph_config(graph, nil) < 0:
      error "Failed to configure filter graph"

  buildGraph(audioStream.codecpar.sample_rate, audioStream.codecpar.format,
    addr audioStream.codecpar.ch_layout)

  # Word cues repeat honestly ("had had"); only whisper loops on a line.
  var oc = OutCtx(f: outFile, format: format, splitWords: splitWords,
    mergeRepeats: not (useApple or useParakeet or splitWords))
  let maxSeg = queue * Rate

  var jobs: Channel[Job]
  jobs.open(MaxPending)

  var seg = newSeqOfCap[float32](maxSeg + Rate)
  var preroll = newSeqOfCap[float32](PrerollMax)
  var inSpeech = false
  var silenceRun = 0
  var speechSamples = 0
  var elapsed: int64 = 0 # total samples seen (real-time clock)
  var pieces: seq[Piece]
  # A model handed one or two words has too little audio to recognize them or
  # their language, so utterances are joined, minus the silence between them,
  # until a segment is full. A live transcript can't wait for that. Parakeet
  # takes long segments with their pauses, except the short-form model.
  let pack = not (live or useApple) and
    (not useParakeet or isShortFormParakeet(model))

  proc flushSeg() =
    # Hand the utterance to the worker and keep capturing; blocks only if the
    # queue is full (whisper falling behind real-time) — never silently drops.
    if seg.len > 0 and speechSamples >= MinSpeech:
      jobs.send(Job(samples: move seg, pieces: move pieces))
    seg = newSeqOfCap[float32](maxSeg + Rate)
    pieces = @[]
    inSpeech = false
    silenceRun = 0
    speechSamples = 0

  proc cutSeg() =
    # A segment that fills up mid-speech ends at its last pause, not its last
    # sample: a model given half a word invents the rest. The audio after the
    # pause opens the next segment.
    let spanStart = seg.len - min(CutSearch, maxSeg div 2)
    let cut = spanStart + quietestCut(seg.toOpenArray(spanStart, seg.high),
      WinSize, threshold)
    let rest = seg[cut .. ^1]
    let restSpeech = loudSamples(rest, WinSize, threshold)
    let restPieces = piecesFrom(pieces, cut)
    let restSilence = min(silenceRun, rest.len)

    seg.setLen(cut)
    speechSamples = max(speechSamples - restSpeech, 0)
    flushSeg()

    seg.add(rest)
    inSpeech = true
    pieces = restPieces
    speechSamples = restSpeech
    silenceRun = restSilence

  proc gateWindow(w: ptr UncheckedArray[float32], L: int) =
    var peak: float32 = 0
    for i in 0 ..< L:
      let a = abs(w[i])
      if a > peak: peak = a
    let winStart = elapsed
    elapsed += L
    if heardMs != nil: heardMs[] = (elapsed * 1000) div Rate

    if peak >= threshold:
      if not inSpeech:
        inSpeech = true
        # back-date to include preroll
        pieces.add (at: seg.len, start: winStart - preroll.len)
        if preroll.len > 0:
          seg.add(preroll)
          preroll.setLen(0)
      for i in 0 ..< L: seg.add(w[i])
      speechSamples += L
      silenceRun = 0
    elif inSpeech:
      for i in 0 ..< L: seg.add(w[i]) # keep the natural trailing tail
      silenceRun += L
      if silenceRun >= SilenceGap:
        if pack:
          inSpeech = false
          silenceRun = 0
        else:
          flushSeg()
    else:
      for i in 0 ..< L: preroll.add(w[i]) # rolling pre-speech buffer
      if preroll.len > PrerollMax:
        preroll = preroll[preroll.len - PrerollMax .. ^1]

    if inSpeech and seg.len >= maxSeg:
      cutSeg()

  proc gateFrame(fr: ptr AVFrame) =
    let n = fr.nb_samples.int
    let data = cast[ptr UncheckedArray[float32]](fr.data[0])
    var i = 0
    while i < n:
      let L = min(WinSize, n - i)
      gateWindow(cast[ptr UncheckedArray[float32]](addr data[i]), L)
      i += L

  let dec = initDecoder(audioStream.codecpar)
  defer: avcodec_free_context(addr dec)
  let frame = av_frame_alloc()
  defer: av_frame_free(addr frame)
  let outFrame = av_frame_alloc()
  defer: av_frame_free(addr outFrame)
  let pkt = av_packet_alloc()
  defer: av_packet_free(addr pkt)

  proc drainSink() =
    while av_buffersink_get_frame_flags(sinkCtx, outFrame, 0) >= 0:
      gateFrame(outFrame)
      av_frame_unref(outFrame)

  proc feed(fr: ptr AVFrame) =
    # abuffer refuses frames that differ from its setup, and a stream can
    # switch channel configurations mid-way (AAC): finish this graph and
    # build one for the new input.
    if fr.sample_rate != inRate or fr.format != inFmt or
        av_channel_layout_compare(addr fr.ch_layout, addr inLayout) != 0:
      discard av_buffersrc_write_frame(srcCtx, nil)
      drainSink()
      buildGraph(fr.sample_rate, fr.format, addr fr.ch_layout)
    discard av_buffersrc_write_frame(srcCtx, fr)
    drainSink()

  var wargs = WorkerArgs(wctx: wctx, apple: useApple, parakeet: useParakeet,
    oc: addr oc, jobs: addr jobs,
    language: language, translate: (if translate: 1.cint else: 0.cint),
    threads: threads, prompt: prompt,
    maxLen: (if splitWords: 1.cint else: 0.cint), debug: debug, live: live)
  var worker: Thread[ptr WorkerArgs]
  createThread(worker, whisperWorker, addr wargs)

  while true:
    let ret = readPacket(pkt)
    if ret == AVERROR_EAGAIN:
      sleep(5)
    else:
      if ret < 0:
        if ret != AVERROR_EOF:
          warning &"Stopped reading audio: {av_err2str(ret)}"
        break
      if pkt.stream_index == audioStream.index and avcodec_send_packet(dec, pkt) >= 0:
        while avcodec_receive_frame(dec, frame) >= 0:
          feed(frame)
          av_frame_unref(frame)
      av_packet_unref(pkt)

  # Flush the decoder first: delay codecs (AAC/MP3) still hold the last frames,
  # which carry the end of the final utterance.
  discard avcodec_send_packet(dec, nil)
  while avcodec_receive_frame(dec, frame) >= 0:
    feed(frame)
    av_frame_unref(frame)

  # Drain the resampler, enqueue whatever utterance was in progress, then let the
  # worker finish the whole backlog (Ctrl-C included) before we tear anything down.
  discard av_buffersrc_write_frame(srcCtx, nil)
  drainSink()
  flushSeg()

  let pending = jobs.peek()
  if pending > 0:
    stderr.writeLine(&"\nFinishing {pending} queued segment(s)...")
  jobs.send(Job(samples: @[])) # sentinel
  joinThread(worker)
  jobs.close()
  flushHeld(addr oc)

proc transcribeFile*(input, model, language: string, threads: int,
    output: string, stop: ptr bool, heardMs: ptr int64 = nil) =
  ## Write `input`'s first audio stream to `output` as an .srt with a cue per
  ## word: `whisper --format srt --split-words`. `model` is a whisper or
  ## parakeet file, or "apple"; parakeet ignores `language`.
  let container = (try: av.open(input) except IOError: error "Could not open " &
    input.extractFilename)
  defer: container.close()
  if container.audio.len == 0: error "No audio stream found"
  let lang = if model != "apple" and isParakeetModel(model): "auto" else: language
  run(fileSource(container.formatContext, stop), container.audio[0], model, lang,
    translate = false, format = "srt", output = output,
    queue = defaultQueue(model),
    threshold = 0.04, prompt = "", threads = threads.cint, splitWords = true,
    debug = false, heardMs = heardMs)