# scorpiox-next-whisper-stream

Live streaming speech-to-text as a single self-contained shared library.
whisper.cpp (ggml, CPU-only) is **statically linked** — no `whisper.dll` sidecar,
no process spawn, no Python, no SDL2, no microphone code.

The caller owns the audio. Push float32 16 kHz mono PCM, poll for JSON.

| Platform | Artefact |
|---|---|
| Linux x86_64 | `libscorpiox-next-whisper-stream.so` |
| Windows x64 | `scorpiox-next-whisper-stream.dll` (MinGW, fully static) |

Both raw C99. Companion: `scorpiox-next-whisper-stream.console` (C# P/Invoke harness).

## Why a separate repo from scorpiox-next-whisper-transcription

`-transcription` is a *batch* engine: load a model, hand it a file, get JSON back,
one call at a time, guarded by a single mutex. Streaming is a different contract —
a background thread owns the model for the lifetime of the stream, the caller writes
from an audio callback and reads from a UI timer, and the unit of output is a
*mutating* segment rather than a finished document. Sharing the repository would mean
one mutex protecting both modes and a file-mode caller stalling behind a live session.
Same vendored whisper.cpp, same build flags, separate binaries, separate dist entry.

## API

```c
int         nxstream_start (const char *model_path, int step_ms, int length_ms);
int         nxstream_write (const float *pcm, int n_samples);   /* 16 kHz mono */
const char *nxstream_read  (void);                              /* JSON, free it */
void        nxstream_free_string(char *ptr);
void        nxstream_stop  (void);
const char *nxstream_last_error(void);
const char *nxstream_version(void);
```

* `step_ms` (default 500) — decode cadence. Each 500 ms of new audio triggers at most
  one decode of the current utterance.
* `length_ms` (default 5000) — longest span decoded as one segment. Longer utterances
  are committed at that boundary and continue under a fresh id, which keeps every decode
  inside the latency budget.

### Utterance model

VAD (Silero v6.2, the same ggml model as `scorpiox-next-whisper-vad`) defines the
utterance. Speech after silence opens one; silence after speech closes it. An utterance
is always decoded from its own start, so successive decodes of the same utterance are
re-transcriptions of the same audio and safely replace each other.

```
open   →  id N, "final": false   (repeat on every step, same id, text may be revised)
close  →  id N, "final": true    (one last decode of exactly [start, last speech])
next   →  id N+1
```

Guarantees the console harness asserts, live and against a fixture:

* ids strictly increase, and each id reaches `final:true` **exactly once**
* `t0_ms` never goes backwards; no negative timestamps
* no interim publish after an id went final, no empty publishes
* nothing is emitted for silence

### `read()` payload

```json
{"count":2,
 "segments":[
   {"id":2,"t0_ms":0,"t1_ms":1180,"text":"...","latency_ms":610,"final":true},
   {"id":3,"t0_ms":1240,"t1_ms":3120,"text":"...","latency_ms":480,"final":false}
 ],
 "stats":{
   "steps":24,"decodes":21,"vad_skips":3,"final_segments":2,
   "dropped_samples":0,"step_ms":500,"max_utterance_ms":5000,
   "audio_ms":24200,"processed_ms":24000,"elapsed_ms":24310,
   "next_id":4,"committed_t1_ms":1180,"live":true,"live_id":3,"gate":"silero",
   "lat_avg_ms":520,"lat_max_ms":980,"lat_samples":9,"decode_avg_ms":390
 }}
```

`latency_ms` is *"this text became available N ms after its audio ended"* — the number to
quote as streaming latency. `stats.audio_ms - stats.processed_ms` is the decode backlog;
watch it rather than polling faster.

## Environment knobs

| Var | Default | Meaning |
|---|---|---|
| `NXSTREAM_VAD_MODEL` | `<dir of model_path>/ggml-silero-v6.2.0.bin` | VAD ggml model |
| `NXSTREAM_VAD` | `1` | `0` disables gating (decodes everything) |
| `NXSTREAM_VAD_THRESHOLD` | `0.5` | Silero speech probability threshold |
| `NXSTREAM_VAD_PAD_MS` | `100` | audio kept before the detected onset |
| `NXSTREAM_ENERGY_THRESHOLD` | `0.008` | RMS gate used when no VAD model is found |
| `NXSTREAM_LANGUAGE` | `auto` | or a 2-letter code |
| `NXSTREAM_THREADS` | `min(cores,16)` | whisper threads |
| `NXSTREAM_MAX_TOKENS` | `256` | max tokens per decode |
| `NXSTREAM_MAX_UTTERANCE_MS` | `length_ms` | utterance cap (1000…30000) |
| `NXSTREAM_LOG` | off | `1` lets whisper/ggml log to stderr |

No VAD model on disk → the engine falls back to an RMS energy gate and reports
`stats.gate == "energy"`. The stream still works; it just transcribes silence too.

## Build

```bash
make           # .so + C self-test + CLI  (Linux, ~15 s on 32 cores)
make win       # cross-build the .dll with MinGW (on a Windows box with gcc 16)
make test      # build the C self-test binary
make cli       # build nxstream-cli
```

Vendored: `vendor/whisper-cpp` (ggml 0.23 CPU backend + whisper.cpp 1.9.4) and
`vendor/yyjson`. Nothing else is required at build or run time.

## Verify without a microphone

```bash
# C self-test: 3 utterances of jfk.wav with 1.2 s gaps, fast feed + 1x realtime feed
./build/test-nxstream ggml-small.bin samples/jfk.wav

# CLI: stream a wav at 1x realtime and print each revision as it lands
./build/nxstream-cli -m ggml-small.bin -f samples/jfk.wav
```

`--no-paced` skips the realtime latency pass. The realtime pass feeds 500 ms blocks
paced at exactly 1x and reports chunk-in → segment-out latency.

## Measured

### Linux — Ryzen 9 5950X, 16 threads, `ggml-small`

| | |
|---|---|
| decode of a 2 s utterance | ~350 ms |
| decode of a 5 s utterance | ~400 ms |
| stream latency, 1x realtime feed | avg **~780 ms**, max ~2.0 s over 14 samples |
| realtime factor | ~0.1x audio duration per decode |

### Windows — .216 (i7-8700B, 4 vCPU, 10 GB), `ggml-small` and `ggml-tiny`

| | `ggml-small` | `ggml-tiny` |
|---|---|---|
| decode of a 10 s utterance | ~2.0 s | ~0.6 s |
| decode of a 5 s utterance | ~1.1 s | ~0.35 s |
| transcript quality on `jfk.wav` | "And so, my fellow Americans, ask not." (truncated at the 5 s window boundary) | "and so my fellow Americans, ask not." |

`audio_ctx` is set to the utterance length in 20 ms mel frames (+160 slack). Leaving it
at whisper's default 0 makes every decode encode the full 30 s context — 2.1 s per 5 s
window instead of 0.4 s on the Ryzen, i.e. it can no longer keep up with a microphone.

**Latency is a hardware property, not an engine property.** A segment is published the
moment the decode of its utterance finishes, so the floor is `decode_avg_ms` and the
observed latency is that plus the step at which the decode was triggered. The self-test
therefore asserts `lat_max < max(6 x decode_avg_ms, 8 s)` rather than a fixed number:
on the Ryzen that is 780 ms measured, on a 4-vCPU Windows VM with `ggml-small` it is
~7 s for a 5 s utterance, and with `ggml-tiny` on the same VM ~7 s for a 10 s file.
Pick the model for the machine (`ggml-base` / `ggml-tiny` on small VMs,
`ggml-small` and up where there are cores).

### Windows build gotcha — link-time strip breaks libgomp

`-Wl,-s` (strip at link time) produces a DLL that **loads fine and then faults with
0xC0000005 inside `libgomp`** the first time `nxstream_start()` creates the OpenMP
thread pool. Measured 2026-11-26 on `.216` against three `-march` variants
(`x86-64`, `avx2`, `haswell`) — all identical fault at the same RVA, one symbol into
`gomp_task_maybe_wait_for_dependencies`. Linking unstripped and running `strip -s` on
the finished DLL as a separate step gives a 3.7 MB artefact that runs correctly. The
Makefile does exactly that.
