Repository navigation
Add an opt-in C ABI for in-process embedding - #1
Closed
christopherthompson81 wants to merge 1 commit into
Closed
christopherthompson81 wants to merge 1 commit into
christopherthompson81 wants to merge 1 commit into
Conversation
Closed
christopherthompson81
force-pushed
the
feat/c-abi
branch
9 times, most recently
from
September 12, 2026 17:47
5346ec6 to
b8011f2
Compare
audio.cpp's three existing surfaces -- the CLI, the server and the WebUI -- are all process-level, so an application that wants the engine in its own process has no entry point: include/engine/** is C++ in engine::runtime, and BUILD_SHARED_LIBS is forced OFF. This adds a thin facade over the existing runtime interfaces. It has no behaviour of its own -- every call maps onto ModelRegistry -> ILoadedVoiceModel -> IVoiceTaskSession, the same surfaces audiocpp_cli uses -- and it depends only on the framework, never on app/, so the CLI and the C API stay independent of each other. The framework already does the hard part. Options are unordered_map<string, string> in ModelLoadRequest, SessionOptions and TaskRequest, and TaskRequest -> TaskResult is generic across families, so the ABI carries zero per-family knowledge and adding a model never changes this header. ModelInspection::cli is exposed too, so a binding can enumerate what a family accepts at runtime -- names, types, defaults and bounds -- instead of hardcoding it. Handles hold their parents alive (session -> model -> registry), so freeing out of order is safe. That is deliberate: callers from garbage-collected runtimes cannot control finalizer order, and an ABI that required it would be a trap. libaudiocpp exports exactly the header's 69 symbols on all three platforms, which takes a different mechanism on each. The visibility presets only reach this target's own sources, so the static libraries linked in need an explicit allowlist: a version script on ELF, an exported-symbols list on Mach-O. Windows has no equivalent, because __declspec(dllexport) is additive -- it says "also export this", never "export only this" -- so a DLL's surface is its own annotations plus its dependencies'. Vendored cJSON annotates all 78 of its public functions by default, which put the first Windows build at 147 exports; cjson_vendor is now compiled with CJSON_HIDE_SYMBOLS, cJSON's own mechanism for this. That is the one line outside the new files, and it is a latent defect in the vendored integration rather than new behaviour -- no DLL is built from this tree today, so nothing was exposed to it before. Purely additive otherwise. AUDIOCPP_BUILD_C_API defaults to OFF and nothing changes in a build that leaves it off. When on, it also sets POSITION_INDEPENDENT_CODE, which the static and object libraries need before they can link into a shared library. Tests, all compiled as C so the header is proven consumable without a C++ runtime on the caller's side: - audiocpp_c_api_path covers the ABI contract, offline and streaming, against the Silero VAD model and speech clip that ship in-repo, so it needs no download or network. - audiocpp_c_api_model covers real families across five task types and every result accessor. - audiocpp_c_api_parity runs the same inputs through audiocpp_cli and compares, because the C API drives the same runtime and so must not merely produce plausible output but the same output. The last two report SKIP (exit 77) when models are absent, so a checkout with no downloads still goes green. Verified on Linux x86_64 (CPU and CUDA), macOS arm64 and x86_64 (CMake 3.31 and 4.4.3, Metal on and off), and Windows x64 (MSVC 14.44). Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01EkxqpYvUbjCpRDnFiNiVfx
christopherthompson81
force-pushed
the
feat/c-abi
branch
from
September 12, 2026 18:12
b8011f2 to
1577aef
Compare
christopherthompson81
pushed a commit
that referenced
this pull request
Sep 21, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Implements the C ABI proposed in 0xShug0#525 — an in-process entry point
for applications that embed audio.cpp rather than shelling out to the CLI or
running the server.
Fork-side PR for review ahead of any upstream submission.
What it adds
include/audiocpp.hsrc/capi/audiocpp.cppsrc/capi/audiocpp.map/.symbolstests/capi/path_test.ctests/capi/model_test.ctests/capi/parity.pyaudiocpp_clidocs/c_api.mdCMakeLists.txtAUDIOCPP_BUILD_C_API, off by defaultAdditive: nothing in
src/frameworkorsrc/modelsis touched, and a build thatleaves the option off is unchanged.
Design
A translation layer over
ModelRegistry→ILoadedVoiceModel→IVoiceTaskSession, the same surfacesaudiocpp_cliuses. It depends only onframework headers, never on
app/, so the CLI and the C API stay independent.Three properties of the runtime are what keep it thin:
unordered_map<string, string>inModelLoadRequest,SessionOptionsandTaskRequest, so the ABI carries zero per-familyknowledge and adding a model family never changes the header.
TaskRequest→TaskResultis already generic, so there are two run pathsto wrap:
IOfflineVoiceTaskSession::runand the streaming chunk/finalize pair.ModelInspection::cliis already self-describing, so it is exposed as-is.A binding enumerates what a family accepts at runtime — names, types, defaults
and bounds — instead of hardcoding knowledge that rots.
Rules held throughout: opaque handles only; no exception escapes (every entry
point returns a status, detail in a thread-local
audiocpp_last_error());accessors rather than struct copies, so
TaskResultcan gain fields withoutbreaking the ABI; returned strings are never NULL (absent reads as
""); freeingNULL is a no-op.
Handles hold their parents alive (session → model → registry), so freeing out
of order is safe. Callers from garbage-collected runtimes cannot control
finalizer order, and an ABI that required it would be a trap. The path test
asserts it by freeing the model and registry and then continuing to use the
session.
The surface covers everything
TaskRequest,TaskResult,ModelLoadRequestandCliOptionInfocarry — including--config/--weightselection, styleconditioning, and artifacts in both directions, so a speaker embedding read out
of one result can be fed into a later request instead of re-derived.
libaudiocpp.soexports exactly the header's 69 symbols and nothing else. Thevisibility presets only reach this target's own sources, so the static libraries
linked in (ggml, cJSON, sentencepiece) need an explicit export list or they are
re-exported and can collide with whatever the host application has already
loaded.
Tests
audiocpp_c_api_pathaudiocpp_c_api_modelaudiocpp_c_api_parityaudiocpp_cliThe latter two report SKIP (CTest exit 77) when models are absent, so a
checkout with no downloads still goes green.
path_test.candmodel_test.carecompiled as C, which is the point: the header must be consumable by a C compiler
with no C++ runtime on the caller's side.
Every result accessor is covered by a real model:
silero_vadkokoro_ttscitrinet_asrparakeet_tdtsortformer_diarbs_roformerBounds come through introspection as well as defaults — Sortformer's
speaker_thresholdreports[0, 1], Kokoro'stext_chunk_sizea floor of 32 —so a generated wrapper can validate rather than only pass values along.
Parity with the CLI
The C API drives the same runtime the CLI does, so for identical inputs the two
must produce identical output. That is the property worth testing: not that the
facade is plausible, but that it agrees.
Worth knowing for anyone else writing comparisons against this engine: Kokoro
draws noise per run, so two unseeded
audiocpp_cliruns over the same textproduce different audio (peak 0.3394 vs 0.3333, different md5). The parity check
seeds both sides through the
seedrequest option; without that the comparisonwould be meaningless.
Validation
Backends: CPU and CUDA, Linux x86_64, RTX 3090 / driver 580.178.04 / CUDA
12.8, GCC, Release. Both find the same 4 segments over the fixture. The
registered ctest entry uses CPU so it needs no GPU; a fourth argument selects
another backend through the ABI.
cmake -S . -B build -DCMAKE_BUILD_TYPE=Release -DAUDIOCPP_BUILD_C_API=ON \ -DAUDIOCPP_C_API_MODEL_ROOT=/path/to/models cmake --build build --target audiocpp_c_api_path_test audiocpp_c_api_model_test audiocpp_cli ctest --test-dir build -R audiocpp_c_api --output-on-failureProduces
libaudiocpp.so → libaudiocpp.so.0 → libaudiocpp.so.0.1.0.The header compiles clean as C99 under
-Wall -Wextra -pedantic, and from C++17including double-inclusion.
Long-lived session under repeated requests — session reuse is the reason to
embed rather than shell out, and the one thing the CLI path cannot exercise. One
session, N offline requests, RSS sampled after a warm-up so first-touch
allocation is excluded:
Constant across a 5× range of iteration counts — flat rather than linear, so
one-time allocator arena growth rather than a per-request leak. Same shape on
CUDA (880 kB), with VRAM steady across the run (1533 MiB idle baseline → ~1890
MiB, no upward trend).
Throughput, 14.07 s of audio per request, 2 threads: CPU 40.5 ms per request
(347× realtime), CUDA 52.0 ms (271×). CUDA is slower here because Silero VAD is a
1.2 MB model where per-launch overhead dominates — noted so the row isn't
mistaken for a regression.
Notes for review
CMAKE_POSITION_INDEPENDENT_CODE.BUILD_SHARED_LIBSis forced OFF atCMakeLists.txt:297, soengine_runtimeandggmlobjects are non-PIC andcannot link into a shared library. Set only inside
if (AUDIOCPP_BUILD_C_API)and before any target is declared. The cost is that enabling the option forces
a full ggml rebuild.
enable_testing()is called in the C API block. The existing call sits atCMakeLists.txt:2256, gated behind theENGINE_BUILD_*options and after thisblock, so an
add_test()here would silently never register. Repeating it isharmless and keeps the C API tests from depending on
ENGINE_BUILD_TESTS.app/cli/args.cpp, because theC API must not depend on
app/. Happy to lift it into the framework instead ifyou would rather have one copy.
omp_set_num_threads(), unlikeaudiocpp_cli.That is process-global state and a library embedded in a host application
should not change it; threads come from
audiocpp_backend_config. Flagging itas a deliberate divergence from CLI behaviour.
🤖 Generated with Claude Code
https://claude.ai/code/session_01EkxqpYvUbjCpRDnFiNiVfx