Skip to content

Add an opt-in C ABI for in-process embedding - #1

Closed
christopherthompson81 wants to merge 1 commit into
mainfrom
feat/c-abi
Closed

christopherthompson81 wants to merge 1 commit into
mainfrom
feat/c-abi

Conversation

@christopherthompson81

@christopherthompson81 christopherthompson81 commented Sep 12, 2026 •

Copy link
Copy Markdown
Owner

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

file
include/audiocpp.h the C header — C99, 69 entry points
src/capi/audiocpp.cpp the facade — one translation unit
src/capi/audiocpp.map / .symbols linker export lists
tests/capi/path_test.c contract test, compiled as C
tests/capi/model_test.c real families across task types
tests/capi/parity.py checks the C API agrees with audiocpp_cli
docs/c_api.md ownership and lifetime rules
CMakeLists.txt AUDIOCPP_BUILD_C_API, off by default

Additive: nothing in src/framework or src/models is touched, and a build that
leaves the option off is unchanged.

Design

A translation layer over ModelRegistry → ILoadedVoiceModel →
IVoiceTaskSession, the same surfaces audiocpp_cli uses. It depends only on
framework headers, never on app/, so the CLI and the C API stay independent.

Three properties of the runtime are what keep it thin:

  • Options are already unordered_map<string, string> in ModelLoadRequest,
    SessionOptions and TaskRequest, so the ABI carries zero per-family
    knowledge and adding a model family never changes the header.
  • TaskRequest → TaskResult is already generic, so there are two run paths
    to wrap: IOfflineVoiceTaskSession::run and the streaming chunk/finalize pair.
  • ModelInspection::cli is 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 TaskResult can gain fields without
breaking the ABI; returned strings are never NULL (absent reads as ""); freeing
NULL 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, ModelLoadRequest and
CliOptionInfo carry — including --config / --weight selection, style
conditioning, 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.so exports exactly the header's 69 symbols and nothing else. The
visibility 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

test needs covers
audiocpp_c_api_path nothing — in-repo model and audio the ABI contract, offline and streaming
audiocpp_c_api_model downloaded models real families across five task types
audiocpp_c_api_parity models + audiocpp_cli that the C API and the CLI agree

The latter two report SKIP (CTest exit 77) when models are absent, so a
checkout with no downloads still goes green. path_test.c and model_test.c are
compiled 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:

family task exercises
silero_vad vad speech segments, offline + streaming, 512-frame chunked pushes
kokoro_tts tts audio output — 3.325 s @ 24 kHz; 12 declared options
citrinet_asr asr transcript
parakeet_tdt asr transcript + 28 word timestamps; 15 declared options
sortformer_diar diar 5 speaker turns; 13 declared options
bs_roformer sep 2 named audio streams (vocals, instrumental)

Bounds come through introspection as well as defaults — Sortformer's
speaker_threshold reports [0, 1], Kokoro's text_chunk_size a 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.

bs_roformer      stems      MATCH cli=['instrumental', 'vocals'] api=['instrumental', 'vocals']
citrinet_asr     transcript MATCH (157 chars)
kokoro_tts       audio      MATCH cli=79800@24000Hz peak=0.3383 api=79800@24000Hz peak=0.3383
parakeet_tdt     transcript MATCH (160 chars)
sortformer_diar  turns      MATCH cli=5 api=5

PARITY OK across 5 families

Worth knowing for anyone else writing comparisons against this engine: Kokoro
draws noise per run, so two unseeded audiocpp_cli runs over the same text
produce different audio (peak 0.3394 vs 0.3333, different md5). The parity check
seeds both sides through the seed request option; without that the comparison
would 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-failure

Produces libaudiocpp.so → libaudiocpp.so.0 → libaudiocpp.so.0.1.0.

The header compiles clean as C99 under -Wall -Wextra -pedantic, and from C++17
including 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:

iterations RSS after warm-up RSS after delta
200 9892 kB 10964 kB 1072 kB
500 9940 kB 11012 kB 1072 kB
1000 9940 kB 11012 kB 1072 kB

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_LIBS is forced OFF at
    CMakeLists.txt:297, so engine_runtime and ggml objects are non-PIC and
    cannot 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 at
    CMakeLists.txt:2256, gated behind the ENGINE_BUILD_* options and after this
    block, so an add_test() here would silently never register. Repeating it is
    harmless and keeps the C API tests from depending on ENGINE_BUILD_TESTS.
  • The backend-name mapping is duplicated from app/cli/args.cpp, because the
    C API must not depend on app/. Happy to lift it into the framework instead if
    you would rather have one copy.
  • The library does not call omp_set_num_threads(), unlike audiocpp_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 it
    as a deliberate divergence from CLI behaviour.

🤖 Generated with Claude Code

https://claude.ai/code/session_01EkxqpYvUbjCpRDnFiNiVfx

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant