Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 8 additions & 6 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -98,11 +98,12 @@ README.md and `docs/` are the documentation for users; what a developer needs is
of `speech serve --open`, plain HTML, CSS and JavaScript modules compiled into `speech`, which `page.cpp` serves
with the endpoints that fetch and load models; `access.cpp` guards them with the Host and the Origin.
- `wasm/` holds what goes beside the library built for WebAssembly, which `emcmake cmake` configures: the C API
compiled whole into `libspeech.js` and `libspeech.wasm`, with the families `SPEECH_WASM_FAMILIES` names, each a line
of the table of families that the build keeps. `speech.mjs` is the thin module that calls it from a Worker and reads
a model from its Blob through WORKERFS, `wav.mjs` reads a WAVE file as `src/common/wav.cpp` does, and `index.html`,
`page.mjs` and `worker.mjs` are a page that detects speech in a file with them. The build makes neither the
executables nor the checks.
compiled whole into `libspeech.js` and `libspeech.wasm`, or with `SPEECH_WASM_THREADS` into `libspeech-threads.js`
and `libspeech-threads.wasm`, with the families `SPEECH_WASM_FAMILIES` names, each a line of the table of families
that the build keeps. `speech.mjs` is the thin module that calls it from a Worker and reads a model from its Blob
through WORKERFS, `wav.mjs` reads a WAVE file as `src/common/wav.cpp` does, `index.html`, `page.mjs` and `worker.mjs`
are a page that detects speech in a file with them, and `serve.py` serves the folder cross-origin isolated, as the
module with threads needs. The build makes neither the executables nor the checks.
- The smoke scripts in `checks/smoke/` drive each entry point as its caller does and fail on a defect:
`worker_smoke.py`, `worker_recognition_smoke.py`, `worker_enhancement_smoke.py` and `worker_dialogue_smoke.py` the
worker protocol through
Expand Down Expand Up @@ -245,7 +246,8 @@ comment.
`checks/smoke/server_enhancement_smoke.py`, `checks/smoke/server_dialogue_smoke.py` and `checks/smoke/server_page_smoke.py`, one to the page `checks/smoke/server_page_browser_smoke.mjs` (with `--dialogue` and Haru for the talk panel), one to the command
line or the parser `checks/smoke/speech_cli_smoke.py`, with a model of each family, one to `tools/catalog/`
`checks/smoke/models_smoke.py`, and one to `wasm/`, to the library's code that a WebAssembly build compiles
differently or to the table of families `checks/smoke/wasm_browser_smoke.mjs`, with Silero VAD.
differently or to the table of families `checks/smoke/wasm_browser_smoke.mjs`, with Silero VAD, on the module without
threads and with `--threads 4` on the module with them.
- Never commit on main. Every change reaches main through a pull request, one coherent unit each: a
model's stage, a fix, a refactor or a documentation change.
- Commit messages and pull request titles are one English sentence in the imperative, without a prefix
Expand Down
44 changes: 31 additions & 13 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,19 @@ endif()
# for projects that read a 32-bit platform from it, and ggml compiles its SIMD128 code only for a processor named wasm;
# for any other it falls back to its generic C. ggml repacks weights only for instructions of x86, Arm and RISC-V,
# and its repacking code, never run in WebAssembly, was 50 KB of the 410 KB of a gzipped module of Silero VAD
# (Emscripten 7.0.0, 2026-11-21).
# (Emscripten 7.0.0, 2026-11-21). With SPEECH_WASM_THREADS every file, ggml's included, is compiled for threads, since
# wasm-ld links no file compiled without atomics into a module of shared memory.
if (EMSCRIPTEN)
option(SPEECH_WASM_THREADS "Build the WebAssembly library with threads, which a page runs only cross-origin isolated" OFF)
set(CMAKE_SYSTEM_PROCESSOR wasm32)
set(GGML_OPENMP OFF CACHE BOOL "" FORCE)
set(GGML_CPU_REPACK OFF CACHE BOOL "" FORCE)
add_compile_options(-fwasm-exceptions)
add_link_options(-fwasm-exceptions)
if (SPEECH_WASM_THREADS)
add_compile_options(-pthread)
add_link_options(-pthread)
endif()
endif()
# CI builds the submodule's ggml once, installs it with static libraries, and reuses it while the
# submodule's commit stays the same; Vulkan's shaders alone take minutes to compile.
Expand Down Expand Up @@ -277,15 +283,26 @@ foreach(family ${SPEECH_FAMILIES})
endforeach()
set_source_files_properties(src/api/speech.cpp PROPERTIES COMPILE_DEFINITIONS "${SPEECH_FAMILY_DEFINITIONS}")

# A WebAssembly build makes the C API once, as libspeech.js and libspeech.wasm, an ES module for a Worker that
# wasm/speech.mjs wraps, and nothing else: the executables and the checks run processes, terminals, devices and the
# network, which a browser does not give them. The module exports every function speech.h declares, and Emscripten's
# file system with WORKERFS, which reads a model from a Blob as it is asked, so that the weights are held once, in the
# module's memory. The memory grows as the model needs, up to the 4 GB a 32-bit address reaches. Emscripten gives the
# stack 64 KB, and ggml builds a graph by recursing once for each node of its longest chain: RE-USE's graph on 2 s of
# audio overflowed 64 KB and ran in 128 KB (Emscripten 7.0.0, 2026-11-21). The stack is 1 MB, as on Windows' main
# thread, the least the library runs on in a native build.
# A WebAssembly build makes the C API once, as libspeech.js and libspeech.wasm (libspeech-threads.js and .wasm with
# threads), an ES module for a Worker that wasm/speech.mjs wraps, and nothing else: the executables and the checks run
# processes, terminals, devices and the network, which a browser does not give them. The module exports every function
# speech.h declares, and Emscripten's file system with WORKERFS, which reads a model from a Blob as it is asked, so
# that the weights are held once, in the module's memory. The memory grows as the model needs, up to the 4 GB a
# 32-bit address reaches, or 1 GB with threads: Safari on iOS counts a shared memory's maximum against the memory of the
# process as it makes it, and refused one of 2 GB on iOS 16.2. The module with threads starts a Worker for each of the
# browser's logical processors before it runs, since a thread that the library starts while it computes would wait for
# a Worker to start, which it cannot until the module returns; a thread past them fails to start rather than waits.
# Emscripten gives the stack 64 KB, and ggml builds a graph by recursing once for each node of its longest chain:
# RE-USE's graph on 2 s of audio overflowed 64 KB and ran in 128 KB (Emscripten 7.0.0, 2026-11-21). The stack is 1 MB,
# as on Windows' main thread, the least the library runs on in a native build.
if (EMSCRIPTEN)
if (SPEECH_WASM_THREADS)
set(output libspeech-threads)
set(memory -sMAXIMUM_MEMORY=1GB -sPTHREAD_POOL_SIZE=navigator.hardwareConcurrency -sPTHREAD_POOL_SIZE_STRICT=2)
else()
set(output libspeech)
set(memory -sMAXIMUM_MEMORY=4GB)
endif()
file(STRINGS include/speech.h api_lines REGEX "^SPEECH_API .*speech_[a-z0-9_]+\\(")
set(exports _malloc _free)
foreach(line ${api_lines})
Expand All @@ -298,15 +315,16 @@ if (EMSCRIPTEN)
target_include_directories(speech-wasm PRIVATE include src/engines)
target_link_libraries(speech-wasm PRIVATE ${SPEECH_FAMILY_LIBRARIES})
target_compile_definitions(speech-wasm PRIVATE SPEECH_VERSION="${PROJECT_VERSION}")
set_target_properties(speech-wasm PROPERTIES OUTPUT_NAME libspeech SUFFIX .js)
set_target_properties(speech-wasm PROPERTIES OUTPUT_NAME ${output} SUFFIX .js)
target_link_options(speech-wasm PRIVATE
-sMODULARIZE -sEXPORT_ES6 -sENVIRONMENT=worker
-sALLOW_MEMORY_GROWTH -sMAXIMUM_MEMORY=4GB -sSTACK_SIZE=1MB
-sALLOW_MEMORY_GROWTH -sSTACK_SIZE=1MB ${memory}
-sEXPORTED_FUNCTIONS=${exports}
-sEXPORTED_RUNTIME_METHODS=FS,WORKERFS,UTF8ToString,stringToNewUTF8,HEAPU8,HEAP32,HEAPU32,HEAPF32,HEAPF64,HEAP64
-lworkerfs.js)
# The module that wraps the library and the page that tries it go beside it, as a release's archive holds them.
foreach(file speech.mjs wav.mjs worker.mjs page.mjs index.html)
# The module that wraps the library, the page that tries it and the server that serves the page cross-origin
# isolated go beside it, as a release's archive holds them.
foreach(file speech.mjs wav.mjs worker.mjs page.mjs index.html serve.py)
configure_file(wasm/${file} ${CMAKE_CURRENT_BINARY_DIR}/${file} COPYONLY)
endforeach()
return()
Expand Down
78 changes: 62 additions & 16 deletions checks/smoke/wasm_browser_smoke.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,27 @@
// option past what the C API takes, as errors naming the input rather than an abort or a value of another size, and
// answer the next request after them; a run must keep its model while another loads one. It prints the time to load
// the model, the RTFx of each file and the most memory the module held. The page is served from 127.0.0.1 with COOP and
// COEP, which the build with threads needs, and the files given at /files/. Chrome is the one at $CHROME, or macOS's;
// the server and Chrome are stopped however the script ends.
// usage: node checks/smoke/wasm_browser_smoke.mjs <speech> <wasm build dir> <detection model> <audio.wav>...
// COEP, which the build with threads needs, and the files given at /files/. With --threads N the page runs the build
// with threads on N threads, and audio of more than its 1 GB must be refused as out_of_memory before the module writes
// it, after which the module still answers. Chrome is the one at $CHROME, or macOS's; the server and Chrome are stopped
// however the script ends.
// usage: node checks/smoke/wasm_browser_smoke.mjs <speech> <wasm build dir> <detection model> <audio.wav>... [--threads N]
import { spawn, execFileSync } from 'node:child_process';
import fs from 'node:fs';
import http from 'node:http';
import os from 'node:os';
import path from 'node:path';

const [speech, build, model, ...audio] = process.argv.slice(2);
if (!audio.length) {
console.error('usage: node checks/smoke/wasm_browser_smoke.mjs <speech> <wasm build dir> <detection model> <audio.wav>...');
const argv = process.argv.slice(2);
const threadsAt = argv.indexOf('--threads');
const threads = threadsAt >= 0 ? Number(argv[threadsAt + 1]) : null;
if (threadsAt >= 0) argv.splice(threadsAt, 2);
const [speech, build, model, ...audio] = argv;
if (!audio.length || (threadsAt >= 0 && !(threads > 1))) {
console.error('usage: node checks/smoke/wasm_browser_smoke.mjs <speech> <wasm build dir> <detection model> <audio.wav>... [--threads N, 2 or more]');
process.exit(2);
}
const library = threads ? 'libspeech-threads' : 'libspeech';
const CHROME = process.env.CHROME ?? '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome';
const wait = (ms) => new Promise((r) => setTimeout(r, ms));

Expand Down Expand Up @@ -82,8 +89,10 @@ const running = [];
let ws = null;
let server = null;
try {
for (const file of ['libspeech.js', 'libspeech.wasm', 'speech.mjs', 'index.html']) {
if (!fs.existsSync(path.join(build, file))) throw new Error(`${build} has no ${file}; build it with emcmake cmake and cmake --build`);
for (const file of [`${library}.js`, `${library}.wasm`, 'speech.mjs', 'index.html']) {
if (!fs.existsSync(path.join(build, file))) {
throw new Error(`${build} has no ${file}; build it with emcmake cmake${threads ? ' -DSPEECH_WASM_THREADS=ON' : ''} and cmake --build`);
}
}
const lines = execFileSync(speech, ['vad', model, '--format', 'json', ...audio], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'inherit'] });
const native = lines.trim().split('\n').map((line) => JSON.parse(line).regions);
Expand Down Expand Up @@ -147,25 +156,29 @@ try {
if (!isolated) throw new Error('the page is not cross-origin isolated, though the server sends COOP and COEP');

const run = (args) => page(`return await speechPage.run(${args}).catch(failure);`);
const all = `{ model: ${JSON.stringify(urls[0])}, audio: ${JSON.stringify(urls.slice(1))} }`;
const on = threads ? `, threads: ${threads}` : '';
const all = `{ model: ${JSON.stringify(urls[0])}, audio: ${JSON.stringify(urls.slice(1))}${on} }`;
const first = await run(all);
if (first.error) throw new Error(`the page failed: ${JSON.stringify(first.error)}`);
const differs = departure(first.detections, native);
if (differs) throw new Error(differs);
console.log(`speech.cpp ${first.version}: the module started in ${first.open.toFixed(1)} ms, and ${first.info.name} `
+ `${first.info.weight_type} loaded in ${first.load.toFixed(1)} ms`);
if (first.info.threads !== (threads ?? 1)) throw new Error(`the model computes with ${first.info.threads} threads, where ${threads ?? 1} were asked for`);
console.log(`speech.cpp ${first.version}, ${library}: the module started in ${first.open.toFixed(1)} ms, and ${first.info.name} `
+ `${first.info.weight_type} loaded in ${first.load.toFixed(1)} ms on ${first.info.threads} threads`);
first.detections.forEach((d, f) => {
console.log(`${path.basename(audio[f])}: ${d.regions.length} regions as speech vad finds them, ${d.seconds.toFixed(2)} s of audio in `
+ `${d.ms.toFixed(1)} ms, RTFx ${(d.seconds / (d.ms / 1000)).toFixed(0)}`);
});
console.log(`the module's memory: ${(first.memory / 2 ** 20).toFixed(1)} MiB at most`);

const one = `audio: ${JSON.stringify(urls.slice(1, 2))}`;
const threads = await run(`{ model: ${JSON.stringify(urls[0])}, ${one}, threads: 2 }`);
if (threads.error?.status !== 'invalid_argument' || threads.error.option !== 'threads') {
throw new Error(`two threads in the build without threads: ${JSON.stringify(threads)}, where invalid_argument naming threads was due`);
const one = `audio: ${JSON.stringify(urls.slice(1, 2))}${on}`;
// One thread more than the build starts: 2 without threads, or one past the browser's logical processors with them.
const most = threads ? await page('return navigator.hardwareConcurrency;') : 1;
const many = await run(`{ model: ${JSON.stringify(urls[0])}, audio: ${JSON.stringify(urls.slice(1, 2))}, threads: ${most + 1}, threaded: ${!!threads} }`);
if (many.error?.status !== 'invalid_argument' || many.error.option !== 'threads') {
throw new Error(`${most + 1} threads in ${library}: ${JSON.stringify(many)}, where invalid_argument naming threads was due`);
}
console.log(`two threads refused: ${threads.error.status} (${threads.error.option}): ${threads.error.message}`);
console.log(`${most + 1} threads refused: ${many.error.status} (${many.error.option}): ${many.error.message}`);
// The model cut in half is loaded while a run of the whole one is under way, which must keep its own model. Both are
// Blobs at hand, so that the second load reaches the Worker before the first run's detection.
const [whole, cut] = await page(`
Expand All @@ -189,6 +202,39 @@ try {
}
console.log(`min_speech_duration_ms of ${value} refused: ${wide.error.status}: ${wide.error.message}`);
}
if (threads) {
// Audio past the 1 GB of the build with threads, in a Worker of its own, since the page reads audio from WAVE files:
// malloc() gives 0 for it, and the module must refuse it before it writes there, then answer the next request.
const big = await page(`
const source = 'import { openSpeech } from ' + JSON.stringify(location.origin + '/speech.mjs') + ';'
+ 'onmessage = async ({ data: { blob, threads } }) => {'
+ ' const speech = await openSpeech({ threads: true });'
+ ' const model = speech.load(blob, { threads });'
+ ' const failed = (e) => ({ status: e.status ?? null, message: e.message });'
+ ' let big;'
+ ' try { big = { regions: model.detect(new Float32Array(2 ** 28 + 2 ** 20), 16000) }; } catch (e) { big = failed(e); }'
+ ' let after;'
+ ' try { after = { regions: model.detect(new Float32Array(16000), 16000) }; } catch (e) { after = failed(e); }'
+ ' postMessage({ big, after, memory: speech.memory });'
+ '};';
const worker = new Worker(URL.createObjectURL(new Blob([source], { type: 'text/javascript' })), { type: 'module' });
const blob = await (await fetch(${JSON.stringify(urls[0])})).blob();
const answer = new Promise((resolve, reject) => {
worker.onmessage = ({ data }) => resolve(data);
worker.onerror = (e) => reject(new Error(e.message));
});
worker.postMessage({ blob, threads: ${threads} });
try {
return await answer;
} finally {
worker.terminate();
}
`);
if (big.big.status !== 'out_of_memory' || !big.after.regions || big.after.regions.length) {
throw new Error(`audio past 1 GB: ${JSON.stringify(big)}, where out_of_memory and then a second of silence without regions were due`);
}
console.log(`audio past 1 GB refused: ${big.big.status}: ${big.big.message}; a second of silence after it: no regions`);
}
const again = await run(`{ model: ${JSON.stringify(urls[0])}, ${one} }`);
if (again.error) throw new Error(`the page failed after the errors: ${JSON.stringify(again.error)}`);
const differsAgain = departure(again.detections, native.slice(0, 1));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,9 @@ catches, which in WebAssembly takes its exceptions: Chrome 95, Firefox 100 and S
Windows does not ship.
- **No CUDA build is released.**
- **Browsers have one archive** (`wasm`): the C API built with Emscripten for WebAssembly with SIMD128 and its
exceptions, with the module that calls it from a module Worker and a page that tries it, which Chrome 95, Firefox 114
and Safari 16.4 and later run. It runs on the CPU and holds the families that are checked in a browser.
exceptions, on one thread and with threads, with the module that calls it from a module Worker and a page that tries
it, which Chrome 95, Firefox 114 and Safari 16.4 and later run. It runs on the CPU and holds the families that are
checked in a browser.

The alternatives were turned down:

Expand Down
Loading
Loading