From f1f8fc8dc6c0a64ce743c1841686150f53c5dbc8 Mon Sep 17 00:00:00 2001 From: sakasegawa Date: Sat, 21 Nov 2026 01:01:49 +0900 Subject: [PATCH 1/3] Build the C API for WebAssembly and run Silero VAD in a browser The library now builds with Emscripten (emcmake cmake) into libspeech.js and libspeech.wasm, an ES module for a Worker that exports every function of speech.h, on ggml's CPU backend with SIMD128 and WebAssembly's exceptions. wasm/speech.mjs is the thin module that calls the C API from a Worker and reads a model from its Blob through WORKERFS, so that the weights are held once, in the module's memory; wasm/wav.mjs reads WAVE as src/common/wav.cpp does, and index.html, page.mjs and worker.mjs are a page that detects speech in a file. SPEECH_WASM_FAMILIES chooses the families of a WebAssembly build, Silero VAD by default: each family's library is made through speech_family() only where the build takes it, and the table of families keeps the line of each one marked SPEECH_FAMILY_. A native build takes every family as before. The build without threads refuses more than one thread at speech_load_params_set_threads(), where ggml would abort the module when its thread does not start. ggml's repacking code, never run in WebAssembly, is left out: 360 KB gzipped instead of 410 KB. checks/smoke/wasm_browser_smoke.mjs runs the page in a headless Chrome and fails unless the regions of each WAVE file are those speech vad finds, number for number, and unless two threads and a model cut in half are refused as errors of the C API, after which the next request still answers. The platform record now has the browser archive, and a new record says why the module runs in a Worker and reads a model through WORKERFS. docs/browser.md says how to use it and its limits and numbers. Checked: wasm_browser_smoke.mjs with Silero VAD F32 on seven WAVE files (the six inputs of reference/silero-vad's dumps, 16 kHz float, and a 48 kHz 16-bit recording): every region equal to speech vad's on the CPU; the smoke fails when speech vad is given another threshold. The page in Safari on the iOS 26.5 simulator gives the same regions. checks/run.py silero-vad on the CPU and Metal; speech-api-check with Qwen3-TTS 0.6B Q8_0, detect with Silero VAD and transcribe with reazonspeech-nemo-v2 F32; a WebAssembly build of every family links (936 KB gzipped). Apple M5, macOS 26.2, Chrome 158, Emscripten 7.0.0. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 18 +- CMakeLists.txt | 153 ++++++++---- README.ja.md | 1 + README.md | 1 + checks/smoke/wasm_browser_smoke.mjs | 189 +++++++++++++++ ...or-the-cpu-and-browsers-in-webassembly.md} | 18 +- ...-a-model-from-its-blob-through-workerfs.md | 44 ++++ docs/browser.md | 119 ++++++++++ docs/c-api.md | 8 +- docs/install.md | 1 + docs/models/silero-vad.md | 4 +- include/speech.h | 3 +- src/api/speech.cpp | 31 ++- src/common/backend.cpp | 13 +- src/common/backend.h | 9 +- wasm/index.html | 46 ++++ wasm/page.mjs | 118 ++++++++++ wasm/speech.mjs | 217 ++++++++++++++++++ wasm/wav.mjs | 62 +++++ wasm/worker.mjs | 39 ++++ 20 files changed, 1035 insertions(+), 59 deletions(-) create mode 100644 checks/smoke/wasm_browser_smoke.mjs rename docs/adr/{releases-run-on-macos-arm64-with-metal-windows-x64-with-vulkan-and-linux-x64-on-glibc-2.34-with-vulkan-or-the-cpu.md => releases-run-on-macos-arm64-with-metal-windows-x64-with-vulkan-linux-x64-on-glibc-2.34-with-vulkan-or-the-cpu-and-browsers-in-webassembly.md} (77%) create mode 100644 docs/adr/the-webassembly-build-runs-the-c-api-in-a-worker-and-reads-a-model-from-its-blob-through-workerfs.md create mode 100644 docs/browser.md create mode 100644 wasm/index.html create mode 100644 wasm/page.mjs create mode 100644 wasm/speech.mjs create mode 100644 wasm/wav.mjs create mode 100644 wasm/worker.mjs diff --git a/AGENTS.md b/AGENTS.md index 6c92aa67..7829a377 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -3,7 +3,7 @@ ## Project speech.cpp runs speech models in C++ on [ggml](https://github.com/ggml-org/ggml), on macOS arm64 with Metal, -Windows x64 with Vulkan and Linux x64 with Vulkan or the CPU alone, as a library with one C API, +Windows x64 with Vulkan and Linux x64 with Vulkan or the CPU alone, and in browsers as WebAssembly, as a library with one C API, `include/speech.h`, for any program that speaks text, recognizes speech or detects it: ASIST's worker, other tools, bindings and other people's applications. Each model's official implementation is the reference: every stage of a port is checked against tensors dumped from it. @@ -97,6 +97,12 @@ README.md and `docs/` are the documentation for users; what a developer needs is `served-models.cpp` holds one model of each task and replaces it once its requests have ended. `page/` is the page 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. - 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 @@ -108,8 +114,9 @@ README.md and `docs/` are the documentation for users; what a developer needs is `server_client.py`, which stops the server however the script ends, `server_page_browser_smoke.mjs` the page itself in a headless Chrome, as a person uses it, `server_openai_smoke.py` the server through the official openai-python client, - `speech_cli_smoke.py` the command line against the worker, and `models_smoke.py` the naming, fetching and removing of - models against a temporary model folder. A script that needs packages outside the standard library is a uv script + `speech_cli_smoke.py` the command line against the worker, `models_smoke.py` the naming, fetching and removing of + models against a temporary model folder, and `wasm_browser_smoke.mjs` the WebAssembly build through its page in a + headless Chrome against `speech vad`. A script that needs packages outside the standard library is a uv script with its dependencies pinned in the script and in a lock file beside it. - `reference//` holds, per model, a uv environment that pins the official code, PyTorch and the rest, `pins.py`, which pins the checkpoints by revision, the conversion of the official weights to one GGUF file per @@ -236,8 +243,9 @@ comment. `checks/smoke/worker_enhancement_smoke.py` with RE-USE; a change to the server runs `checks/smoke/server_smoke.py`, `checks/smoke/server_realtime_smoke.py`, `checks/smoke/server_diarization_smoke.py`, `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, and one to `tools/catalog/` - `checks/smoke/models_smoke.py`. + 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. - 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 diff --git a/CMakeLists.txt b/CMakeLists.txt index bb52806a..4c06d571 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -13,7 +13,23 @@ endif() # ggml is linked in statically, so that a release is speech beside the shared libspeech and needs no library of ggml. option(BUILD_SHARED_LIBS "Build ggml as shared libraries" OFF) # The shared libspeech links the same static libraries as the executables. -set(CMAKE_POSITION_INDEPENDENT_CODE ON) +if (NOT EMSCRIPTEN) + set(CMAKE_POSITION_INDEPENDENT_CODE ON) +endif() +# A build configured with Emscripten's emcmake is the library alone, as WebAssembly for a page's Worker (wasm/). Its C++ +# throws and catches as every build does, with WebAssembly's exceptions, which Chrome 95, Firefox 100 and Safari 15.2 +# and later run; without them Emscripten aborts at the first throw. Emscripten's toolchain names the processor x86, +# 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). +if (EMSCRIPTEN) + 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) +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. option(SPEECH_INSTALLED_GGML "Link a ggml installed from the submodule, found through CMAKE_PREFIX_PATH" OFF) @@ -70,7 +86,41 @@ if (WIN32) target_link_libraries(speechcommon PUBLIC shell32) endif() -add_library(qwen3tts STATIC +# The families the library runs, by their folders in src/families/, each with its engine, src/engines/-engine.cpp. +# A WebAssembly build takes the ones SPEECH_WASM_FAMILIES names, so that a page fetches the code of the models it runs +# and no more; every other build takes them all, which speech and the checks need. +set(SPEECH_ALL_FAMILIES qwen3-tts irodori-tts drama3 haru fastconformer qwen3-asr nemotron-transcribe silero-vad sortformer semamba) +if (EMSCRIPTEN) + set(SPEECH_WASM_FAMILIES silero-vad CACHE STRING "The families of the WebAssembly build, by their folders in src/families/, or all") + if (SPEECH_WASM_FAMILIES STREQUAL "all") + set(SPEECH_FAMILIES ${SPEECH_ALL_FAMILIES}) + else() + set(SPEECH_FAMILIES ${SPEECH_WASM_FAMILIES}) + endif() + if (NOT SPEECH_FAMILIES) + message(FATAL_ERROR "SPEECH_WASM_FAMILIES names no family; name one or more of ${SPEECH_ALL_FAMILIES}, or all") + endif() + foreach(family ${SPEECH_FAMILIES}) + if (NOT family IN_LIST SPEECH_ALL_FAMILIES) + message(FATAL_ERROR "SPEECH_WASM_FAMILIES names ${family}, which is not a family; the families are ${SPEECH_ALL_FAMILIES}, or all") + endif() + endforeach() +else() + set(SPEECH_FAMILIES ${SPEECH_ALL_FAMILIES}) +endif() +# A family's code is the library of its folder's name without dashes, made only where the build takes the family. Code +# names the family in its includes ("qwen3-tts/codec.h"), since several families have a codec.h. +function(speech_family family) + if (NOT family IN_LIST SPEECH_FAMILIES) + return() + endif() + string(REPLACE "-" "" target ${family}) + add_library(${target} STATIC ${ARGN}) + target_include_directories(${target} PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/src/families) + target_link_libraries(${target} PUBLIC speechcommon) +endfunction() + +speech_family(qwen3-tts src/families/qwen3-tts/layout.cpp src/families/qwen3-tts/codec.cpp src/families/qwen3-tts/talker.cpp @@ -79,11 +129,8 @@ add_library(qwen3tts STATIC src/families/qwen3-tts/graph-sampler.cpp src/families/qwen3-tts/synthesizer.cpp ) -# Code names the family in its includes ("qwen3-tts/codec.h"), since both families have a codec.h. -target_include_directories(qwen3tts PUBLIC src/families) -target_link_libraries(qwen3tts PUBLIC speechcommon) -add_library(irodoritts STATIC +speech_family(irodori-tts src/families/irodori-tts/layout.cpp src/families/irodori-tts/text-normalizer.cpp src/families/irodori-tts/tokenizer.cpp @@ -99,11 +146,9 @@ add_library(irodoritts STATIC src/families/irodori-tts/synthesizer.cpp src/families/irodori-tts/voice-file.cpp ) -target_include_directories(irodoritts PUBLIC src/families) -target_link_libraries(irodoritts PUBLIC speechcommon) # FastConformer speech recognition (NVIDIA NeMo): the family. -add_library(fastconformer STATIC +speech_family(fastconformer src/families/fastconformer/layout.cpp src/families/fastconformer/encoder.cpp src/families/fastconformer/transducer.cpp @@ -122,11 +167,9 @@ add_library(fastconformer STATIC src/families/fastconformer/vocabulary.cpp src/families/fastconformer/guard.cpp ) -target_include_directories(fastconformer PUBLIC src/families) -target_link_libraries(fastconformer PUBLIC speechcommon) # Qwen3-ASR speech recognition (Qwen): the family. -add_library(qwen3asr STATIC +speech_family(qwen3-asr src/families/qwen3-asr/layout.cpp src/families/qwen3-asr/frontend.cpp src/families/qwen3-asr/encoder.cpp @@ -137,47 +180,41 @@ add_library(qwen3asr STATIC src/families/qwen3-asr/split.cpp src/families/qwen3-asr/recognizer.cpp ) -target_include_directories(qwen3asr PUBLIC src/families) -target_link_libraries(qwen3asr PUBLIC speechcommon) # Silero VAD speech detection (Silero Team): the family. -add_library(silerovad STATIC +speech_family(silero-vad src/families/silero-vad/layout.cpp src/families/silero-vad/network.cpp src/families/silero-vad/regions.cpp src/families/silero-vad/detector.cpp ) -target_include_directories(silerovad PUBLIC src/families) -target_link_libraries(silerovad PUBLIC speechcommon) -add_library(sortformer STATIC +speech_family(sortformer src/families/sortformer/layout.cpp src/families/sortformer/segments.cpp src/families/sortformer/diarizer.cpp ) -target_include_directories(sortformer PUBLIC src/families) -target_link_libraries(sortformer PUBLIC speechcommon) # The speaker cache's scores and the segments' times are float32 arithmetic whose roundings decide which frames the cache # keeps and whether two padded segments meet, rounded after each operation as torch rounds them: a fused multiply-add # moves a value by a unit in its last place. GCC fuses across statements by default and Clang within one; MSVC's # /fp:precise does not fuse. if (NOT MSVC) - target_compile_options(sortformer PRIVATE -ffp-contract=off) set_source_files_properties(src/common/sortformer-cache.cpp PROPERTIES COMPILE_OPTIONS -ffp-contract=off) + if (TARGET sortformer) + target_compile_options(sortformer PRIVATE -ffp-contract=off) + endif() endif() # NVIDIA NemotronLabs RE-USE speech enhancement (NVIDIA): the family of SEMamba. -add_library(semamba STATIC +speech_family(semamba src/families/semamba/layout.cpp src/families/semamba/stft.cpp src/families/semamba/network.cpp src/families/semamba/enhancer.cpp ) -target_include_directories(semamba PUBLIC src/families) -target_link_libraries(semamba PUBLIC speechcommon) # NVIDIA Nemotron 3.5 Transcribe speech recognition (NVIDIA): the family. -add_library(nemotrontranscribe STATIC +speech_family(nemotron-transcribe src/families/nemotron-transcribe/layout.cpp src/families/nemotron-transcribe/tokenizer.cpp src/families/nemotron-transcribe/encoder.cpp @@ -192,15 +229,13 @@ add_library(nemotrontranscribe STATIC src/families/nemotron-transcribe/alignment.cpp src/families/nemotron-transcribe/timing.cpp ) -target_include_directories(nemotrontranscribe PUBLIC src/families) # The alignment computes as NumPy and PyTorch do, every product and sum rounded on its own. if(NOT MSVC) set_source_files_properties(src/families/nemotron-transcribe/alignment.cpp PROPERTIES COMPILE_OPTIONS -ffp-contract=off) endif() -target_link_libraries(nemotrontranscribe PUBLIC speechcommon) # Fish Audio Drama 3 speech synthesis (Fish Audio): the family. -add_library(drama3 STATIC +speech_family(drama3 src/families/drama3/layout.cpp src/families/drama3/codec.cpp src/families/drama3/sampler.cpp @@ -212,11 +247,9 @@ add_library(drama3 STATIC src/families/drama3/voice-file.cpp src/families/drama3/placement.cpp ) -target_include_directories(drama3 PUBLIC src/families) -target_link_libraries(drama3 PUBLIC speechcommon) # Haru full-duplex spoken dialogue (higurashi): the family. -add_library(haru STATIC +speech_family(haru src/families/haru/layout.cpp src/families/haru/codec.cpp src/families/haru/head.cpp @@ -226,25 +259,65 @@ add_library(haru STATIC src/families/haru/dialogue.cpp src/families/haru/voice-file.cpp ) -target_include_directories(haru PUBLIC src/families) -target_link_libraries(haru PUBLIC speechcommon) # The C API, include/speech.h, twice: static for the executables, so that each stays one file, and shared as # libspeech for bindings and other programs. On Windows the two would both write speech.lib, the static one as -# the library and the shared one as its import library, hence speech-static. -set(SPEECH_SOURCES src/api/speech.cpp src/api/info.cpp src/api/request.cpp src/api/detection.cpp src/api/diarization.cpp src/api/enhancement.cpp src/api/dialogue.cpp src/api/voice.cpp - src/engines/qwen3-tts-engine.cpp src/engines/irodori-tts-engine.cpp src/engines/drama3-engine.cpp src/engines/fastconformer-engine.cpp - src/engines/qwen3-asr-engine.cpp src/engines/nemotron-transcribe-engine.cpp src/engines/silero-vad-engine.cpp src/engines/sortformer-engine.cpp - src/engines/semamba-engine.cpp src/engines/haru-engine.cpp) +# the library and the shared one as its import library, hence speech-static. The table of families in +# src/api/speech.cpp holds the line of each family the build takes, which SPEECH_FAMILY_ marks. +set(SPEECH_SOURCES src/api/speech.cpp src/api/info.cpp src/api/request.cpp src/api/detection.cpp src/api/diarization.cpp src/api/enhancement.cpp src/api/dialogue.cpp src/api/voice.cpp) +set(SPEECH_FAMILY_LIBRARIES "") +set(SPEECH_FAMILY_DEFINITIONS "") +foreach(family ${SPEECH_FAMILIES}) + list(APPEND SPEECH_SOURCES src/engines/${family}-engine.cpp) + string(REPLACE "-" "" library ${family}) + list(APPEND SPEECH_FAMILY_LIBRARIES ${library}) + string(MAKE_C_IDENTIFIER "SPEECH_FAMILY_${family}" definition) + string(TOUPPER ${definition} definition) + list(APPEND SPEECH_FAMILY_DEFINITIONS ${definition}) +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. +if (EMSCRIPTEN) + file(STRINGS include/speech.h api_lines REGEX "^SPEECH_API .*speech_[a-z0-9_]+\\(") + set(exports _malloc _free) + foreach(line ${api_lines}) + string(REGEX MATCH "speech_[a-z0-9_]+\\(" name "${line}") + string(REPLACE "(" "" name "${name}") + list(APPEND exports _${name}) + endforeach() + list(JOIN exports "," exports) + add_executable(speech-wasm ${SPEECH_SOURCES}) + 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) + target_link_options(speech-wasm PRIVATE + -sMODULARIZE -sEXPORT_ES6 -sENVIRONMENT=worker + -sALLOW_MEMORY_GROWTH -sMAXIMUM_MEMORY=4GB + -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) + configure_file(wasm/${file} ${CMAKE_CURRENT_BINARY_DIR}/${file} COPYONLY) + endforeach() + return() +endif() add_library(speech-static STATIC ${SPEECH_SOURCES}) target_include_directories(speech-static PUBLIC include PRIVATE src/engines) -target_link_libraries(speech-static PUBLIC qwen3tts irodoritts drama3 haru fastconformer qwen3asr nemotrontranscribe silerovad sortformer semamba) +target_link_libraries(speech-static PUBLIC ${SPEECH_FAMILY_LIBRARIES}) target_compile_definitions(speech-static PRIVATE SPEECH_VERSION="${PROJECT_VERSION}") add_library(speech SHARED ${SPEECH_SOURCES}) target_include_directories(speech PUBLIC include PRIVATE src/engines) -target_link_libraries(speech PRIVATE qwen3tts irodoritts drama3 haru fastconformer qwen3asr nemotrontranscribe silerovad sortformer semamba) +target_link_libraries(speech PRIVATE ${SPEECH_FAMILY_LIBRARIES}) target_compile_definitions(speech PRIVATE SPEECH_BUILD_SHARED SPEECH_VERSION="${PROJECT_VERSION}" INTERFACE SPEECH_SHARED) set_target_properties(speech PROPERTIES C_VISIBILITY_PRESET hidden CXX_VISIBILITY_PRESET hidden VISIBILITY_INLINES_HIDDEN ON) # The shared library's SOVERSION is the C API's major version, which speech.h defines and nothing else repeats. diff --git a/README.ja.md b/README.ja.md index 15bbb6fb..bff1fb86 100644 --- a/README.ja.md +++ b/README.ja.md @@ -219,6 +219,7 @@ FastConformer のモデル(parakeet、ReazonSpeech、Haas-ja-v1.0)は、2026-10- | [Server and page](docs/server.md) | `speech serve` と OpenAI の音声 API | | [Worker protocol](docs/worker.md) | プログラムから使う `speech worker` | | [C API](docs/c-api.md) | `speech.h` | +| [Browser](docs/browser.md) | WebAssembly のビルド。ウェブページの中で Silero VAD を動かす | ## ライセンス diff --git a/README.md b/README.md index feb06766..b01a5878 100644 --- a/README.md +++ b/README.md @@ -252,6 +252,7 @@ more. | [Server and page](docs/server.md) | `speech serve` and OpenAI's audio API | | [Worker protocol](docs/worker.md) | `speech worker` for programs | | [C API](docs/c-api.md) | `speech.h` | +| [Browser](docs/browser.md) | the WebAssembly build: Silero VAD inside a web page | ## License diff --git a/checks/smoke/wasm_browser_smoke.mjs b/checks/smoke/wasm_browser_smoke.mjs new file mode 100644 index 00000000..65a843cf --- /dev/null +++ b/checks/smoke/wasm_browser_smoke.mjs @@ -0,0 +1,189 @@ +// Runs the WebAssembly build of speech.cpp in a headless Chrome through its page (wasm/index.html), as a script drives +// it, and fails on a defect: the regions where someone speaks in each WAVE file must be those `speech vad` finds in it on +// the CPU, number for number; the build must refuse more threads than it starts, and a model file cut short, as errors +// of the C API naming the input rather than an abort, and answer the next request after both. 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 ... +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 ...'); + process.exit(2); +} +const CHROME = process.env.CHROME ?? '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'; +const wait = (ms) => new Promise((r) => setTimeout(r, ms)); + +/** A child process, and a promise that rejects when it cannot start or exits before it is stopped. */ +function start(command, args, options) { + const child = spawn(command, args, options); + let stopping = false; + const failed = new Promise((_, reject) => { + child.on('error', (e) => reject(new Error(`${command} could not start: ${e.message}`))); + child.on('exit', (code) => stopping || reject(new Error(`${command} exited with ${code}`))); + }); + failed.catch(() => {}); + return { child, failed, stop: () => ((stopping = true), child.kill()) }; +} + +/** `promise`, or the first failure of `processes`, or a timeout. */ +function racing(promise, processes, ms, what) { + let timer; + const timeout = new Promise((_, reject) => (timer = setTimeout(() => reject(new Error(`timed out waiting for ${what}`)), ms))); + return Promise.race([promise, timeout, ...processes.map((p) => p.failed)]).finally(() => clearTimeout(timer)); +} + +const types = { '.html': 'text/html', '.js': 'text/javascript', '.mjs': 'text/javascript', '.wasm': 'application/wasm' }; + +/** Serves the build's files at / and `files` at /files//, cross-origin isolated. */ +function serve(files) { + const root = path.resolve(build); + return http.createServer((request, response) => { + const url = decodeURIComponent(new URL(request.url, 'http://x').pathname); + const given = /^\/files\/(\d+)\//.exec(url); + const file = given ? files[Number(given[1])] : path.join(root, url === '/' ? 'index.html' : url); + if (!file || (!given && !file.startsWith(root + path.sep)) || !fs.existsSync(file) || !fs.statSync(file).isFile()) { + response.writeHead(404).end(); + return; + } + response.writeHead(200, { + 'Content-Type': types[path.extname(file)] ?? 'application/octet-stream', + 'Cross-Origin-Opener-Policy': 'same-origin', + 'Cross-Origin-Embedder-Policy': 'require-corp', + 'Cache-Control': 'no-store', + }); + fs.createReadStream(file).pipe(response); + }); +} + +/** Where `got`, the page's regions of each file, departs from `expected`, `speech vad`'s, or null where it does not. */ +function departure(got, expected) { + for (let f = 0; f < expected.length; f++) { + const [g, e] = [got[f].regions, expected[f]]; + for (let i = 0; i < Math.max(g.length, e.length); i++) { + if (g[i]?.start !== e[i]?.start || g[i]?.end !== e[i]?.end) { + return `${audio[f]}: region ${i + 1} is ${JSON.stringify(g[i] ?? null)} in the page and ${JSON.stringify(e[i] ?? null)} in speech vad ` + + `(${g.length} and ${e.length} regions)`; + } + } + } + return null; +} + +const profile = fs.mkdtempSync(path.join(os.tmpdir(), 'wasm-smoke-chrome-')); +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`); + } + 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); + + const files = [model, ...audio].map((f) => path.resolve(f)); + server = serve(files); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + const origin = `http://127.0.0.1:${server.address().port}`; + const urls = files.map((f, i) => `/files/${i}/${encodeURIComponent(path.basename(f))}`); + + const chrome = start(CHROME, ['--headless=new', '--remote-debugging-port=0', `--user-data-dir=${profile}`, '--no-first-run'], { stdio: 'ignore' }); + running.push(chrome); + const port = await racing((async () => { + for (;;) { + try { + return fs.readFileSync(path.join(profile, 'DevToolsActivePort'), 'utf8').split('\n')[0]; + } catch { + // Chrome writes the file once it listens. + await wait(100); + } + } + })(), [chrome], 30000, 'Chrome to listen'); + const targets = await (await fetch(`http://127.0.0.1:${port}/json/list`)).json(); + ws = new WebSocket(targets.find((t) => t.type === 'page').webSocketDebuggerUrl); + await racing(new Promise((resolve) => ws.addEventListener('open', resolve)), [chrome], 30000, 'Chrome\'s page'); + let id = 0; + const pending = new Map(); + const errors = []; + ws.addEventListener('message', (event) => { + const message = JSON.parse(event.data); + if (message.id && pending.has(message.id)) { + pending.get(message.id)(message); + pending.delete(message.id); + } else if (message.method === 'Runtime.exceptionThrown') { + errors.push(message.params.exceptionDetails.exception?.description ?? message.params.exceptionDetails.text); + } + }); + const send = (method, params = {}) => racing(new Promise((resolve) => { + const n = ++id; + pending.set(n, resolve); + ws.send(JSON.stringify({ id: n, method, params })); + }), running, 300000, method); + /** The value of `body`, an async function's body, run in the page; a run's error comes back as { error }. */ + const page = async (body) => { + const expression = `(async () => { + const failure = (e) => ({ error: { status: e.status ?? null, option: e.option ?? null, message: e.message } }); + ${body} + })()`; + const r = await send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true }); + if (r.result?.exceptionDetails) throw new Error(r.result.exceptionDetails.exception?.description ?? JSON.stringify(r.result.exceptionDetails)); + return r.result?.result?.value; + }; + + await send('Runtime.enable'); + await send('Page.enable'); + await send('Page.navigate', { url: `${origin}/index.html` }); + await racing((async () => { + while (!(await page('return !!window.speechPage;'))) await wait(100); + })(), running, 30000, 'the page'); + const isolated = await page('return crossOriginIsolated;'); + 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 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`); + 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`); + } + console.log(`two threads refused: ${threads.error.status} (${threads.error.option}): ${threads.error.message}`); + const cut = await page(` + const whole = await (await fetch(${JSON.stringify(urls[0])})).blob(); + const model = new File([whole.slice(0, Math.floor(whole.size / 2))], 'cut.gguf'); + return await speechPage.run({ model, ${one} }).catch(failure); + `); + if (cut.error?.status !== 'model_file') throw new Error(`a model cut in half: ${JSON.stringify(cut)}, where model_file was due`); + console.log(`a model cut in half refused: ${cut.error.status}: ${cut.error.message}`); + 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)); + if (differsAgain) throw new Error(`after the errors, ${differsAgain}`); + console.log('the next request after both: the same regions'); + + if (errors.length) throw new Error(`the page threw: ${errors.join('; ')}`); + console.log('ok'); +} finally { + ws?.close(); + server?.close(); + for (const child of running.reverse()) child.stop(); + await wait(500); + fs.rmSync(profile, { recursive: true, force: true, maxRetries: 5, retryDelay: 200 }); +} diff --git a/docs/adr/releases-run-on-macos-arm64-with-metal-windows-x64-with-vulkan-and-linux-x64-on-glibc-2.34-with-vulkan-or-the-cpu.md b/docs/adr/releases-run-on-macos-arm64-with-metal-windows-x64-with-vulkan-linux-x64-on-glibc-2.34-with-vulkan-or-the-cpu-and-browsers-in-webassembly.md similarity index 77% rename from docs/adr/releases-run-on-macos-arm64-with-metal-windows-x64-with-vulkan-and-linux-x64-on-glibc-2.34-with-vulkan-or-the-cpu.md rename to docs/adr/releases-run-on-macos-arm64-with-metal-windows-x64-with-vulkan-linux-x64-on-glibc-2.34-with-vulkan-or-the-cpu-and-browsers-in-webassembly.md index 2ac10d73..565642c0 100644 --- a/docs/adr/releases-run-on-macos-arm64-with-metal-windows-x64-with-vulkan-and-linux-x64-on-glibc-2.34-with-vulkan-or-the-cpu.md +++ b/docs/adr/releases-run-on-macos-arm64-with-metal-windows-x64-with-vulkan-linux-x64-on-glibc-2.34-with-vulkan-or-the-cpu-and-browsers-in-webassembly.md @@ -1,9 +1,10 @@ -# Releases run on macOS arm64 with Metal, Windows x64 with Vulkan, and Linux x64 on glibc 2.34 with Vulkan or the CPU +# Releases run on macOS arm64 with Metal, Windows x64 with Vulkan, Linux x64 on glibc 2.34 with Vulkan or the CPU, and browsers in WebAssembly ## Context A release is one archive per platform, `speech--.zip`, holding `speech`, `libspeech` and `speech.h`, -which CI builds and checks on every run. Vulkan runs the GPUs of NVIDIA, AMD and Intel, NVIDIA's at the speeds +or for a browser the library in WebAssembly, which CI builds and checks on every run. Callers such as ASIST pin an +archive by its SHA-256. Vulkan runs the GPUs of NVIDIA, AMD and Intel, NVIDIA's at the speeds docs/models/ lists for an RTX 2080, and on Windows every GPU driver of the three installs the Vulkan loader, `vulkan-1.dll`. @@ -15,6 +16,10 @@ other functions glibc 2.34 moved into libc), and nothing from 2.35. The Linux Vu need glibc 2.34 and GCC 11's libstdc++ (`GLIBCXX_3.4.29`). GitHub retired its Ubuntu 20.04 runners in April 2025; `ubuntu-22.04` is the oldest it hosts. +A browser runs a page's code as WebAssembly on the CPU, in a memory of the page's own, and runs ggml's SIMD128 code +where it runs WebAssembly's 128-bit SIMD: Chrome 91, Firefox 89 and Safari 16.4 and later. speech.cpp's C++ throws and +catches, which in WebAssembly takes its exceptions: Chrome 95, Firefox 100 and Safari 15.2 and later. + ## Decision - **macOS arm64 with Metal** (`macos-arm64-metal`) is the one macOS build. An Intel Mac builds from source. @@ -35,6 +40,9 @@ need glibc 2.34 and GCC 11's libstdc++ (`GLIBCXX_3.4.29`). GitHub retired its Ub that needs another. MSVC's OpenMP runtime, `vcomp140.dll`, comes only with the Visual C++ Redistributable, which 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. The alternatives were turned down: @@ -59,10 +67,14 @@ The alternatives were turned down: - A CUDA build. It would carry cuBLAS, several hundred megabytes, or require the user's CUDA toolkit to match, would tie the binary to a range of NVIDIA drivers, and would put the CUDA toolkit and its kernel compilation into CI. It stays a build from source (`-DGGML_CUDA=ON`). +- Leaving the WebAssembly build to be built from source with Emscripten. Every page would build a module of its own, + with its own Emscripten, and none would be the module that CI checks and that a caller can pin by its SHA-256 as it + pins the other archives. ## Consequences A CPU without AVX2 is not supported by any release, and a Mac with an Intel CPU, a system of another architecture and a -Linux system with musl build from source. The installers pick the archive from these rules. When GitHub retires +Linux system with musl build from source; a browser without WebAssembly's SIMD128 runs no release. The installers pick +the archive from these rules and leave out the WebAssembly one, which a page serves. When GitHub retires `ubuntu-22.04`, the Linux jobs move to the next image, and the glibc check shows at once whether the floor moves; the floor in the workflow, the installer, README.md, docs/install.md, AGENTS.md and this record then change together. diff --git a/docs/adr/the-webassembly-build-runs-the-c-api-in-a-worker-and-reads-a-model-from-its-blob-through-workerfs.md b/docs/adr/the-webassembly-build-runs-the-c-api-in-a-worker-and-reads-a-model-from-its-blob-through-workerfs.md new file mode 100644 index 00000000..1c8c89c8 --- /dev/null +++ b/docs/adr/the-webassembly-build-runs-the-c-api-in-a-worker-and-reads-a-model-from-its-blob-through-workerfs.md @@ -0,0 +1,44 @@ +# The WebAssembly build runs the C API in a Worker and reads a model from its Blob through WORKERFS + +## Context + +A page that runs speech.cpp keeps the audio in the browser. The C API blocks until a request ends and loads a model +from a path, while a browser gives a page no file system of its own and a model only as a Blob: a File a person +chooses, or the body of a fetch. A page's memory is one WebAssembly memory of at most 4 GB, which a phone's browser +gives less of, and a page downloads every byte of the module before it runs. The library reads a model file with +`fread()` a piece at a time and copies each tensor into its buffer. + +## Decision + +- **The library is the C API compiled whole** with Emscripten, every function of `speech.h` exported, as an ES module + that runs in a Worker. `wasm/speech.mjs` is a thin module over it in the Worker: it loads a model, runs a request + and turns a status into an error with the library's message and the input at fault. It adds no behavior of its own, + so what the C API checks and refuses, a page meets the same way. +- **A model is read from its Blob through Emscripten's WORKERFS**, which gives the library a file whose reads come from + the Blob as the library asks. The library reads it as it reads a file on a disk, and the weights are held once, in the + module's memory. +- **The families a module holds are chosen when it is built** (`SPEECH_WASM_FAMILIES`), each a line of the table of + families that the build keeps or leaves out, so that a page downloads the code of the models it runs and no more. + Silero VAD's module is 360 KB gzipped, and one of every family 936 KB (Emscripten 7.0.0, 2026-11-21). +- **The module without threads refuses more than one** at `speech_load_params_set_threads()`, where ggml would abort + the module when the thread it starts does not. +- **A WAVE file is read in JavaScript as the library reads one** (`wasm/wav.mjs`), since the C API takes samples, so + that a page and `speech` give a model the same samples of the same file. + +The alternatives were turned down: + +- Emscripten's MEMFS, a file system in the module's memory. The file is copied into it whole before the library + reads it, and the module holds the model twice while it loads, the file and the weights made from it. +- A function of the C API that loads a model from bytes in memory. The bytes are in the module's memory while the + weights are made from them, twice as with MEMFS, and the C API would have a second way to load a model for one + platform. +- The module on the page's own thread. Each call would stop the page until it returned, and WORKERFS reads a Blob with + `FileReaderSync`, which only a Worker has. +- A JavaScript API of its own, with promises and its own names for options and errors. It would be a second API to + keep in step with `speech.h` and to document, and a binding of the C API in any other language would differ from it. + +## Consequences + +A page starts a Worker for the module and talks to it with messages of its own. The Blob of a loaded model must not +change while the model is loaded. A family is in a module only when it is built in, and a model of another family is +refused as a model file of an architecture the build does not run. diff --git a/docs/browser.md b/docs/browser.md new file mode 100644 index 00000000..0dc4a365 --- /dev/null +++ b/docs/browser.md @@ -0,0 +1,119 @@ +# Browser + +This page describes speech.cpp's WebAssembly build, which runs the C API inside a web page, so that the audio never +leaves the browser. It holds Silero VAD, which finds where someone speaks in a recording. + +## What it is + +| File | What it is | +|---|---| +| `libspeech.js`, `libspeech.wasm` | the library: the C API compiled to WebAssembly, an ES module for a Worker | +| `speech.mjs` | the module a Worker imports to load a model and run requests | +| `wav.mjs` | reads a WAVE file into samples as `speech` reads it | +| `index.html`, `page.mjs`, `worker.mjs` | a page that finds the regions of speech in a WAVE file you choose | + +It runs on the CPU, on one thread, in Chrome and Edge 95, Firefox 114 and Safari 16.4 and later, on phones too. + +## Try the page + +Serve the folder over HTTP, since a page opened from a file cannot load modules, and open it: + +```sh +cd build-wasm +python3 -m http.server 8000 +``` + +Open , choose the model, `silero-vad-309K-v6.2-F32.gguf` (`speech pull silero-vad` fetches it, +or take it from [Hugging Face](https://huggingface.co/sakasegawa/silero-vad-GGUF)), and a WAVE file, and press +**Detect speech**. The page shows each region, the load time, the RTFx and the module's memory. A link can name both +files on the same server: `index.html?model=silero-vad-309K-v6.2-F32.gguf&audio=meeting.wav` runs as it opens. + +## Use it in a page + +The library runs in a Worker. A module Worker of your page: + +```js +import { openSpeech } from './speech.mjs'; +import { readWav } from './wav.mjs'; + +const speech = await openSpeech(); +onmessage = async ({ data: { model, audio } }) => { // a File or Blob of the model, and of a WAVE file + const m = speech.load(model); + const { sampleRate, samples } = readWav(await audio.arrayBuffer(), audio.name); + postMessage(m.detect(samples, sampleRate, { min_silence_duration_ms: 500 })); // [{ start, end }] in seconds + m.free(); +}; +``` + +and the page: + +```js +const worker = new Worker(new URL('./my-worker.mjs', import.meta.url), { type: 'module' }); +worker.onmessage = ({ data }) => console.log(data); +worker.postMessage({ model: modelInput.files[0], audio: audioInput.files[0] }); +``` + +| In `speech.mjs` | What it does | +|---|---| +| `await openSpeech()` | loads `libspeech.js` and `libspeech.wasm` from beside `speech.mjs` | +| `speech.version` | the release, as `speech_version()` gives it | +| `speech.memory` | the bytes of the module's memory, which grows as needed and never shrinks | +| `speech.load(blob, { threads })` | loads a model from a Blob or File, as `speech_model_load()` does | +| `model.info` | the model's information, the JSON `speech info --json` prints | +| `model.detect(samples, sampleRate, options)` | the regions of a `Float32Array` of mono samples at any rate, with the request options of [Silero VAD](models/silero-vad.md#options) by name | +| `model.free()` | frees the model | + +Every call blocks the Worker until the library returns. A failure throws a `SpeechError` with the C API's `status` +(`invalid_argument`, `model_file`, …), its `message`, and the `option` at fault, or null. + +## Limits + +- **A Worker.** The library runs in a Worker, not on the page's own thread: its calls block, and it reads a model from + its Blob with `FileReaderSync`, which a Worker alone has. +- **The model is read from its Blob.** The library reads the file a piece at a time as it loads, and holds the weights + once, in the module's memory. The Blob must not change while the model is loaded. A model the page fetches is a Blob + the browser keeps as well. +- **4 GB.** The module's memory grows as a model and its requests need, up to 4 GB, the most a 32-bit WebAssembly + address reaches; a phone's browser gives a page less. A request copies its audio into the module's memory, beside + the Worker's `Float32Array`. +- **One thread.** The library computes on one thread and refuses `threads` above 1 as `invalid_argument`. +- **Silero VAD alone.** A model of another family is refused as `model_file`, a model of an architecture this build + does not run. + +## Size and speed + +Silero VAD F32 on an Apple M5 (macOS 26.2) in headless Chrome 158, built with Emscripten 7.0.0, 2026-11-21: + +| | | +|---|---| +| `libspeech.wasm`, gzipped | 360 KB (1.1 MB as it is) | +| `libspeech.js`, gzipped | 18 KB | +| the module started, from the same machine | 6 ms | +| load time | 9 ms | +| a minute of audio, the first request after loading | 0.12 s, an RTFx of 490 | +| a minute of audio, the later requests | 0.09 s, an RTFx of 670 | +| the module's memory, at most | 28.6 MiB | + +The first request is slower because the browser compiles the module's code again, faster, once it runs often. `speech +vad` on the same CPU with one thread takes 0.089 s, an RTFx of 675. The page gives the regions `speech vad` gives, number +for number, in Chrome and in Safari on iOS 26.5. + +## Build it + +The build needs [Emscripten](https://emscripten.org/) 7.0.0, through emsdk: + +```sh +git clone https://github.com/emscripten-core/emsdk.git +cd emsdk +git checkout 7.0.0 +./emsdk install 7.0.0 +./emsdk activate 7.0.0 +source ./emsdk_env.sh +cd ../speech.cpp +emcmake cmake -B build-wasm +cmake --build build-wasm -j +``` + +It makes `build-wasm/libspeech.js`, `libspeech.wasm` and the files beside them in the table above. +`-DSPEECH_WASM_FAMILIES="silero-vad;qwen3-asr"` builds other families in, by their folders in `src/families/`, or +`all`; each adds to the module, and only Silero VAD is checked in a browser. diff --git a/docs/c-api.md b/docs/c-api.md index b32ac9dc..108672cc 100644 --- a/docs/c-api.md +++ b/docs/c-api.md @@ -132,7 +132,8 @@ and link `speech.lib`. Inside this CMake project, link the target `speech` (shar compared without case. A device asked for by `gpu` or by name that is not there or does not start is an error, and no other device takes its place. - the CPU's threads, which apply to whatever runs on the CPU; by default the machine's performance cores, or its - physical cores where the system does not tell them apart. + physical cores where the system does not tell them apart. The WebAssembly build ([browser.md](browser.md)) computes + on one thread and refuses more. - a warm-up that runs a short request while the model loads, so that a GPU compiles its kernels before the first request. It is off by default; `speech worker` and `speech serve` turn it on. - **Model information.** `speech_model_info_open()` reads what a model file says of its model from its metadata, without @@ -505,5 +506,6 @@ loaded on Metal, with two of its nine voices and four of its options shown: - `device` and `threads` are there for a loaded model alone. `threads` is the number of CPU threads in effect for a model on the CPU or for a model on a GPU that can compute part of a request on the CPU (FastConformer's decoding with `decode_on_cpu`, or Drama 3's and Nemotron 3.5 Transcribe's experts that its GPU does not hold), and 0 for a model on - a GPU that computes nothing there. Setting threads is never an error, since with the device `auto` a caller cannot - know where the model will run. + a GPU that computes nothing there. Setting threads is never an error in the builds for a system, since with the + device `auto` a caller cannot know where the model will run; the WebAssembly build, which has the CPU alone, refuses + more threads than it computes with. diff --git a/docs/install.md b/docs/install.md index 9125529e..612fbc61 100644 --- a/docs/install.md +++ b/docs/install.md @@ -139,6 +139,7 @@ It makes `build/speech` and the shared library beside it. A build from source is | CPU | `cmake -B build` elsewhere | checked and released for Linux | | Vulkan | `cmake -B build -DGGML_VULKAN=ON` | checked on NVIDIA and released for Windows and Linux; needs the Vulkan SDK to build | | CUDA | `cmake -B build -DGGML_CUDA=ON` | builds, but is not checked or released | +| WebAssembly | `emcmake cmake -B build-wasm` | the library alone, for a web page; needs Emscripten ([browser.md](browser.md#build-it)) | On Linux, the [Vulkan SDK](https://vulkan.lunarg.com/sdk/home#linux) brings everything the Vulkan build needs in one archive: diff --git a/docs/models/silero-vad.md b/docs/models/silero-vad.md index 36a04b73..28f9a6e8 100644 --- a/docs/models/silero-vad.md +++ b/docs/models/silero-vad.md @@ -26,8 +26,8 @@ speech vad silero-vad --min-silence-duration-ms 1000 --max-speech-duration-s 10 ends, once 100 ms of silence has ended the region. A region under way is said to be kept once its speech has lasted longer than `min_speech_duration_ms`, 250 ms by default, which it then is. - The file is F32 alone: `speech quantize` writes no other type of it. -- `speech vad`, `speech asr --vad`, `speech serve` (for `chunking_strategy`) and the C API's `speech_detect()` and - detections take it; `speech worker` does not. +- `speech vad`, `speech asr --vad`, `speech serve` (for `chunking_strategy`), the C API's `speech_detect()` and + detections, and the WebAssembly build in a web page ([browser.md](../browser.md)) take it; `speech worker` does not. ## Options diff --git a/include/speech.h b/include/speech.h index 0a025161..dbd1c4ac 100644 --- a/include/speech.h +++ b/include/speech.h @@ -610,7 +610,8 @@ SPEECH_API speech_status speech_load_params_set_device(speech_load_params * para * whatever the model computes on the CPU: all of its graphs for a model on the CPU, and for a model on a GPU those it * computes on the CPU, such as a decoding with decode_on_cpu, or none. Without it the library takes the machine's * performance cores, or its physical cores where the system does not tell them apart. The model's information reports - * the number in effect (speech_model_info_threads()). + * the number in effect (speech_model_info_threads()). A WebAssembly build without threads computes with 1 alone and + * refuses more as SPEECH_ERROR_INVALID_ARGUMENT. */ SPEECH_API speech_status speech_load_params_set_threads(speech_load_params * params, int threads); diff --git a/src/api/speech.cpp b/src/api/speech.cpp index 0db5a0b9..7bfcf4b3 100644 --- a/src/api/speech.cpp +++ b/src/api/speech.cpp @@ -35,19 +35,40 @@ namespace { /** * The families speech.cpp runs: the task of each, the layout its reader takes, which names its general.architecture, * its table of options with what else its information says, its engine, and how it makes a voice file where it takes - * them. Adding a family is adding its line. + * them. Adding a family is adding its line. A build holds the line of each family it takes, which CMake marks with + * SPEECH_FAMILY_: every family, but in WebAssembly those it is configured with. */ const Family families[] = { +#ifdef SPEECH_FAMILY_QWEN3_TTS {SPEECH_TASK_SYNTHESIS, qwen3_tts_layout, describe_qwen3_tts, load_qwen3_tts, nullptr}, +#endif +#ifdef SPEECH_FAMILY_IRODORI_TTS {SPEECH_TASK_SYNTHESIS, irodori::model_layout, describe_irodori_tts, load_irodori_tts, make_irodori_tts_voice}, +#endif +#ifdef SPEECH_FAMILY_DRAMA3 {SPEECH_TASK_SYNTHESIS, drama3::model_layout, describe_drama3, load_drama3, make_drama3_voice}, +#endif +#ifdef SPEECH_FAMILY_FASTCONFORMER {SPEECH_TASK_RECOGNITION, fastconformer::layout, describe_fastconformer, load_fastconformer, nullptr}, +#endif +#ifdef SPEECH_FAMILY_QWEN3_ASR {SPEECH_TASK_RECOGNITION, qwen3_asr::layout, describe_qwen3_asr, load_qwen3_asr, nullptr}, +#endif +#ifdef SPEECH_FAMILY_NEMOTRON_TRANSCRIBE {SPEECH_TASK_RECOGNITION, nemotron_transcribe::layout, describe_nemotron_transcribe, load_nemotron_transcribe, nullptr}, +#endif +#ifdef SPEECH_FAMILY_SILERO_VAD {SPEECH_TASK_DETECTION, silero_vad::layout, describe_silero_vad, load_silero_vad, nullptr}, +#endif +#ifdef SPEECH_FAMILY_SORTFORMER {SPEECH_TASK_DIARIZATION, sortformer::layout, describe_sortformer, load_sortformer, nullptr}, +#endif +#ifdef SPEECH_FAMILY_SEMAMBA {SPEECH_TASK_ENHANCEMENT, semamba::layout, describe_semamba, load_semamba, nullptr}, +#endif +#ifdef SPEECH_FAMILY_HARU {SPEECH_TASK_DIALOGUE, haru::model_layout, describe_haru, load_haru, make_haru_voice}, +#endif }; thread_local std::string last_error; @@ -253,7 +274,7 @@ const Family & family_of(const std::string & path) { } std::string known; for (const Family & f : families) known += (known.empty() ? "" : ", ") + std::string(f.layout.architecture); - throw Error(Fault::File, path + " is a model of " + architecture + ", which speech.cpp does not run; it runs " + known); + throw Error(Fault::File, path + " is a model of " + architecture + ", which this build of speech.cpp does not run; it runs " + known); } const OptionSpec * FileInfo::spec(speech_option option) const { @@ -458,6 +479,12 @@ speech_status speech_load_params_set_threads(speech_load_params * params, int th if (threads < 1) { throw ApiError(SPEECH_ERROR_INVALID_ARGUMENT, "the threads are " + std::to_string(threads) + "; give 1 or more", "threads"); } + if (threads > max_threads()) { + const std::string most = std::to_string(max_threads()); + throw ApiError(SPEECH_ERROR_INVALID_ARGUMENT, "the threads are " + std::to_string(threads) + ", and this build of speech.cpp computes with " + + (max_threads() == 1 ? "one thread alone; give 1" : "at most " + most + "; give 1 to " + most), + "threads"); + } params->threads = threads; return SPEECH_OK; }); diff --git a/src/common/backend.cpp b/src/common/backend.cpp index 2506c06d..9d05115b 100644 --- a/src/common/backend.cpp +++ b/src/common/backend.cpp @@ -3,6 +3,7 @@ #include #include #include +#include #include #include #include @@ -120,7 +121,7 @@ ggml_backend_t start_device(ggml_backend_dev_t device, int threads) { } int default_threads() { - static const int threads = [] { + static const int threads = std::min(max_threads(), [] { #ifdef __APPLE__ for (const char * key : {"hw.perflevel0.physicalcpu", "hw.physicalcpu"}) { int n = 0; @@ -162,10 +163,18 @@ int default_threads() { if (!cores.empty()) return (int) cores.size(); #endif return (int) std::max(1u, std::thread::hardware_concurrency()); - }(); + }()); return threads; } +int max_threads() { +#if defined(__EMSCRIPTEN__) && !defined(__EMSCRIPTEN_PTHREADS__) + return 1; +#else + return std::numeric_limits::max(); +#endif +} + ggml_backend_t init_backend(const std::string & name) { return start_device(find_device(name.empty() ? "auto" : name), default_threads()); } diff --git a/src/common/backend.h b/src/common/backend.h index e31d5a96..792f2d26 100644 --- a/src/common/backend.h +++ b/src/common/backend.h @@ -29,10 +29,17 @@ ggml_backend_t start_device(ggml_backend_dev_t device, int threads); /** * The CPU threads the library computes with when the caller does not choose: the machine's performance cores, or its - * physical cores where the system does not tell them apart, or its logical processors where it tells neither. + * physical cores where the system does not tell them apart, or its logical processors where it tells neither, up to + * max_threads(). */ int default_threads(); +/** + * The most CPU threads this build can compute with: one in WebAssembly without threads, which starts none, and no limit + * elsewhere. ggml aborts the process when a thread it starts does not. + */ +int max_threads(); + /** * The backend of the device `name` asks for as find_device() reads it, "auto" when it is empty, with the default * threads: what the checks run on. diff --git a/wasm/index.html b/wasm/index.html new file mode 100644 index 00000000..72fe5858 --- /dev/null +++ b/wasm/index.html @@ -0,0 +1,46 @@ + + + + + +speech.cpp in the browser + + + +

speech.cpp in the browser

+

Finds where someone speaks in a WAVE file with Silero VAD, inside this page; nothing is sent anywhere.

+
+ + + + + + +
+ + + + diff --git a/wasm/page.mjs b/wasm/page.mjs new file mode 100644 index 00000000..20c7a4e7 --- /dev/null +++ b/wasm/page.mjs @@ -0,0 +1,118 @@ +// The page in index.html: finds the regions where someone speaks in a WAVE file with a detection model, both chosen by +// the person, through speech.mjs in a Worker (worker.mjs), and shows the regions, the load time, the RTFx and the module's +// memory. window.speechPage.run() does the same for a script, such as checks/smoke/wasm_browser_smoke.mjs, from URLs or +// Blobs: run({ model, audio: [...], threads, options }) loads the model once and detects in each audio in turn. A link +// with ?model=URL&audio=URL runs on those files as the page opens, as on a phone, where a script cannot reach the page. + +const $ = (id) => document.getElementById(id); + +let worker = null; +let opened = null; +let next = 0; +const waiting = new Map(); + +/** Sends `op` to the Worker and resolves with its value, or rejects with its error. */ +function call(op, args = {}) { + return new Promise((resolve, reject) => { + const id = ++next; + waiting.set(id, { resolve, reject }); + worker.postMessage({ id, op, ...args }); + }); +} + +function answered({ data: { id, value, error } }) { + const { resolve, reject } = waiting.get(id); + waiting.delete(id); + if (!error) return resolve(value); + const e = new Error(error.message); + Object.assign(e, error); + reject(e); +} + +/** The Worker with the library loaded, started on first use. */ +function library() { + if (!opened) { + worker = new Worker(new URL('./worker.mjs', import.meta.url), { type: 'module' }); + worker.onmessage = answered; + opened = call('open'); + } + return opened; +} + +/** A Blob of `source`, a Blob as it is or a URL fetched, named by the URL's last part. */ +async function blobOf(source) { + if (source instanceof Blob) return source; + const response = await fetch(source); + if (!response.ok) throw new Error(`${source}: ${response.status} ${response.statusText}`); + return new File([await response.blob()], decodeURIComponent(new URL(source, location.href).pathname.split('/').pop())); +} + +/** Loads `model` and detects speech in each of `audio`, with the threads and the request options given. */ +async function run({ model, audio, threads, options = {} }) { + const open = await library(); + const loaded = await call('load', { blob: await blobOf(model), threads }); + const detections = []; + for (const source of audio) detections.push(await call('detect', { blob: await blobOf(source), options })); + return { version: open.version, open: open.ms, load: loaded.ms, info: loaded.info, detections, memory: detections.at(-1)?.memory ?? loaded.memory }; +} + +const seconds = (s) => `${s.toFixed(3)} s`; + +function show(result) { + const detection = result.detections[0]; + $('version').textContent = `speech.cpp ${result.version}`; + $('stats').replaceChildren(...[ + ['Model', `${result.info.name} (${result.info.weight_type})`], + ['Load time', `${result.load.toFixed(1)} ms`], + ['Audio', seconds(detection.seconds)], + ['Detection', `${detection.ms.toFixed(1)} ms`], + ['RTFx', (detection.seconds / (detection.ms / 1000)).toFixed(0)], + ['Memory', `${(result.memory / 2 ** 20).toFixed(1)} MiB`], + ].flatMap(([term, value]) => { + const dt = document.createElement('dt'); + const dd = document.createElement('dd'); + dt.textContent = term; + dd.textContent = value; + return [dt, dd]; + })); + $('regions').replaceChildren(...detection.regions.map((r, i) => { + const row = document.createElement('tr'); + for (const text of [String(i + 1), seconds(r.start), seconds(r.end)]) { + const cell = document.createElement('td'); + cell.textContent = text; + row.append(cell); + } + return row; + })); + $('result').hidden = false; +} + +/** Runs on the model and audio given, or the files chosen, showing the result or the error. */ +async function detect({ model = $('model').files[0], audio = $('audio').files[0] } = {}) { + $('error').hidden = true; + $('detect').disabled = true; + $('status').textContent = 'Detecting…'; + try { + const options = $('options').value.trim() ? JSON.parse($('options').value) : {}; + show(await run({ model, audio: [audio], options })); + } catch (e) { + $('error').textContent = e.status ? `${e.status}${e.option ? ` (${e.option})` : ''}: ${e.message}` : e.message; + $('error').hidden = false; + } finally { + $('status').textContent = ''; + $('detect').disabled = false; + } +} + +const ready = () => ($('detect').disabled = !($('model').files.length && $('audio').files.length)); +$('model').addEventListener('change', ready); +$('audio').addEventListener('change', ready); +$('form').addEventListener('submit', (event) => { + event.preventDefault(); + detect(); +}); +ready(); + +window.speechPage = { run }; +const linked = new URLSearchParams(location.search); +if (linked.has('model') && linked.has('audio')) detect({ model: linked.get('model'), audio: linked.get('audio') }); diff --git a/wasm/speech.mjs b/wasm/speech.mjs new file mode 100644 index 00000000..e7fa8b5e --- /dev/null +++ b/wasm/speech.mjs @@ -0,0 +1,217 @@ +// speech.cpp's C API in a Worker, over the library compiled to WebAssembly: libspeech.js and libspeech.wasm. A model is +// read from a Blob or File through Emscripten's WORKERFS, which reads the file a piece at a time as the library asks for +// it, so that the weights are held once, in the module's memory. Each call blocks until the library returns, as the C +// API's do, and WORKERFS reads with FileReaderSync, which a Worker alone has: the module runs in a Worker. +// +// usage, in a module Worker: +// import { openSpeech } from './speech.mjs'; +// const speech = await openSpeech(); +// const model = speech.load(file); // a Blob or File of a GGUF model +// const regions = model.detect(samples, 16000, { threshold: 0.5 }); // [{ start, end }] in seconds +// model.free(); + +const OK = 0; +const TYPE_STRING = 0, TYPE_INT = 1, TYPE_FLOAT = 2, TYPE_BOOL = 3; + +/** A failure the library reports: its status ("invalid_argument", "model_file", ...), message and input at fault. */ +export class SpeechError extends Error { + constructor(status, message, option) { + super(message); + this.name = 'SpeechError'; + this.status = status; + this.option = option; + } +} + +/** The library, loaded from libspeech.js beside this file, or from `url`. */ +export async function openSpeech({ url } = {}) { + const module = url ?? new URL('./libspeech.js', import.meta.url).href; + const { default: create } = await import(module); + return new Speech(await create()); +} + +/** Throws the library's error for `status` unless it is SPEECH_OK. */ +function check(m, status) { + if (status === OK) return; + const option = m._speech_last_error_option(); + throw new SpeechError(m.UTF8ToString(m._speech_status_name(status)), m.UTF8ToString(m._speech_last_error()), + option ? m.UTF8ToString(option) : null); +} + +/** + * Runs `call` with the address of a word that the library writes, as the C API's out parameters, and returns the word: + * a pointer, which a module of more than 2 GB holds above 2^31, read unsigned. + */ +function out(m, call) { + const at = m._malloc(4) >>> 0; + try { + check(m, call(at)); + return m.HEAPU32[at >>> 2]; + } finally { + m._free(at); + } +} + +/** Runs `call` with `text` in the module's memory as a UTF-8 C string. */ +function withString(m, text, call) { + const at = m.stringToNewUTF8(text) >>> 0; + try { + return call(at); + } finally { + m._free(at); + } +} + +/** Sets the request option `name` to `value`, a JavaScript value of the option's type. */ +function setOption(m, request, name, value) { + const option = withString(m, name, (text) => out(m, (at) => m._speech_option_from_name(text, at))); + const type = m._speech_option_type(option); + const refuse = (wanted) => { + throw new SpeechError('invalid_argument', `the option ${name} takes ${wanted}, not ${typeof value} ${String(value)}`, name); + }; + if (type === TYPE_STRING) { + if (typeof value !== 'string') refuse('a string'); + withString(m, value, (text) => check(m, m._speech_request_set_string(request, option, text))); + } else if (type === TYPE_INT) { + if (typeof value !== 'bigint' && !Number.isInteger(value)) refuse('an integer'); + check(m, m._speech_request_set_int(request, option, BigInt(value))); + } else if (type === TYPE_FLOAT) { + if (typeof value !== 'number') refuse('a number'); + check(m, m._speech_request_set_float(request, option, value)); + } else if (type === TYPE_BOOL) { + if (typeof value !== 'boolean') refuse('true or false'); + check(m, m._speech_request_set_bool(request, option, value ? 1 : 0)); + } else { + throw new Error(`the option ${name} is of a type ${type} this module does not know`); + } +} + +let mounts = 0; + +/** The library: loads models from Blobs. */ +class Speech { + #m; + + constructor(m) { + this.#m = m; + } + + /** The release of speech.cpp, as speech_version() gives it. */ + get version() { + return this.#m.UTF8ToString(this.#m._speech_version()); + } + + /** The bytes of the module's memory, which grows as the library asks and never shrinks: the most it has used. */ + get memory() { + return this.#m.HEAPU8.length; + } + + /** + * Loads the GGUF model in `blob` with the threads given, or the library's default, as speech_model_load() does. The + * Blob is read as the library reads the file and must not change while the model is loaded. + */ + load(blob, { threads } = {}) { + const m = this.#m; + const folder = `/models/${++mounts}`; + const name = blob.name || 'model.gguf'; + m.FS.mkdirTree(folder); + m.FS.mount(m.WORKERFS, { blobs: [{ name, data: blob }] }, folder); + const unmount = () => { + m.FS.unmount(folder); + m.FS.rmdir(folder); + }; + try { + const params = out(m, (at) => m._speech_load_params_new(at)); + try { + if (threads !== undefined) check(m, m._speech_load_params_set_threads(params, threads)); + const model = withString(m, `${folder}/${name}`, (path) => out(m, (at) => m._speech_model_load(path, params, at))); + return new Model(m, model, unmount); + } finally { + m._speech_load_params_free(params); + } + } catch (e) { + unmount(); + throw e; + } + } +} + +/** A loaded model, which serves one request at a time. */ +class Model { + #m; + #model; + #unmount; + + constructor(m, model, unmount) { + this.#m = m; + this.#model = model; + this.#unmount = unmount; + } + + /** The model's information, as speech_model_info_json() writes it. */ + get info() { + const m = this.#m; + const info = out(m, (at) => m._speech_model_get_info(this.#live(), at)); + try { + return JSON.parse(m.UTF8ToString(m._speech_model_info_json(info))); + } finally { + m._speech_model_info_free(info); + } + } + + /** + * The regions where someone speaks in `samples`, a Float32Array of mono audio at `sampleRate` Hz, with the request + * options in `options` by their names: [{ start, end }] in seconds, as speech_detect() gives them. + */ + detect(samples, sampleRate, options = {}) { + const m = this.#m; + return this.#request(samples, sampleRate, options, (request) => m._speech_detect(request), (result) => { + const n = m._speech_result_segment_count(result) >>> 0; + const regions = []; + const at = m._malloc(24) >>> 0; + try { + for (let i = 0; i < n; i++) { + check(m, m._speech_result_segment(result, i, at, at + 8, at + 16)); + regions.push({ start: m.HEAPF64[at >>> 3], end: m.HEAPF64[(at >>> 3) + 1] }); + } + } finally { + m._free(at); + } + return regions; + }); + } + + /** Frees the model; it cannot be used again. */ + free() { + if (!this.#model) return; + this.#m._speech_model_free(this.#model); + this.#model = 0; + this.#unmount(); + } + + #live() { + if (!this.#model) throw new Error('the model has been freed'); + return this.#model; + } + + /** Runs a request of `samples` with `options` through `run`, and reads its result with `read` before freeing it. */ + #request(samples, sampleRate, options, run, read) { + const m = this.#m; + if (!(samples instanceof Float32Array)) throw new TypeError('the samples are a Float32Array'); + const request = out(m, (at) => m._speech_request_new(this.#live(), at)); + try { + const audio = m._malloc(Math.max(1, samples.length) * 4) >>> 0; + try { + m.HEAPF32.set(samples, audio >>> 2); + check(m, m._speech_request_set_audio(request, audio, samples.length, sampleRate)); + } finally { + m._free(audio); + } + for (const [name, value] of Object.entries(options)) setOption(m, request, name, value); + check(m, run(request)); + return read(m._speech_request_result(request) >>> 0); + } finally { + m._speech_request_free(request); + } + } +} diff --git a/wasm/wav.mjs b/wasm/wav.mjs new file mode 100644 index 00000000..c679dafd --- /dev/null +++ b/wasm/wav.mjs @@ -0,0 +1,62 @@ +// Reads a WAVE file into mono float32 samples as `speech` reads one (src/common/wav.cpp): 16-, 24- and 32-bit PCM and +// 32-bit float, every channel averaged in float32, so that a page gives the library the samples the command line gives +// it for the same file, and the same results. +// +// usage: +// import { readWav } from './wav.mjs'; +// const { sampleRate, samples } = readWav(await file.arrayBuffer(), file.name); + +const FORMAT_PCM = 1, FORMAT_FLOAT = 3, FORMAT_EXTENSIBLE = 0xfffe; + +/** The mono samples and the sample rate of the WAVE file in `buffer`, an ArrayBuffer; `name` names it in errors. */ +export function readWav(buffer, name = 'the audio') { + const view = new DataView(buffer); + const tag = (at) => String.fromCharCode(view.getUint8(at), view.getUint8(at + 1), view.getUint8(at + 2), view.getUint8(at + 3)); + if (buffer.byteLength < 12 || tag(0) !== 'RIFF' || tag(8) !== 'WAVE') throw new Error(`${name} is not a WAVE file`); + let format = 0, bits = 0, channels = 0, sampleRate = 0, data = -1, dataSize = 0; + for (let at = 12; at + 8 <= buffer.byteLength;) { + const size = view.getUint32(at + 4, true); + if (at + 8 + size > buffer.byteLength) throw new Error(`${name} ends inside a chunk`); + if (tag(at) === 'fmt ' && size >= 16) { + format = view.getUint16(at + 8, true); + channels = view.getUint16(at + 10, true); + sampleRate = view.getUint32(at + 12, true); + bits = view.getUint16(at + 22, true); + if (format === FORMAT_EXTENSIBLE && size >= 40) format = view.getUint16(at + 32, true); + } else if (tag(at) === 'data') { + data = at + 8; + dataSize = size; + } + at += 8 + size + (size & 1); + } + if (data < 0 || channels === 0) throw new Error(`${name} has no format or no data`); + const pcm = format === FORMAT_PCM && (bits === 16 || bits === 24 || bits === 32); + const ieee = format === FORMAT_FLOAT && bits === 32; + if (!pcm && !ieee) { + throw new Error(`${name} is neither 16-, 24- or 32-bit PCM nor 32-bit float WAVE (format ${format}, ${bits} bits)`); + } + const width = bits / 8; + const frames = Math.floor(Math.floor(dataSize / width) / channels); + const sample = (i) => { + const at = data + i * width; + if (ieee) { + const x = view.getFloat32(at, true); + if (!Number.isFinite(x)) throw new Error(`${name} holds a sample that is not a finite number, sample ${i}; write the recording again from its source`); + return x; + } + if (bits === 16) return view.getInt16(at, true) / 32768; + if (bits === 24) return ((view.getUint8(at) << 8 | view.getUint8(at + 1) << 16 | view.getUint8(at + 2) << 24) >> 8) / 8388608; + return Math.fround(view.getInt32(at, true) / 2147483648); + }; + const samples = new Float32Array(frames); + for (let f = 0; f < frames; f++) { + if (channels === 1) { + samples[f] = sample(f); + continue; + } + let sum = 0; + for (let c = 0; c < channels; c++) sum = Math.fround(sum + sample(f * channels + c)); + samples[f] = sum / channels; + } + return { sampleRate, samples }; +} diff --git a/wasm/worker.mjs b/wasm/worker.mjs new file mode 100644 index 00000000..e89e5cd6 --- /dev/null +++ b/wasm/worker.mjs @@ -0,0 +1,39 @@ +// The Worker of the page in index.html: runs speech.mjs on the page's messages, one at a time, and answers each with +// its value or its error. A message is { id, op, ...arguments }: "open" loads the library; "load" loads a model from a +// Blob, freeing the one before; "detect" reads a WAVE Blob as `speech` reads the file and finds the regions where +// someone speaks. Each answer carries the milliseconds the library took and the bytes of its memory. +import { openSpeech } from './speech.mjs'; +import { readWav } from './wav.mjs'; + +let speech = null; +let model = null; + +const ops = { + async open() { + const start = performance.now(); + speech = await openSpeech(); + return { version: speech.version, ms: performance.now() - start }; + }, + load({ blob, threads }) { + model?.free(); + model = null; + const start = performance.now(); + model = speech.load(blob, { threads }); + return { ms: performance.now() - start, info: model.info }; + }, + async detect({ blob, options }) { + const { sampleRate, samples } = readWav(await blob.arrayBuffer(), blob.name); + const start = performance.now(); + const regions = model.detect(samples, sampleRate, options); + return { regions, seconds: samples.length / sampleRate, ms: performance.now() - start }; + }, +}; + +onmessage = async ({ data: { id, op, ...args } }) => { + try { + const value = await ops[op](args); + postMessage({ id, value: { ...value, memory: speech?.memory ?? 0 } }); + } catch (e) { + postMessage({ id, error: { name: e.name, status: e.status ?? null, message: e.message, option: e.option ?? null } }); + } +}; From 4134f27dbc3325b2fa9294cb85766c9058345fdc Mon Sep 17 00:00:00 2001 From: sakasegawa Date: Sat, 21 Nov 2026 01:07:43 +0900 Subject: [PATCH 2/3] Check the module's allocations, keep the page's runs apart and refuse integers past 64 bits From the review: speech.mjs wrote into the address malloc() gave without checking it, and malloc() gives 0 when the module's memory cannot grow, so the audio went over the module's own data; it now refuses with out_of_memory, naming the bytes asked for, before any write. Two runs of the page shared the Worker's one model, so a run that loaded another while one detected freed or replaced it under the first; runs now wait for the ones before them. A BigInt reached the library modulo 2^64 and a Number past 2^53 as another integer, so -2^64 set an option to 0; an integer option now takes a Number that holds the integer exactly or a BigInt of 64 bits, and refuses the rest naming the option. Checked: wasm_browser_smoke.mjs now runs a whole model with one cut in half loaded beside it, and min_speech_duration_ms of -2^64 and 2^60; both fail before the fixes and pass after, with every region of the seven WAVE files equal to speech vad's. The allocation's refusal needs a module whose memory cannot grow, which the smoke of the build with threads, of 1 GB, will reach. Co-Authored-By: Claude Opus 5.5 --- checks/smoke/wasm_browser_smoke.mjs | 29 +++++++++++++++++++------ wasm/page.mjs | 14 +++++++++++- wasm/speech.mjs | 33 +++++++++++++++++++++++------ 3 files changed, 63 insertions(+), 13 deletions(-) diff --git a/checks/smoke/wasm_browser_smoke.mjs b/checks/smoke/wasm_browser_smoke.mjs index 65a843cf..5f8275cc 100644 --- a/checks/smoke/wasm_browser_smoke.mjs +++ b/checks/smoke/wasm_browser_smoke.mjs @@ -1,7 +1,8 @@ // Runs the WebAssembly build of speech.cpp in a headless Chrome through its page (wasm/index.html), as a script drives // it, and fails on a defect: the regions where someone speaks in each WAVE file must be those `speech vad` finds in it on -// the CPU, number for number; the build must refuse more threads than it starts, and a model file cut short, as errors -// of the C API naming the input rather than an abort, and answer the next request after both. It prints the time to load +// the CPU, number for number; the build must refuse more threads than it starts, a model file cut short and an integer +// 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. @@ -165,18 +166,34 @@ try { throw new Error(`two threads in the build without threads: ${JSON.stringify(threads)}, where invalid_argument naming threads was due`); } console.log(`two threads refused: ${threads.error.status} (${threads.error.option}): ${threads.error.message}`); - const cut = await page(` + // 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(` const whole = await (await fetch(${JSON.stringify(urls[0])})).blob(); const model = new File([whole.slice(0, Math.floor(whole.size / 2))], 'cut.gguf'); - return await speechPage.run({ model, ${one} }).catch(failure); + return await Promise.all([ + speechPage.run({ model: new File([whole], 'whole.gguf'), ${one} }).catch(failure), + speechPage.run({ model, ${one} }).catch(failure), + ]); `); if (cut.error?.status !== 'model_file') throw new Error(`a model cut in half: ${JSON.stringify(cut)}, where model_file was due`); - console.log(`a model cut in half refused: ${cut.error.status}: ${cut.error.message}`); + if (whole.error) throw new Error(`a run with a model cut in half after it failed: ${JSON.stringify(whole.error)}`); + const differsBeside = departure(whole.detections, native.slice(0, 1)); + if (differsBeside) throw new Error(`a run with a model cut in half after it: ${differsBeside}`); + console.log(`a model cut in half refused: ${cut.error.status}: ${cut.error.message}; the run before it kept its own model`); + // A BigInt past 64 bits would reach the library modulo 2^64, as 0, and a Number past 2^53 as another integer. + for (const [value, status] of [['-(2n ** 64n)', 'out_of_range'], ['2 ** 60', 'invalid_argument']]) { + const wide = await run(`{ model: ${JSON.stringify(urls[0])}, ${one}, options: { min_speech_duration_ms: ${value} } }`); + if (wide.error?.status !== status || wide.error.option !== 'min_speech_duration_ms') { + throw new Error(`min_speech_duration_ms of ${value}: ${JSON.stringify(wide)}, where ${status} naming it was due`); + } + console.log(`min_speech_duration_ms of ${value} refused: ${wide.error.status}: ${wide.error.message}`); + } 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)); if (differsAgain) throw new Error(`after the errors, ${differsAgain}`); - console.log('the next request after both: the same regions'); + console.log('the next request after them: the same regions'); if (errors.length) throw new Error(`the page threw: ${errors.join('; ')}`); console.log('ok'); diff --git a/wasm/page.mjs b/wasm/page.mjs index 20c7a4e7..42cd5e5b 100644 --- a/wasm/page.mjs +++ b/wasm/page.mjs @@ -48,7 +48,7 @@ async function blobOf(source) { } /** Loads `model` and detects speech in each of `audio`, with the threads and the request options given. */ -async function run({ model, audio, threads, options = {} }) { +async function runNow({ model, audio, threads, options = {} }) { const open = await library(); const loaded = await call('load', { blob: await blobOf(model), threads }); const detections = []; @@ -56,6 +56,18 @@ async function run({ model, audio, threads, options = {} }) { return { version: open.version, open: open.ms, load: loaded.ms, info: loaded.info, detections, memory: detections.at(-1)?.memory ?? loaded.memory }; } +let queue = Promise.resolve(); + +/** + * runNow() once the runs before it have ended: the Worker holds one model, which a run that loads another while one + * detects would replace or free under it. + */ +function run(args) { + const result = queue.then(() => runNow(args)); + queue = result.catch(() => {}); + return result; +} + const seconds = (s) => `${s.toFixed(3)} s`; function show(result) { diff --git a/wasm/speech.mjs b/wasm/speech.mjs index e7fa8b5e..4e3c8610 100644 --- a/wasm/speech.mjs +++ b/wasm/speech.mjs @@ -38,12 +38,26 @@ function check(m, status) { option ? m.UTF8ToString(option) : null); } +/** The error of the module's memory, which cannot grow to hold `what`. */ +function outOfMemory(m, what) { + return new SpeechError('out_of_memory', `the module's memory of ${m.HEAPU8.length} bytes cannot grow to hold ${what}; ` + + 'free a model or give less audio', null); +} + /** - * Runs `call` with the address of a word that the library writes, as the C API's out parameters, and returns the word: - * a pointer, which a module of more than 2 GB holds above 2^31, read unsigned. + * The address of `bytes` of the module's memory, which malloc() gives as 0, and which would then be written over the + * module's own data, where the memory cannot grow to hold them. A pointer of a module of more than 2 GB is above 2^31 + * and read unsigned. */ +function alloc(m, bytes) { + const at = bytes < 2 ** 32 ? m._malloc(bytes) >>> 0 : 0; + if (!at) throw outOfMemory(m, `${bytes} bytes more`); + return at; +} + +/** Runs `call` with the address of a word that the library writes, as the C API's out parameters, and returns the word. */ function out(m, call) { - const at = m._malloc(4) >>> 0; + const at = alloc(m, 4); try { check(m, call(at)); return m.HEAPU32[at >>> 2]; @@ -55,6 +69,7 @@ function out(m, call) { /** Runs `call` with `text` in the module's memory as a UTF-8 C string. */ function withString(m, text, call) { const at = m.stringToNewUTF8(text) >>> 0; + if (!at) throw outOfMemory(m, `a string of ${text.length} characters`); try { return call(at); } finally { @@ -73,7 +88,13 @@ function setOption(m, request, name, value) { if (typeof value !== 'string') refuse('a string'); withString(m, value, (text) => check(m, m._speech_request_set_string(request, option, text))); } else if (type === TYPE_INT) { - if (typeof value !== 'bigint' && !Number.isInteger(value)) refuse('an integer'); + // WebAssembly takes a BigInt for an int64_t modulo 2^64, and a Number past 2^53 is not the integer it was written as. + if (typeof value === 'number' ? !Number.isSafeInteger(value) : typeof value !== 'bigint') { + refuse('an integer, a Number of at most 2^53 or a BigInt'); + } + if (BigInt(value) < -(2n ** 63n) || BigInt(value) >= 2n ** 63n) { + throw new SpeechError('out_of_range', `the option ${name} is ${value}, which is not a 64-bit integer`, name); + } check(m, m._speech_request_set_int(request, option, BigInt(value))); } else if (type === TYPE_FLOAT) { if (typeof value !== 'number') refuse('a number'); @@ -168,7 +189,7 @@ class Model { return this.#request(samples, sampleRate, options, (request) => m._speech_detect(request), (result) => { const n = m._speech_result_segment_count(result) >>> 0; const regions = []; - const at = m._malloc(24) >>> 0; + const at = alloc(m, 24); try { for (let i = 0; i < n; i++) { check(m, m._speech_result_segment(result, i, at, at + 8, at + 16)); @@ -200,7 +221,7 @@ class Model { if (!(samples instanceof Float32Array)) throw new TypeError('the samples are a Float32Array'); const request = out(m, (at) => m._speech_request_new(this.#live(), at)); try { - const audio = m._malloc(Math.max(1, samples.length) * 4) >>> 0; + const audio = alloc(m, Math.max(1, samples.length) * 4); try { m.HEAPF32.set(samples, audio >>> 2); check(m, m._speech_request_set_audio(request, audio, samples.length, sampleRate)); From f3a628044ef165216bb1596cb0737bf5e47cb39c Mon Sep 17 00:00:00 2001 From: sakasegawa Date: Sat, 21 Nov 2026 01:44:48 +0900 Subject: [PATCH 3/3] Give the WebAssembly module a stack of 1 MB Emscripten gives a module's stack 64 KB, and ggml builds a graph by recursing in ggml_visit_parents_graph() once for each node of its longest chain. A module of every family overflowed it building RE-USE's graph on two seconds of audio, which aborted the module with "memory access out of bounds"; it ran in 128 KB. The stack is now 1 MB, the stack of Windows' main thread, the least the library runs on in a native build. Silero VAD's graphs fit in 64 KB, and its module now holds 29.9 MiB at most instead of 28.6 MiB. Checked: RE-USE F32 in a module of every family, built with -sSTACK_OVERFLOW_CHECK=2, stops on a stack overflow in ggml_visit_parents_graph() with 64 KB and enhances the two seconds with 128 KB; wasm_browser_smoke.mjs on the seven WAVE files with this module. Co-Authored-By: Claude Opus 5.5 --- CMakeLists.txt | 14 ++++++++------ docs/browser.md | 2 +- 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 4c06d571..69c5eb70 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -278,11 +278,13 @@ 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. +# 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. if (EMSCRIPTEN) file(STRINGS include/speech.h api_lines REGEX "^SPEECH_API .*speech_[a-z0-9_]+\\(") set(exports _malloc _free) @@ -299,7 +301,7 @@ if (EMSCRIPTEN) set_target_properties(speech-wasm PROPERTIES OUTPUT_NAME libspeech SUFFIX .js) target_link_options(speech-wasm PRIVATE -sMODULARIZE -sEXPORT_ES6 -sENVIRONMENT=worker - -sALLOW_MEMORY_GROWTH -sMAXIMUM_MEMORY=4GB + -sALLOW_MEMORY_GROWTH -sMAXIMUM_MEMORY=4GB -sSTACK_SIZE=1MB -sEXPORTED_FUNCTIONS=${exports} -sEXPORTED_RUNTIME_METHODS=FS,WORKERFS,UTF8ToString,stringToNewUTF8,HEAPU8,HEAP32,HEAPU32,HEAPF32,HEAPF64,HEAP64 -lworkerfs.js) diff --git a/docs/browser.md b/docs/browser.md index 0dc4a365..2d51bd8f 100644 --- a/docs/browser.md +++ b/docs/browser.md @@ -92,7 +92,7 @@ Silero VAD F32 on an Apple M5 (macOS 26.2) in headless Chrome 158, built with Em | load time | 9 ms | | a minute of audio, the first request after loading | 0.12 s, an RTFx of 490 | | a minute of audio, the later requests | 0.09 s, an RTFx of 670 | -| the module's memory, at most | 28.6 MiB | +| the module's memory, at most | 29.9 MiB | The first request is slower because the browser compiles the module's code again, faster, once it runs often. `speech vad` on the same CPU with one thread takes 0.089 s, an RTFx of 675. The page gives the regions `speech vad` gives, number