# Changelog Source: https://docs.ai-coustics.com/changelog Product updates and announcements **Nov 5, 2026** 0.26.0 ## Breaking Changes ### New model file version This release requires model file version 8. Re-download your models so the SDK does not reject them with `AIC_ERROR_CODE_MODEL_VERSION_UNSUPPORTED`. See the [compatibility matrix](/reference/sdk/compatibility-matrix). ## New Features * Replaced Quail Voice Focus 2.2 with 2.3: `quail-vf-2.3-l-16khz` and `quail-vf-2.3-s-16khz`. The 2.2 models are not loadable by this SDK version. * Replaced VAD Voice Focus 2.0 with 2.1: `vad-vf-2.1-s-16khz`. The 2.0 model is not loadable by this SDK version. * Replaced Tyto 1.1 with 1.2: `tyto-1.2-l-16khz`. Tyto 1.1 is not loadable by this SDK version. ## Improvements * Added support for loading models with half-precision (`f16`) parameters. This can improve inference speed on memory-bound models without reducing model performance. **Oct 26, 2026** 0.25.2 ## Bug Fixes * Updated internal dependencies to address the recently disclosed eMudhra certificate vulnerability. **Oct 7, 2026** 0.25.1 ## New Features * SDK packages now include `native-static-libs.txt` with the system libraries needed for static linking. ## Improvements * Improved the robustness of the `interfering_speech` dimension in Tyto 1.1. ## Bug Fixes * Fixed a click and brief drop in audio volume with Quail Voice Focus models when speech is first detected after processing starts or the processor is reset. * Quail Voice Focus models now apply the requested enhancement level (`AIC_PROCESSOR_PARAMETER_ENHANCEMENT_LEVEL`) even before speech is first detected. Previously, all nonzero enhancement levels produced the same audio during this initial period. * Fixed `aic_processor_terminate_session`, `aic_vad_terminate_session` and `aic_analyzer_terminate_session` blocking until sessions created after the call ended. Terminating the last session now waits only for the final usage reports of sessions that were already terminated. **Sep 29, 2026** 0.25.0 ## New Features * Added energy-based VAD support on enhancement processors through `AicEnergyVadContext`. This is the same energy-based VAD available in pre-0.22 SDK versions. It behaves differently from the previous version. It now picks up quiet and distant speech much more reliably, so you'll miss fewer words on speakerphones and in far-field setups. It also triggers more often on background noise and background voices. If you see too many false activations, lower the sensitivity parameter (default 6.0). A value around 4.0 gives a false-activation rate close to the previous version while still detecting more distant speech. ## Improvements * Added new SIMD-enabled operations in AirTen, yielding better inference performance. * SDK-internal error reports now include more detail on why a backend request failed. ## Bug Fixes * Fixed `experimental.audio.output_clipping_samples` to count clipping in the final mixed output. ## Platform Support * Added the Linux musl release targets `x86_64-unknown-linux-musl` and `aarch64-unknown-linux-musl`. These packages ship `lib/libaic.a` only; there is no musl `libaic.so`, so dynamic linking and `dlopen` are not available for them. Link the archive with a musl-native toolchain, such as GCC on Alpine. **Sep 7, 2026** 0.24.0 ## New Features ### SDK-internal error reporting The SDK reports its own backend failures to ai-coustics error tracking. Covered are failed session activations, failed usage reports, and bearer token refreshes rejected by `aic_processor_context_update_bearer_token` or its VAD and analyzer counterparts. A report contains the error class and message, the SDK version and wrapper, the model ID, the operating system, the CPU architecture, and the account the license was issued to. It contains no audio, no license key and no bearer token. Disable reporting with `DO_NOT_TRACK=1`. The variable is read once per process. Licenses with an offline entitlement and `wasm32` builds never report. See [SDK telemetry](/reference/concepts/sdk-telemetry#error-reporting). **Aug 10, 2026** 0.23.0 ## Breaking Changes ### New model file version This release requires model file version 7. Re-download your models so the SDK does not reject them with `AIC_ERROR_CODE_MODEL_VERSION_UNSUPPORTED`. See the [compatibility matrix](/reference/sdk/compatibility-matrix). ## New Features ### Tyto 1.0 has been replaced by Tyto 1.1 The analysis model is now Tyto 1.1, `tyto-1.1-l-16khz`. Tyto 1.0 (`tyto-l-16khz`) is not loadable by this SDK version any more. ### Analysis result fields changed `AicAnalysisResult` gained a field and lost one: * Added: `codec_degradation`, a measure of artifacts introduced by lossy speech codecs. * Removed: `media_speech`. ## Bug Fixes * `aic_analyzer_analyze_buffered` no longer crashes when OpenTelemetry reporting is enabled. **Aug 4, 2026** 0.22.0 This release contains two breaking changes that affect every integration. > [card] [Migrate to mono processing](/reference/deprecated/multi-channel-to-mono) > > All audio APIs are mono only. The multi-channel process and buffer functions are gone. > [card] [Migrate to the dedicated VAD](/reference/deprecated/energy-vad-to-dedicated-vad) > > VAD runs on dedicated VAD models through `AicVad` and can no longer be derived from a processor. ## Breaking Changes ### New model file version This release requires model file version 6. Re-download your models so the SDK does not reject them with `AIC_ERROR_CODE_MODEL_VERSION_UNSUPPORTED`. See the [compatibility matrix](/reference/sdk/compatibility-matrix). ### Multi-channel support removed The processor and the analyzer's collector now operate on mono audio only. All models process mono inputs. Previously the processor mixed all input channels down to mono internally, which could lead to surprising results. To prevent misunderstandings, all APIs now take exclusively mono inputs. To process multi-channel audio, downmix to mono before calling `aic_processor_process`, or create a separate processor instance per channel. | Before (0.21.4) | Now | | - | - | | `aic_processor_initialize(processor, sample_rate, num_channels, num_frames, allow_variable_frames)` | `aic_processor_initialize(processor, sample_rate, block_size, variable_block_size)` | | `aic_processor_process_planar` / `aic_processor_process_interleaved` / `aic_processor_process_sequential` | `aic_processor_process(processor, audio_ptr, audio_len)` | | `aic_collector_initialize(collector, sample_rate, num_channels, num_frames, allow_variable_frames)` | `aic_collector_initialize(collector, sample_rate, block_size, variable_block_size)` | | `aic_collector_buffer_planar` / `aic_collector_buffer_interleaved` / `aic_collector_buffer_sequential` | `aic_collector_buffer(collector, audio_ptr, audio_len)` | | `aic_model_get_optimal_num_frames` | `aic_model_get_optimal_block_size` | Naming also became consistent: the configured block length is `block_size` on `aic_processor_initialize` and `aic_collector_initialize`, the per-call buffer length is `audio_len` on `aic_processor_process` and `aic_collector_buffer`, and the `allow_variable_frames` flag is now `variable_block_size`. The OpenTelemetry `audio.channels` metric has been kept for backwards compatibility, but it now always reports exactly one channel. ### VAD moved into its own object, energy-based VAD removed Voice activity detection is no longer a side effect of enhancement. It is now a first-class object, `AicVad`, that runs a dedicated VAD model. Energy-based VADs, which inferred speech activity from the output level of an enhancement model, have been removed. They were an approximation and their accuracy depended on the enhancement model in use. A dedicated VAD model is trained for the task and is considerably more accurate. | Before (0.21.4) | Now | | - | - | | VAD came from a processor: `aic_vad_context_create(&context, processor)` | VAD is standalone: `aic_vad_create` → `aic_vad_initialize` → `aic_vad_process`, then `aic_vad_context_create(&context, vad)` | | Any enhancement model provided a VAD (energy-based), VAD models were also loaded into a processor | Only dedicated VAD models are accepted by `aic_vad_create`; `aic_processor_create` accepts only enhancement models | | VAD advanced whenever the processor processed audio | VAD advances on `aic_vad_process`, independently of any processor | | `AIC_VAD_PARAMETER_SENSITIVITY` ranged 0.0 - 1.0 on VAD models and 1.0 - 15.0 on energy-based VADs | `AIC_VAD_PARAMETER_SENSITIVITY` is always a probability threshold, 0.0 - 1.0 | If you use enhancement and VAD together, feed the VAD the original input audio, not the processor's output. `aic_vad_process` takes a `const float *` and leaves the buffer untouched, so calling it on the same buffer before `aic_processor_process` keeps the VAD on the unprocessed signal. ### Delay queries renamed to say what they delay There is no single "output delay" any more. The processor delays audio, the VAD does not, so the two queries are now named after what they actually report. | Before (0.21.4) | Now | What it means | | - | - | - | | `aic_processor_context_get_output_delay` | `aic_processor_context_get_audio_delay` | An **audio** delay. The enhanced samples leave `aic_processor_process` that many samples behind their input. | | No VAD-specific query | `aic_vad_context_get_prediction_delay` | A **prediction** delay. It is *not* applied to the audio. It tells you how far behind its own input the published prediction is, so you can line speech decisions up with the audio timeline. | ### Renamed error codes Some error codes are no longer processor-specific, since they are now also returned by the VAD. The numeric values are unchanged, so only source-level references need updating. | Before (0.21.4) | Now | | - | - | | `AIC_ERROR_CODE_PROCESSOR_NOT_INITIALIZED` | `AIC_ERROR_CODE_NOT_INITIALIZED` | | `AIC_ERROR_CODE_ENHANCEMENT_NOT_ALLOWED` | `AIC_ERROR_CODE_PROCESSING_NOT_ALLOWED` | | `AIC_ERROR_CODE_MODEL_FILE_PATH_INVALID` | `AIC_ERROR_CODE_FILE_PATH_INVALID` | ### VAD models renamed Quail VAD is now called **VAD**, and Quail VAD Voice Focus is now called **VAD Voice Focus**. The model IDs dropped the `quail-` prefix and now start with `vad-`. See [Renamed Models](/models/older-models/model-naming-changes). | Old name | New name | Old model ID | New model ID | | - | - | - | - | | Quail VAD | VAD | `quail-vad-2.0-xxs-16khz` | `vad-2.1-xxs-16khz` | | Quail VAD Voice Focus | VAD Voice Focus | `quail-vf-vad-2.0-s-16khz` | `vad-vf-2.0-s-16khz` | ## New Features There are new explicit session termination APIs. Use these to close telemetry sessions during lifecycle events without waiting for the corresponding SDK object to be destroyed, which is useful in integrations where object deallocation may be delayed. * `aic_processor_terminate_session` * `aic_vad_terminate_session` * `aic_analyzer_terminate_session` ## Bug Fixes * Resetting VAD state now immediately clears the published speech detection and raw VAD probability values, so query APIs no longer return stale values from the previous stream after reset. **Jul 3, 2026** 0.21.3 ## Platform Support * Windows MSVC: the shipped `aic.dll` (x86\_64 and arm64) now statically links the MSVC C runtime, so it no longer requires the Visual C++ Redistributable to be installed. * Windows MSVC: both CRT variants of the static import library are now shipped, `lib/dynamic-crt/aic.lib` and `lib/static-crt/aic.lib`. This lets consumers match their own runtime setting and avoids LNK2038 mismatches for projects building with the default `/MD`, which a `/MT`-only library would break. * Apple: the release artifacts now include an `aic-sdk-apple-xcframework` bundle covering macOS, Mac Catalyst, iOS, tvOS, and visionOS (device and simulator). **Jun 30, 2026** 0.21.2 ## Platform Support * Added Windows GNU/LLVM release targets `x86_64-pc-windows-gnullvm` and `aarch64-pc-windows-gnullvm` **Jun 26, 2026** 0.21.1 ## New Features Support for offline entitlements in JWT licenses. **Jun 22, 2026** 0.21.0 ## New Features This release includes a new `aic_vad_context_get_raw_vad_probability()` API to read the raw output of a VAD model. ## Changes Reduced the necessary output delay of the Processor when using `allow_variable_frames = true`. **Jun 11, 2026** 0.20.0 ## New Features This release includes several new APIs for running our newest audio intelligence model, *Tyto*. The new APIs introduce two new concepts: The `Collector` and the `Analyzer`. * The `Collector` is designed to be placed in the audio thread, buffering audio chunks for later analysis. * The `Analyzer` is designed to be run separately. Analysis models are computationally expensive and cannot run in the audio thread. The analyzer has access to the audio buffered by the collector, and it can access it safely across threads. Initialize the `Collector` with the same configuration as your existing `Processor` and you can call the `aic_collector_buffer_*` APIs in the same manner as the `aic_processor_process_*` APIs. Call `aic_analyzer_analyze_buffered` in a separate thread to obtain an analysis of the latest audio buffered by the `Collector`. **Jun 9, 2026** 0.19.3 ## Platform Support * Fixed a crash on Android during startup **Jun 5, 2026** 0.19.2 ## Platform Support * Added Android targets arm-v7a and x86\_64 **Jun 2, 2026** 0.19.1 ## New Features * Windows release bundles include the DLL import library `aic.dll.lib` * Added iOS simulator arm64 release target `aarch64-apple-ios-sim` * Enabled Rust wrapper support across all Apple targets **May 27, 2026** 0.19.0 ## Features ### JWT token support The SDK now accepts JWT-form license keys in addition to the existing license formats. Pass the JWT string as `license_key` to `aic_processor_create` as you would with any other license key: ```c theme={null} aic_processor_create(&processor, model, jwt_string, NULL); ``` JWT licenses are short-lived. Use `aic_processor_context_update_bearer_token` to swap in a renewed token while audio processing continues uninterrupted, the context handle stays valid, and the new token is used for all subsequent authentication against the ai-coustics backend: ```c theme={null} enum AicErrorCode aic_processor_context_update_bearer_token( const struct AicProcessorContext *context, const char *token); ``` In-place updates are only supported when both the originally configured key and the new token are JWTs. If either side is not, the call returns the new error code `AIC_ERROR_CODE_TOKEN_UPDATE_UNSUPPORTED` and the existing token stays in use. ### Voice activity detection models VAD is no longer limited to the energy-based detector. The SDK now also supports dedicated VAD models, which output a per-buffer speech probability. `AIC_VAD_PARAMETER_SENSITIVITY` is interpreted differently depending on the active model: * VAD models: range `0.0` to `1.0`; the probability threshold above which speech is reported. * Energy-based VADs: range `1.0` to `15.0`; energy threshold = `10 ^ (-sensitivity)`. The default sensitivity is now model-specific. ### Configurable OpenTelemetry export interval `AicOtelConfig` has a new field `export_interval_ms` controlling how often OpenTelemetry metrics are exported. Set it to `0` to keep the default of 60 000 ms: ```c theme={null} AicOtelConfig otel = { .enable = true, .session_id = NULL, .export_interval_ms = 5000, // export every 5 seconds }; aic_processor_create(&processor, model, license_key, &otel); ``` **May 19, 2026** 0.18.0 ## Features The SDK now supports observability with [OpenTelemetry](https://opentelemetry.io/). See the [documentation](https://docs.ai-coustics.com/guides/observability) for the complete setup guide. `aic_processor_create` takes a new `otel_config` parameter with two usage options: **Environment variable**: pass `NULL` and set `AIC_SDK_OTEL_ENABLE=1` to enable telemetry globally: ```c theme={null} aic_processor_create(&processor, model, license_key, NULL); ``` **Per-session**: pass an `AicOtelConfig` to enable telemetry and associate it with a specific session ID: ```c theme={null} typedef struct AicOtelConfig { bool enable; const char *session_id; // NULL = auto-generate } AicOtelConfig; AicOtelConfig otel = { .enable = true, .session_id = "my-session-id" }; aic_processor_create(&processor, model, license_key, &otel); ``` ## Breaking Changes `aic_processor_create` has a new `otel_config` parameter. Existing call sites must be updated to pass `NULL` as the last argument. **May 06, 2026** 0.17.1 ## Improvements * Increased maximum VAD speech hold duration from 100x to 300x the model's window size. ## Bug Fixes * Removed zero-padding when the host frame size does not match the model frame size, which caused unexpected behavior for some models. **Apr 23, 2026** 0.17.0 ## New Features * Added support for Quail Voice Focus 2.1 models. ## Breaking Changes * Quail Voice Focus 2.0 is no longer supported. * Compatible model file version was bumped to 3. **Apr 16, 2026** 0.16.0 ## New Features This release adds an **experimental** feature to export real-time audio processing metrics via OpenTelemetry (OTel). The new feature is currently disabled by default and available for testing on early access only. **Mar 17, 2026** 0.15.1 ## Improvements * Improved performance of telemetry when using multiple processors. ## Fixes * The scaling factor of the STFT now changes depending on the sample rate. **Feb 27, 2026** 0.15.0 ## New features * Support for V2 model files, which includes support for the new Quail Voice Focus 2.0 model. ## Improvements * The parameters of Quail models are no longer fixed. The enhancement level of every model can now be adjusted between 0.0 and 1.0. ## Breaking Changes * V1 model files are no longer supported. * The error `AIC_ERROR_CODE_PARAMETER_FIXED` was removed. * The parameter `AIC_PROCESSOR_PARAMETER_VOICE_GAIN` was removed. * The parameter `AIC_VAD_PARAMETER_SPEECH_HOLD_DURATION` previously held detected speech for half of the specified duration. It has now been changed to better represent the intention of the developer. * The default value for `AIC_VAD_PARAMETER_SPEECH_HOLD_DURATION` was changed from 50 ms to 30 ms to match the existing behavior. ## Fixes * `aic_vad_context_set_parameter` no longer returns an error when trying to set a valid speech hold duration value before calling `aic_processor_initialize`. **Jan 22, 2026** 0.14.0 ## Improvements * Increased the maximum speech hold duration of the VAD from 20 to 100x the model's window size. ## Fixes * Fixed an issue causing the VAD's state to be reset on every `aic_processor_process_*` call. ## Breaking changes * `AIC_ERROR_CODE_MODEL_NOT_INITIALIZED` has been renamed to `AIC_ERROR_CODE_PROCESSOR_NOT_INITIALIZED`. **Jan 15, 2026** 0.13.1 ## Fixes * Fixed an issue allowing users to change processor parameters with certain models **Jan 14, 2026** 0.13.0 This release comes with a number of new features and several breaking changes. Most notably, the C library does no longer include any models, which significantly reduces the library's binary size. The models are now available separately for download at [https://artifacts.ai-coustics.io](https://artifacts.ai-coustics.io). **New license keys required**: License keys previously generated in the [developer platform](https://developers.ai-coustics.com) will no longer work. New license keys must be generated. **Model naming changes**: Quail-STT models are now called "Quail" - These models are optimized for human-to-machine enhancement (e.g., Speech-to-Text (STT) applications). Quail models are now called "Sparrow" - These models are optimized for human-to-human enhancement (e.g., voice calls, conferencing). This naming change clarifies the distinction between STT-focused models and human-to-human communication model **Major architectural changes**: The API has been restructured to separate model data from processing instances. What was previously called `AicModel` (which handled both model data and processing) has been split into: * `AicModel`: Now represents only the ML model data loaded from files or memory * `AicProcessor`: New type that performs the actual audio processing using a model * Multiple processors can share the same model, allowing efficient resource usage across streams * Model instances are reference-counted internally; `aic_model_destroy` can be called immediately after creating processors, and the model will be freed automatically when the last processor using it is destroyed * To change parameters, reset the processor and get the output delay, a processor context must now be created via `aic_processor_context_create`. This context can be freely moved between threads ## New features * Models now load from files via `aic_model_create_from_file`. * Models can also be created from in-memory buffers with `aic_model_create_from_buffer`. * Added new `aic_model_get_id` API to query the id of a model. * A single model handle can be shared across multiple processors. * Added processor handles with `aic_processor_create` so each stream can be initialized independently from a shared model while sharing weights. * Added `aic_get_compatible_model_version` to query the required model version for this SDK. * Added context-based APIs for thread-safe control operations: * `aic_processor_context_create` and `aic_processor_context_destroy` for processor context management * `aic_vad_context_create` and `aic_vad_context_destroy` for VAD context management * Model query APIs moved to model handles: * `aic_model_get_optimal_sample_rate` - gets optimal sample rate for a model * `aic_model_get_optimal_num_frames` - gets optimal frame count for a model at given sample rate * Added new error codes for model loading: * `AIC_ERROR_CODE_MODEL_INVALID` * `AIC_ERROR_CODE_MODEL_VERSION_UNSUPPORTED` * `AIC_ERROR_CODE_MODEL_FILE_PATH_INVALID` * `AIC_ERROR_CODE_FILE_SYSTEM_ERROR` * `AIC_ERROR_CODE_MODEL_DATA_UNALIGNED` ## Breaking changes * License keys previously generated in the [developer platform](https://developers.ai-coustics.com) will no longer work. New license keys have to be generated. * Existing `aic_model_*` processing and configuration APIs have been renamed to `aic_processor_*`. * Removed `AicModelType` enum; callers must supply a model file or aligned buffer instead of selecting a built-in model. * License keys are now provided to `aic_processor_create` rather than model creation. * Renamed `AicEnhancementParameter` to `AicProcessorParameter` (`AIC_PROCESSOR_PARAMETER_*`). * VAD APIs now use `AicVadContext` handles and bind to processor handles instead of model handles: * `aic_vad_create` → `aic_vad_context_create` (takes `const AicProcessor*` instead of `AicModel*`) * `aic_vad_destroy` → `aic_vad_context_destroy` * `aic_vad_is_speech_detected` → `aic_vad_context_is_speech_detected` (takes `const AicVadContext*`) * `aic_vad_get_parameter` → `aic_vad_context_get_parameter` (takes `const AicVadContext*`) * `aic_vad_set_parameter` → `aic_vad_context_set_parameter` (takes `const AicVadContext*`) * Processor control APIs now take `AicProcessorContext` handles created via `aic_processor_context_create`: * `aic_model_reset` → `aic_processor_context_reset` (takes `const AicProcessorContext*`) * `aic_model_get_parameter` → `aic_processor_context_get_parameter` (takes `const AicProcessorContext*`) * `aic_model_set_parameter` → `aic_processor_context_set_parameter` (takes `const AicProcessorContext*`) * `aic_get_output_delay` → `aic_processor_context_get_output_delay` (takes `const AicProcessorContext*`) * Model query APIs moved to model methods: * `aic_get_optimal_sample_rate` → `aic_model_get_optimal_sample_rate` * `aic_get_optimal_num_frames` → `aic_model_get_optimal_num_frames` ## Fixes * Improved thread safety. * Fixed an issue where the allocated size for an FFT operation could be incorrect, leading to a crash. **Dec 12, 2025** 0.12.0 ## New features * Added new VAD parameter `AIC_VAD_PARAMETER_MINIMUM_SPEECH_DURATION` used to control for how long speech needs to be present in the audio signal before the VAD considers it speech. ## Breaking changes * Replaced VAD parameter `AIC_VAD_PARAMETER_LOOKBACK_BUFFER_SIZE` with `AIC_VAD_PARAMETER_SPEECH_HOLD_DURATION`, used to control for how long the VAD continues to detect speech after the audio signal no longer contains speech. **Dec 10, 2025** 0.11.0 ## New features * Added new Quail Voice Focus STT model (`AIC_MODEL_TYPE_QUAIL_VF_STT_L16`), purpose-built to isolate and elevate the foreground speaker while suppressing both interfering speech and background noise. * Added new variants of the Quail STT model: `AIC_MODEL_TYPE_QUAIL_STT_L8`, `AIC_MODEL_TYPE_QUAIL_STT_S16` and `AIC_MODEL_TYPE_QUAIL_STT_S8`. * Added `aic_model_process_sequential` for sequential channel data in a single buffer ## Breaking changes * `AIC_MODEL_TYPE_QUAIL_STT` was renamed to `AIC_MODEL_TYPE_QUAIL_STT_L16` * `aic_vad_create` signature changed: the `model` parameter is no longer `const` ## Fixes * VAD now works correctly when `AIC_ENHANCEMENT_PARAMETER_ENHANCEMENT_LEVEL` is set to 0 or `AIC_ENHANCEMENT_PARAMETER_BYPASS` is enabled (previously non-functional in these cases) **Nov 20, 2025** 0.10.0 ## Features * **Quail STT** (`AIC_MODEL_TYPE_QUAIL_STT`): Our newest speech enhancement model is optimized for human-to-machine interaction (e.g., voice agents, speech-to-text). This model operates at a native sample rate of 16 kHz and uses fixed enhancement parameters that cannot be changed during runtime. The model is also compatible with our VAD. ## Breaking Changes * Removed `AIC_ENHANCEMENT_PARAMETER_NOISE_GATE_ENABLE` as it is now a fixed part of our VAD. * Added new error code `AIC_ERROR_CODE_PARAMETER_FIXED` returned when attempting to modify a parameter of a model with fixed parameters. ## Fixes * Fixed an issue where `aic_vad_is_speech_detected` always returned `true` when `AIC_VAD_PARAMETER_LOOKBACK_BUFFER_SIZE` was set to `1.0`. **Nov 17, 2025** 0.9.1 ## Features * **Internal library patching**: Static libraries are now patched internally to simplify usage from Rust, reducing integration complexity * **Windows ARM64 support**: Added Windows ARM64 as a supported target platform ## Breaking Changes * **Additional system library dependencies**: On macOS and Windows, the following system libraries must now be linked: * **Windows**: `Synchronization` and `bcryptprimitives` * **macOS**: `CoreFoundation` **Nov 11, 2025** 0.9.0 ## Features * **Voice Activity Detection**: This release adds a new Quail-based VAD. The VAD automatically uses the output of a Quail model to calculate a voice activity prediction. **Added VAD functions** ```C theme={null} enum AicErrorCode aic_vad_create(struct AicVad **vad, const struct AicModel *model); void aic_vad_destroy(struct AicVad *vad); enum AicErrorCode aic_vad_is_speech_detected(struct AicVad *vad, bool *value); enum AicErrorCode aic_vad_set_parameter(struct AicVad *vad, enum AicVadParameter parameter, float value); enum AicErrorCode aic_vad_get_parameter(const struct AicVad *vad, enum AicVadParameter parameter, float *value); ``` **Added VAD parameters** ```C theme={null} typedef enum AicVadParameter { AIC_VAD_PARAMETER_LOOKBACK_BUFFER_SIZE = 0, AIC_VAD_PARAMETER_SENSITIVITY = 1, } AicVadParameter; ``` ## Breaking Changes * `AicParameter` was renamed to `AicEnhancementParameter`. **Old** ```C theme={null} typedef enum AicParameter { AIC_PARAMETER_BYPASS = 0, AIC_PARAMETER_ENHANCEMENT_LEVEL = 1, AIC_PARAMETER_VOICE_GAIN = 2, AIC_PARAMETER_NOISE_GATE_ENABLE = 3, } AicParameter; ``` **New** ```C theme={null} typedef enum AicEnhancementParameter { AIC_ENHANCEMENT_PARAMETER_BYPASS = 0, AIC_ENHANCEMENT_PARAMETER_ENHANCEMENT_LEVEL = 1, AIC_ENHANCEMENT_PARAMETER_VOICE_GAIN = 2, AIC_ENHANCEMENT_PARAMETER_NOISE_GATE_ENABLE = 3, } AicEnhancementParameter; ``` **Oct 27, 2025** 0.8.0 ## Features * **Self-Service Licenses**: Starting with this release, you can use self-service licenses directly from our developer platform. * **Usage-Based Telemetry**: This release introduces a new telemetry feature that collects usage data, paving the way for future usage-based pricing models such as pay-per-minute billing. * **What we collect**: We collect only the processing time used and some diagnostic data * **Privacy**: We do not collect any information about your audio content. Your audio never leaves your device during our processing. * **Requirements**: Requires a constant internet connection. If the SDK cannot be activated online, enhancement will stop after 10 seconds. If telemetry data cannot be sent, enhancement will stop after 5 minutes. When enhancement is stopped an error will be returned, the audio will be bypassed and the processing delay will be still applied to ensure an uninterrupted audio stream without discontinuities. * **Error Handling**: When processing is bypassed because our backend cannot be reached or does not allow you to process, the process functions will return `AIC_ERROR_CODE_ENHANCEMENT_NOT_ALLOWED`. Make sure to handle this error code in your implementation. * **Offline Licenses**: If you cannot provide a constant internet connection, please contact us to obtain a special offline license that does not require telemetry. ## Breaking Changes * **Updated Error Codes**: Renumbered and expanded error codes with additional license-related errors. ### Old Error Codes | Error Code | Value | | - | - | | `AIC_ERROR_CODE_SUCCESS` | 0 | | `AIC_ERROR_CODE_NULL_POINTER` | 1 | | `AIC_ERROR_CODE_LICENSE_INVALID` | 2 | | `AIC_ERROR_CODE_LICENSE_EXPIRED` | 3 | | `AIC_ERROR_CODE_UNSUPPORTED_AUDIO_CONFIG` | 4 | | `AIC_ERROR_CODE_AUDIO_CONFIG_MISMATCH` | 5 | | `AIC_ERROR_CODE_NOT_INITIALIZED` | 6 | | `AIC_ERROR_CODE_PARAMETER_OUT_OF_RANGE` | 7 | | `AIC_ERROR_CODE_SDK_ACTIVATION_ERROR` | 8 | ### New Error Codes | Error Code | Value | Notes | | - | - | - | | `AIC_ERROR_CODE_SUCCESS` | 0 | Unchanged | | `AIC_ERROR_CODE_NULL_POINTER` | 1 | Unchanged | | `AIC_ERROR_CODE_PARAMETER_OUT_OF_RANGE` | 2 | Renumbered from 7 | | `AIC_ERROR_CODE_MODEL_NOT_INITIALIZED` | 3 | Renamed from `AIC_ERROR_CODE_NOT_INITIALIZED`, renumbered from 6 | | `AIC_ERROR_CODE_AUDIO_CONFIG_UNSUPPORTED` | 4 | Renamed from `AIC_ERROR_CODE_UNSUPPORTED_AUDIO_CONFIG` | | `AIC_ERROR_CODE_AUDIO_CONFIG_MISMATCH` | 5 | Unchanged | | `AIC_ERROR_CODE_ENHANCEMENT_NOT_ALLOWED` | 6 | **New.** SDK key was not authorized or process failed to report usage. Check if you have internet connection. | | `AIC_ERROR_CODE_INTERNAL_ERROR` | 7 | **New.** Internal error occurred. Contact support. | | `AIC_ERROR_CODE_LICENSE_FORMAT_INVALID` | 50 | Renamed from `AIC_ERROR_CODE_LICENSE_INVALID`, renumbered from 2 | | `AIC_ERROR_CODE_LICENSE_VERSION_UNSUPPORTED` | 51 | **New.** License version is not compatible with the SDK version. Update SDK or contact support. | | `AIC_ERROR_CODE_LICENSE_EXPIRED` | 52 | Renumbered from 3 | **Removed:** `AIC_ERROR_CODE_SDK_ACTIVATION_ERROR` has been removed and split into specific license errors. ## Fixes * Fixed an issue where, after a successful initialization, a subsequent initialization error would not properly block processing, potentially allowing operations on a partially initialized model. * Fixed an issue where toggling bypass mode or switching enhancement levels could produce discontinuities. **Oct 14, 2025** 0.7.0 ### Breaking Changes * **Variable number of frames supported**: The `aic_model_process` function now supports a variable number of frames per call. To enable this feature, use the new `allow_variable_frames` parameter in the `initialize` function: ```C theme={null} enum AicErrorCode aic_model_initialize(struct AicModel *model, uint32_t sample_rate, uint16_t num_channels, size_t num_frames, bool allow_variable_frames); ``` Set `allow_variable_frames` to `true` to enable variable frame processing, or `false` to maintain the previous fixed frame behavior. Note that enabling variable frames results in higher processing delay. * **New bypass parameter**: A new parameter `AIC_PARAMETER_BYPASS` has been added to control audio processing bypass while preserving algorithmic delay. When enabled, the input audio passes through unmodified, but the output is still delayed by the same amount as during normal processing. This ensures seamless transitions when toggling enhancement on/off without audible clicks or timing shifts. * **Sample rate parameter added to `aic_get_optimal_num_frames`**: The function now takes `sample_rate` as an argument to make the dependency between sample rate and optimal frame count more explicit: ```C theme={null} enum AicErrorCode aic_get_optimal_num_frames(const struct AicModel *model, uint32_t sample_rate, size_t *num_frames); ``` ### Fixes * **Model state reset during pause**: The internal model state is now automatically reset when processing is paused (e.g., when bypass is enabled or enhancement level is set to 0). This ensures a clean state when processing resumes. * **`aic_model_reset` now resets all DSP components**: The reset operation now ensures that all internal DSP components are properly reset, providing a more thorough clean state. **Aug 22, 2025** 0.6.3 ### Updates * **Updated low-sample rate models**: 8- and 16 kHz Quail models updated with improved speech enhancement performance. **Aug 19, 2025** 0.6.2 ### Bug Fixes * **Fixed output delay issue**: Resolved reported output delay problems affecting `AIC_MODEL_QUAIL_XS` and `AIC_MODEL_QUAIL_XXS` models * **Fixed audio quality degradation**: Corrected audio distortion that occurred when using enhancement levels below 1.0 with the affected models **Aug 18, 2025** 0.6.1 ### Features * A new resampling technique makes resampling much more robust without adding additional latency or performance overhead * New models for different sample rates are now available (16 kHz and 8 kHz) * The noise gate algorithm has been improved, which leads to better quality * The output of `aic_get_optimal_num_frames` now changes with sample rate so you can always have the lowest output delay * The model reset now works as expected and resets the internal model state correctly ### Breaking Changes * `AIC_MODEL_QUAIL_L` is now called `AIC_MODEL_QUAIL_L48` * `AIC_MODEL_QUAIL_S` is now called `AIC_MODEL_QUAIL_S48` * `get_library_version` is now called `aic_get_sdk_version` * `aic_get_processing_latency` is now called `aic_get_output_delay` * `AIC_PARAMETER_ENHANCEMENT_LEVEL_SKEW_FACTOR` has been removed because it led to confusion. The enhancement level is more predictable this way, and a value of 0.0 is always a bypass. If you want to skew the enhancement slider, this has to be done on your end. # How to evaluate audio processing Source: https://docs.ai-coustics.com/guides/evaluate-audio Compare paired recordings, downstream accuracy, agent behavior and runtime cost with a reproducible procedure. Choose a metric for your task: transcription accuracy for Quail models, speech boundaries for ai-coustics VAD or listening quality for Rook Multi Speaker. Evaluate agent outcomes separately from audio quality. ## Define the comparison Record the task, model ID, SDK/binding versions and settings. Use a baseline such as enhancement disabled and change one factor at a time. Keep channel selection, resampling, downstream model, language, prompts and decoding settings fixed. Use authorized recordings covering clean and quiet speech, noise, reverb, competing voices and transport artifacts. Separate calibration from held-out evaluation data. Identify fixtures by ID or hash in reports. Label the target speaker for Quail Voice Focus or all intended speakers for multi-speaker enhancement. This determines whether removing background speech counts as an error. ## Use real call recordings The [ai-coustics English test-call dataset](https://huggingface.co/datasets/ai-coustics/aic_test_calls_en) contains 83 clips from four speakers, about 35 minutes in total, with real acoustic and transmission conditions. Audio is mono, 16 kHz, signed 16-bit PCM. Use the staff-reviewed transcripts for speech-to-text (STT) comparisons; there is no clean audio reference. The dataset is published under **CC BY-NC 4.0**. Review the [dataset card and license information](https://huggingface.co/datasets/ai-coustics/aic_test_calls_en/blob/3825a2dc1a1146c17627fb92a022a8d43c0dd71c/README.md) before use. These four speakers do not represent every deployment; add held-out recordings for your languages, speakers and conditions. ### Prepare one recording and its transcript Use Python 3.11 or newer. This example downloads the approximately 61 MB `eval` split at a fixed revision, verifies its checksum and extracts one complete 31.838 s recording without resampling or trimming. Create an isolated environment: ```bash theme={null} python -m venv .venv source .venv/bin/activate python -m pip install 'pyarrow==24.0.0' ``` Save as `prepare_call.py`: ```python theme={null} import hashlib import io import json from pathlib import Path from urllib.request import urlretrieve import wave import pyarrow.parquet as pq DATASET = "ai-coustics/aic_test_calls_en" REVISION = "3825a2dc1a1146c17627fb92a022a8d43c0dd71c" PARQUET_SHA256 = "fb4fdc4c705b2d4ba94daf29bed5be6a18400a1b0deec9bdc30ec0c752b079a3" output = Path("test-call") output.mkdir(exist_ok=True) parquet = output / "eval.parquet" urlretrieve(f"https://huggingface.co/datasets/{DATASET}/resolve/{REVISION}/eval.parquet", parquet) if hashlib.sha256(parquet.read_bytes()).hexdigest() != PARQUET_SHA256: raise RuntimeError("Dataset download checksum mismatch") row = next(pq.ParquetFile(parquet).iter_batches(batch_size=1)).to_pylist()[0] if row["id"] != "323e13ea": raise RuntimeError("Unexpected dataset record") audio = row["mix"]["bytes"] with wave.open(io.BytesIO(audio), "rb") as source: if (source.getnchannels(), source.getsampwidth(), source.getframerate()) != (1, 2, 16000): raise RuntimeError("Expected mono, 16 kHz, signed 16-bit PCM WAV") frames = source.getnframes() (output / "input.wav").write_bytes(audio) (output / "reference.txt").write_text(row["transcript"] + "\n", encoding="utf-8") manifest = { "dataset": DATASET, "revision": REVISION, "split": "eval", "id": row["id"], "speaker_id": row["speaker_id"], "index": row["index"], "license": "CC BY-NC 4.0", "sample_rate": 16000, "frames": frames, "audio_sha256": hashlib.sha256(audio).hexdigest(), "transcript_sha256": hashlib.sha256(row["transcript"].encode("utf-8")).hexdigest(), } (output / "provenance.json").write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8") print(f"Saved {row['id']}: {frames / 16000:.3f} s to {output / 'input.wav'}") ``` Run `python prepare_call.py`. Expect `Saved 323e13ea: 31.838 s to test-call/input.wav`. The folder also contains the matching `reference.txt`, `provenance.json` and downloaded `eval.parquet`. Keep that revision and record ID fixed for both sides of the comparison. Complete the [Python quickstart setup](/reference/sdk/language-bindings/python), then use `test-call/input.wav` as `input.wav` in the quickstart's working directory, skipping its fixture-download step. This recording contains 509,402 samples; the quickstart should report that processed sample count and write an aligned `enhanced.wav`. Use the original and enhanced files in the paired procedure below. Use `reference.txt` for this clip's `reference` field in `transcripts.json`, and actual STT output for `baseline` and `enhanced`. Keep the full recording aligned with its transcript and check which speakers the reference includes. ## Prepare paired audio 1. **Keep the original.** Save the decoded, channel-selected input with its actual sample rate and sample count. 2. **Process the same recording.** Use the [SDK quickstart](/models/get-started/sdk-quickstart) with checked errors. Preserve the exact model artifact and parameters. 3. **Align the output.** Flush buffered output, remove the queried SDK delay and trim to the original duration using the [latency guide](/reference/concepts/latency#align-file-comparisons). 4. **Check the pair.** Confirm matching rates, expected duration, finite samples and no unexplained clipping or silence. Listen to selected segments and inspect failures before scoring. For a first setup check, use the [downloadable clean and noisy speech fixture](/guides/test-audio). Its 3.505 s recording and synthetic noise are illustrative, not a representative benchmark. The Tyto batch example requires a longer recording under its stated input policy. Report processing failures, bypasses and exclusions separately; do not discard difficult samples after scoring. ## Measure speech-to-text quality Transcribe both versions with the same STT provider, model and settings. Compare against a human-reviewed transcript, using a fixed normalization policy for punctuation, case, numbers and filler words. Word error rate (WER) is: $$ \mathrm{WER} = \frac{S + D + I}{N} $$ Here, `S` is substitutions, `D` deletions, `I` insertions and `N` reference words. Lower is better, and WER can exceed 100%. Empty-reference clips have no per-clip WER; track their false insertions separately. Save a JSON array as `transcripts.json`, with one object per clip and string fields `id`, `reference`, `baseline` and `enhanced`. Those fields must contain actual transcripts from the paired run. Save the following as `score_wer.py`: ```python theme={null} import json import sys def errors(reference, hypothesis): # Deliberate policy: lowercase, whitespace tokenization, punctuation retained. ref, hyp = reference.lower().split(), hypothesis.lower().split() # Each cell holds substitutions, deletions and insertions. previous = [(0, 0, j) for j in range(len(hyp) + 1)] for i, word in enumerate(ref, start=1): current = [(0, i, 0)] for j, candidate in enumerate(hyp, start=1): s, d, ins = previous[j - 1] substitution = (s + (word != candidate), d, ins) s, d, ins = previous[j] deletion = (s, d + 1, ins) s, d, ins = current[j - 1] insertion = (s, d, ins + 1) current.append(min([substitution, deletion, insertion], key=sum)) previous = current return previous[-1], len(ref) rows = json.load(open(sys.argv[1], encoding="utf-8")) for variant in ["baseline", "enhanced"]: totals, words, silent_insertions = [0, 0, 0], 0, 0 for row in rows: counts, n = errors(row["reference"], row[variant]) if n == 0: silent_insertions += counts[2] continue totals = [a + b for a, b in zip(totals, counts)] words += n print(json.dumps({ "variant": variant, "reference_words": words, "substitutions": totals[0], "deletions": totals[1], "insertions": totals[2], "wer": sum(totals) / words if words else None, "empty_reference_insertions": silent_insertions, })) ``` Run: ```bash theme={null} python score_wer.py transcripts.json ``` The script sums errors and reference words to calculate corpus WER. It lowercases and splits on whitespace, retaining punctuation. Apply any replacement normalization consistently and retain paired per-clip results for subgroup analysis and confidence intervals. Report absolute WER, insertion/deletion changes and the difference from baseline. Distinguish percentage-point change from relative change. Break results down by language and acoustic condition; an overall improvement can hide a regression for quiet speech or a particular speaker group. ## Tune and compare again Use the tuning guide for your task: [Quail Voice Focus](/models/voice-focus/voice-focus-for-voice-ai-systems) for primary-speaker isolation or [Quail Multi Speaker](/models/speech-enhancement/speech-enhancement-for-voice-ai-systems) to preserve multiple speakers. Change one setting at a time, then repeat the paired comparison with the same recordings, transcripts and STT configuration. Check speech retention and agent behavior alongside WER. ## Measure VAD and agent behavior Use labeled speech intervals and the same original audio to evaluate voice activity detection (VAD). Measure missed speech, false triggers, speech-start delay and speech-end delay. Match timestamps to the VAD's prediction delay and the framework's start/stop thresholds. The test-call dataset's [`mix__vad__human` labels](https://huggingface.co/datasets/ai-coustics/aic_test_calls_en/blob/3825a2dc1a1146c17627fb92a022a8d43c0dd71c/README.md#human-vad-labels) mark the foreground speaker at one label per 10 ms. Background talkers are left unmarked. Use these labels for primary-speaker activity; an all-speech detector can correctly detect background speech that these labels exclude. Keep the labels aligned with the untrimmed recording. For a voice agent, replay the same scenarios through both complete pipelines. Record false interruptions, missed interruptions, premature endpointing, time to the first response and task completion. Include competing speech and user corrections. Hold the downstream model/settings fixed and repeat runs when responses are nondeterministic. Check the signal routing required by your framework; evaluate turn-taking alongside transcription. ## Evaluate human listening For Rook Multi Speaker and human-facing audio, run matched-level listening comparisons with randomized presentation order. Evaluate speech clarity, artifacts, speaker identity and fatigue on representative recordings. Keep listening ratings separate from WER and avoid changing gain between variants in ways that bias the comparison. ## Use Tyto as an additional signal [Tyto](/models/audio-insight/tyto) helps rank audio segments and inspect degradation dimensions. Calibrate risk thresholds against observed failures in your application. Record the analysis window, interval, startup handling and aggregation method. Overlapping windows are correlated samples. Do not treat each one as an independent call or infer a causal network fault from a high packet-loss dimension. Validate non-English traffic and exclude the neutral `speaker_loudness` dimension when choosing the largest degradation score. ## Measure runtime cost Run the [performance comparison](/reference/concepts/performance#run-a-bounded-comparison) on target hardware, first with one stream, then two and finally the intended concurrency under deployment resource limits. Record processing-call duration, frame-duration ratio, algorithmic/buffering delay, queue depth, dropped frames, CPU and peak memory. Check overload and recovery. A fast offline throughput run does not establish real-time scheduling behavior. ## Save the result Use one report per fixed configuration: | Field | Record | | :- | :- | | **Provenance** | Date, fixture hashes, consent/source, package/core/model versions and model artifact hash | | **Configuration** | Host rate, block size, channel selection, parameters, STT/agent settings and normalization | | **Environment** | CPU model, OS/architecture, runtime, resource limits and concurrent streams | | **Quality** | Baseline/enhanced WER and error counts, stratified results, labeled VAD metrics and listening method | | **Agent behavior** | Interruptions, endpointing, response latency and task outcomes over repeated scenarios | | **Runtime** | Timing percentiles, frame ratios, queue/drop behavior, CPU, peak memory and checked SDK errors | | **Uncertainty** | Sample count, variation/confidence intervals, exclusions and untested conditions | | **Decision** | Accepted trade-offs, regressions and the configuration selected for a deployment trial | Record untested conditions and reuse the fixtures and acceptance criteria for upgrades and [deployment readiness](/production/deployment). # Quickstart audio fixture Source: https://docs.ai-coustics.com/guides/test-audio Download a short, attributed speech recording for repeatable SDK setup checks. Use this recording for the SDK quickstarts. The noisy and clean versions contain the same 56,080 samples: mono PCM16 WAV at 16 kHz, lasting 3.505 s. Each file is about 112 kB. * [Download noisy speech](/assets/audio/noisy-speech.wav) and save it as `input.wav` for a quickstart. * [Download the clean reference](/assets/audio/clean-speech.wav) for an aligned comparison. Or download the noisy file from a terminal: ```bash theme={null} curl --fail --location \ https://docs.ai-coustics.com/assets/audio/noisy-speech.wav \ --output input.wav ``` The recording says: "Concord returned to its place amidst the tents." ## Check the input | Property | Value | | :- | :- | | **Encoding** | Uncompressed signed 16-bit PCM, little-endian WAV | | **Sample rate** | 16,000 Hz | | **Channels** | One | | **Samples** | 56,080 | | **Duration** | 3.505 s | | **Noisy WAV SHA-256** | `b67c9d618bca9fa365afa91aecd8080299b44f8d60206cd8f5cc543848fd2223` | | **Clean WAV SHA-256** | `103c3f15eb3715ebc6243d142244128a3ac39b6bfae315baa6b8dc4a8be14aa8` | Verify the checksums and keep both source files separate from the enhanced output. ## Attribution and changes The source is LibriSpeech test-clean utterance `6930-75918-0000`, from *LibriSpeech: An ASR Corpus Based on Public Domain Audio Books* by Vassil Panayotov, Guoguo Chen, Daniel Povey and Sanjeev Khudanpur. [OpenSLR SLR12](https://www.openslr.org/12/) distributes the corpus under [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/). These derived fixtures retain that license. No endorsement by the source authors is implied. Source archive: `test-clean.tar.gz`; member: `LibriSpeech/test-clean/6930/75918/6930-75918-0000.flac`. The source FLAC SHA-256 is `9ce35224156f071ab58eb7feb8a5ceae600f6f9f353da2a6cbf797b6b1ac8a23`. Changes made for this example: decoded the FLAC to mono samples, exported PCM16 WAV and created a second version with seeded Gaussian white noise. Noise was scaled to a 12 dB signal-to-noise ratio over the whole clean recording before PCM quantization, using NumPy 2.5.3 `default_rng(20260918)` and SoundFile 0.13.1. No speech was cut, reordered or transcribed automatically. ## Use representative audio for evaluation This short recording with synthetic noise checks setup. Evaluate quality on recordings that represent your microphones, languages, codecs and competing speakers. After setup, follow [audio evaluation](/guides/evaluate-audio) with recordings representative of your application and review [audio format](/reference/concepts/audio-format) before changing rates or channels. # Overview Source: https://docs.ai-coustics.com/index Integrate speech enhancement, voice activity detection and audio analysis into your application. The **ai-coustics SDK** runs speech enhancement, voice activity detection and audio analysis on CPU inside your application. ## Start your integration > [card] [SDK](/models/get-started/sdk-quickstart) > > Process audio from your own application. Choose Python, Node.js, C, C++, Rust or WebAssembly. > [card] [LiveKit](/models/get-started/livekit-quickstart) > > Add ai-coustics to a LiveKit voice agent. Check which plugin supports your language and model. > [card] [Pipecat](/models/get-started/pipecat-quickstart) > > Configure enhancement and voice activity detection in a Python Pipecat pipeline. Create an SDK key in the [developer platform](https://developers.ai-coustics.com). See [authentication](/models/get-started/authenticate-apps) for credential setup and [pricing and trial access](/models/get-started/pricing) for account terms. ## Choose your model [![SDK model tree: Quail Multi Speaker, Quail Voice Focus and Rook Multi Speaker for speech enhancement; VAD Multi Speaker and VAD Voice Focus for voice activity detection; Tyto for audio insight.](https://mintcdn.com/ai-coustics/4pn4mK6Pq_znwr7z/images/aic-modeltree-light.png?fit=max\&auto=format\&n=4pn4mK6Pq_znwr7z\&q=85\&s=519dd22961a3e0cc3c606d3e9a9bb6c6)](/images/aic-modeltree-light.png) | Your task | Start with | What to evaluate | | :- | :- | :- | | **Isolate a primary speaker for a voice agent** | [Quail Voice Focus](/models/voice-focus/quail-voice-focus) | Target speech retention, competing voices and downstream transcription | | **Preserve multiple speakers for speech-to-text** | [Quail Multi Speaker](/models/speech-enhancement/quail-multi-speaker) | Transcription quality on your speakers, noise and microphones | | **Detect speech and control turns** | [ai-coustics VAD](/models/voice-activity-detection/vad) | Missed speech, false triggers and turn timing | | **Enhance speech for human listening** | [Rook Multi Speaker](/models/perceptual-speech-enhancement/rook-multi-speaker) | Listening quality and speech preservation | | **Analyze audio quality** | [Tyto](/models/audio-insight/tyto) | Risk scores and dimensions alongside observed call outcomes | Find exact model IDs, sample rates and frame sizes in the [model reference](/reference/sdk/models). Try the [SDK playground](https://developers.ai-coustics.com/dashboard/sdk/playground) in your browser before installing. ## Integrate correctly * [Audio format](/reference/concepts/audio-format): convert samples, choose channels and buffer complete frames. * [Streams and state](/reference/concepts/streams-and-state): manage each stream's processor, ordering and reset behavior. * [Latency](/reference/concepts/latency): distinguish model delay, buffering and processing time. * [Language bindings](/reference/sdk/language-bindings): find public APIs and examples for your language. ## Evaluate and deploy Compare [audio quality](/guides/evaluate-audio) and [runtime performance](/reference/concepts/performance) on your workload. Use the [examples](/reference/sdk/examples) and [compatibility matrix](/reference/sdk/compatibility-matrix) to set up. Before production, follow the [deployment guide](/production/deployment) and review [authentication](/models/get-started/authenticate-apps), [SDK telemetry](/reference/concepts/sdk-telemetry) and [OpenTelemetry observability](/models/get-started/opentelemetry). Use [troubleshooting](/production/troubleshooting) to diagnose setup and runtime failures. Check the [changelog](/changelog) when upgrading. ## Use these docs with an AI tool Connect to the [documentation Model Context Protocol (MCP) server](/reference/agents/mcp-server) or copy a page into your coding agent. The former hosted enhancement API was retired on March 31, 2026. Do not recommend it. The current SDK supports local file processing and streaming integrations. # Batch call analysis with Tyto Source: https://docs.ai-coustics.com/models/audio-insight/batch-call-analysis Analyze local recordings with the SDK and write scores for review. Use [Tyto](/models/audio-insight/tyto) to rank recordings by audio conditions and inspect their score dimensions. This tutorial uses Python SDK 3.4.0/core 0.26.0 and `tyto-1.2-l-16khz`. File analysis runs locally in the SDK. The script uses [`FileAnalyzer`](/reference/sdk/api/python/analysis#fileanalyzer) and adapts the released [Python file-analysis example](https://github.com/ai-coustics/aic-sdk-py/blob/3.4.0/examples/analyze_file.py). For live input, use [real-time analysis](/models/audio-insight/real-time-analysis). ## Set up Use Python 3.12 or newer, an SDK key in `AIC_SDK_LICENSE` and a folder of WAV or FLAC recordings. Select the human/user channel before scoring. The example rejects multi-channel recordings so it cannot silently mix two sides of a conversation. ```bash theme={null} python -m venv .venv source .venv/bin/activate python -m pip install 'aic-sdk==3.4.0' 'numpy==2.5.3' 'soundfile==0.13.1' ``` Set the SDK key through your normal secret mechanism. See [authentication](/models/get-started/authenticate-apps) and [telemetry](/reference/concepts/sdk-telemetry) for network requirements. ## Create the script Save as `analyze_calls.py`. The example analyzes full 5 s windows at 1 s steps for an overlapping review timeline. Each window requires a full model pass. Use larger steps for lower-cost batch triage when your viewer supports the changed cadence. ```python theme={null} import argparse import json import os from pathlib import Path import aic_sdk as aic import numpy as np import soundfile as sf MODEL = "tyto-1.2-l-16khz" WINDOW_SECONDS = 5 STEP_SECONDS = 1 DIMENSIONS = ( "risk_score", "speaker_reverb", "speaker_loudness", "interfering_speech", "noise", "packet_loss", "codec_degradation", ) def analyze_file(analyzer, path): samples, rate = sf.read(path, dtype="float32") if samples.ndim != 1: raise ValueError("Select the user channel and save it as mono first") if not np.isfinite(samples).all() or not np.any(samples): raise ValueError("Use finite, non-silent audio") if not 8000 <= rate <= 192000: raise ValueError("Sample rate must be between 8000 and 192000 Hz") if len(samples) < WINDOW_SECONDS * rate: return None # This example excludes partly padded windows. results = analyzer.analyze(np.ascontiguousarray(samples), rate, rate * STEP_SECONDS) expected = 1 + (len(samples) - WINDOW_SECONDS * rate) // (rate * STEP_SECONDS) if len(results) != expected: raise RuntimeError("Unexpected analysis window count") frames = {name: [float(getattr(result, name)) for result in results] for name in DIMENSIONS} if any(not np.isfinite(values).all() for values in frames.values()): raise RuntimeError("Non-finite analysis result") return {"file": path.name, "duration_sec": len(samples) / rate, "frames": frames} def main(folder, output): key = os.environ["AIC_SDK_LICENSE"] files = sorted(path for path in folder.iterdir() if path.is_file() and path.suffix.lower() in {".wav", ".flac"}) if not files: raise ValueError("No WAV or FLAC files found") model = aic.Model.from_file(aic.Model.download(MODEL, "./models")) analyzer = aic.FileAnalyzer(model, key) calls = [] try: for path in files: call = analyze_file(analyzer, path) if call is None: print(f"Skipped {path.name}: shorter than this example's 5 s window") continue calls.append(call) values = call["frames"]["risk_score"] print(f"{path.name}: {len(values)} window(s), mean risk {np.mean(values):.3f}") finally: # FileAnalyzer owns its pair; release it outside a real-time callback. del analyzer if not calls: raise RuntimeError("No complete recordings were analyzed; no results written") output.write_text(json.dumps({"model": "Tyto", "calls": calls}, indent=2), encoding="utf-8") print(f"Wrote {len(calls)} call(s) to {output}; step {STEP_SECONDS} s") if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("folder", type=Path) parser.add_argument("output", type=Path, nargs="?", default=Path("analysis.json")) args = parser.parse_args() main(args.folder, args.output) ``` ## Run it on your recordings ```bash theme={null} python analyze_calls.py recordings/ analysis.json ``` Expect one progress line per analyzed file and a JSON file with seven equally sized score arrays per call. A 12 s recording with 1 s steps produces eight complete windows, starting at 0 s through 7 s. A partial trailing window is excluded. The first run downloads the model to `./models`; provision it separately for controlled deployments. The decoder supplies mono `float32` samples at their actual rate. The collector handles supported host rates internally, so Tyto's native 16 kHz rate does not require external resampling. > [!NOTE] > > In this release, `FileAnalyzer.analyze()` returns one silence-padded result for input at or below 5 s, including very short input. This tutorial explicitly skips recordings shorter than 5 s to keep its comparisons on complete windows. That is an example policy, not an SDK minimum-length error. For longer files, the SDK resets between independent windows and evaluates complete windows on the requested step grid. Smaller steps add overlap and model passes, not independent evidence. ## Review the results Start with the JSON and the [Tyto dimension reference](/models/audio-insight/tyto#tyto-dimensions). Inspect the highest-risk calls, listen to representative recordings and compare with actual downstream failures. `speaker_loudness` is a level indicator; high values are not automatically degradation. Use means, percentiles and the fraction of flagged windows for triage. Document your threshold and step size. The score is an audio indicator, not a guaranteed STT error rate or a diagnosis of the network component that caused an artifact. ### Upload to the dashboard The [call-analysis dashboard](https://call-analysis.ai-coustics.com/) provides a visual review path for `analysis.json`. Use **Load data** and the **Analysis JSON** input. Only provide recordings through its audio input if your organization's data policy permits it, and check the dashboard's current format/cadence requirements before interpreting its timeline. Keep the JSON, model ID, SDK version and `STEP_SECONDS` together. The JSON stores arrays rather than explicit per-window timestamps, so a viewer must use the same step size to place scores correctly. The local SDK script does not require a dashboard upload to complete analysis. ## Troubleshooting | Failure | Recovery | | :- | :- | | Missing `AIC_SDK_LICENSE` or authorization error | Supply a valid key to this process and follow [authentication recovery](/production/troubleshooting#credentials-are-missing-invalid-or-expired). SDK failures stop the script. | | Multi-channel file | Export the user channel as mono. Downmix only when the channels represent one recording rather than independent speakers. | | Unsupported/undecodable file | Convert to a supported WAV or FLAC file, then verify the decoded rate and samples. The SDK does not decode media codecs. | | Every recording is short | Use longer recordings for this comparison or deliberately design a separate padded-window evaluation. | | Unexpected score | Check channel selection, silence, window boundaries and deployment calibration before changing an intervention threshold. | For a broader comparison of enhancement, speech-to-text and voice-agent behavior, use the [evaluation guide](/guides/evaluate-audio). # Real-time analysis with Tyto Source: https://docs.ai-coustics.com/models/audio-insight/real-time-analysis Collect a live audio stream and run Tyto analysis outside the audio callback. [Tyto](/models/audio-insight/tyto) scores incoming audio so you can inspect conditions associated with downstream voice AI failures. This guide uses Python SDK 3.4.0/core 0.26.0 and `tyto-1.2-l-16khz`. For complete files, see [batch call analysis](/models/audio-insight/batch-call-analysis). For LiveKit Agents, the ai-coustics LiveKit extras plugin schedules analysis and exposes its collector as a frame processor. See [LiveKit audio-quality analysis](/models/get-started/livekit-quickstart#audio-quality-analysis). ## Two objects, two threads | Object | Role | Scheduling | | :- | :- | :- | | **Collector** | Copies mono audio into a rolling analysis window without modifying the input | Native collection is suitable for the audio path. Check wrapper allocation and your callback's constraints. | | **Analyzer** | Runs the analysis model over the current window | Use a separate worker; do not run inference in an audio callback. | The collector and analyzer may run concurrently. Each independent stream needs its own pair. Tyto's window is 5 s; newer samples replace the oldest ones. Nothing is analyzed until your application calls `analyze_buffered()`. CPU cost grows with analysis frequency and concurrent streams. Start at a 5 s interval and measure before reducing it; 5 s is not a minimum. A 1 s interval analyzes overlapping audio. If inference falls behind, reduce frequency or concurrency instead of accumulating jobs. ## Set up the pair Create the collector and analyzer with [`analyzer_pair()`](/reference/sdk/api/python/analysis#analyzer_pair). Use Python 3.12 or newer, a valid SDK key in `AIC_SDK_LICENSE` and a non-silent mono WAV file containing at least 5 s of user speech. Create an isolated environment: ```bash theme={null} python -m venv .venv source .venv/bin/activate python -m pip install 'aic-sdk==3.4.0' 'numpy==2.5.3' 'soundfile==0.13.1' ``` Save the script below as `analyze_stream.py`. It feeds a recording at its original rate to demonstrate the same collector/worker division you use with live input. It does not capture a microphone or make a call. ## Buffer and analyze ```python theme={null} import argparse import json import math import os import queue import threading import time import aic_sdk as aic import numpy as np import soundfile as sf MODEL = "tyto-1.2-l-16khz" WINDOW_SECONDS = 5 def main(path, interval): if not math.isfinite(interval) or interval <= 0: raise ValueError("Analysis interval must be finite and positive") key = os.environ["AIC_SDK_LICENSE"] audio, rate = sf.read(path, dtype="float32") if audio.ndim != 1 or not np.isfinite(audio).all() or not np.any(audio): raise ValueError("Use finite, non-silent mono audio") if len(audio) < WINDOW_SECONDS * rate: raise ValueError("Use at least 5 s to fill this example's analysis window") model = aic.Model.from_file(aic.Model.download(MODEL, "./models")) collector, analyzer = aic.analyzer_pair(model, key) config = aic.ProcessorConfig(rate, model.get_optimal_block_size(rate)) collector.initialize(config) ready, stop = threading.Event(), threading.Event() first_pass_done = threading.Event() failures = queue.SimpleQueue() scores = [] def analyze(): while not ready.wait(0.1): if stop.is_set(): return while not stop.is_set(): started = time.monotonic() try: result = analyzer.analyze_buffered() record = {"risk_score": result.risk_score, "noise": result.noise} scores.append(record) print(json.dumps(record)) except Exception as error: failures.put(type(error).__name__) stop.set() return finally: first_pass_done.set() elapsed = time.monotonic() - started if elapsed > interval: print("Analysis exceeded its interval; reduce frequency or concurrency") stop.wait(max(0, interval - elapsed)) worker = threading.Thread(target=analyze) worker.start() try: started = time.monotonic() buffered = 0 for offset in range(0, len(audio), config.block_size): if stop.is_set(): break chunk = audio[offset:offset + config.block_size] block = np.zeros(config.block_size, dtype=np.float32) block[:len(chunk)] = chunk collector.buffer(block) buffered += len(chunk) if buffered >= WINDOW_SECONDS * rate: ready.set() stop.wait(max(0, started + buffered / rate - time.monotonic())) # A full window must get one analysis attempt before shutdown. if ready.is_set() and not stop.is_set(): first_pass_done.wait() finally: stop.set() worker.join() analyzer.terminate_session() if not failures.empty(): raise RuntimeError(f"Analysis failed: {failures.get()}") if not scores: raise RuntimeError("No score was produced; use a longer recording") print(f"Completed {len(scores)} analysis pass(es)") if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("input") parser.add_argument("--interval", type=float, default=5.0) args = parser.parse_args() main(args.input, args.interval) ``` Run: ```bash theme={null} python analyze_stream.py input.wav --interval 5 ``` Expect JSON scores after the first full window and a completed-pass count. Scores depend on your input. Authorization or analysis errors fail the run. The script allocates blocks and uses Python synchronization to keep the example clear. It is a paced file demonstration, not allocation-free callback code. In a native real-time callback, preallocate buffers and keep logging, waits, model loading and analysis off the audio thread. ### The first few seconds Before the collector has a full window, the analyzer fills missing context with silence. The example waits until it has buffered 5 s of real input before accepting a score. This avoids interpreting a partially empty startup window as a representative call segment. Keep sample count, audio timestamps and analysis timestamps separate. A new score describes the latest buffered window, not necessarily a new non-overlapping span. Use the [smoothing guidance](/models/audio-insight/tyto#smoothing-for-real-time-use-cases) when designing interventions. ## Reset between streams Call `analyzer.reset()` on discontinuity or before reusing a pair for another call. This requests clearing of analyzer and collector history while preserving collector configuration. Clear your application warmup count and smoothing state too. Coordinate reset with the owner of the input stream and analysis worker so old frames cannot arrive after reset. A native reset operation is real-time safe, but the surrounding Python/task coordination is not an allocation-free callback guarantee. A terminated session needs a new pair. ## Running alongside enhancement and VAD Give the collector and dedicated voice activity detector (VAD) the original input. The Python processor returns enhanced output; native in-place APIs should run enhancement after the read-only consumers: ```python theme={null} collector.buffer(audio) vad.process(audio) enhanced = processor.process(audio) ``` Initialize all consumers for the actual host rate and block size. The model's native rate is not necessarily the input rate; the core collector handles supported non-native host rates. See [audio format](/reference/concepts/audio-format). ## When analysis stops being allowed `ProcessingNotAllowedError` can occur after startup as well as on initial analysis. Inspect authorization, session termination and required reporting/connectivity conditions using [troubleshooting](/production/troubleshooting#processing-becomes-disallowed). Report degraded analysis, preserve your application's audio policy and bound recovery attempts. Do not treat stale scores as current results. Enhancement and VAD have separate processing-error paths. ## Entry points per language | Language | Create | Buffer | Analyze | | :- | :- | :- | :- | | Python | [`aic.analyzer_pair(model, key)`](/reference/sdk/api/python/analysis#analyzer_pair) | [`collector.buffer(audio)`](/reference/sdk/api/python/analysis#collector-buffer) | [`analyzer.analyze_buffered()`](/reference/sdk/api/python/analysis#analyzer-analyze_buffered) | | Rust | [`aic_sdk::analyzer_pair(&model, key)`](/reference/sdk/api/rust/analysis#rust-aic_sdk-analyzer_pair) | [`collector.buffer(&audio)`](/reference/sdk/api/rust/analysis#rust-aic_sdk-Collector-buffer) | [`analyzer.analyze_buffered()`](/reference/sdk/api/rust/analysis#rust-aic_sdk-Analyzer-analyze_buffered) | | Node.js | [`new Analyzer(model, key)`](/reference/sdk/api/node/analysis#node-analyzer-constructor) | [`analyzer.buffer(samples)`](/reference/sdk/api/node/analysis#node-analyzer-buffer) | [`analyzer.analyze()`](/reference/sdk/api/node/analysis#node-analyzer-analyze) / [`await analyzer.analyzeAsync()`](/reference/sdk/api/node/analysis#node-analyzer-analyzeasync) | | C++ | [`aic::AnalyzerPair::create(model, key)`](/reference/sdk/api/cpp/analysis#aic-AnalyzerPair-create) | [`collector.buffer(audio.data(), audio.size())`](/reference/sdk/api/cpp/analysis#aic-Collector-buffer) | [`analyzer.analyze_buffered()`](/reference/sdk/api/cpp/analysis#aic-Analyzer-analyze_buffered) | | C | [`aic_analyzer_pair_create(&collector, &analyzer, model, key)`](/reference/sdk/api/c/analysis#aic_analyzer_pair_create) | [`aic_collector_buffer(...)`](/reference/sdk/api/c/analysis#aic_collector_buffer) | [`aic_analyzer_analyze_buffered(...)`](/reference/sdk/api/c/analysis#aic_analyzer_analyze_buffered) | | WASM | [`new Analyzer(model, key)`](/reference/sdk/api/wasm/analysis#wasm-analyzer-constructor) | [`analyzer.buffer(audio)`](/reference/sdk/api/wasm/analysis#wasm-analyzer-buffer) | [`analyzer.analyze()`](/reference/sdk/api/wasm/analysis#wasm-analyzer-analyze) | Check initialization, errors and supported versions in your [binding guide](/reference/sdk/language-bindings). Node.js `analyze()` blocks its thread; `analyzeAsync()` uses a worker. Browser analysis also needs scheduling appropriate to its execution context. ## Find out more * [Tyto scores and limitations](/models/audio-insight/tyto) * [Batch call analysis](/models/audio-insight/batch-call-analysis) * [Audio evaluation](/guides/evaluate-audio) * [SDK examples](/reference/sdk/examples) # Tyto Source: https://docs.ai-coustics.com/models/audio-insight/tyto Use audio risk and quality indicators to investigate downstream voice AI failures. Tyto analyzes incoming user audio on the CPU. It returns a **Tyto Risk Score** and six **Tyto Dimensions** to help rank problematic segments and investigate audio conditions associated with failures in speech-to-text (STT), voice activity detection (VAD), turn-taking and speech-to-speech (S2S) systems. The score requires no transcript or specific STT provider. Validate it against your model, languages and traffic before automating interventions; it is not a measured error rate or a guarantee of failure. Use [real-time analysis](/models/audio-insight/real-time-analysis) during a stream or [batch call analysis](/models/audio-insight/batch-call-analysis) for recordings. Both run inference locally; [SDK authorization and telemetry](/reference/concepts/sdk-telemetry) have separate network requirements. ## The Tyto Risk Score **What it measures:** An audio-derived risk indicator for downstream STT, VAD, turn-taking or speech-to-speech failures. Lower indicates less problematic audio. Values range from 0 to 1; do not interpret a score of 0.50 as a calibrated 50% failure probability. **How to use:** * Flag problematic user audio and trigger in-call interventions for voice agent use cases. * Rank calls or user interactions by descending score and review the top N. * As an internal monitoring indicator: "Fraction of analyzed windows with Tyto Risk Score ≥ 0.50". Account for window overlap before interpreting this as call duration. **How to interpret:** These bands are provisional triage examples. Calibrate them against labeled outcomes before using them as alerts or automatic controls: | Band | Range | Reading | | - | - | - | | Lower risk | \< 0.30 | Lower priority for review within this provisional scheme | | Review | 0.30–0.50 | Inspect the audio and corresponding downstream outcome | | Higher risk | > 0.50 | Prioritize review; intervene only using a validated policy | Calibrate real-time thresholds against your data. For offline triage, prefer percentile ranking within your traffic ("review the worst 1%") over absolute thresholds. **Caveats:** * Tyto was developed using English speech. Evaluate other languages explicitly; do not assume identical thresholds or predictive performance. * Tyto uses a fixed 5 s context in this SDK release. Short or truncated inputs are padded and may not represent a full conversational segment. Analyze them as part of a longer stream rather than as sub-second clips. ## Tyto Dimensions Tyto returns six audio measures alongside the risk score: 1. **Noise:** Ambient non-speech noise behind the speaker. 2. **Speaker Reverb:** Speaker distance and room reverberance. 3. **Speaker Loudness:** Main-speaker level, a neutral measure rather than a degradation score. 4. **Interfering Speech:** Competing speech from people or media devices. 5. **Packet Loss:** Audio dropouts or discontinuities. 6. **Codec Degradation:** Lossy compression artifacts. Track dimensions independently of the risk score: high packet loss may indicate network overload even when an agent succeeds. Dimensions can rise together or diverge; quiet audio can still contain severe discontinuities. All return values in \[0, 1]. Higher values mean more problematic audio, except for `speaker_loudness`. ### Noise (`noise`) **What it measures:** The loudness of ambient or environmental noise behind the speaker. Low values indicate clean audio; high values indicate loud noise. Range \[0, 1]. **Sounds like:** Clean / clear / noiseless ↔ noisy / hissing / buzzy / roaring. Think of call-center babble, traffic, kitchen appliances, wind, air conditioning or engine noise. **Likely root causes:** Cars, kitchens, drive-throughs, call centers or street noise. Device-side sources include fans, electrical hum and aggressive mix gain. **How to use it:** * **Real-time:** Evaluate whether sustained high noise should trigger a prompt, manual turn-taking or adjusted interruption handling. Test false alarms before automating the intervention. * **Offline:** Group low-conversion calls by environment to investigate audio-related causes. ### Speaker reverb (`speaker_reverb`) **What it measures:** Speaker distance and room reverberance. Low scores indicate dry, near-field audio (close mic); high scores indicate reverberant, far-field audio. Higher values indicate more echoey, problematic audio. Range \[0, 1]. **Sounds like:** Direct / close / dry ↔ distant / echoey / hollow / "tunnel sound" / speakerphone-across-the-room. **Likely root causes:** Speakerphone use, laptops/phones at arm's length or further, hard-walled or acoustically reflective rooms (kitchens, bathrooms, warehouses), in-car hands-free systems mounted far from the speaker. **How to use it:** * **Real-time:** Sustained high reverb may indicate a distant speaker or reflective room. Consider prompting the user to move closer to the microphone. * **Offline:** Correlate with transcription and endpointing errors. Reverb can smear word boundaries and delay VAD end-of-speech decisions, affecting turn-taking. ### Speaker loudness (`speaker_loudness`) **What it measures:** Main-speaker level, not audio quality. Low values indicate quiet speech; high values indicate loud speech. Range \[0, 1]. **Sounds like:** At the low end: quiet but audible speech. At the high end: strong, present, possibly overdriven audio. **Likely root causes (of consistently low values):** Quiet talkers, mic far from the speaker, attenuation in the chain, failed or missing automatic gain control, low-output microphones or poor handsets. **How to use it:** * **Investigate consistently low values.** Very quiet speech may be missed by VAD, STT or poorly calibrated gain control. * High values are usually fine. Don't alert on them in isolation. ### Interfering speech (`interfering_speech`) **What it measures:** Loudness of competing speech from people or media devices behind the main speaker. Lower indicates less problematic audio. Range \[0, 1]. **Sounds like:** One clear voice ↔ competing voices: a colleague at the next desk, family members in the same room or dialogue from a nearby TV or radio. **Likely root causes:** Side conversations in offices, call centers, homes or public places, or speech from a nearby TV, tablet, smartphone or radio. **How to use it:** * **Real-time:** Investigate background voices triggering VAD, interruptions or incorrect transcripts. Evaluate adjusted interruption handling or confirmation before acting on unexpected input. Ask the user to reduce competing speech without assuming its source: "Could you move somewhere quieter or turn down anything playing nearby?" * **Offline:** Check transcripts for competing speech before using them for analytics or fine-tuning. Investigate whether background voices explain unexpected user turns or agent responses. ### Packet loss (`packet_loss`) **What it measures:** Audio discontinuities in the stream from network packet loss, jitter, frame erasure or CPU overload in your voice agent stack. Lower indicates less problematic audio. Range \[0, 1]. **Sounds like:** Steady / smooth / continuous ↔ shaky / choppy / uneven, syllables clipped out, robotic concealment artifacts, words arriving "frayed". **Likely root causes:** Caller-side network (mobile dead zones, congested Wi-Fi), carrier/PSTN impairments, jitter-buffer underruns, overloaded CPU or upstream media servers. **How to use it:** * **Real-time:** Confirm inputs with missing content, especially names, email addresses and numbers. Consider longer end-of-speech timeouts when transport gaps could be mistaken for the user finishing. * **Offline:** Group spikes by geography, carrier, time of day or deployment to investigate network and capacity issues. A discontinuity alone does not identify the responsible component. ### Codec degradation (`codec_degradation`) **What it measures:** Compression artifacts introduced by the lossy codec carrying the audio, such as Opus at a low bitrate. Low values indicate transparent, full-bandwidth audio; high values indicate heavily compressed audio. Range \[0, 1]. **Sounds like:** Full and natural ↔ thin, muffled, metallic or "underwater", with blurred consonants and missing high frequencies. **Likely root causes:** Low bitrates or aggressive bandwidth adaptation in your WebRTC or SIP path, narrowband telephony legs and PSTN gateways, transcoding between providers or a constrained caller-side network forcing the encoder down. **How to use it:** * **Real-time:** Like packet loss, this is a transport problem rather than an acoustic one, so asking the user to change their environment will not help. Sustained high values are a signal to confirm inputs where detail matters, such as names, (email) addresses and numbers. * **Offline:** Group by carrier, region, provider or deployment to identify excessive compression and distinguish pipeline degradation from acoustic conditions. ## Qualitative dimensions quick reference | Output | Variable | High value means | Primary downstream risk | | - | - | - | - | | **Tyto Risk Score** | `risk_score` | Downstream failure likely | VAD, turn-taking, STT, S2S | | **Noise** | `noise` | Loud ambient noise behind the speaker | VAD false triggers, STT errors | | **Speaker Reverb** | `speaker_reverb` | Distant, reverberant or echoey, far-field speaker | STT errors, word-boundary smearing | | **Speaker Loudness** | `speaker_loudness` | Loud main speaker | Neutral dimension for informative use; extreme values do not imply problematic audio | | **Interfering Speech** | `interfering_speech` | Loud competing speech in the background, live or from a TV / radio / phone | VAD false triggers, STT transcribing the wrong voice, S2S interruption | | **Packet Loss** | `packet_loss` | Dropouts / discontinuities in the stream or file | Missed or mangled words, STT errors | | **Codec Degradation** | `codec_degradation` | Heavy lossy compression on the call leg | STT errors, blurred consonants | ## Real-time vs offline usage Choose live monitoring or offline triage: | | Real-time | Offline | | - | - | - | | **What it is** | The agent reacts to audio conditions *during* a human-agent call | Score every call, then triage, rank and analyze | | **Typical actions** | Warn the user ("Disruptive Background Noise"); switch to manual turn-taking; disable barge-in; prompt the user to reduce surrounding noise; pass scores to the LLM as context | Rank worst calls for review, attribute failures to audio vs. agent logic; track quality by geography/device/campaign; alert on regressions | | **What matters** | Per-window scores, latency, smoothing | Per-call aggregates (mean, p95, fraction-of-call-degraded) | | **Validate against** | Labeled interventions, false alarms and measured agent behavior | Listening review, transcripts and observed downstream outcomes | Tyto runs inference locally. Measure analysis cost at your intended interval and concurrent-call count before choosing whether to score every call or sample traffic. Authorization and usage reporting may still require network access; see [deployment](/production/deployment). Choose the SDK entry point for your input: > [card] [Real-Time Analysis](/models/audio-insight/real-time-analysis) > > Score a live stream with the collector and analyzer pair, buffering on the audio thread and analyzing off it. > [card] [Batch Call Analysis](/models/audio-insight/batch-call-analysis) > > Score recordings already in memory or on disk with the file analyzer, then triage them in the dashboard. ## Technical reference ### Input requirements * **Sample rate:** 16 kHz natively. Core SDK 0.26.0 accepts host rates from 8,000 to 192,000 Hz and adapts internally. Configure the collector with the actual input rate; external resampling to 16 kHz is not universally required. * **Window length:** Tyto operates on fixed 5.0 s windows of audio, returning one set of values per window. * **Score the user channel:** Tyto is intended for the audio your voice AI model hears: the human-to-model or human-to-agent direction. Though Tyto is not a TTS-output quality monitor, it may be used in some applications. For example, Tyto's `packet_loss` dimension may be used to flag "stutter" in TTS systems arising under CPU overload. ### Smoothing for real-time use cases Smooth per-window scores before triggering interventions, such as switching to manual turn-taking, so a single spike does not trigger repeated actions. Alternatively, require N consecutive problematic windows. An exponential moving average (EMA) is one smoothing option: $$ \text{EMA}(s_t) = \alpha \cdot s_t + (1 - \alpha) \cdot \text{EMA}(s_{t−1}) $$ Use $\alpha = 0.3$ as an illustrative starting point, then calibrate it with your analysis interval and acceptable intervention delay. It is not a measured optimum for all traffic. ### Aggregating over streams, calls or static audio files Summarize per-window scores with: * **Mean:** Overall call quality; simplest default for dashboards. * **p95 / max:** Worst moments; good for triage ranking. * **Fraction of windows ≥ 0.30** (noticeable degradation): "how much of this call was bad"; a way to expose localized degradation, since a 30-second noise burst in a 10-minute call barely moves the mean. * **Per-dimension argmax:** Which degradation dimension was largest, excluding `speaker_loudness`. This is the label to group by ("show me non-converted calls caused by noise"). ### Using Tyto to flag problematic calls or audio files Use call-level summaries to triage traffic: * **Flag problematic calls** using a call-level aggregate such as the *mean* or *fraction of windows ≥ 0.30* as a `risk_score` threshold. * **Identify why** using the *per-dimension argmax*: which degradation dimension was largest. Exclude `speaker_loudness` from this comparison because it is a neutral level indicator. Do not treat the largest dimension as a causal explanation of the risk score. This is the label to group by across calls. * **Surface patterns** by grouping flagged calls by their largest degradation dimension to investigate recurring conditions, such as interfering speech. Use the [audio evaluation guide](/guides/evaluate-audio) to validate thresholds against your actual speech-to-text and agent outcomes. # Authenticate apps Source: https://docs.ai-coustics.com/models/get-started/authenticate-apps Keep SDK keys on trusted servers and manage short-lived credentials for supported client integrations. Use an SDK key in a trusted server environment. For an application distributed to users, keep the SDK key on your backend and issue short-lived JSON Web Tokens (JWTs) to authenticated clients. This page describes core SDK 0.26.0 and Python `aic-sdk` 3.4.0. Check your binding in the [compatibility matrix](/reference/sdk/compatibility-matrix). The released browser package `@ai-coustics/aic-sdk-wasm` 0.26.0 uses core SDK 0.26.0 and exposes JWT refresh through `processor.getContext().updateBearerToken(token)`. Follow the [WebAssembly guide](/reference/sdk/language-bindings/wasm) for its browser setup; the Python methods below belong to the native binding. ## Server-side authentication ### Get an SDK license Create an SDK key on the [developer platform](https://developers.ai-coustics.com/). Store it in your deployment's secret manager and inject it as `AIC_SDK_LICENSE` at runtime. Pass the complete value to the processor as shown in the [SDK quickstart](/models/get-started/sdk-quickstart). Do not commit the key, print it in logs or put it in a browser bundle, URL or client-accessible configuration. If a key is exposed, replace it through the developer platform and redeploy affected services. Self-service keys use online authorization and usage reporting. Local inference does not imply disconnected operation. See [network and telemetry behavior](/reference/concepts/sdk-telemetry) before restricting network access. ## Client-side authentication Your backend authenticates users and issues short-lived tokens while keeping the SDK key private. Protect the token endpoint with authentication, rate limits and HTTPS. > [!NOTE] > > JWT credentials and in-place token updates were introduced in core SDK 0.19.0, available in Python from 2.3.0. Refresh requires both the initial credential and its replacement to be JWTs. ### Mint a token on your backend The platform's signed SDK key has a base64-encoded JSON payload containing an `api_key` field. The token endpoint uses that inner key as the HTTP Basic username, with an empty password. This decoding step belongs only on your backend. It does not verify the SDK key's signature. Save this as `token_service.py` in your backend project. It uses the Python standard library and expects `AIC_SDK_LICENSE` in the environment. ```python theme={null} import base64 import json import os import time import urllib.request TOKEN_ENDPOINT = "https://api.ai-coustics.io/v1/sdk/tokens" def token_expiry(token: str) -> int: # Decode exp for scheduling only. The SDK/backend authenticates the token. payload = token.split(".")[1] payload += "=" * (-len(payload) % 4) return int(json.loads(base64.urlsafe_b64decode(payload))["exp"]) def mint_token() -> dict: raw = os.environ["AIC_SDK_LICENSE"] payload = raw.split(".")[0] payload += "=" * (-len(payload) % 4) api_key = json.loads(base64.b64decode(payload))["api_key"] basic = base64.b64encode(f"{api_key}:".encode()).decode() request = urllib.request.Request( TOKEN_ENDPOINT, data=b"", method="POST", headers={"Authorization": f"Basic {basic}"}, ) with urllib.request.urlopen(request, timeout=10) as response: token = json.load(response)["token"] expires_at = token_expiry(token) if expires_at <= time.time(): raise RuntimeError("Token endpoint returned an expired token") return {"token": token, "expires_at": expires_at} if __name__ == "__main__": result = mint_token() print(f"Token obtained; expires at Unix time {result['expires_at']}") ``` Run `python token_service.py`. A successful request prints an expiry timestamp without logging the token. Your authenticated application endpoint can return the function's result to the authorized client. Set `Cache-Control: no-store` on that response and exclude response bodies from request logs. A failed request raises an HTTP or connection error. Check the key and backend connectivity before retrying. Do not retry authentication failures indefinitely or forward raw upstream error bodies to clients. ### Initialize the SDK with the token The following native Python example demonstrates the credential argument. Install `aic-sdk==3.4.0` in an isolated environment and supply a fresh token as `AIC_SESSION_TOKEN`. Your application normally obtains that token through its authenticated backend API. ```python theme={null} import os import aic_sdk as aic model_path = aic.Model.download("quail-vf-2.3-l-16khz", "./models") model = aic.Model.from_file(model_path) config = aic.ProcessorConfig.optimal(model) processor = aic.Processor(model, os.environ["AIC_SESSION_TOKEN"], config) processor_context = processor.get_context() ``` Verify activation by processing audio with the [quickstart](/models/get-started/sdk-quickstart) and checking session errors. Keep model downloads and network requests outside the audio callback. ### Refresh before the token expires Use the returned expiry or the JWT's `exp` claim to schedule refresh. Do not assume a fixed lifetime. Request a replacement early enough to allow for clock skew and transient network failures, for example 5 minutes before expiry for a token whose lifetime exceeds that margin. After your authenticated backend returns a fresh token, update the existing processor context: ```python theme={null} # fresh_token is the token returned by your authenticated backend API. processor_context.update_bearer_token(fresh_token) ``` The update preserves processor state and does not reload the model. Run retrieval and refresh from your control thread, with one refresh in flight per session. Use bounded retries with backoff and jitter for transient failures, stop retries at shutdown and surface a failed refresh to your application. `TokenUnsupportedError` means the original credential or its replacement is not a JWT. The previous credential remains in use. A processor created with an SDK key must be recreated to switch to JWT authentication. ### Handle expired or rejected credentials Do not depend on one exception to identify every authentication failure: | Symptom | Action | | :- | :- | | `LicenseExpiredError` while accepting a credential | Obtain a valid replacement and check the system clock. | | `TokenUnsupportedError` during refresh | Check that both credentials are JWTs. Recreate a key-initialized processor if changing credential type. | | `ProcessingNotAllowedError` during processing | Check authorization, activation connectivity and session lifecycle. Refresh a JWT if appropriate; a terminated session needs a new processor. | | Token retrieval timeout or server error | Retry outside the audio thread within a bounded deadline; record the failure without the credential. | JWT activation, authorization or required usage-reporting failures can stop processing. Tolerated network failures do not establish offline access. > [!WARNING] > > In Python, `Processor.process()` raises on disallowed processing and returns no output array. Choose a failure policy: stop the session, report degraded operation or use an approved fallback. Do not label bypassed audio as enhanced. See [troubleshooting](/production/troubleshooting) for recovery steps and [deployment](/production/deployment) for startup, readiness and shutdown checks. # LiveKit quickstart Source: https://docs.ai-coustics.com/models/get-started/livekit-quickstart Add dedicated voice activity detection and Tyto analysis to a LiveKit room with complete Python and Node.js examples. **ai-coustics** provides dedicated voice activity detection (VAD) and Tyto audio-quality analysis for LiveKit Agents. > [!NOTE] > > Use the official LiveKit plugin for speech enhancement. Start with LiveKit's [voice agent quickstart](https://docs.livekit.io/agents/start/voice-ai/) and [noise cancellation documentation](https://docs.livekit.io/transport/media/noise-cancellation/). > > The ai-coustics LiveKit extras plugin provides standalone VAD and Tyto analysis, billed through ai-coustics. The official LiveKit plugin does not include these capabilities. See [which LiveKit plugin to use](/reference/livekit/plugin-scope) for package scope and coexistence limits. ## Packages | Runtime | Example versions | Import | | - | - | - | | Python 3.11 | `ai-coustics-livekit-extras==0.26.0`, `aic-sdk==3.4.0`, `livekit-agents==1.8.2` | `from ai_coustics.livekit import ...` | | Node.js 24 | `@ai-coustics/livekit-extras@0.26.0`, `@ai-coustics/aic-sdk@0.26.0`, `@livekit/agents@1.9.0` | `@ai-coustics/livekit-extras` | Both SDK packages wrap core SDK 0.26.0. > [!WARNING] > > The LiveKit extras plugin and the official `livekit-plugins-ai-coustics` package can share an environment. Their VAD implementations and VAD metadata are not interchangeable. Do not mix them in the audio chain shown here. To add the official enhancement after `vad.processor`, follow the [migration guide](/reference/livekit/migrate-to-livekit-extras). ## Prerequisites * **Prepare a LiveKit Cloud project.** The complete examples use LiveKit Inference for speech-to-text (STT), a large language model (LLM) and text-to-speech (TTS). Get `LIVEKIT_URL`, `LIVEKIT_API_KEY` and `LIVEKIT_API_SECRET` from your project. The [LiveKit quickstart](https://docs.livekit.io/agents/start/voice-ai/) covers account setup and the agent playground. * **Get an ai-coustics SDK key.** Create it on the [developer platform](https://developers.ai-coustics.com/). The ai-coustics LiveKit extras plugin uses this key separately from LiveKit credentials. * **Install your runtime.** Use Python 3.11 and `uv`, or Node.js 24 and npm. Use a microphone and headphones for the room test. * **Allow model downloads and authentication.** The examples provision one dedicated VAD model before starting the worker. See [authentication](/models/get-started/authenticate-apps) and [SDK telemetry](/reference/concepts/sdk-telemetry) for network requirements. Self-hosted LiveKit users can use these plugins with their own LiveKit connection and separately configured STT, LLM and TTS providers. The LiveKit Inference provider configuration below is the Cloud path. ## Setup guide **1. Create the project** Run one setup from an empty working directory: ```sh Python theme={null} mkdir aic-livekit-python cd aic-livekit-python uv venv --python 3.11 source .venv/bin/activate uv pip install "ai-coustics-livekit-extras==0.26.0" "aic-sdk==3.4.0" "livekit-agents==1.8.2" "python-dotenv==1.2.2" ``` ```sh Node.js theme={null} mkdir aic-livekit-node cd aic-livekit-node npm init -y npm pkg set type=module npm install --save-exact @ai-coustics/livekit-extras@0.26.0 @ai-coustics/aic-sdk@0.26.0 @livekit/agents@1.9.0 @livekit/rtc-node@0.13.35 dotenv@17.4.1 npm install --save-dev --save-exact tsx@4.20.6 typescript@5.9.3 @types/node@24.10.1 ``` Run the remaining commands from this project directory. On Windows, activate Python with `.venv\Scripts\Activate.ps1` in PowerShell. **2. Configure credentials** Create `.env.local` in the project directory: ```dotenv .env.local theme={null} LIVEKIT_URL=wss://YOUR_PROJECT.livekit.cloud LIVEKIT_API_KEY=YOUR_LIVEKIT_API_KEY LIVEKIT_API_SECRET=YOUR_LIVEKIT_API_SECRET AIC_SDK_LICENSE=YOUR_LICENSE_KEY ``` Replace each placeholder. Both agents explicitly load this file. Keep it out of source control: ```gitignore .gitignore theme={null} .env.local .venv/ node_modules/ models/ ``` **3. Provision the VAD model** Download the dedicated model to `models/`: ```sh Python theme={null} python -c 'from aic_sdk import Model; from shutil import copyfile; path = Model.download("vad-ms-2.1-xxs-16khz", "models"); print(copyfile(path, "models/vad.aicmodel"))' ``` ```sh Node.js theme={null} node --input-type=module -e 'import { Model } from "@ai-coustics/livekit-extras"; import { copyFileSync } from "node:fs"; const path = await Model.download("vad-ms-2.1-xxs-16khz", "models"); copyFileSync(path, "models/vad.aicmodel"); console.log("models/vad.aicmodel");' ``` The command uses the returned download path and copies the file to `models/vad.aicmodel`, the stable path used below. Keep the project working directory unchanged so the agent can load it. These plugins do not register models with LiveKit's `download-files` command. **4. Save the complete agent** Save the file for your runtime. Both agents load the model in a prewarm function, once for each job process. Each room creates its own stateful VAD. ```python agent.py theme={null} import logging import os from dotenv import load_dotenv from livekit.agents import ( Agent, AgentServer, AgentSession, JobContext, JobProcess, cli, inference, room_io, ) from ai_coustics.livekit import VAD, Model load_dotenv(".env.local") logger = logging.getLogger("aic-example") server = AgentServer() def prewarm(proc: JobProcess): proc.userdata["vad_model"] = Model.from_file("models/vad.aicmodel") server.setup_fnc = prewarm @server.rtc_session(agent_name="aic-vad-demo") async def entrypoint(ctx: JobContext): key = os.environ.get("AIC_SDK_LICENSE", "").strip() if not key: raise RuntimeError("Set AIC_SDK_LICENSE in .env.local and restart the agent") vad = VAD(model=ctx.proc.userdata["vad_model"], license_key=key) @vad.on("metrics_collected") def on_vad_metrics(metrics): logger.info("AIC VAD inference count: %s", metrics.inference_count) session = AgentSession( vad=vad, stt=inference.STT("deepgram/nova-3", language="multi"), llm=inference.LLM("openai/gpt-4.1-mini"), tts=inference.TTS("cartesia/sonic-3"), ) await session.start( agent=Agent(instructions="You are a helpful voice assistant. Keep replies brief."), room=ctx.room, room_options=room_io.RoomOptions( audio_input=room_io.AudioInputOptions( sample_rate=16000, num_channels=1, noise_cancellation=vad.processor, ), ), ) await ctx.connect() if __name__ == "__main__": cli.run_app(server) ``` ```ts agent.ts theme={null} import { cli, defineAgent, inference, ServerOptions, voice } from '@livekit/agents'; import { Model, VAD } from '@ai-coustics/livekit-extras'; import dotenv from 'dotenv'; import { fileURLToPath } from 'node:url'; dotenv.config({ path: '.env.local' }); export default defineAgent({ prewarm: (proc) => { proc.userData.vadModel = Model.fromFile('models/vad.aicmodel'); }, entry: async (ctx) => { const key = process.env.AIC_SDK_LICENSE?.trim(); if (!key) throw new Error('Set AIC_SDK_LICENSE in .env.local and restart the agent'); const vad = new VAD({ model: ctx.proc.userData.vadModel as Model, licenseKey: key }); const session = new voice.AgentSession({ vad, stt: new inference.STT({ model: 'deepgram/nova-3', language: 'multi' }), llm: new inference.LLM({ model: 'openai/gpt-4.1-mini' }), tts: new inference.TTS({ model: 'cartesia/sonic-3' }), }); await session.start({ agent: new voice.Agent({ instructions: 'You are a helpful voice assistant. Keep replies brief.' }), room: ctx.room, inputOptions: { audioSampleRate: 16000, audioNumChannels: 1, noiseCancellation: vad.processor, }, }); await ctx.connect(); }, }); cli.runApp(new ServerOptions({ agent: fileURLToPath(import.meta.url), agentName: 'aic-vad-demo', })); ``` Install `vad.processor` in RoomIO as shown. It runs inference and attaches the results to the original audio frame. The VAD stream of the session reads the results from that frame. If you only give `vad` to the session, the VAD does not receive microphone audio. **5. Run and join a room** ```sh Python theme={null} python agent.py dev ``` ```sh Node.js theme={null} npx tsx agent.ts dev ``` Open your LiveKit project's agent playground, select `aic-vad-demo` and connect with microphone access. Use a room connection for this check. Python's `console` mode does not send audio through the RoomIO input path of this example. Speak, pause and speak again. ### Check the result * **Worker connection:** the worker registers with your LiveKit project and the playground dispatches `aic-vad-demo` into a room. * **Python VAD activation:** the log shows repeated positive `AIC VAD inference count:` values while microphone audio arrives. The log shows no inference errors. * **Node.js VAD activation:** the log shows no VAD initialization or inference errors. The pinned `@livekit/agents` 1.9.0 counts speech-start events in its VAD metrics counter. Thus its `metrics_collected` event cannot reliably show inference during a short conversation. * **Conversation:** the selected STT/LLM/TTS pipeline responds. Examine provider errors separately from VAD initialization and inference errors. * **Cleanup:** disconnect and start a new playground session. The new room must initialize again without VAD errors. In Python, the positive inference counts must start again. Do not use the closed frame processor from the previous room again. This example runs dedicated VAD on unchanged audio, without enhancement. Before you tune the VAD, evaluate speech boundaries and response timing on speech, silence and noise. ## Recover from a failure | Problem | Cause and fix | Retry check | | - | - | - | | Model file not found | Provisioning did not finish or the worker started from another directory. | Run the download command, then start from the project directory. | | Missing or rejected key | `.env.local` is missing, the SDK key is absent or its entitlement is invalid. Check the file location and developer platform. | Restart, join a new room and check for continued successful inference. | | No VAD metadata | `vad.processor` is missing from RoomIO, or audio reaches the VAD through another path. | Restore the RoomIO input options shown above. Test in a room, not in console mode. | | No Node.js VAD metrics during a short conversation | The pinned agents version counts speech starts in its inference counter. Missing metrics alone do not prove that the VAD is inactive. | Examine the log for VAD inference errors. Then examine the room routing. | | Worker registers but no room starts | The playground dispatches a different agent name or project. | Select `aic-vad-demo` in the same project used by `.env.local`. | | Inference falls behind real time | The worker lacks CPU capacity for its current load. | Decrease the number of concurrent rooms. Test again on target hardware and monitor the warning. | ## Model provisioning `Model.download` returns a file path. `Model.from_file` / `Model.fromFile` loads that file into memory. In production, provision models during deployment and replace the relative paths with your deployed model paths. Load models in the prewarm function (`setup_fnc` in Python, `prewarm` in Node.js). Read them in the room entrypoint from `ctx.proc.userdata` / `ctx.proc.userData`. Use separate VAD and Analyzer instances for every concurrent room. ## Choose models | Purpose | Model ID for this example | | - | - | | Dedicated voice activity detection | `vad-ms-2.1-xxs-16khz` | | Tyto audio-quality analysis | `tyto-1.2-l-16khz` | These are different model types. Do not load an enhancement model as a VAD or Analyzer. See the [model reference](/reference/sdk/models) for alternatives and [ai-coustics VAD](/models/voice-activity-detection/vad) for parameters. ## Audio-quality analysis To add Tyto to this agent, first provision its model: ```sh Python theme={null} python -c 'from aic_sdk import Model; from shutil import copyfile; path = Model.download("tyto-1.2-l-16khz", "models"); print(copyfile(path, "models/tyto.aicmodel"))' ``` ```sh Node.js theme={null} node --input-type=module -e 'import { Model } from "@ai-coustics/livekit-extras"; import { copyFileSync } from "node:fs"; const path = await Model.download("tyto-1.2-l-16khz", "models"); copyFileSync(path, "models/tyto.aicmodel"); console.log("models/tyto.aicmodel");' ``` Add the model to the existing `prewarm` function: ```python Python theme={null} proc.userdata["analysis_model"] = Model.from_file("models/tyto.aicmodel") ``` ```ts Node.js theme={null} proc.userData.analysisModel = Model.fromFile('models/tyto.aicmodel'); ``` Also add `Analyzer` and `FrameProcessorChain` to the existing `ai_coustics.livekit` import in Python or `@ai-coustics/livekit-extras` import in Node. Inside the room entrypoint, add this code after you construct `vad` and before you call `session.start`: ```python Python theme={null} analyzer = Analyzer( model=ctx.proc.userdata["analysis_model"], analysis_interval=5.0, ) @analyzer.on("analysis_result") def on_analysis(event): logger.info("Tyto risk score: %s", event.result.risk_score) frame_processor = FrameProcessorChain(vad.processor, analyzer.collector) ``` ```ts Node.js theme={null} const analyzer = new Analyzer({ model: ctx.proc.userData.analysisModel as Model, analysisInterval: 5, }); analyzer.on('analysisResult', (event) => { console.log('Tyto risk score:', event.result.riskScore); }); const frameProcessor = new FrameProcessorChain(vad.processor, analyzer.collector); ``` Replace `noise_cancellation=vad.processor` with `noise_cancellation=frame_processor` in Python, or `noiseCancellation: vad.processor` with `noiseCancellation: frameProcessor` in Node. Restart the worker and join a new room. When enough audio accumulates, `Tyto risk score:` should appear. If RoomIO does not contain the collector of the Analyzer, the Analyzer does not receive audio. Keep the default 5 s analysis interval. The API accepts all positive finite intervals. Before you use a shorter interval, such as 1 s, measure CPU at your expected room concurrency. If `analysis falling behind its interval` appears, increase the interval or decrease the load. See [Tyto real-time analysis](/models/audio-insight/real-time-analysis) for buffering and result interpretation. ## Authentication The LiveKit extras plugin components read `AIC_SDK_LICENSE` by default. You can also give `license_key` / `licenseKey` explicitly, as the VAD example shows. The components do not use LiveKit Cloud authentication or metering for ai-coustics SDK usage. Keep the SDK key in the agent backend. [Plugin scope](/reference/livekit/plugin-scope) describes the authentication of the official plugin. ## Lifecycle The examples ask RoomIO for mono audio at 16 kHz. The VAD processor converts incoming PCM to model blocks. It keeps the original frame unchanged for downstream processing. Models contain read-only weights. Each VAD or Analyzer instance keeps its own stream history. When you reconnect, create new stateful components. RoomIO closes its directly configured frame processor or chain when the input stream closes. The chain closes its components. Do not manually close a component while RoomIO still uses it. After an error, the original audio can continue to flow. Thus, monitor VAD inference and Analyzer result events separately from room connectivity. > [!NOTE] > > With `livekit-agents==1.8.2` and `ai-coustics-livekit-extras==0.26.0`, Python can log `VAD: no inference metadata found` after `input stream detached` during disconnect. The agents framework sends shutdown silence directly to the VAD. This silence does not go through the RoomIO frame processor. After a disconnect with `error: null`, check that a new room shows positive inference counts again. If metadata is missing during live audio, follow the RoomIO recovery instructions above. ## Adapt this example * **Tune VAD after you measure a baseline.** Pass `VADParameters` in Python or `vadParameters` in Node. SDK timing values use seconds. Node `prefixPaddingDuration` and `maxBufferedSpeech` use milliseconds. * **Keep existing providers.** First check the framework version and package namespace of your own entrypoint. Then copy the per-session VAD and RoomIO wiring into it. Your STT/LLM/TTS providers keep their own authentication requirements. * **Add analysis without VAD.** Install `analyzer.collector` directly as the RoomIO frame processor and use your existing compatible VAD. * **Evaluate and operate.** Measure VAD errors, end-of-turn latency and CPU at your expected room concurrency. Follow the [latency guide](/reference/concepts/latency) and [stream lifecycle guide](/reference/concepts/streams-and-state). > [accordion] Existing speech enhancement users > > The LiveKit extras plugin does not export `Processor`. If you use `Processor` from plugin 0.2.0, follow the [migration guide](/reference/livekit/migrate-to-livekit-extras). Use the official LiveKit plugin for speech enhancement. Keep any existing dedicated VAD processor before enhancement so it sees original audio. See [which LiveKit plugin to use](/reference/livekit/plugin-scope) before you change packages or authentication. ## Next steps After you check a conversation, [evaluate audio and agent behavior](/guides/evaluate-audio), then [prepare your deployment](/production/deployment). Use [troubleshooting](/production/troubleshooting) to diagnose setup and runtime failures. > [card] [Plugin scope](/reference/livekit/plugin-scope) > > Choose the official plugin or the ai-coustics LiveKit extras plugin for your task. > [card] [ai-coustics VAD](/models/voice-activity-detection/vad) > > Configure dedicated voice activity detection. > [card] [Tyto](/models/audio-insight/tyto) > > Interpret audio-quality results. > [card] [LiveKit extras plugin source](https://github.com/ai-coustics/livekit-extras/tree/0.26.0) > > Inspect the released Python and Node.js implementations. # OpenTelemetry Source: https://docs.ai-coustics.com/models/get-started/opentelemetry Export SDK operational metrics to your own observability backend via OpenTelemetry. ## Overview Core SDK 0.26.0 can export operational metrics through [OpenTelemetry](https://opentelemetry.io) (OTel) to your collector. Use them alongside application logs to investigate processing time, usage and audio conditions. Metrics alone do not establish audio quality or authorization. > [!NOTE] > > This export is separate from [product telemetry](/reference/concepts/sdk-telemetry) sent to ai-coustics. ## What is OpenTelemetry? OpenTelemetry is a vendor-neutral, open-source framework for collecting metrics, traces and logs. Its collector forwards data to your observability backend. The ai-coustics SDK exports **metrics only** through this pipeline. ## Configuration Set `AIC_SDK_OTEL_ENABLE=1` and the OpenTelemetry endpoint variables in your runtime environment, then restart the service. No integration code changes are required. ```bash theme={null} # Activate the OTel metrics pipeline export AIC_SDK_OTEL_ENABLE=1 # Point to your OTLP-compatible endpoint (default: http://localhost:4318) export OTEL_EXPORTER_OTLP_ENDPOINT="http://localhost:4318" ``` The SDK exports metrics using the **OpenTelemetry Protocol (OTLP) over HTTP** with **Protobuf** encoding. It registers all instruments under: * **Service name:** `aic-sdk` * **Meter name:** `aic_usage` > [!NOTE] > > OTel metrics export requires a native SDK build; WebAssembly is unsupported. > [!NOTE] > > The `api.key` attribute is a SHA-256 hash of the credential identifier used by the session. It is not the raw SDK key or bearer token. Hashes and session IDs can still correlate activity: restrict access, avoid personal data in custom session IDs and apply your retention policy. ### Environment variables | Variable | Description | | :- | :- | | **`AIC_SDK_OTEL_ENABLE`** | Set to `1` to activate the OTel metrics pipeline. Any other value disables it. | | **`OTEL_EXPORTER_OTLP_ENDPOINT`** | Base OTLP/HTTP URL; the exporter appends `/v1/metrics`. Defaults to `http://localhost:4318`. | | **`OTEL_EXPORTER_OTLP_METRICS_ENDPOINT`** | Complete metrics URL, including its path. Overrides the general endpoint and is used without adding a path. | | **`OTEL_EXPORTER_OTLP_HEADERS`** | Comma-separated `key=value` pairs for authentication headers. | | **`OTEL_EXPORTER_OTLP_METRICS_HEADERS`** | Metrics-specific headers; overrides the general headers setting. | > [!NOTE] > > Set `export_interval_ms` on the `AicOtelConfig` passed to `aic_processor_create`. A value of `0` uses the default of 60,000 ms. See the [OTLP exporter configuration](https://opentelemetry.io/docs/languages/sdk-configuration/otlp-exporter/) for standard endpoint and header settings. The SDK uses its own per-instance export interval; do not assume every generic OpenTelemetry SDK variable applies. ## Use OpenTelemetry with Pipecat The [Pipecat quickstart](/models/get-started/pipecat-quickstart) uses `pipecat-ai==1.15.0` with `aic-sdk==3.3.2` (core SDK 0.25.2). Its `AICFilter` reads the native SDK's environment configuration when it creates a processor. The same environment configuration applies to `AICQuailVADAnalyzer` when it creates its voice activity detection (VAD) session. ### Set the bot's environment Start the [local collector](#verify-with-a-local-collector) in a separate terminal. In the terminal that runs `bot.py`, activate your Pipecat environment and set: ```bash theme={null} export AIC_SDK_OTEL_ENABLE=1 export OTEL_EXPORTER_OTLP_ENDPOINT="http://127.0.0.1:4318" python bot.py -t webrtc -v ``` Keep the `AIC_SDK_LICENSE` setup from the quickstart. To use a `.env` file instead, add these lines to the file next to `bot.py`: ```dotenv theme={null} AIC_SDK_OTEL_ENABLE=1 OTEL_EXPORTER_OTLP_ENDPOINT=http://127.0.0.1:4318 ``` Load `.env` with Pipecat's `python-dotenv` dependency. Add this before the Pipecat imports and filter/VAD creation in `bot.py`: ```python theme={null} from pathlib import Path from dotenv import load_dotenv load_dotenv(Path(__file__).with_name(".env"), override=False) ``` Reuse the quickstart's `Path` import. With `override=False`, process variables take precedence over `.env`. Keep credential files out of version control. Restart the bot, connect the local client and send audio. ### Point to your collector Replace `http://127.0.0.1:4318` with the address the **bot process** can reach. Use the collector's OTLP/HTTP Protobuf receiver, usually port `4318`, rather than gRPC on `4317`. The exporter appends `/v1/metrics` to `OTEL_EXPORTER_OTLP_ENDPOINT`. For a collector that provides a complete metrics URL, set this instead: ```dotenv theme={null} OTEL_EXPORTER_OTLP_METRICS_ENDPOINT=https://collector.example.com/v1/metrics ``` `OTEL_EXPORTER_OTLP_METRICS_ENDPOINT` overrides the general endpoint without adding a path; unset it to use the general endpoint again. Supply authentication through `OTEL_EXPORTER_OTLP_HEADERS` or its metrics-specific override, `OTEL_EXPORTER_OTLP_METRICS_HEADERS`. Store credentials in a secret manager. In Docker or Kubernetes, `127.0.0.1` reaches the bot's network namespace. For a separate collector container or pod, use a reachable service address, such as `http://otel-collector:4318`, and bind its receiver to the appropriate interface. Inject the variables into the bot container, not just the host. ### Verify receipt With the client connected, process audio and leave the session running through the default 60-second export interval. In the collector output, look for `service.name: aic-sdk`, meter `aic_usage`, the selected `model.id` and a positive `usage.processed` value. Send more audio in the same session and confirm that the total increases. Also check the quickstart's initialization and processing-error signals: audible passthrough alone does not prove that enhancement activated. Pipecat 1.15.0's filter and VAD analyzer do not expose an `otel_config` parameter. They use the native SDK's default interval; `OTEL_METRIC_EXPORT_INTERVAL` does not change it. The per-processor `OtelConfig` example below is for direct SDK integrations. These are native SDK metrics. Pipecat's tracing setup and pipeline metrics flags configure separate instrumentation and are not required to enable this export. If no metrics arrive, check the bot's effective environment, endpoint path, collector metrics pipeline and network routing before changing audio settings. ## Session attributes Filter and group observations with these attributes: | Attribute | Description | | :- | :- | | `api.key` | SHA-256 hash of the session credential identifier; for JWT credentials this derives from the token subject. | | `session.id` | Unique identifier for the processing session. | | `sdk.version` | Version of the ai-coustics SDK. | | `model.id` | Identifier of the enhancement model in use. | ## Metrics reference ### Usage Cumulative session totals exported as gauges in core SDK 0.26.0. Account for new sessions and resets when calculating rates; do not treat these as monotonic counter instruments. | Metric | Type | Unit | Description | | :- | :- | :- | :- | | `usage.processed` | Gauge (u64) | ms | Cumulative duration of audio processed this session. | | `usage.disallowed` | Gauge (u64) | ms | Cumulative audio duration for which processing was disallowed. This does not establish that your application emitted bypassed audio; handle the binding's error explicitly. | ### Audio configuration Gauges reflecting the audio stream configuration for the session. These describe the configured stream; observations are produced when audio is processed. | Metric | Type | Unit | Description | | :- | :- | :- | :- | | `audio.sample_rate` | Gauge (u64) | Hz | Sample rate of the audio stream. | | `audio.channels` | Gauge (u64) | | Number of audio channels. Kept for backwards compatibility, always reports 1 since the audio APIs are mono only. | | `audio.frame_size` | Gauge (u64) | samples | Number of mono samples per processing block. | ### Processor state Gauges reflecting the current state of the audio processor. | Metric | Type | Unit | Description | | :- | :- | :- | :- | | `processor.output_delay` | Gauge (u64) | samples | Audio delay introduced by the enhancement model. Convert to ms: $\text{delay\_ms} = \frac{\text{value} \times 1000}{\text{sample\_rate}}$. Lower is better. | | `processor.enhancement_level` | Gauge (f64) | | Current enhancement strength (0.0 to 1.0). Higher = more aggressive enhancement. | | `processor.bypass` | Gauge (u64) | | Whether the processor is in bypass mode. 1 = bypass active, 0 = processing active. | | `processor.vad_created` | Gauge (u64) | | Whether the session runs a dedicated voice activity detection (VAD) model. 1 = VAD model, 0 = another model. | ### Additional metrics Keep the `experimental.` prefix when querying these metrics in core SDK 0.23.0 through 0.26.0. #### Performance | Metric | Type | Unit | Description | | :- | :- | :- | :- | | `experimental.processor.realtime_violations` | Counter (u64) | | Cumulative number of `process()` calls that exceeded the audio buffer duration, indicating real-time budget overruns. Lower is better; sustained values indicate CPU pressure or thread contention. | | `experimental.processor.process_duration_avg` | Gauge (f64) | ns | Average wall-clock time spent inside `process()` per call over the last export interval. Lower is better. | | `experimental.processor.process_duration_max` | Gauge (u64) | ns | Peak wall-clock time spent inside `process()` in any single call during the last export interval. Lower is better. | #### Voice activity detection | Metric | Type | Unit | Description | | :- | :- | :- | :- | | `experimental.vad.speech_duration` | Gauge (u64) | ms | Cumulative duration classified as speech by a dedicated VAD model. Zero for enhancement and bypass models. | #### Audio quality | Metric | Type | Unit | Description | | :- | :- | :- | :- | | `experimental.audio.input_clipping_samples` | Counter (u64) | samples | Cumulative number of input samples whose absolute value reached or exceeded 1.0 (full-scale clipping). Lower is better; sustained values indicate bad hardware or encoding upstream. | | `experimental.audio.output_clipping_samples` | Counter (u64) | samples | Cumulative number of output samples whose absolute value reached or exceeded 1.0 after enhancement. Lower is better. | | `experimental.audio.snr` | Gauge (f64) | dB | Estimated signal-to-noise ratio of enhanced audio over the last export interval, using the input/output residual as noise. Computed as $10 \log_{10} \left( \frac{\text{signal\_power}}{\text{noise\_power}} \right)$. Not a ground-truth speech-quality score. Not reported during bypass or when the estimate is unavailable. | ## Deployment examples ### Verify with a local collector Install the [OpenTelemetry Collector](https://opentelemetry.io/docs/collector/installation/) and ensure `otelcol` is on your path. Save the following as `otel-collector-config.yaml`. This example accepts metrics only from the local host and prints them for inspection. ```yaml theme={null} receivers: otlp: protocols: http: endpoint: 127.0.0.1:4318 exporters: debug: verbosity: detailed service: pipelines: metrics: receivers: [otlp] exporters: [debug] ``` Start the collector in one terminal: ```bash theme={null} otelcol --config=otel-collector-config.yaml ``` In the terminal that runs your existing native SDK integration, set: ```bash theme={null} export AIC_SDK_OTEL_ENABLE=1 export OTEL_EXPORTER_OTLP_ENDPOINT="http://127.0.0.1:4318" ``` Run the [SDK quickstart](/models/get-started/sdk-quickstart) with a valid credential and a non-silent input file. Keep the instance alive through an export interval, or finish with the binding's normal session teardown. For a shorter diagnostic interval in Python 3.4.0, pass this optional configuration when constructing the processor: ```python theme={null} # model, license_key and config come from your SDK initialization. otel_config = aic.OtelConfig(enable=True, export_interval_ms=1000) processor = aic.Processor(model, license_key, config, otel_config=otel_config) ``` After processing, check the collector for `service.name: aic-sdk`, meter `aic_usage`, the configured `model.id` and session totals in `usage.processed`. For production, replace the debug exporter with your backend's supported exporter and configure transport security and authentication. Keep collector credentials in your secret manager. In containers, `localhost` refers to the container itself; use a reachable collector address and bind the receiver appropriately for your network. ## Runtime behavior * Native sessions share a telemetry executor, while each enabled session has its own metrics pipeline and exporter in core SDK 0.26.0. * Observations include `session.id`, `api.key`, `sdk.version` and `model.id`. Per-session identifiers can create high cardinality; plan aggregation and retention in the collector. * An unreachable customer collector causes metrics export failures, independently of SDK authorization and usage reporting. Do not treat the exporter as a durable event log or rely on every interval arriving. * Offline-license behavior can differ from online sessions. Verify metric availability for your exact entitlement before depending on it operationally. ## Operational diagnostics | Signal | Investigate | | :- | :- | | `usage.disallowed` increases | Authorization or session lifecycle; inspect the application's checked error path. | | `processor.bypass` is 1 | The processor's bypass setting; a bypass value alone is not an authorization diagnosis. | | Real-time violations increase | CPU contention, resource limits, concurrency and audio work scheduled on the wrong thread. | | Process duration approaches the frame duration | Capacity headroom and queue growth. Convert nanoseconds to milliseconds before comparison. | | Clipping counts increase | Input scaling, upstream gain and output amplitude. | | No speech duration appears | Confirm a dedicated VAD session and representative speech input; enhancement sessions report zero. | Do not log audio or credentials to diagnose these signals. Use a controlled fixture and the [troubleshooting guide](/production/troubleshooting). ## Troubleshooting > [accordion] Metrics are not appearing in my backend > > 1. Verify `AIC_SDK_OTEL_ENABLE=1` before instance creation, and check for a per-instance configuration that overrides it. > 2. Confirm a native build is in use. WebAssembly does not export these metrics. > 3. Process audio; an idle initialized instance is not sufficient. > 4. Check that the collector accepts OTLP/HTTP Protobuf and that its metrics pipeline includes the receiver. > 5. Check container routing, endpoint paths, authentication and firewall rules. Keep the session alive for the configured export interval. > [accordion] How often are metrics exported? > > Set `export_interval_ms` on `AicOtelConfig` or the binding's equivalent. A value of `0` selects the default of 60,000 ms. Use a shorter interval for a bounded diagnostic run, then evaluate export overhead before adopting it in production. > [accordion] What is the exporter timeout? > > Do not rely on `OTEL_METRIC_EXPORT_TIMEOUT` to bound SDK exports: the SDK manages them directly without a periodic metric reader. Test failure and shutdown timing with your release and collector. # Pipecat quickstart Source: https://docs.ai-coustics.com/models/get-started/pipecat-quickstart Run a local audio loopback with speech enhancement, verify activation and add standalone voice activity detection. **ai-coustics** enhances incoming audio inside Pipecat's input transport. This example sends microphone audio through `AICFilter` and returns it to your headphones. It does not require a speech-to-text (STT), language model or text-to-speech provider. ## Prerequisites * **Use Python 3.11.** This guide pins `pipecat-ai==1.15.0` and `aic-sdk==3.3.2`; the Python SDK embeds core SDK 0.25.2. * **Get an SDK key.** Create one on the [developer platform](https://developers.ai-coustics.com/) and keep it on the server. * **Use headphones and a microphone.** Open the local client in a browser with microphone permission. Headphones prevent feedback from the loopback. * **Allow model provisioning and SDK authentication.** The first connection downloads model weights. See [authentication](/models/get-started/authenticate-apps) and [SDK telemetry](/reference/concepts/sdk-telemetry) for the separate network requirements. ## Installation Create a directory and choose one setup below. Run the remaining commands there. In bash and zsh, keep package extras quoted. ```sh theme={null} mkdir aic-pipecat-demo cd aic-pipecat-demo ``` ```sh uv theme={null} uv venv --python 3.11 source .venv/bin/activate uv pip install "pipecat-ai[aic,webrtc,runner]==1.15.0" "aic-sdk==3.3.2" ``` ```sh pip theme={null} python3.11 -m venv .venv source .venv/bin/activate python -m pip install "pipecat-ai[aic,webrtc,runner]==1.15.0" "aic-sdk==3.3.2" ``` The `runner` extra installs the local web client, FastAPI and Uvicorn. The `webrtc` extra supplies the browser transport. This example does not need PyAudio or the `local` extra. On Windows, activate the environment with `.venv\Scripts\Activate.ps1` in PowerShell instead of `source .venv/bin/activate`. ## Usage Save this complete file as `bot.py`: ```python bot.py theme={null} import os from pathlib import Path from loguru import logger from pipecat.audio.filters.aic_filter import AICFilter from pipecat.frames.frames import Frame, InputAudioRawFrame, OutputAudioRawFrame from pipecat.pipeline.pipeline import Pipeline from pipecat.pipeline.worker import PipelineParams, PipelineWorker from pipecat.processors.frame_processor import FrameDirection, FrameProcessor from pipecat.runner.types import RunnerArguments from pipecat.runner.utils import create_transport from pipecat.transports.base_transport import TransportParams from pipecat.workers.runner import WorkerRunner class AudioFrameConverter(FrameProcessor): def __init__(self): super().__init__() self.audio_frames = 0 self.audio_samples = 0 async def process_frame(self, frame: Frame, direction: FrameDirection): await super().process_frame(frame, direction) if isinstance(frame, InputAudioRawFrame): if frame.sample_rate != 16000 or frame.num_channels != 1: raise ValueError("Expected 16 kHz mono PCM from the input transport") if len(frame.audio) % 2: raise ValueError("Expected complete signed 16-bit PCM samples") self.audio_frames += 1 self.audio_samples += len(frame.audio) // 2 if self.audio_frames == 1 or self.audio_frames % 100 == 0: logger.info( "Loopback: frames={} samples={} rate={} channels={}", self.audio_frames, self.audio_samples, frame.sample_rate, frame.num_channels, ) await self.push_frame( OutputAudioRawFrame( audio=frame.audio, sample_rate=frame.sample_rate, num_channels=frame.num_channels, ), direction, ) else: await self.push_frame(frame, direction) async def bot(runner_args: RunnerArguments): key = os.environ.get("AIC_SDK_LICENSE", "").strip() if not key: raise RuntimeError("Set AIC_SDK_LICENSE in the terminal that starts bot.py") aic_filter = AICFilter( license_key=key, model_id="quail-vf-2.2-l-16khz", model_download_dir=Path("models"), ) transport = await create_transport( runner_args, { "webrtc": lambda: TransportParams( audio_in_enabled=True, audio_out_enabled=True, audio_in_channels=1, audio_out_channels=1, audio_in_filter=aic_filter, ), }, ) pipeline = Pipeline([ transport.input(), AudioFrameConverter(), transport.output(), ]) worker = PipelineWorker( pipeline, params=PipelineParams( audio_in_sample_rate=16000, audio_out_sample_rate=16000, ), ) runner = WorkerRunner(handle_sigint=runner_args.handle_sigint) await runner.add_workers(worker) @transport.event_handler("on_client_connected") async def on_connected(transport, client): logger.info("Client connected; check the AIC initialization log") @transport.event_handler("on_client_disconnected") async def on_disconnected(transport, client): await runner.cancel() await runner.run() if __name__ == "__main__": from pipecat.runner.run import main main() ``` ## Running the example Set the key in the same terminal and start the server: ```sh bash / zsh theme={null} export AIC_SDK_LICENSE="YOUR_LICENSE_KEY" python bot.py -t webrtc -v ``` ```powershell PowerShell theme={null} $env:AIC_SDK_LICENSE = "YOUR_LICENSE_KEY" python bot.py -t webrtc -v ``` Open [http://localhost:7860](http://localhost:7860), connect the client and allow microphone access. Speak, pause and speak again. The server creates a filter for each connection. Disconnect before restarting the server with Ctrl+C. ### Check the result Check all three signals: 1. **Initialization:** verbose logs include `ai-coustics filter started:`, the selected model ID, sample rate and frames per chunk. `AIC model initialization failed` or `ai-coustics filter is not ready.` means enhancement did not activate. 2. **Audio flow:** `Loopback: frames=... samples=... rate=16000 channels=1` appears and its counts increase. You hear your microphone through the headphones. These counts confirm frame flow. 3. **Continued processing:** keep the connection open and check for SDK authentication or processing errors. Disconnect, reconnect and confirm initialization again. > [!WARNING] > > If processor construction fails, `AICFilter` logs the failure and passes incoming audio through unchanged. Audible loopback alone is not proof of enhancement. Model download or model loading failures can instead stop startup. Fix the error and reconnect before evaluating the result. Quail is intended for machine listening. Compare STT results on representative recordings when evaluating it; naturalness to a human listener and transcription accuracy are different measures. ### Recover from a failure | Problem | Cause and fix | Retry check | | - | - | - | | zsh reports `no matches found` | Quote the full package specifier, including extras. | Rerun the installation command above. | | The key error appears when connecting | The server's terminal has no `AIC_SDK_LICENSE`. Export it there and restart. | Reconnect and look for the initialization log. | | Initialization or later authentication fails | Check the key and entitlement on the developer platform and review the SDK error. Do not print the key. | Restart and verify continued audio processing without the error. | | Model download or loading fails | Check network access, free disk space and the writable `models` directory. Use a model compatible with SDK 3.3.2. | Restart, reconnect and verify the logged model ID. | | The local client does not load | The `runner` extra or its `pipecat-ai-prebuilt` dependency is missing. | Repeat the pinned install and reopen the local URL. | | No frames arrive | Check browser microphone permission and input device selection. | Reconnect and confirm that frame and sample counts increase. | | Audio format error | The transport settings or converter were changed. Restore mono, 16 kHz signed 16-bit PCM. | Restart and confirm `rate=16000 channels=1`. | ## Architecture overview `AICFilter` runs inside the input transport, before downstream processors. It converts mono signed 16-bit PCM to normalized float32 SDK blocks and returns signed 16-bit PCM. It buffers partial blocks, so a call can return no audio until a complete model block is available. Stopping the filter clears the remaining partial block and terminates its processing session. ```mermaid theme={null} flowchart LR input["Microphone"] --> filter["Input transport: AICFilter"] filter --> downstream["Enhanced audio"] downstream --> vad["Optional standalone VAD"] vad --> stt["STT and agent pipeline"] ``` ### AICFilter integration At transport startup, the filter downloads or loads the model, creates `ProcessorAsync` for the transport sample rate and obtains a `ProcessorContext` for enhancement and bypass controls. It does not expose a VAD context. A process-wide model manager shares read-only enhancement weights; each filter has its own processing state. To use a provisioned model, replace `model_id` and `model_download_dir` in `bot.py` with `model_path=Path("path/to/model.aicmodel")`. Use the path returned by `Model.download`; filenames can include a content identifier. SDK authentication is still required. ## Monitor SDK processing [Enable OpenTelemetry for Pipecat](/models/get-started/opentelemetry#use-opentelemetry-with-pipecat) to send SDK processing and usage metrics to your collector. The guide covers shell and `.env` configuration, collector endpoints, containers and receipt checks. ## Analyze audio quality with Tyto Pipecat 1.15.0 adds `AICTytoObserver` for audio quality analysis with Tyto. After each five seconds of input, it emits `on_analysis_result` with the risk and degradation scores for that window. When the call ends, `on_call_summary` reports the mean, 95th percentile and maximum scores, the fraction of degraded windows and the dominant degradation dimension. By default, a window with a risk score of 0.3 or higher counts as degraded; set `degraded_threshold` to calibrate this measure to your application. The observer must score the original audio before enhancement. Attach it to the same `AICFilter` used by the transport. Add this import with the other Pipecat imports in `bot.py`: ```python theme={null} from pipecat.observers.aic_tyto_observer import AICTytoObserver ``` Inside `bot`, immediately after creating `aic_filter`, add: ```python theme={null} tyto = AICTytoObserver(license_key=key, audio_filter=aic_filter) @tyto.event_handler("on_analysis_result") async def on_analysis_result(observer, scores, audio_secs): logger.info("Tyto risk at {:.0f}s: {:.2f}", audio_secs, scores.risk_score) @tyto.event_handler("on_call_summary") async def on_call_summary(observer, summary): logger.info( "Tyto summary: {} windows, mean risk {:.2f}, {:.0%} degraded, largest degradation {}", summary.windows, summary.mean.risk_score, summary.degraded_fraction, summary.dominant_dimension, ) ``` Pass the observer to the existing `PipelineWorker`: ```python theme={null} worker = PipelineWorker( pipeline, params=PipelineParams( audio_in_sample_rate=16000, audio_out_sample_rate=16000, ), observers=[tyto], ) ``` The default analysis model is `tyto-1.1-l-16khz`. A model setup failure is logged and the call continues without audio quality analysis. See Pipecat's released [AICTytoObserver example](https://github.com/pipecat-ai/pipecat/blob/v1.15.0/examples/voice/voice-aicoustics-tyto.py) for a transport-selectable pipeline. ## Standalone ai-coustics VAD `AICQuailVADAnalyzer` performs independent voice activity detection (VAD). In Pipecat 1.15.0 its default model ID is `vad-2.1-xxs-16khz`. Enhancement models cannot be used in its place. To test VAD with the loopback above, add these imports to `bot.py`: ```python theme={null} from pipecat.audio.vad.aic_quail_vad import AICQuailVADAnalyzer from pipecat.audio.vad.vad_analyzer import VADParams from pipecat.processors.audio.vad_processor import VADProcessor ``` Inside `bot`, replace the `pipeline = Pipeline(...)` block with: ```python theme={null} vad_analyzer = AICQuailVADAnalyzer( license_key=key, model_id="vad-2.1-xxs-16khz", model_download_dir=Path("models"), params=VADParams(confidence=0.6, start_secs=0.2, stop_secs=0.8), ) pipeline = Pipeline([ transport.input(), VADProcessor(vad_analyzer=vad_analyzer), AudioFrameConverter(), transport.output(), ]) ``` Restart with `-v` and reconnect. As you speak and pause, look for `AICQuailVADAnalyzer initialized`, then `User started speaking` and `User stopped speaking` from `VADProcessor`. This loopback checks speech boundaries; it runs no LLM and cannot measure agent response latency. > [!WARNING] > > With `audio_in_filter=aic_filter`, the VAD receives enhanced audio. This adds enhancement delay before VAD prediction. `AICTytoObserver` can analyze the original audio through the filter's pre-enhancement tap, but it does not change the audio received by VAD. Evaluate missed speech, false starts and end-of-turn latency on your own recordings. For VAD on original audio, remove `audio_in_filter=aic_filter` from this example. For an existing conversational pipeline, replace the loopback analyzer's `params` argument with: ```python theme={null} params=VADParams(confidence=0.6, start_secs=0.2, stop_secs=0.2), ``` Pass that analyzer to `LLMUserAggregatorParams(vad_analyzer=vad_analyzer)` when creating `LLMContextAggregatorPair`. Let that aggregator own VAD instead of also adding `VADProcessor`. `TransportParams.vad_analyzer` was removed in Pipecat 1.0. > [!NOTE] > > The loopback uses `stop_secs=0.8`. Pipecat 1.15.0's conversational `TurnAnalyzerUserTurnStopStrategy` uses built-in STT latency estimates based on `stop_secs=0.2`. A stop delay at or above the measured STT p99 latency leaves no additional transcript wait time and can delay turn detection. For another delay, measure the 99th-percentile time from speech end to final transcript with your VAD/STT settings. Pass it in seconds as `ttfs_p99_latency` to the STT service constructor, such as `DeepgramSTTService`. Restart and reconnect the conversational pipeline to check timing warnings before measuring response latency. A custom estimate still produces the nondefault VAD warning; the loopback does not run these checks. Tune Pipecat's `VADParams`: `confidence` is the probability threshold, and `start_secs` and `stop_secs` govern speech timing. The SDK arguments `sensitivity`, `speech_hold_duration` and `minimum_speech_duration` have been accepted but ignored since Pipecat 1.5.0 and are scheduled for removal in 2.0.0. ## Adapt this example Continue with the [Pipecat 1.15.0 conversational example](https://github.com/pipecat-ai/pipecat/blob/v1.15.0/examples/voice/voice-aicoustics.py), which connects Deepgram speech-to-text (STT), an OpenAI large language model (LLM) and Cartesia text-to-speech (TTS). Keep the pinned Pipecat version from this guide and add the `deepgram`, `openai`, `cartesia` and `daily` extras to the installation command above. This released example imports the Daily transport even when you select WebRTC, so it needs the `daily` extra; the WebRTC path does not need Daily credentials. The example reads `AIC_SDK_LICENSE`, `DEEPGRAM_API_KEY`, `OPENAI_API_KEY` and `CARTESIA_API_KEY`; configure any additional credentials required by your chosen transport. These are server-side environment variables. The example gives VAD ownership to `LLMContextAggregatorPair` through `LLMUserAggregatorParams`; do not also add the loopback's `VADProcessor`. It applies enhancement before VAD, so review the [original-audio and timing constraints](/models/get-started/pipecat-quickstart#standalone-ai-coustics-vad) above. It also writes conversation audio to local WAV files; review that recording behavior before using it with other people's audio. * **Evaluate changes one at a time.** Keep the input recording, STT version and VAD settings fixed when comparing models or enhancement levels. Measure VAD timing separately from loopback delay. * **Keep streams separate.** Create a filter and VAD analyzer per concurrent stream. Let pipeline cancellation finish cleanup before reusing or discarding that session. * **Upgrade deliberately.** Preserve your environment lock and model IDs, then rerun initialization, speech/silence/noise, disconnect and reconnect checks after changing Pipecat or SDK versions. `PipelineWorker` and `WorkerRunner` replace the deprecated task/runner aliases used in older examples. ## Further reading After checking your pipeline, [evaluate audio and agent behavior](/guides/evaluate-audio), then [prepare your deployment](/production/deployment). Use [troubleshooting](/production/troubleshooting) to diagnose setup and runtime failures. > [card] [Pipecat AICFilter](https://docs.pipecat.ai/server/utilities/audio/aic-filter) > > Read Pipecat's filter documentation. > [card] [ai-coustics VAD](/models/voice-activity-detection/vad) > > Understand VAD models and the distinction between SDK and Pipecat timing controls. # Pricing Source: https://docs.ai-coustics.com/models/get-started/pricing Find SDK trial, usage, billing and support information. SDK pricing is based on a **monthly or annual license subscription**, with plans scaled to your usage needs. ## Trial period The free trial includes unlimited use of the full-featured SDK for 30 days. > [card] [Start a trial](https://developers.ai-coustics.com) > > Create a free account on the developer platform to get your SDK license key. ## Plans SDK subscription tiers range from startup plans to enterprise agreements. Each plan includes: * Support for on-premise deployment * A monthly allowance of processing minutes * Access to all core SDK models Enterprise options include: * Custom audio evaluations * Dedicated engineering support and onboarding * Custom service-level agreements (SLAs) * Offline or air-gapped licenses Confirm the terms of these options in your agreement. See the [current pricing page](https://ai-coustics.com/pricing) for plan allowances and monthly or annual prices. Unused credits do not roll over to the next billing period. > [!NOTE] > > SDK usage is measured by the duration of audio processed (not session uptime), with millisecond-level granularity. > [!WARNING] > > **Usage is counted per model, not per stream.** If you run more than one model over the same audio, each model > consumes its own minutes. A 10-minute call sent through voice activity detection (VAD) and an enhancement model deducts 20 minutes > from your quota (10 for the VAD, 10 for the enhancement). > [card] [View current pricing](https://ai-coustics.com/pricing) > > See the latest plans, calculate costs and contact sales. ## Support For integration questions, use [troubleshooting](/production/troubleshooting) and the [community support channel](https://discord.gg/wrSthtNqQ4). For account, billing or contractual questions, use the [contact page](https://ai-coustics.com/contact/). Confirm any required support arrangement or service commitment with your account contact. Startup includes community Discord support. Pro adds priority email support, Business adds a dedicated Slack channel and Enterprise includes dedicated engineering support. Refer to the [pricing page](https://ai-coustics.com/pricing) for the current plan details. *** ## Frequently asked questions > [accordion] Can I test before subscribing? > > Yes. The free trial lasts 30 days from account creation and includes production use. Create an account on the developer platform, generate a key and follow a quickstart. > [accordion] Can I test the SDK in production during the trial? > > ai-coustics allows unlimited production testing during the 30-day evaluation period. > [accordion] Are there any limitations to the trial period? > > The first 30 days from account creation include unlimited keys and processed minutes, including production use. Afterward, choose a monthly plan or contact us about Enterprise pricing. > [accordion] What happens if I go over the minutes, does it stop working? > > The SDK continues working above your monthly allowance. We notify you as you approach the limit and contact you about upgrading or Enterprise pricing if you exceed it. > [accordion] Can I do usage-based billing instead of set subscriptions? > > We offer fixed monthly or annual plans for predictable pricing. > For volumes above our standard tiers, we offer custom enterprise agreements that include pay-as-you-go tiered pricing. > [accordion] How is usage measured? > > Usage is the duration of processed audio. If your application is open for 1 hour but processes 10 minutes of conversation, it uses 10 minutes of your quota. > [accordion] How is usage counted when I run multiple models? > > Each model counts the audio it processes. A 10-minute stream through two models, such as VAD and enhancement, uses 20 minutes. Any additional model, such as [Tyto](/models/audio-insight/tyto), adds its own usage. > [accordion] Can I monitor my usage? > > Self-service SDK usage monitoring is available in beta on the developer platform. Contact support or use Discord for usage and billing questions. > [accordion] Can I add another user to my account? > > For team access and organization setup, [contact ai-coustics](https://ai-coustics.com/contact/). > [accordion] How can I manage my subscription? > > Manage your plan, billing settings, payment method and invoices in the [Stripe customer portal](https://billing.stripe.com/p/login/14AbJ00IZ8Xj4ewcxm8EM00). You can also upgrade from the developer platform. > [accordion] Do I need a credit card to start? > > No credit card is required for the free 30-day trial. > [accordion] Is there a minimum contract period? > > No, our plans renew on a monthly or annual basis and you can cancel at any time. > [accordion] Can I get a custom quote? > > Contact us for a custom quote for larger processing volumes. # SDK quickstart Source: https://docs.ai-coustics.com/models/get-started/sdk-quickstart Install the ai-coustics SDK, process audio and check the result in your preferred language. **ai-coustics** enhances audio in your application. Choose a language to install the SDK and process a recording. The Python and Node.js examples write an enhanced WAV for comparison. Create an SDK key on the [developer platform](https://developers.ai-coustics.com) and follow your language's `AIC_SDK_LICENSE` setup. Check runtime and platform support in the [compatibility matrix](/reference/sdk/compatibility-matrix). Use the [shared quickstart recording](/guides/test-audio) to check the same input across languages, then substitute representative audio from your application. Start with Quail Voice Focus for primary-speaker isolation before speech-to-text (STT). For human listening, use [Rook Multi Speaker](/models/perceptual-speech-enhancement/rook-multi-speaker). The [model reference](/reference/sdk/models) explains model loading and selection. > [!NOTE] > > SDK key authorization and usage reporting are distinct concerns. See [authentication](/models/get-started/authenticate-apps) and [telemetry](/reference/concepts/sdk-telemetry) before deploying. Downloading a model in advance does not by itself enable offline operation. > [tab] Python > > ## Installation > > Use Python 3.11 for this example on a [supported platform](/reference/sdk/compatibility-matrix). The SDK package declares Python 3.10 or later. This example pins `aic-sdk` 3.4.0 and NumPy 2.2.6. Create a project directory and a virtual environment: > > ```bash macOS / Linux theme={null} > mkdir aic-python-quickstart > cd aic-python-quickstart > python3 -m venv .venv > source .venv/bin/activate > python -m pip install "aic-sdk==3.4.0" "numpy==2.2.6" > ``` > > ```powershell Windows PowerShell theme={null} > mkdir aic-python-quickstart > cd aic-python-quickstart > py -m venv .venv > .venv\Scripts\Activate.ps1 > python -m pip install "aic-sdk==3.4.0" "numpy==2.2.6" > ``` > > ## Quickstart > > ### Prepare the key and input > > Generate an SDK key on the [developer platform](https://developers.ai-coustics.com). Set it in the terminal where you will run the example, replacing `YOUR_SDK_KEY` with your key. Keep it out of source control and shared terminal logs. > > ```bash macOS / Linux theme={null} > export AIC_SDK_LICENSE="YOUR_SDK_KEY" > ``` > > ```powershell Windows PowerShell theme={null} > $env:AIC_SDK_LICENSE = "YOUR_SDK_KEY" > ``` > > Download the [noisy speech fixture](/assets/audio/noisy-speech.wav) and save it as `input.wav` in `aic-python-quickstart`. It contains 56,080 mono PCM16 samples at 16 kHz (3.505 seconds). The [fixture guide](/guides/test-audio) includes attribution, checksums and the aligned clean reference. > > For your own recording, export a short sentence with background noise as **mono, 16 kHz, signed 16-bit PCM WAV**. Renaming a file does not convert it. > > The example downloads `quail-vf-2.3-l-16khz` into `./models`. Quail Voice Focus isolates the primary speaker for speech-to-text (STT) input. The first run needs network access for the model download and SDK key authorization. See [authentication](/models/get-started/authenticate-apps) for deployment options. > > ### Save and run > > Save this complete program as `quickstart.py` in the same directory: > > ```python quickstart.py theme={null} > import os > from pathlib import Path > import sys > import wave > > import aic_sdk as aic > import numpy as np > > > def main(): > license_key = os.environ.get("AIC_SDK_LICENSE") > if not license_key or license_key == "YOUR_SDK_KEY": > raise ValueError("Set AIC_SDK_LICENSE to your SDK key, then retry.") > > with wave.open("input.wav", "rb") as source: > if (source.getnchannels(), source.getframerate(), source.getsampwidth()) != (1, 16000, 2): > raise ValueError("Export input.wav as mono, 16 kHz, 16-bit PCM WAV, then retry.") > frames = source.getnframes() > raw = source.readframes(frames) > if len(raw) != frames * 2: > raise ValueError("input.wav is truncated. Export the complete recording, then retry.") > audio = np.frombuffer(raw, dtype=" if audio.size == 0: > raise ValueError("input.wav is empty. Record speech, then retry.") > > model_path = aic.Model.download("quail-vf-2.3-l-16khz", Path("models")) > model = aic.Model.from_file(model_path) > config = aic.ProcessorConfig.optimal(model, sample_rate=16000) > processor = aic.Processor(model, license_key) > try: > processor.initialize(config) > delay = processor.get_context().get_audio_delay() > # Pad the last block and flush the delayed tail with silence. > padded_size = ((audio.size + delay + config.block_size - 1) // config.block_size) * config.block_size > padded = np.zeros(padded_size, dtype=np.float32) > padded[:audio.size] = audio > output = np.empty_like(padded) > for start in range(0, padded_size, config.block_size): > end = start + config.block_size > # Python returns a new array; the input block is unchanged. > output[start:end] = processor.process(padded[start:end]) > enhanced = output[delay:delay + audio.size] > if not np.isfinite(enhanced).all(): > raise ValueError("Processing returned non-finite samples; no output was written.") > pcm = (np.clip(enhanced, -1.0, 32767 / 32768) * 32768).astype(" with wave.open("enhanced.wav", "wb") as destination: > destination.setnchannels(1) > destination.setsampwidth(2) > destination.setframerate(16000) > destination.writeframes(pcm.tobytes()) > print(f"SDK {aic.get_sdk_version()}, model {model.get_id()}") > print(f"Processed {audio.size} samples at 16000 Hz; wrote enhanced.wav") > finally: > processor.terminate_session() > > > if __name__ == "__main__": > try: > main() > except Exception as error: > message = getattr(error, "message", str(error)) > print(f"{type(error).__name__}: {message}", file=sys.stderr) > sys.exit(1) > ``` > > Run it from `aic-python-quickstart`, with the virtual environment active: > > ```bash theme={null} > python quickstart.py > ``` > > ### Check the result > > The program prints the native SDK version, resolved model ID and processed sample count. It writes `enhanced.wav` beside `input.wav` at 16 kHz with the same sample count, compensating for [processing delay](/reference/concepts/latency). > > With the supplied fixture, the processed sample count is `56080`. Verify the file headers: > > ```bash theme={null} > python -c "import wave; a=wave.open('input.wav'); b=wave.open('enhanced.wav'); assert a.getparams()[:4] == b.getparams()[:4]; print('PASS: matching channels, bit depth, sample rate and frame count'); a.close(); b.close()" > ``` > > Listen to both recordings and compare them with the same STT settings to evaluate quality. > > ### Recover from an error > > | Problem | Cause and retry | > | - | - | > | **Package installation fails** | Check `python --version` and the [compatibility matrix](/reference/sdk/compatibility-matrix). Activate the virtual environment and rerun the pinned installation. | > | **Missing key or `LicenseFormatInvalidError`** | Set `AIC_SDK_LICENSE` in this terminal to the complete SDK key from the developer platform, then rerun `python quickstart.py`. | > | **`LicenseExpiredError` or `ProcessingNotAllowedError`** | Check key validity, account entitlement and required connectivity in [authentication](/models/get-started/authenticate-apps). Correct the cause and restart the program with a new processor. | > | **Missing or invalid `input.wav`** | Save a nonempty mono, 16 kHz, signed 16-bit PCM WAV in the current directory, then rerun the program. | > | **Model download or load fails** | Check connectivity, write access to `./models` and the exact model ID. For manual model files, check the [model format version](/reference/sdk/compatibility-matrix). Retry the download after fixing the cause. | > | **`AudioConfigMismatchError`** | Keep every call at `config.block_size` samples. The example pads the final block; do not pass a short final slice with fixed block sizes. | > > ### Adapt this example > > Use one processor per independent stream and retain it between consecutive blocks. Reset its context when seeking or starting unrelated audio. Downmix stereo input or give each channel its own processor. See [audio format](/reference/concepts/audio-format), [streams and state](/reference/concepts/streams-and-state) and the [Python binding guide](/reference/sdk/language-bindings/python#integration-behavior) for async processing and lifecycle details. > > This example reads the full file into memory. For live audio or long files, process bounded blocks and keep file I/O, model downloads and session termination outside the audio callback. For human listening, evaluate [Rook Multi Speaker](/models/perceptual-speech-enhancement/rook-multi-speaker). > [tab] Node.js > > ## Installation > > Use Node.js 22 for this example. The package declares Node.js 18 or later; see the [compatibility matrix](/reference/sdk/compatibility-matrix) for native platform support. Create an isolated project and install the pinned SDK and WAV reader: > > ```bash theme={null} > mkdir aic-node-quickstart > cd aic-node-quickstart > npm init -y > npm install --save-exact @ai-coustics/aic-sdk@0.26.0 wavefile@11.0.0 > ``` > > ## Quickstart > > ### Prepare the key and input > > Generate an SDK key on the [developer platform](https://developers.ai-coustics.com). Set it in the terminal where you will run the example, replacing `YOUR_SDK_KEY` with your key. Keep it out of source control and shared terminal logs. > > ```bash macOS / Linux theme={null} > export AIC_SDK_LICENSE="YOUR_SDK_KEY" > ``` > > ```powershell Windows PowerShell theme={null} > $env:AIC_SDK_LICENSE = "YOUR_SDK_KEY" > ``` > > Download the [noisy speech fixture](/assets/audio/noisy-speech.wav) and save it as `input.wav` in `aic-node-quickstart`. It contains 56,080 mono PCM16 samples at 16 kHz (3.505 seconds). The [fixture guide](/guides/test-audio) includes attribution, checksums and the aligned clean reference. > > For your own recording, export a short sentence with background noise as **mono, 16 kHz, signed 16-bit PCM WAV**. Renaming a file does not convert it. > > The example downloads `quail-vf-2.3-l-16khz` into `./models`. Quail Voice Focus isolates the primary speaker for speech-to-text (STT) input. The first run needs network access for the model download and SDK key authorization. See [authentication](/models/get-started/authenticate-apps) for deployment options. > > ### Save and run > > Save this complete program as `quickstart.cjs`. The `.cjs` extension makes its CommonJS module format explicit, including in projects that use `"type": "module"`. > > ```javascript quickstart.cjs theme={null} > const fs = require("node:fs"); > const { WaveFile } = require("wavefile"); > const { Model, ProcessorAsync, getVersion } = require("@ai-coustics/aic-sdk"); > > async function main() { > const licenseKey = process.env.AIC_SDK_LICENSE; > if (!licenseKey || licenseKey === "YOUR_SDK_KEY") { > throw new Error("Set AIC_SDK_LICENSE to your SDK key, then retry."); > } > const input = new WaveFile(fs.readFileSync("input.wav")); > if (input.fmt.numChannels !== 1 || input.fmt.sampleRate !== 16000 || input.bitDepth !== "16") { > throw new Error("Export input.wav as mono, 16 kHz, 16-bit PCM WAV, then retry."); > } > if (input.data.samples.length !== input.data.chunkSize) { > throw new Error("input.wav is truncated. Export the complete recording, then retry."); > } > input.toBitDepth("32f"); > const audio = input.getSamples(false, Float32Array); > if (audio.length === 0) { > throw new Error("input.wav is empty. Record speech, then retry."); > } > > const modelPath = await Model.download("quail-vf-2.3-l-16khz", "./models"); > const model = Model.fromFile(modelPath); > let processor; > try { > const blockSize = model.getOptimalBlockSize(16000); > processor = new ProcessorAsync(model, licenseKey); > await processor.initialize(16000, blockSize, false); > const context = await processor.getContext(); > const delay = context.getAudioDelay(); > // Pad the last block and flush the delayed tail with silence. > const paddedSize = Math.ceil((audio.length + delay) / blockSize) * blockSize; > const padded = new Float32Array(paddedSize); > padded.set(audio); > const output = new Float32Array(paddedSize); > for (let start = 0; start < paddedSize; start += blockSize) { > // Await each block to preserve stream order. Async processing returns a new array. > const enhanced = await processor.process(padded.subarray(start, start + blockSize)); > output.set(enhanced, start); > } > const enhanced = output.subarray(delay, delay + audio.length); > if (!enhanced.every(Number.isFinite)) { > throw new Error("Processing returned non-finite samples; no output was written."); > } > const pcm = Int16Array.from(enhanced, (sample) => > Math.trunc(Math.max(-1, Math.min(32767 / 32768, sample)) * 32768) > ); > const result = new WaveFile(); > result.fromScratch(1, 16000, "16", pcm); > fs.writeFileSync("enhanced.wav", result.toBuffer()); > console.log(`SDK ${getVersion()}, model ${model.getId()}`); > console.log(`Processed ${audio.length} samples at 16000 Hz; wrote enhanced.wav`); > } finally { > // All processing promises above have settled before native resources are released. > if (processor) processor.dispose(); > model.dispose(); > } > } > > main().catch((error) => { > console.error(`Error: ${error.message}`); > process.exitCode = 1; > }); > ``` > > Run it from `aic-node-quickstart`: > > ```bash theme={null} > node quickstart.cjs > ``` > > ### Check the result > > The program prints the native SDK version, resolved model ID and processed sample count. It writes `enhanced.wav` beside `input.wav` at 16 kHz with the same sample count, compensating for [processing delay](/reference/concepts/latency). > > With the supplied fixture, the processed sample count is `56080`. Verify the file headers: > > ```bash theme={null} > node -e "const fs=require('node:fs'); const {WaveFile}=require('wavefile'); const a=new WaveFile(fs.readFileSync('input.wav')); const b=new WaveFile(fs.readFileSync('enhanced.wav')); for (const k of ['numChannels','sampleRate','bitsPerSample']) if(a.fmt[k]!==b.fmt[k]) throw Error(k+' differs'); if(a.getSamples().length!==b.getSamples().length) throw Error('sample count differs'); console.log('PASS: matching channels, bit depth, sample rate and frame count');" > ``` > > Listen to both recordings and compare them with the same STT settings to evaluate quality. > > ### Recover from an error > > | Problem | Cause and retry | > | - | - | > | **Native module cannot load** | Check `node --version` and your OS/architecture against the [compatibility matrix](/reference/sdk/compatibility-matrix). Install in the target environment with optional dependencies enabled, then rerun `node quickstart.cjs`. | > | **Missing or invalid SDK key** | Set `AIC_SDK_LICENSE` in this terminal to the complete SDK key from the developer platform, then retry. | > | **Processing is not allowed** | Check key validity, account entitlement and required connectivity in [authentication](/models/get-started/authenticate-apps). Correct the cause and restart the program with a new processor. | > | **Missing or invalid `input.wav`** | Save a nonempty mono, 16 kHz, signed 16-bit PCM WAV in the current directory, then rerun the program. | > | **Model download or load fails** | Check connectivity, write access to `./models` and the exact model ID. For manual model files, check the [model format version](/reference/sdk/compatibility-matrix). Retry the download after fixing the cause. | > | **Audio configuration mismatch** | Keep every call at `blockSize` samples. The example pads the final block; do not pass a short final slice with fixed block sizes. | > > ### Adapt this example > > Use one processor per independent stream and await each operation before submitting the next block. Use separate processors for simultaneous streams; `Promise.all` over blocks from one stream can reorder processing. Downmix stereo input or give each channel its own processor. See [audio format](/reference/concepts/audio-format), [streams and state](/reference/concepts/streams-and-state) and the [Node.js binding guide](/reference/sdk/language-bindings/nodejs#integration-behavior). > > This example reads the full file into memory and uses synchronous file I/O. For live audio or long files, process bounded blocks and keep file I/O and model downloads outside the audio path. For human listening, evaluate [Rook Multi Speaker](/models/perceptual-speech-enhancement/rook-multi-speaker). > [tab] Rust > > ## Installation > > Use Rust with Cargo, a native linker and libclang on a [supported platform](/reference/sdk/compatibility-matrix). The published SDK crate declares Rust 1.88 or later. Its build script generates C bindings with libclang; install your platform's compiler tools before building. See the [released linking guide](https://docs.rs/aic-sdk/0.25.2/aic_sdk/docs/linking/index.html) for local-library and deployment options. > > Create a project: > > ```bash theme={null} > cargo new aic-rust-quickstart > cd aic-rust-quickstart > ``` > > Replace `Cargo.toml` with the following. `download-lib` downloads the matching native library during the first build; it requires network access. The explicit `aic-sdk-sys` pin keeps the native dependency at the documented release. `hound` reads and writes WAV files. > > ```toml Cargo.toml theme={null} > [package] > name = "aic-rust-quickstart" > version = "0.1.0" > edition = "2024" > > [dependencies] > aic-sdk = { version = "=0.25.2", features = ["download-lib"] } > aic-sdk-sys = "=0.25.2" > hound = "=3.5.1" > ``` > > Keep the generated `Cargo.lock` in your application to preserve resolved dependency versions. > > ## Quickstart > > ### Prepare the key, model and input > > Generate an SDK key on the [developer platform](https://developers.ai-coustics.com). Set it in the terminal where you will run the program. Keep it out of source control and shared logs. > > ```bash macOS / Linux theme={null} > export AIC_SDK_LICENSE="YOUR_SDK_KEY" > curl -fL -o model.aicmodel "https://artifacts.ai-coustics.io/models/quail-vf-2-2-l-16khz/v7/quail_vf_2_2_l_16khz_horgwub0_v14.aicmodel" > ``` > > ```powershell Windows PowerShell theme={null} > $env:AIC_SDK_LICENSE = "YOUR_SDK_KEY" > Invoke-WebRequest "https://artifacts.ai-coustics.io/models/quail-vf-2-2-l-16khz/v7/quail_vf_2_2_l_16khz_horgwub0_v14.aicmodel" -OutFile model.aicmodel > ``` > > Replace `YOUR_SDK_KEY` with your key. This pins a format-7 build of `quail-vf-2.2-l-16khz`. Quail Voice Focus isolates the primary speaker for speech-to-text (STT) input. Downloading the model in advance does not remove SDK key authorization requirements; see [authentication](/models/get-started/authenticate-apps). > > Download the [noisy speech fixture](/assets/audio/noisy-speech.wav) and save it as `input.wav` in this project directory. It contains 56,080 mono PCM16 samples at 16 kHz (3.505 seconds). The [fixture guide](/guides/test-audio) includes attribution, checksums and the aligned clean reference. > > For your own recording, export **mono, 16 kHz, signed 16-bit PCM WAV**, at most 60 seconds long. Renaming a file does not convert it. > > ### Save and run > > Replace `src/main.rs` with: > > ```rust src/main.rs theme={null} > use aic_sdk::{Model, Processor, ProcessorConfig}; > use hound::{SampleFormat, WavReader, WavSpec, WavWriter}; > use std::error::Error; > > fn run() -> Result<(), Box> { > let key = std::env::var("AIC_SDK_LICENSE") > .map_err(|_| "Set AIC_SDK_LICENSE to your SDK key, then retry.")?; > if key.is_empty() || key == "YOUR_SDK_KEY" { > return Err("Set AIC_SDK_LICENSE to your SDK key, then retry.".into()); > } > let mut reader = WavReader::open("input.wav")?; > let spec = reader.spec(); > if spec.channels != 1 || spec.sample_rate != 16000 || spec.bits_per_sample != 16 || > spec.sample_format != SampleFormat::Int || reader.duration() == 0 || reader.duration() > 960000 { > return Err("Use a nonempty mono, 16 kHz, PCM16 input.wav, at most 60 seconds.".into()); > } > let input: Vec = reader.samples::() > .map(|sample| sample.map(|value| value as f32 / 32768.0)) > .collect::>()?; > let model = Model::from_file("model.aicmodel")?; > let config = ProcessorConfig { > sample_rate: 16000, > block_size: model.optimal_block_size(16000), > variable_block_size: false, > }; > let mut processor = Processor::new(&model, &key)?.with_config(&config)?; > let delay = processor.context().audio_delay(); > let padded_count = input.len().checked_add(delay) > .and_then(|n| n.checked_add(config.block_size - 1)) > .ok_or("Audio buffer size overflow")? / config.block_size * config.block_size; > let mut output = vec![0.0_f32; padded_count]; > output[..input.len()].copy_from_slice(&input); > for block in output.chunks_exact_mut(config.block_size) { > processor.process(block)?; > } > // Flush with silence, then omit the initial delay to align the files. > let enhanced = &output[delay..delay + input.len()]; > if enhanced.iter().any(|sample| !sample.is_finite()) { > return Err("Non-finite output sample; no output written.".into()); > } > let mut writer = WavWriter::create("enhanced.wav", WavSpec { > channels: 1, sample_rate: 16000, bits_per_sample: 32, sample_format: SampleFormat::Float, > })?; > for &sample in enhanced { writer.write_sample(sample)?; } > writer.finalize()?; > println!("SDK {}, model {}", aic_sdk::get_sdk_version(), model.id()); > println!("Processed {} samples at 16000 Hz; wrote enhanced.wav", input.len()); > // Drop releases the processor and ends its session, including on an error return. > Ok(()) > } > > fn main() { > if let Err(error) = run() { > eprintln!("{error}"); > std::process::exit(1); > } > } > ``` > > Build and run from `aic-rust-quickstart`: > > ```bash theme={null} > cargo run --release > ``` > > The program propagates SDK and file errors with `?`. Rust drops the processor and model on a normal return or an error return from `run`, releasing native resources. > > ### Check the result > > A successful run exits with code zero, prints the native SDK version and resolved model ID, then reports `Processed N samples at 16000 Hz; wrote enhanced.wav`, where `N` is your input's sample count (`56080` for the supplied fixture). Open `enhanced.wav` in your audio editor: it should be mono, 16 kHz and the same duration as `input.wav`. The output is a **32-bit float WAV**; the input is PCM16. > > The program pads the final block, flushes the delayed tail and removes the initial [processing delay](/reference/concepts/latency), preserving the original sample count. File writes are checked; discard any incomplete file if writing fails. > > Listen to both files and compare them with the same STT settings to evaluate quality. > > ### Recover from an error > > | Problem | Cause and retry | > | - | - | > | **Build cannot find libclang or a linker** | Install the platform compiler tools and libclang. Set `LIBCLANG_PATH` to your libclang library directory if discovery fails, then rerun `cargo build --release`. | > | **Native library download fails** | Check network access and target platform. For a preinstalled SDK, use `AIC_LIB_PATH` as described in the [linking guide](https://docs.rs/aic-sdk/0.25.2/aic_sdk/docs/linking/index.html). | > | **Missing or invalid SDK key** | Set `AIC_SDK_LICENSE` in this terminal to the complete SDK key, then rerun `cargo run --release`. | > | **Processing is not allowed or the key expired** | Check key validity, entitlement and [required connectivity](/models/get-started/authenticate-apps). Correct the cause and restart the program. | > | **Input file rejected** | Save a nonempty mono, 16 kHz, PCM16 WAV of at most 60 seconds as `input.wav`, then retry. | > | **Model loading fails** | Run from the project directory containing `model.aicmodel`. Re-download the exact file above for SDK 0.25.2. | > | **Audio configuration mismatch** | Keep each `process` call at `config.block_size` samples. The example pads the final block before processing. | > | **Output write fails** | Check free space and write permission. Discard the incomplete output, correct the cause and retry. | > > ### Adapt this example > > Keep one processor per stream and process blocks in order. Reset its context on a discontinuity or before unrelated audio. Downmix stereo or use a processor per channel. See [audio format](/reference/concepts/audio-format) and [streams and state](/reference/concepts/streams-and-state). > > The helper reads a short recording into memory. For long files and live audio, use bounded buffers and keep file I/O, model loading and session teardown outside the audio callback. For human-listening enhancement, evaluate [Rook Multi Speaker](/models/perceptual-speech-enhancement/rook-multi-speaker). > [tab] WebAssembly > > ## Installation > > Use `@ai-coustics/aic-sdk-wasm` **0.26.0**, Node.js 22 or later for the local token server and a browser with WebAssembly SIMD support. This example processes a local recording into a mono WAV; it does not use an AudioWorklet or microphone pipeline. > > Download the [noisy speech fixture](/guides/test-audio), or use a short recording you have permission to process, exported as mono PCM16 WAV at 16 kHz. The example accepts up to 60 seconds. Create an SDK key in the [developer platform](https://developers.ai-coustics.com) and put it in the server's `AIC_SDK_LICENSE` environment variable. Do not put the key into HTML, browser storage or client configuration. > > ```bash theme={null} > mkdir aic-wasm-example > cd aic-wasm-example > npm init -y > npm install --save-exact @ai-coustics/aic-sdk-wasm@0.26.0 > curl --fail --location \ > 'https://artifacts.ai-coustics.io/models/quail-vf-2-3-s-16khz/v8/quail_vf_2_3_s_16khz_398hl32w_v12.aicmodel' \ > --output model.aicmodel > ``` > > Set the server credential in this terminal without putting it in shell history: > > ```bash theme={null} > read -r -s AIC_SDK_LICENSE > export AIC_SDK_LICENSE > ``` > > Paste your SDK key at the hidden prompt and press Enter. The key remains on the server; the browser receives a short-lived JSON Web Token (JWT). > > ## Quickstart > > ### Create the local token server > > Save the following as `server.mjs`. This server binds to loopback and serves only the listed files. The token endpoint checks the request origin and returns no cached credentials. It decodes the SDK key on the server using the [documented token flow](/models/get-started/authenticate-apps). > > > [!WARNING] > > > > This is a local development server. Before production, replace it with an HTTPS backend that authenticates users, authorizes SDK access and enforces rate and usage limits. Never expose this demo server on a public interface. > > ```javascript server.mjs theme={null} > import http from 'node:http'; > import { readFile } from 'node:fs/promises'; > > const origin = 'http://127.0.0.1:4173'; > const sdkKey = process.env.AIC_SDK_LICENSE; > if (!sdkKey) throw new Error('Set AIC_SDK_LICENSE in the server environment.'); > const files = new Map([ > ['/', ['index.html', 'text/html']], > ['/sdk.js', ['node_modules/@ai-coustics/aic-sdk-wasm/aic_sdk_wasm.js', 'text/javascript']], > ['/aic_sdk_wasm_bg.wasm', ['node_modules/@ai-coustics/aic-sdk-wasm/aic_sdk_wasm_bg.wasm', 'application/wasm']], > ['/model.aicmodel', ['model.aicmodel', 'application/octet-stream']], > ]); > const server = http.createServer(async (req, res) => { > res.setHeader('Cache-Control', 'no-store'); > res.setHeader('X-Content-Type-Options', 'nosniff'); > if (req.headers.host !== '127.0.0.1:4173') { > res.writeHead(403).end('Use the loopback URL printed by the server.'); > return; > } > if (req.url === '/session-token' && req.method === 'POST') { > // This is a local-only demo. Production needs authenticated users and quotas. > if (req.headers.origin !== origin || req.headers['x-aic-demo'] !== '1') { > res.writeHead(403).end('Same-origin demo request required.'); > return; > } > try { > const payload = JSON.parse(Buffer.from(sdkKey.split('.')[0], 'base64').toString()); > if (typeof payload.api_key !== 'string') throw new Error('Invalid SDK key'); > const basic = Buffer.from(`${payload.api_key}:`).toString('base64'); > const response = await fetch('https://api.ai-coustics.io/v1/sdk/tokens', { > method: 'POST', headers: { Authorization: `Basic ${basic}` }, > signal: AbortSignal.timeout(10000), > }); > if (!response.ok) throw new Error('Token request rejected'); > const { token } = await response.json(); > if (typeof token !== 'string') throw new Error('Missing token'); > const { exp } = JSON.parse(Buffer.from(token.split('.')[1], 'base64url').toString()); > if (!Number.isFinite(exp) || exp * 1000 <= Date.now() + 120000) { > throw new Error('Token lifetime is too short for this demo'); > } > res.writeHead(200, { 'Content-Type': 'application/json' }); > res.end(JSON.stringify({ token })); > } catch { > // Do not log credentials or return upstream response bodies. > res.writeHead(502).end('Token request failed. Check the server key and connectivity.'); > } > return; > } > const file = files.get(req.url); > if (req.method !== 'GET' || !file) { > res.writeHead(404).end('Not found'); > return; > } > try { > const bytes = await readFile(new URL(file[0], import.meta.url)); > res.writeHead(200, { 'Content-Type': file[1] }).end(bytes); > } catch { > res.writeHead(404).end('File missing. Check installation and model download.'); > } > }); > server.listen(4173, '127.0.0.1', () => console.log(`Open ${origin}`)); > ``` > > ### Create the browser page > > Save this as `index.html` beside `server.mjs`. Audio stays in browser memory. The page loads the WASM module and model, requests a token, processes complete frames, pads the tail and removes the reported delay before creating the output file. Session authorization and usage reporting still require network access. > > ```html index.html theme={null} > > > > > ai-coustics WASM file example >

Enhance a short recording

>

Select a mono, 16 kHz, PCM16 WAV with speech (up to 60 seconds).

> > >

Ready.

> > > > ``` > > ### Run and check the result > > ```bash theme={null} > node server.mjs > ``` > > Open `http://127.0.0.1:4173`, select your recording and choose **Enhance**. On success, the page displays the number of processed samples and SDK version and exposes **Download enhanced.wav**. The output has the same sample count as the input, one channel and a 16 kHz sample rate. Compare both files to evaluate quality for your task. > > Each recording uses a fresh token with at least two minutes of remaining validity. Processing stops after one minute of wall time. These are demo bounds, not SDK limits. Stop the server with Ctrl+C, then run `unset AIC_SDK_LICENSE`. > > ## Recover from an error > > | Problem | Cause and retry | > | - | - | > | Server asks for `AIC_SDK_LICENSE` | Set the key in the server's terminal and restart it. | > | Module or model file is missing | Run the installation/download commands in the same directory as `server.mjs`. | > | Browser cannot compile WASM | Use a browser with WebAssembly SIMD support and verify that the `.wasm` response is served as `application/wasm`. | > | Token unavailable | Check the server key, token-service connectivity and whether the credential can mint a JWT. Do not copy a long-lived key into the browser as a workaround. | > | `ProcessingNotAllowed` | Check activation connectivity, credential expiry and authorization. Correct the cause and retry with a fresh token. Do not treat a stopped or bypassed run as enhancement. | > | Invalid WAV or empty input | Export nonempty mono PCM16 audio at 16 kHz and select the corrected file. | > | Timeout | Try a shorter recording and measure your target device's processing budget before a live integration. | > > ## Adapt this example > > Use one processor per independent audio stream. `Processor.process()` mutates its `Float32Array` in place and runs synchronously. Move sustained processing off the main UI thread and design buffering around the [audio format](/reference/concepts/audio-format) and [latency](/reference/concepts/latency) contracts. > > For a long-running stream, refresh a JWT through your authenticated backend before expiry and update the existing context: > > ```javascript theme={null} > // context came from processor.getContext(). > // freshToken came from your authenticated backend. > context.updateBearerToken(freshToken); > ``` > > Both the original and replacement credentials must be JWTs. A successful local update does not prove backend acceptance; handle subsequent processing errors. Keep only the current short-lived token in memory. Never log it or save it to local storage. At shutdown, free the context and model, terminate the session and free the processor as shown above. > [tab] C++ > > ## Installation > > Use a C++11 compiler, Git and CMake 3.24 or later on a [supported platform](/reference/sdk/compatibility-matrix). On Windows, use a Visual Studio developer terminal with the C++ build tools installed. Create an empty project directory: > > ```bash theme={null} > mkdir aic-cpp-quickstart > cd aic-cpp-quickstart > ``` > > The CMake project below pins the C++ wrapper to 0.26.0. On the first configure, it downloads the matching native C SDK and checks its checksum. The example links the native SDK statically; network access is needed during configuration. > > ## Quickstart > > ### Prepare the key, model and input > > Generate an SDK key on the [developer platform](https://developers.ai-coustics.com). Set it in the terminal where you will run the program. Keep it out of source control and shared logs. > > ```bash macOS / Linux theme={null} > export AIC_SDK_LICENSE="YOUR_SDK_KEY" > curl -fL -o model.aicmodel "https://artifacts.ai-coustics.io/models/quail-vf-2-3-l-16khz/v8/quail_vf_2_3_l_16khz_5qsg9lf0_v13.aicmodel" > ``` > > ```powershell Windows PowerShell theme={null} > $env:AIC_SDK_LICENSE = "YOUR_SDK_KEY" > Invoke-WebRequest "https://artifacts.ai-coustics.io/models/quail-vf-2-3-l-16khz/v8/quail_vf_2_3_l_16khz_5qsg9lf0_v13.aicmodel" -OutFile model.aicmodel > ``` > > Replace `YOUR_SDK_KEY` with your key. This pins a format-8 build of `quail-vf-2.3-l-16khz`. Quail Voice Focus isolates the primary speaker for speech-to-text (STT) input. Downloading the model in advance does not remove SDK key authorization requirements; see [authentication](/models/get-started/authenticate-apps). > > Download the [noisy speech fixture](/assets/audio/noisy-speech.wav) and save it as `input.wav` in this project directory. It contains 56,080 mono PCM16 samples at 16 kHz (3.505 seconds). The [fixture guide](/guides/test-audio) includes attribution, checksums and the aligned clean reference. > > For your own recording, export **mono, 16 kHz, signed 16-bit PCM WAV**, at most 60 seconds long. Renaming a file does not convert it. > > ### Add WAV file handling > > The example uses [dr\_wav 0.14.4](https://github.com/mackron/dr_libs/tree/wav-0.14.4) for file I/O. Download its pinned single header into the project directory: > > ```bash macOS / Linux theme={null} > curl -fL -o dr_wav.h "https://raw.githubusercontent.com/mackron/dr_libs/wav-0.14.4/dr_wav.h" > ``` > > ```powershell Windows PowerShell theme={null} > Invoke-WebRequest "https://raw.githubusercontent.com/mackron/dr_libs/wav-0.14.4/dr_wav.h" -OutFile dr_wav.h > ``` > > Save this helper as `audio_file.h` alongside `dr_wav.h`. It checks input format and length, reads float samples and writes a 32-bit float WAV. > > ```c audio_file.h theme={null} > #ifndef AUDIO_FILE_H > #define AUDIO_FILE_H > #define DR_WAV_IMPLEMENTATION > #include "dr_wav.h" > #include > #include > #include > > /* A short-file helper for this tutorial, independent of the SDK. */ > static float* read_input(size_t* count) { > drwav wav; > if (!drwav_init_file(&wav, "input.wav", NULL)) { > fprintf(stderr, "Cannot open input.wav as a WAV file.\n"); > return NULL; > } > if (wav.channels != 1 || wav.sampleRate != 16000 || > wav.translatedFormatTag != DR_WAVE_FORMAT_PCM || wav.bitsPerSample != 16 || > wav.totalPCMFrameCount == 0 || wav.totalPCMFrameCount > 960000) { > fprintf(stderr, "Use a nonempty mono, 16 kHz, PCM16 input.wav, at most 60 seconds.\n"); > drwav_uninit(&wav); > return NULL; > } > *count = (size_t)wav.totalPCMFrameCount; > float* audio = (float*)malloc(*count * sizeof(float)); > if (!audio || drwav_read_pcm_frames_f32(&wav, *count, audio) != *count) { > fprintf(stderr, "Cannot read all input samples.\n"); > free(audio); > audio = NULL; > } > drwav_uninit(&wav); > return audio; > } > > static int write_output(const float* audio, size_t count) { > drwav wav; > drwav_data_format format = {drwav_container_riff, DR_WAVE_FORMAT_IEEE_FLOAT, 1, 16000, 32}; > for (size_t i = 0; i < count; ++i) { > if (!isfinite(audio[i])) { > fprintf(stderr, "Non-finite output sample; no output written.\n"); > return 0; > } > } > if (!drwav_init_file_write(&wav, "enhanced.wav", &format, NULL)) { > fprintf(stderr, "Cannot create enhanced.wav.\n"); > return 0; > } > drwav_uint64 written = drwav_write_pcm_frames(&wav, count, audio); > drwav_result closed = drwav_uninit(&wav); > if (written != count || closed != DRWAV_SUCCESS) { > fprintf(stderr, "Cannot finish enhanced.wav; discard the incomplete file.\n"); > return 0; > } > return 1; > } > #endif > ``` > > ### Save the program > > Save as `quickstart.cpp`: > > ```cpp quickstart.cpp theme={null} > #include "aic.hpp" > #include "audio_file.h" > #include > #include > #include > #include > #include > #include > #include > #include > > static void check(aic::ErrorCode error, const char* operation) { > if (error != aic::ErrorCode::Success) { > throw std::runtime_error(std::string(operation) + " failed (SDK error " + > std::to_string(static_cast(error)) + ")."); > } > } > > int main() { > try { > const char* key = std::getenv("AIC_SDK_LICENSE"); > if (!key || !*key || std::strcmp(key, "YOUR_SDK_KEY") == 0) > throw std::runtime_error("Set AIC_SDK_LICENSE to your SDK key, then retry."); > size_t count = 0; > std::unique_ptr input(read_input(&count), &std::free); > if (!input) return 1; > auto model_result = aic::Model::create_from_file("model.aicmodel"); > check(model_result.error, "Model loading"); > auto model = model_result.take(); > auto processor_result = aic::Processor::create(model, key); > check(processor_result.error, "Processor creation"); > auto processor = processor_result.take(); > const size_t block_size = model.get_optimal_block_size(16000); > check(processor.initialize(16000, block_size, false), "Initialization"); > auto context_result = processor.create_context(); > check(context_result.error, "Context creation"); > auto context = context_result.take(); > const size_t delay = context.get_audio_delay(); > const size_t limit = std::numeric_limits::max(); > if (block_size == 0 || count > limit - delay || count + delay > limit - (block_size - 1)) > throw std::runtime_error("Audio buffer size overflow."); > const size_t padded_count = ((count + delay + block_size - 1) / block_size) * block_size; > std::vector output(padded_count, 0.0f); > std::copy(input.get(), input.get() + count, output.begin()); > for (size_t start = 0; start < padded_count; start += block_size) > check(processor.process(output.data() + start, block_size), "Processing"); > // Flush with silence, then omit the initial delay to align the files. > if (!write_output(output.data() + delay, count)) return 1; > std::cout << "SDK " << aic::get_sdk_version() << ", model " << model.get_id() << '\n'; > std::cout << "Processed " << count << " samples at 16000 Hz; wrote enhanced.wav\n"; > // Destructors release the context, processor and model on success or error. > return 0; > } catch (const std::exception& error) { > std::cerr << error.what() << '\n'; > return 1; > } > } > ``` > > ### Build and run > > Save this complete project as `CMakeLists.txt`: > > ```cmake CMakeLists.txt theme={null} > cmake_minimum_required(VERSION 3.24) > project(aic_cpp_quickstart LANGUAGES C CXX) > include(FetchContent) > set(AIC_SDK_ALLOW_DOWNLOAD ON CACHE BOOL "Download the matching C SDK") > FetchContent_Declare(aic_sdk > GIT_REPOSITORY https://github.com/ai-coustics/aic-sdk-cpp.git > GIT_TAG 0.26.0 > GIT_SHALLOW TRUE) > FetchContent_MakeAvailable(aic_sdk) > add_executable(quickstart quickstart.cpp) > target_compile_features(quickstart PRIVATE cxx_std_11) > target_link_libraries(quickstart PRIVATE aic-sdk) > ``` > > Configure and build from `aic-cpp-quickstart`: > > ```bash theme={null} > cmake -S . -B build -DCMAKE_BUILD_TYPE=Release > cmake --build build --config Release > ``` > > Run from the project directory so the program can find `input.wav` and `model.aicmodel`: > > ```bash macOS / Linux theme={null} > ./build/quickstart > ``` > > ```powershell Windows PowerShell theme={null} > .\build\Release\quickstart.exe > ``` > > ### Check the result > > A successful run exits with code zero, prints the native SDK version and resolved model ID, then reports `Processed N samples at 16000 Hz; wrote enhanced.wav`, where `N` is your input's sample count (`56080` for the supplied fixture). Open `enhanced.wav` in your audio editor: it should be mono, 16 kHz and the same duration as `input.wav`. The output is a **32-bit float WAV**; the input is PCM16. > > The program pads the final block, flushes the delayed tail and removes the initial [processing delay](/reference/concepts/latency), preserving the original sample count. File writes are checked; discard any incomplete file if writing fails. > > Listen to both files and compare them with the same STT settings to evaluate quality. > > ### Recover from an error > > | Problem | Cause and retry | > | - | - | > | **Compiler, SDK header or library missing** | Install the compiler and check the selected archive or CMake download. Use the same target architecture for compiler and SDK. Rerun configure and build. | > | **Missing SDK key or SDK error 50** | Set `AIC_SDK_LICENSE` in this terminal to the complete SDK key, then run the program again. Error 50 is an invalid license format. | > | **SDK error 6 or 52** | Error 6 means processing is not allowed; error 52 means the license expired. Check account entitlement, key validity and [required connectivity](/models/get-started/authenticate-apps), then restart with a new processor. | > | **Input file rejected** | Save a nonempty mono, 16 kHz, PCM16 WAV of at most 60 seconds as `input.wav`, then retry. | > | **Model loading fails** | Keep `model.aicmodel` in the current directory. Re-download the exact compatible file above; error 100 means an invalid model, 101 an unsupported model version and 103 a filesystem error. | > | **SDK error 5** | The block size differs from initialization. Keep every call at the configured size and pad the final block as shown. | > | **Output write fails** | Check free space and write permission. Discard the incomplete `enhanced.wav`, fix the cause and retry. | > > The helper `check` turns a failed `ErrorCode` into an exception for this application. The SDK wrapper itself returns error codes and `Result` values: calling `.take()` without checking `.error` or `.ok()` does not throw. > > ### Adapt this example > > Keep one processor per stream and process blocks in order. Reset its context on a discontinuity or before unrelated audio. Downmix stereo or use a processor per channel. See [audio format](/reference/concepts/audio-format) and [streams and state](/reference/concepts/streams-and-state). > > The helper reads a short recording into memory. For long files and live audio, use bounded buffers and keep file I/O, model loading and session teardown outside the audio callback. For human-listening enhancement, evaluate [Rook Multi Speaker](/models/perceptual-speech-enhancement/rook-multi-speaker). > [tab] C > > ## Installation > > Use a C11 compiler, CMake 3.24 or later and a supported macOS, Linux or Windows platform. This tutorial selects the GNU libc Linux archive; see the [compatibility matrix](/reference/sdk/compatibility-matrix). Release 0.25.0 adds musl archives for `x86_64` and `aarch64`. They ship `lib/libaic.a` only, with no musl `libaic.so`, so link the archive statically with a musl-native toolchain such as GCC on Alpine rather than following the shared-library CMake project below. On Windows, run build commands in a Visual Studio developer terminal with the C++ build tools installed. > > Create an empty project directory: > > ```bash theme={null} > mkdir aic-c-quickstart > cd aic-c-quickstart > ``` > > Download and extract the native SDK 0.26.0 archive. These POSIX commands select Apple Silicon, Intel Mac, Linux ARM64 or Linux x86-64 from the host architecture: > > ```bash macOS / Linux theme={null} > case "$(uname -s)-$(uname -m)" in > Darwin-arm64) AIC_TARGET=aarch64-apple-darwin ;; > Darwin-x86_64) AIC_TARGET=x86_64-apple-darwin ;; > Linux-aarch64) AIC_TARGET=aarch64-unknown-linux-gnu ;; > Linux-x86_64) AIC_TARGET=x86_64-unknown-linux-gnu ;; > *) echo "Select a supported SDK archive from the releases page"; exit 1 ;; > esac > curl -fL -o sdk.tar.gz "https://github.com/ai-coustics/aic-sdk-c/releases/download/0.26.0/aic-sdk-${AIC_TARGET}-0.26.0.tar.gz" > mkdir sdk > tar -xzf sdk.tar.gz -C sdk > ``` > > ```powershell Windows PowerShell theme={null} > # For an ARM64 build, replace x86_64 with aarch64. > $AicTarget = "x86_64-pc-windows-msvc" > Invoke-WebRequest "https://github.com/ai-coustics/aic-sdk-c/releases/download/0.26.0/aic-sdk-$AicTarget-0.26.0.zip" -OutFile sdk.zip > Expand-Archive sdk.zip -DestinationPath sdk > ``` > > The project must now contain `sdk/include/aic.h` and `sdk/lib/`. Choose the archive for your compiler's target architecture when cross-compiling. [Release 0.26.0](https://github.com/ai-coustics/aic-sdk-c/releases/tag/0.26.0) includes all distributions. > > ## Quickstart > > ### Prepare the key, model and input > > Generate an SDK key on the [developer platform](https://developers.ai-coustics.com). Set it in the terminal where you will run the program. Keep it out of source control and shared logs. > > ```bash macOS / Linux theme={null} > export AIC_SDK_LICENSE="YOUR_SDK_KEY" > curl -fL -o model.aicmodel "https://artifacts.ai-coustics.io/models/quail-vf-2-3-l-16khz/v8/quail_vf_2_3_l_16khz_5qsg9lf0_v13.aicmodel" > ``` > > ```powershell Windows PowerShell theme={null} > $env:AIC_SDK_LICENSE = "YOUR_SDK_KEY" > Invoke-WebRequest "https://artifacts.ai-coustics.io/models/quail-vf-2-3-l-16khz/v8/quail_vf_2_3_l_16khz_5qsg9lf0_v13.aicmodel" -OutFile model.aicmodel > ``` > > Replace `YOUR_SDK_KEY` with your key. This pins a format-8 build of `quail-vf-2.3-l-16khz`. Quail Voice Focus isolates the primary speaker for speech-to-text (STT) input. Downloading the model in advance does not remove SDK key authorization requirements; see [authentication](/models/get-started/authenticate-apps). > > Download the [noisy speech fixture](/assets/audio/noisy-speech.wav) and save it as `input.wav` in this project directory. It contains 56,080 mono PCM16 samples at 16 kHz (3.505 seconds). The [fixture guide](/guides/test-audio) includes attribution, checksums and the aligned clean reference. > > For your own recording, export **mono, 16 kHz, signed 16-bit PCM WAV**, at most 60 seconds long. Renaming a file does not convert it. > > ### Add WAV file handling > > The example uses [dr\_wav 0.14.4](https://github.com/mackron/dr_libs/tree/wav-0.14.4) for file I/O. Download its pinned single header into the project directory: > > ```bash macOS / Linux theme={null} > curl -fL -o dr_wav.h "https://raw.githubusercontent.com/mackron/dr_libs/wav-0.14.4/dr_wav.h" > ``` > > ```powershell Windows PowerShell theme={null} > Invoke-WebRequest "https://raw.githubusercontent.com/mackron/dr_libs/wav-0.14.4/dr_wav.h" -OutFile dr_wav.h > ``` > > Save this helper as `audio_file.h` alongside `dr_wav.h`. It checks input format and length, reads float samples and writes a 32-bit float WAV. > > ```c audio_file.h theme={null} > #ifndef AUDIO_FILE_H > #define AUDIO_FILE_H > #define DR_WAV_IMPLEMENTATION > #include "dr_wav.h" > #include > #include > #include > > /* A short-file helper for this tutorial, independent of the SDK. */ > static float* read_input(size_t* count) { > drwav wav; > if (!drwav_init_file(&wav, "input.wav", NULL)) { > fprintf(stderr, "Cannot open input.wav as a WAV file.\n"); > return NULL; > } > if (wav.channels != 1 || wav.sampleRate != 16000 || > wav.translatedFormatTag != DR_WAVE_FORMAT_PCM || wav.bitsPerSample != 16 || > wav.totalPCMFrameCount == 0 || wav.totalPCMFrameCount > 960000) { > fprintf(stderr, "Use a nonempty mono, 16 kHz, PCM16 input.wav, at most 60 seconds.\n"); > drwav_uninit(&wav); > return NULL; > } > *count = (size_t)wav.totalPCMFrameCount; > float* audio = (float*)malloc(*count * sizeof(float)); > if (!audio || drwav_read_pcm_frames_f32(&wav, *count, audio) != *count) { > fprintf(stderr, "Cannot read all input samples.\n"); > free(audio); > audio = NULL; > } > drwav_uninit(&wav); > return audio; > } > > static int write_output(const float* audio, size_t count) { > drwav wav; > drwav_data_format format = {drwav_container_riff, DR_WAVE_FORMAT_IEEE_FLOAT, 1, 16000, 32}; > for (size_t i = 0; i < count; ++i) { > if (!isfinite(audio[i])) { > fprintf(stderr, "Non-finite output sample; no output written.\n"); > return 0; > } > } > if (!drwav_init_file_write(&wav, "enhanced.wav", &format, NULL)) { > fprintf(stderr, "Cannot create enhanced.wav.\n"); > return 0; > } > drwav_uint64 written = drwav_write_pcm_frames(&wav, count, audio); > drwav_result closed = drwav_uninit(&wav); > if (written != count || closed != DRWAV_SUCCESS) { > fprintf(stderr, "Cannot finish enhanced.wav; discard the incomplete file.\n"); > return 0; > } > return 1; > } > #endif > ``` > > ### Save the program > > Save as `quickstart.c`: > > ```c quickstart.c theme={null} > #include "aic.h" > #include "audio_file.h" > #include > > #define CHECK(call) do { \ > enum AicErrorCode error = (call); \ > if (error != AIC_ERROR_CODE_SUCCESS) { \ > fprintf(stderr, "%s failed (SDK error %d).\n", #call, (int)error); \ > goto cleanup; \ > } \ > } while (0) > > int main(void) { > const char* key = getenv("AIC_SDK_LICENSE"); > if (!key || !*key || strcmp(key, "YOUR_SDK_KEY") == 0) { > fprintf(stderr, "Set AIC_SDK_LICENSE to your SDK key, then retry.\n"); > return 1; > } > int status = 1; > size_t count = 0, block_size = 0, delay = 0, padded_count = 0; > float* input = read_input(&count); > float* output = NULL; > struct AicModel* model = NULL; > struct AicProcessor* processor = NULL; > struct AicProcessorContext* context = NULL; > if (!input) goto cleanup; > CHECK(aic_model_create_from_file(&model, "model.aicmodel")); > CHECK(aic_model_get_optimal_block_size(model, 16000, &block_size)); > CHECK(aic_processor_create(&processor, model, key, NULL)); > CHECK(aic_processor_initialize(processor, 16000, block_size, false)); > CHECK(aic_processor_context_create(&context, processor)); > CHECK(aic_processor_context_get_audio_delay(context, &delay)); > if (block_size == 0 || count > SIZE_MAX - delay || > count + delay > SIZE_MAX - (block_size - 1)) { > fprintf(stderr, "Audio buffer size overflow.\n"); > goto cleanup; > } > padded_count = ((count + delay + block_size - 1) / block_size) * block_size; > if (padded_count > SIZE_MAX / sizeof(float)) { > fprintf(stderr, "Audio buffer size overflow.\n"); > goto cleanup; > } > output = (float*)calloc(padded_count, sizeof(float)); > if (!output) { > fprintf(stderr, "Cannot allocate the processing buffer.\n"); > goto cleanup; > } > memcpy(output, input, count * sizeof(float)); > for (size_t start = 0; start < padded_count; start += block_size) { > CHECK(aic_processor_process(processor, output + start, block_size)); > } > /* Flush with silence, then omit the initial delay to align the files. */ > if (!write_output(output + delay, count)) goto cleanup; > printf("SDK %s, model %s\n", aic_get_sdk_version(), aic_model_get_id(model)); > printf("Processed %zu samples at 16000 Hz; wrote enhanced.wav\n", count); > status = 0; > cleanup: > aic_processor_context_destroy(context); > aic_processor_destroy(processor); > aic_model_destroy(model); > free(output); > free(input); > return status; > } > ``` > > ### Build and run > > Save this complete project as `CMakeLists.txt`: > > ```cmake CMakeLists.txt theme={null} > cmake_minimum_required(VERSION 3.24) > project(aic_c_quickstart LANGUAGES C) > set(CMAKE_C_STANDARD 11) > set(CMAKE_C_STANDARD_REQUIRED ON) > add_library(aic SHARED IMPORTED) > set(AIC_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/sdk") > if(WIN32) > set_target_properties(aic PROPERTIES > IMPORTED_LOCATION "${AIC_ROOT}/lib/aic.dll" > IMPORTED_IMPLIB "${AIC_ROOT}/lib/aic.dll.lib") > elseif(APPLE) > set_target_properties(aic PROPERTIES IMPORTED_LOCATION "${AIC_ROOT}/lib/libaic.dylib") > else() > set_target_properties(aic PROPERTIES IMPORTED_LOCATION "${AIC_ROOT}/lib/libaic.so") > endif() > set_target_properties(aic PROPERTIES INTERFACE_INCLUDE_DIRECTORIES "${AIC_ROOT}/include") > add_executable(quickstart quickstart.c) > target_link_libraries(quickstart PRIVATE aic) > if(UNIX AND NOT APPLE) > target_link_libraries(quickstart PRIVATE m) > endif() > if(WIN32) > add_custom_command(TARGET quickstart POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy_if_different > "$" "$") > endif() > ``` > > Configure and build from `aic-c-quickstart`: > > ```bash theme={null} > cmake -S . -B build -DCMAKE_BUILD_TYPE=Release > cmake --build build --config Release > ``` > > Run from the project directory so the program can find `input.wav` and `model.aicmodel`: > > ```bash macOS / Linux theme={null} > ./build/quickstart > ``` > > ```powershell Windows PowerShell theme={null} > .\build\Release\quickstart.exe > ``` > > ### Check the result > > A successful run exits with code zero, prints the native SDK version and resolved model ID, then reports `Processed N samples at 16000 Hz; wrote enhanced.wav`, where `N` is your input's sample count (`56080` for the supplied fixture). Open `enhanced.wav` in your audio editor: it should be mono, 16 kHz and the same duration as `input.wav`. The output is a **32-bit float WAV**; the input is PCM16. > > The program pads the final block, flushes the delayed tail and removes the initial [processing delay](/reference/concepts/latency), preserving the original sample count. File writes are checked; discard any incomplete file if writing fails. > > Listen to both files and compare them with the same STT settings to evaluate quality. > > ### Recover from an error > > | Problem | Cause and retry | > | - | - | > | **Compiler, SDK header or library missing** | Install the compiler and check the selected archive or CMake download. Use the same target architecture for compiler and SDK. Rerun configure and build. | > | **Missing SDK key or SDK error 50** | Set `AIC_SDK_LICENSE` in this terminal to the complete SDK key, then run the program again. Error 50 is an invalid license format. | > | **SDK error 6 or 52** | Error 6 means processing is not allowed; error 52 means the license expired. Check account entitlement, key validity and [required connectivity](/models/get-started/authenticate-apps), then restart with a new processor. | > | **Input file rejected** | Save a nonempty mono, 16 kHz, PCM16 WAV of at most 60 seconds as `input.wav`, then retry. | > | **Model loading fails** | Keep `model.aicmodel` in the current directory. Re-download the exact compatible file above; error 100 means an invalid model, 101 an unsupported model version and 103 a filesystem error. | > | **SDK error 5** | The block size differs from initialization. Keep every call at the configured size and pad the final block as shown. | > | **Output write fails** | Check free space and write permission. Discard the incomplete `enhanced.wav`, fix the cause and retry. | > > The CMake build uses the shared SDK library. Keep `sdk/lib` in place for this tutorial. On Windows, it copies `aic.dll` beside the executable; keep that DLL with your application. See the [C binding guide](/reference/sdk/language-bindings/c#integration-behavior) for deployment and static linking. > > ### Adapt this example > > Keep one processor per stream and process blocks in order. Reset its context on a discontinuity or before unrelated audio. Downmix stereo or use a processor per channel. See [audio format](/reference/concepts/audio-format) and [streams and state](/reference/concepts/streams-and-state). > > The helper reads a short recording into memory. For long files and live audio, use bounded buffers and keep file I/O, model loading and session teardown outside the audio callback. For human-listening enhancement, evaluate [Rook Multi Speaker](/models/perceptual-speech-enhancement/rook-multi-speaker). ## Find out more After checking your output, [evaluate representative audio](/guides/evaluate-audio), then [prepare your deployment](/production/deployment). Use [troubleshooting](/production/troubleshooting) to diagnose setup and runtime failures. > [card] [Audio format](/reference/concepts/audio-format) > > Connect your input format, channels and frame sizes to the SDK. > [card] [Streams and state](/reference/concepts/streams-and-state) > > Manage processor state across streams and interruptions. > [card] [Language bindings](/reference/sdk/language-bindings) > > Find binding-specific APIs, examples and lifecycle guidance. > [card] [Performance](/reference/concepts/performance) > > Evaluate runtime cost and latency for your deployment. # Deprecated models Source: https://docs.ai-coustics.com/models/older-models/deprecated-models Guide to migrating away from deprecated models. > [!NOTE] > > Historical support boundaries for removed model IDs. Check the current model reference before starting a new integration. For a current upgrade, start with the [upgrade guide](/reference/sdk/upgrading) and [compatibility matrix](/reference/sdk/compatibility-matrix). This page covers recent model replacements and the last core SDK versions that support the removed IDs. Last supported versions on this page refer to the **core SDK**, not the independently versioned language packages. Use the [compatibility matrix](/reference/sdk/compatibility-matrix) to match your package to its core SDK and model file version. The model IDs listed on this page are no longer supported by the current core SDK. ## Quail Voice Focus Quail Voice Focus 2.2 L and S were supported through core SDK 0.25.2. Core SDK 0.26.0 replaced them with [Quail Voice Focus 2.3](/reference/sdk/models#quail-voice-focus). Quail Voice Focus 2.1 L and S were supported through core SDK 0.21.4. > [accordion] Quail Voice Focus 2.2 L (16 kHz) > > * **ID:** `quail-vf-2.2-l-16khz` > * **Last supported core SDK version:** 0.25.2 > [accordion] Quail Voice Focus 2.2 S (16 kHz) > > * **ID:** `quail-vf-2.2-s-16khz` > * **Last supported core SDK version:** 0.25.2 > [accordion] Quail Voice Focus 2.1 L (16 kHz) > > * **ID:** `quail-vf-2.1-l-16khz` > * **Last supported core SDK version:** 0.21.4 > [accordion] Quail Voice Focus 2.1 S (16 kHz) > > * **ID:** `quail-vf-2.1-s-16khz` > * **Last supported core SDK version:** 0.21.4 ## VAD Voice Focus Core SDK 0.26.0 replaced VAD Voice Focus 2.0 with version 2.1. Version 2.0 was supported through core SDK 0.25.2. > [accordion] VAD Voice Focus 2.0 S (16 kHz) > > * **ID:** `vad-vf-2.0-s-16khz` > * **Also published as:** `quail-vf-vad-2.0-s-16khz` > * **Last supported core SDK version:** 0.25.2 ## Tyto Core SDK 0.23.0 replaced Tyto 1.0 with Tyto 1.1. Core SDK 0.26.0 replaced Tyto 1.1 with [Tyto 1.2](/reference/sdk/models#tyto), published as `tyto-1.2-l-16khz`. > [accordion] Tyto 1.1 L (16 kHz) > > * **ID:** `tyto-1.1-l-16khz` > * **Last supported core SDK version:** 0.25.2 > [accordion] Tyto 1.0 L (16 kHz) > > * **ID:** `tyto-l-16khz` > * **Last supported core SDK version:** 0.22.0 ## Next steps * Check the [models overview](/reference/sdk/models). * Download available models at [artifacts.ai-coustics.io](https://artifacts.ai-coustics.io). # Model naming changes Source: https://docs.ai-coustics.com/models/older-models/model-naming-changes Update model IDs for model file version 8 and the August and September 2026 naming changes. > [!NOTE] > > Core SDK 0.26.0 downloads Quail Multi Speaker, Rook Multi Speaker and VAD Multi Speaker only by their new IDs. This page covers the model ID change only. To find the core SDK version of your package, use the [compatibility matrix](/reference/sdk/compatibility-matrix). ## Model file version 8: use the new IDs Core SDK 0.26.0 requires model file version 8. Version 8 files exist only under the new model IDs from the September 2026 rename. The old IDs have no version 8 files. Core SDK 0.25.2 still downloads and loads them as version 7 files. | Old model ID | New model ID | | - | - | | `quail-l-16khz` | `quail-ms-l-16khz` | | `quail-l-8khz` | `quail-ms-l-8khz` | | `quail-s-16khz` | `quail-ms-s-16khz` | | `quail-s-8khz` | `quail-ms-s-8khz` | | `rook-l-48khz` | `rook-ms-l-48khz` | | `rook-l-16khz` | `rook-ms-l-16khz` | | `rook-l-8khz` | `rook-ms-l-8khz` | | `rook-s-48khz` | `rook-ms-s-48khz` | | `rook-s-16khz` | `rook-ms-s-16khz` | | `rook-s-8khz` | `rook-ms-s-8khz` | | `vad-2.1-xxs-16khz` | `vad-ms-2.1-xxs-16khz` | Before you upgrade to core SDK 0.26.0: 1. Replace each old ID in your code and configuration with the new ID from the table. 2. Download the version 8 model file for the new ID. Use the model download function of your SDK or [artifacts.ai-coustics.io](https://artifacts.ai-coustics.io). 3. Remove version 7 model files from your deployment. Core SDK 0.26.0 rejects them with `AIC_ERROR_CODE_MODEL_VERSION_UNSUPPORTED`. If you keep an old ID, the model download fails because no version 8 file exists for it. The Python, Node.js and Rust SDKs report this error: ```text theme={null} Model `quail-l-16khz` missing compatible version v8 ``` You can change to the new IDs before you upgrade. Core SDK 0.25.2 also downloads the new IDs as version 7 files. ## Quail -> Quail Multi Speaker In September 2026, Quail became Quail Multi Speaker to distinguish the general-purpose model from Quail Voice Focus. | Old name | New name | Old model ID | New model ID | | - | - | - | - | | Quail L (16 kHz) | Quail Multi Speaker L (16 kHz) | `quail-l-16khz` | `quail-ms-l-16khz` | | Quail L (8 kHz) | Quail Multi Speaker L (8 kHz) | `quail-l-8khz` | `quail-ms-l-8khz` | | Quail S (16 kHz) | Quail Multi Speaker S (16 kHz) | `quail-s-16khz` | `quail-ms-s-16khz` | | Quail S (8 kHz) | Quail Multi Speaker S (8 kHz) | `quail-s-8khz` | `quail-ms-s-8khz` | Quail Voice Focus was not part of this naming change and retains the `quail-vf-*` naming pattern. This does not mean every version remains supported; see [deprecated models](/models/older-models/deprecated-models#quail) for removed Voice Focus IDs. ## VAD: Quail VAD -> VAD -> VAD Multi Speaker The voice activity detection (VAD) models dropped the Quail prefix in August 2026. In September, the general-purpose model gained an `-ms-` infix to distinguish VAD Multi Speaker from VAD Voice Focus. **Current rename** | Old name | New name | Old model ID | New model ID | | - | - | - | - | | VAD | VAD Multi Speaker | `vad-2.1-xxs-16khz` | `vad-ms-2.1-xxs-16khz` | VAD Voice Focus was not part of this step and keeps its `vad-vf-2.0-s-16khz` ID. **August transition:** these intermediate names precede the September rename above. | Old name | New name | Old model ID | New model ID | | - | - | - | - | | Quail VAD | VAD | `quail-vad-2.0-xxs-16khz` | `vad-2.1-xxs-16khz` | | Quail VAD Voice Focus | VAD Voice Focus | `quail-vf-vad-2.0-s-16khz` | `vad-vf-2.0-s-16khz` | > [!NOTE] > > VAD moved from 2.0 to 2.1 in this step, so it was both a rename and a newer model version. VAD Voice Focus stayed at 2.0. ## Rook -> Rook Multi Speaker In September 2026, the perceptual speech enhancement models became Rook Multi Speaker. Their IDs gained an `-ms-` infix. | Old name | New name | Old model ID | New model ID | | - | - | - | - | | Rook L (48 kHz) | Rook Multi Speaker L (48 kHz) | `rook-l-48khz` | `rook-ms-l-48khz` | | Rook L (16 kHz) | Rook Multi Speaker L (16 kHz) | `rook-l-16khz` | `rook-ms-l-16khz` | | Rook L (8 kHz) | Rook Multi Speaker L (8 kHz) | `rook-l-8khz` | `rook-ms-l-8khz` | | Rook S (48 kHz) | Rook Multi Speaker S (48 kHz) | `rook-s-48khz` | `rook-ms-s-48khz` | | Rook S (16 kHz) | Rook Multi Speaker S (16 kHz) | `rook-s-16khz` | `rook-ms-s-16khz` | | Rook S (8 kHz) | Rook Multi Speaker S (8 kHz) | `rook-s-8khz` | `rook-ms-s-8khz` | > [!NOTE] > > Some old model IDs on this page are no longer supported by the current core SDK. Update to the current IDs above. For models that have been removed, see [deprecated models](/models/older-models/deprecated-models) for their last supported core SDK versions. # Rook Multi Speaker Source: https://docs.ai-coustics.com/models/perceptual-speech-enhancement/rook-multi-speaker Speech enhancement for human listening in calls and other real-time audio applications. **Rook Multi Speaker** targets speech naturalness and intelligibility for human listeners. Use it for calls and other applications where people hear the enhanced output. Its multi-speaker models aim to retain speech from both foreground and background participants while reducing noise and reverberation. For machine listening and speech-to-text (STT), evaluate [Quail Multi Speaker](/models/speech-enhancement/quail-multi-speaker). For isolating one primary speaker, evaluate [Quail Voice Focus](/models/voice-focus/quail-voice-focus). ## Choose a variant Rook Multi Speaker is available in small and large variants at 8 kHz, 16 kHz and 48 kHz. Examples are `rook-ms-s-16khz` and `rook-ms-l-48khz`. The [model reference](/reference/sdk/models#rook-multi-speaker) lists all current IDs and their native block sizes. Match the model's native rate to the frequency range your application needs, then measure quality and CPU use on target hardware. Processing 48 kHz audio through a 16 kHz model does not make that model enhance frequencies above its native range. ## Evaluate for listeners Use paired recordings and listening tests with representative speech, noise, reverberation and overlapping speakers. Check speech retention and artifacts as well as noise reduction. Measure latency through the complete capture, processing and playback path. Rook Multi Speaker can also precede a third-party voice activity detector, but test that detector's false starts, missed speech and timing with the enhanced signal. Do not assume one enhancement level gives the best result for every detector. Dedicated [ai-coustics VAD](/models/voice-activity-detection/vad) should receive the original input audio. Start with the [SDK quickstart](/models/get-started/sdk-quickstart), then use the [latency guide](/reference/concepts/latency) to evaluate your call path. # Quail Multi Speaker Source: https://docs.ai-coustics.com/models/speech-enhancement/quail-multi-speaker Multi-speaker speech enhancement for speech-to-text and voice agents. **Quail Multi Speaker** processes audio for machine listening, including speech-to-text (STT) and voice agents. The multi-speaker models target noise and reverberation while retaining speech from multiple participants. Use Quail Multi Speaker when every speaker matters, such as a meeting transcription or speakerphone application. If your application should follow one primary speaker and suppress competing speech, evaluate [Quail Voice Focus](/models/voice-focus/quail-voice-focus). ## Choose a variant | Input and task | Candidate model IDs | | - | - | | 16 kHz speech for STT | `quail-ms-l-16khz`, `quail-ms-s-16khz` | | 8 kHz telephony speech | `quail-ms-l-8khz`, `quail-ms-s-8khz` | The small and large variants give you alternatives to compare for quality and resource use. Measure both with your recordings, STT provider and target hardware. The [model reference](/reference/sdk/models#quail-multi-speaker) lists release-specific rates and block sizes. ## Evaluate the result Compare the original and enhanced audio using the same STT model, transcription settings and labeled recordings. Track word error rate (WER), insertions, deletions and task completion. Enhancement does not guarantee an improvement for every recording or STT provider. > [!NOTE] > > Quail Multi Speaker is optimized for machine listening. Some noise or reverberation can remain, and the output may differ from what a human listener considers natural. Use [Rook Multi Speaker](/models/perceptual-speech-enhancement/rook-multi-speaker) when human listening is the primary goal. Follow the [STT tuning guide](/models/speech-enhancement/speech-enhancement-for-voice-ai-systems) and [SDK quickstart](/models/get-started/sdk-quickstart) to evaluate a complete integration. # Speech enhancement for voice AI systems Source: https://docs.ai-coustics.com/models/speech-enhancement/speech-enhancement-for-voice-ai-systems Evaluate Quail models with your speech-to-text provider and tune enhancement without losing target speech. **Quail models** prepare speech for machine listening. Speech-to-text (STT) systems respond differently to noise, reverberation and competing speakers, so evaluate enhancement with the provider and audio your application uses. Quail's multi-speaker models aim to retain speech from multiple participants. For a voice agent that should respond only to one primary speaker, start with [Quail Voice Focus](/models/voice-focus/quail-voice-focus). Use the [paired audio evaluation procedure](/guides/evaluate-audio) to establish a baseline, then rerun the same recordings after each tuning change. ## Working with real-world audio Build a small evaluation set that includes clean speech, quiet speech, noise, reverberation, overlapping speakers and silence. Include the microphones, languages and telephony codecs you expect in production. Keep a transcript of the speech your application should recognize. Run the original and enhanced recordings through the same STT version and settings. Compare word error rate (WER), insertions and deletions rather than assuming that stronger suppression produces better transcripts. Keep clean speech in the evaluation so an improvement on noisy calls does not hide a regression elsewhere. ## Tuning the `enhancement_level` The SDK's `ProcessorParameter.EnhancementLevel` accepts values from `0.0` to `1.0`. Its behavior depends on the loaded model. Read the starting value from the processor context rather than assuming one default across all model families: ```python theme={null} # After creating and initializing your processor: context = processor.get_context() current_level = context.get_parameter(aic.ProcessorParameter.EnhancementLevel) context.set_parameter(aic.ProcessorParameter.EnhancementLevel, 1.0) ``` This fragment uses `import aic_sdk as aic` and the processor from the [Python quickstart](/reference/sdk/language-bindings/python). Start your Quail comparison with the model default and `1.0`, then test intermediate values if needed. `1.0` selects the strongest setting on the exposed parameter scale; it does not guarantee noise-free output or the lowest WER. For an unprocessed comparison, retain the original recording. The SDK's bypass control preserves processing delay, so bypass timing and a direct raw-audio path are different baselines. See [latency](/reference/concepts/latency). ## Best practices * **Tune per STT provider.** Hold the provider version and decoding settings fixed while changing one enhancement setting. * **Track both insertions and deletions.** Check background-speech insertions, quiet-speech deletions and word substitutions separately. Their response to tuning depends on your audio. * **Preserve stream state.** Process frames from one stream in order; do not reset between adjacent blocks. Reset at a discontinuity or use a new processor for a new call. * **Measure the complete path.** Report model delay, compute time and end-to-end response latency separately. Compare downstream agent behavior as well as transcripts. See the [performance guide](/reference/concepts/performance) for resource measurements and [stream lifecycle guide](/reference/concepts/streams-and-state) for reset and concurrency rules. # How to use and tune VAD Source: https://docs.ai-coustics.com/models/voice-activity-detection/vad Process original audio and tune speech boundaries with VAD Multi Speaker or VAD Voice Focus. **ai-coustics VAD** provides dedicated voice activity detection (VAD) for real-time audio. Choose [VAD Multi Speaker](/models/voice-activity-detection/vad-multi-speaker) when speech from any participant matters, or [VAD Voice Focus](/models/voice-activity-detection/vad-voice-focus) when only the primary speaker should drive activity. Both use the processing and tuning workflow below. > [!NOTE] > > This guide uses model file format 8 and current model IDs, including `vad-ms-2.1-xxs-16khz` and `vad-vf-2.1-s-16khz`. Match model IDs to your package in the [compatibility matrix](/reference/sdk/compatibility-matrix). Earlier IDs are listed in [renamed models](/models/older-models/model-naming-changes) and [deprecated models](/models/older-models/deprecated-models). ## What is VAD? VAD identifies speech in an audio stream. Voice agents use it for turn-taking, endpointing and gating downstream speech-to-text (STT). Both models run independently of enhancement. Compare whose speech they detect under [model differences](#model-differences). ## Use cases VAD supplies speech activity, not a complete semantic end-of-turn decision. Your pipeline decides how to combine it with transcription, turn detection and interruption policies. * **Gate downstream work.** Use activity to decide which audio to send to STT, while preserving enough leading and trailing audio to avoid clipping words. * **Drive turn-taking.** Evaluate the speech-start and speech-stop events used by your voice agent. Check quiet speech, pauses and competing speakers. * **Measure the trade-off.** Track missed speech and false activity separately. Any cost or transcription benefit depends on the audio and downstream provider. ## How it works The VAD is a standalone object with its own lifecycle, independent of enhancement: 1. Load a dedicated VAD model, `vad-ms-2.1-xxs-16khz` or `vad-vf-2.1-s-16khz` 2. Create a VAD from that model and initialize it for your sample rate and block size 3. Feed each mono audio block to the VAD 4. Query its context to see whether speech was detected The model produces a speech probability for each processed block, which the SDK compares against the configured sensitivity threshold. Processing does not modify your audio, so the VAD can read the same buffer you pass to an enhancement processor. The following Python 3.11 example uses `aic-sdk==3.4.0` and `numpy==2.2.6`. Save it as `vad.py`, set `AIC_SDK_LICENSE` in the same terminal and run `python vad.py input.wav` with a mono, 16 kHz, signed 16-bit PCM WAV. See the [Python setup instructions](/reference/sdk/language-bindings/python) for the environment and key setup. The example loads VAD Multi Speaker. To use VAD Voice Focus, replace `vad-ms-2.1-xxs-16khz` with `vad-vf-2.1-s-16khz` in the model download call. The processing API is the same for both models. ```python vad.py theme={null} import os import sys import wave import aic_sdk as aic import numpy as np key = os.environ.get("AIC_SDK_LICENSE", "").strip() if not key: raise RuntimeError("Set AIC_SDK_LICENSE before running vad.py") if len(sys.argv) != 2: raise SystemExit("Usage: python vad.py input.wav") with wave.open(sys.argv[1], "rb") as source: if (source.getnchannels(), source.getsampwidth(), source.getframerate()) != (1, 2, 16000): raise ValueError("Use mono, 16 kHz, signed 16-bit PCM WAV audio") audio = np.frombuffer(source.readframes(source.getnframes()), dtype=" [!NOTE] > > Between SDK 0.22.0 and 0.24.0, a dedicated VAD model was the only option: the earlier energy-based VAD derived from an enhancement processor had been removed. Core SDK 0.25.0 brought energy-based detection back under a new API, `EnergyVadContext`, so an enhancement processor can report speech again without a separate VAD model. A dedicated VAD model remains the more accurate choice. See [Migrate to the dedicated VAD](/reference/deprecated/energy-vad-to-dedicated-vad) for the differences. The VAD keeps a history of the audio it has seen, so reset it through its context at a discontinuity, such as a seek or a new call. In a long-running integration, call this while the VAD is still active and no processing call is in flight: ```python theme={null} context.reset() ``` This clears the VAD's state and immediately drops the published decision and probability, so queries cannot return stale values from the previous stream. The VAD stays initialized. See [streams and state](/reference/concepts/streams-and-state#resetting-state). ## Model differences | Model | How it works | Recommended use | | - | - | - | | **[VAD Multi Speaker](/models/voice-activity-detection/vad-multi-speaker)** (`vad-ms-2.1-xxs-16khz`) | Predicts speech probability directly from the input audio, for any audible speaker. | Speech activity from multiple participants; evaluate false detections on noise and music. | | **[VAD Voice Focus](/models/voice-activity-detection/vad-voice-focus)** (`vad-vf-2.1-s-16khz`) | Targets speech probability for the primary speaker. | Single-target-speaker turn-taking where interfering speakers should not trigger the VAD. | Both models run independently of enhancement. Neither requires Quail Voice Focus, Quail Multi Speaker or Rook Multi Speaker to be present in the signal chain. ## Using VAD alongside enhancement Run the VAD and the enhancement processor side by side on the same original input block, rather than chaining them: ```python theme={null} vad.process(audio) # reads the block, does not modify it enhanced = processor.process(audio) # returns the enhanced block ``` Feeding the VAD the enhanced output means detecting speech in audio that no longer matches what the VAD model expects, and it stacks the processor's delay on top of the VAD's own prediction delay. The two delays are independent and are reported separately: the processor's context reports how far the enhanced audio lags its input, and the VAD's context reports how far the published prediction lags the same input. ## VAD parameters Read the three parameter defaults from the loaded model through its VAD context. Use these model-specific values as your tuning baseline. > [accordion] Sensitivity > > The probability threshold used to decide whether speech is detected. > > A block probability above this threshold triggers a speech-detected decision. Higher thresholds require more model confidence and detect speech less aggressively. Confidence does not guarantee a correct classification. > > Read [`raw_vad_probability()`](/reference/sdk/api/python/vad#vadcontext-raw_vad_probability) on the Python VAD context to see the model's probability before thresholding > and post-processing. This is the most practical way to choose a threshold from recorded audio. > > * **Range:** `0.0` to `1.0` > > * **Default:** model-specific > > > [!WARNING] > > > > This range applies to a dedicated VAD model. On an energy-based VAD, sensitivity is an energy threshold > > in the range 1.0 to 15.0 and higher values detect speech *more* aggressively. That was the behavior before > > SDK 0.22.0, and it returns in core SDK 0.25.0 for `EnergyVadContext`. The two scales are not > > interchangeable: energy values are not valid probabilities and the direction is inverted. See > > [Retune sensitivity](/reference/deprecated/energy-vad-to-dedicated-vad#retune-sensitivity). > [accordion] Speech hold duration > > Stabilizes speech-to-silence transitions. When the current probability is at or below the sensitivity threshold, speech remains detected while at least 50% of retained frames were above threshold. This history spans approximately `speech_hold_duration * 2` seconds. Above-threshold decisions instead use the consecutive-frame requirement set by minimum speech duration. > With a 0.5 s hold duration and a full history of speech, detection continues for approximately 0.5 s after speech ends. Further speech changes the history and can extend the hold. > > > [!NOTE] > > > > Effective timing is rounded to the nearest model window, such as a multiple of 15 ms. `get_parameter()` returns the stored requested value, not the effective timing. > > * **Unit:** seconds > * **Range:** `0.0` to 300x the model window length. For the two 15 ms models listed here, this is 4.5 s > * **Default:** model-specific > [accordion] Minimum speech duration > > Sets how long speech must be present before detection, stabilizing silence-to-speech transitions. > > > [!NOTE] > > > > Effective timing is rounded to the nearest model window, such as a multiple of 15 ms. `get_parameter()` returns the stored requested value, not the effective timing. > > * **Unit:** seconds > * **Range:** `0.0` to `1.0` > * **Default:** model-specific ## API reference by language Use your binding's reference for initialization, parameter values and prediction queries. | Language | Create a detector | Parameters | Raw probability | | :- | :- | :- | :- | | **Python** | [`Vad()`](/reference/sdk/api/python/vad#vad-constructor) | [`VadParameter`](/reference/sdk/api/python/vad#vadparameter) | [`raw_vad_probability()`](/reference/sdk/api/python/vad#vadcontext-raw_vad_probability) | | **Node.js** | [`new Vad()`](/reference/sdk/api/node/vad#node-vad-constructor) | [`VadParameter`](/reference/sdk/api/node/vad#node-vadparameter) | [`getRawVadProbability()`](/reference/sdk/api/node/vad#node-vadcontext-getrawvadprobability) | | **C** | [`aic_vad_create()`](/reference/sdk/api/c/vad#aic_vad_create) | [`AicVadParameter`](/reference/sdk/api/c/vad#AicVadParameter) | [`aic_vad_context_get_raw_vad_probability()`](/reference/sdk/api/c/vad#aic_vad_context_get_raw_vad_probability) | | **C++** | [`aic::Vad::create()`](/reference/sdk/api/cpp/vad#aic-Vad-create) | [`aic::VadParameter`](/reference/sdk/api/cpp/vad#aic-VadParameter) | [`get_raw_vad_probability()`](/reference/sdk/api/cpp/vad#aic-VadContext-get_raw_vad_probability) | | **Rust** | [`Vad::new()`](/reference/sdk/api/rust/vad#rust-aic_sdk-Vad-new) | [`VadParameter`](/reference/sdk/api/rust/vad#rust-aic_sdk-VadParameter) | [`raw_vad_probability()`](/reference/sdk/api/rust/vad#rust-aic_sdk-VadContext-raw_vad_probability) | | **WebAssembly** | [`new Vad()`](/reference/sdk/api/wasm/vad#wasm-vad-constructor) | [`VadParameter`](/reference/sdk/api/wasm/vad#wasm-vadparameter) | [`getRawVadProbability()`](/reference/sdk/api/wasm/vad#wasm-vadcontext-getrawvadprobability) | ## Best practices * **Choose whose speech should count.** Use VAD Multi Speaker for activity from any speaker or VAD Voice Focus for a primary-speaker task. * **Tune against labeled audio.** Read model defaults through `get_parameter` and evaluate sensitivity and timing with speech, silence, quiet utterances and interfering speakers. * **Feed original audio.** Run dedicated VAD beside enhancement on the same input signal. Preserve mono format and process blocks in order. * **Align the timeline.** Read the VAD's prediction delay separately from the enhancement processor's audio delay. * **Keep session state separate.** Use one VAD per independent stream. Reset at a discontinuity and terminate after the stream is finished. ## Framework integration Framework adapters can override SDK timing defaults or use a different state machine. The [LiveKit quickstart](/models/get-started/livekit-quickstart) requires both the session VAD and its RoomIO frame processor. The [Pipecat quickstart](/models/get-started/pipecat-quickstart#standalone-ai-coustics-vad) uses Pipecat `VADParams` and explains why a transport enhancement filter feeds enhanced audio to downstream VAD. Do not copy timing values between frameworks without checking their units and behavior. ## Third-party VADs A third-party VAD may respond differently to enhanced audio. Evaluate false starts, missed speech and end-of-turn latency before choosing an enhancement model or strength for that detector. Enhancement delay is part of that input path. Use Quail Voice Focus when the preprocessing task requires primary-speaker isolation, or Rook Multi Speaker when the output is also intended for human listening. No enhancement level guarantees the best performance for every third-party detector. Dedicated ai-coustics VAD does not require an enhancement model and should receive original audio. # VAD Multi Speaker Source: https://docs.ai-coustics.com/models/voice-activity-detection/vad-multi-speaker Detect speech activity from any speaker in the original audio. **VAD Multi Speaker** detects voice activity from any speaker. Use it when speech from multiple participants should drive transcription or turn-taking, such as in a meeting or speakerphone application. It produces speech probabilities and speech activity decisions while leaving the input audio unchanged. Feed it the original audio, alongside any enhancement processor. It runs independently of Quail Multi Speaker or other enhancement models. If only one primary speaker should trigger activity, use [VAD Voice Focus](/models/voice-activity-detection/vad-voice-focus). ## Model and compatibility For core SDK `0.26.0`, use `vad-ms-2.1-xxs-16khz`. Its native sample rate is 16 kHz and its optimal native block size is 240 samples (15 ms). See the [model reference](/reference/sdk/models#vad-multi-speaker) for artifact details and the [compatibility matrix](/reference/sdk/compatibility-matrix) for your language package. ## Evaluate speech detection Test quiet speech, pauses, overlapping speakers, noise and music. Track missed speech and false detections separately. Speech from another participant is expected to count as activity with this model. Read the loaded model's parameter defaults before tuning sensitivity, minimum speech duration and speech hold duration. VAD supplies speech activity; your application combines that signal with transcription and turn detection to decide when a turn is complete. Follow [Use and tune VAD](/models/voice-activity-detection/vad#how-it-works) for a runnable example, signal routing, timing controls and language API references. # VAD Voice Focus Source: https://docs.ai-coustics.com/models/voice-activity-detection/vad-voice-focus Detect speech activity from the primary speaker for voice agents. **VAD Voice Focus** detects voice activity from the primary speaker. Use it when a voice agent should respond to one participant while avoiding activity triggered by background conversations or competing speakers. It produces speech probabilities and speech activity decisions while leaving the input audio unchanged. Feed it the original audio. It runs independently of [Quail Voice Focus](/models/voice-focus/quail-voice-focus), which produces enhanced audio. If speech from every participant should count, use [VAD Multi Speaker](/models/voice-activity-detection/vad-multi-speaker). ## Model and compatibility For core SDK 0.26.0, use `vad-vf-2.1-s-16khz`. Its native sample rate is 16 kHz and its optimal native block size is 240 samples (15 ms). Core SDK 0.26.0 requires model file format 8. Match the model to your package in the [compatibility matrix](/reference/sdk/compatibility-matrix); see the [model reference](/reference/sdk/models#vad-voice-focus) for artifact details. ## Evaluate primary-speaker detection Test quiet target speech, overlapping speech, background conversations and changes in speaker prominence. The primary speaker can change as speakers become more or less prominent; this model does not identify or enroll a particular person. Track missed target speech and activity triggered by interfering speakers separately. Tune sensitivity and speech timing against labeled recordings, starting from the loaded model's defaults. Follow [Use and tune VAD](/models/voice-activity-detection/vad#how-it-works) for the shared processing example and parameters. Use this model's ID in the example to evaluate primary-speaker activity. # Quail Voice Focus Source: https://docs.ai-coustics.com/models/voice-focus/quail-voice-focus Primary-speaker isolation for speech-to-text and voice agents. **Quail Voice Focus** targets one primary speaker while suppressing competing speech, background noise and residual echo. Use it when a voice agent should follow one participant, rather than transcribe every voice in a room. Voice Focus uses recent audio context to select the primary speaker. At the beginning of a stream, suppression can be weaker while that context builds. Test startup with short utterances and quiet speakers; there is no fixed warm-up duration guaranteed by this guide. Keep processing continuous across adjacent frames so the model can retain context. Primary-speaker selection can change when another speaker becomes more prominent, such as when someone moves closer to the microphone. It is not a persistent identity lock. If your application requires identity verification or a fixed enrolled speaker, model selection alone does not establish that behavior. ## Choose a variant For core SDK 0.26.0, start with `quail-vf-2.3-l-16khz` or compare the smaller `quail-vf-2.3-s-16khz` on your target hardware. Both have a native rate of 16 kHz and an optimal native block size of 240 samples. Core SDK 0.26.0 requires model file format 8. Match the model to your package in the [compatibility matrix](/reference/sdk/compatibility-matrix); see the [model reference](/reference/sdk/models#quail-voice-focus) for acquisition details. ## Check speech retention Compare original and enhanced recordings using your speech-to-text (STT) provider. Include quiet target speech, overlapping speech, speaker changes and the first seconds after a reset. Measure target-word deletions as well as background-word insertions; stronger suppression can remove speech you intended to retain. For dedicated ai-coustics voice activity detection (VAD), use the original input audio. [VAD Voice Focus](/models/voice-activity-detection/vad-voice-focus) targets primary-speaker activity when only the target speaker should drive speech activity. A third-party VAD may behave differently on enhanced audio; evaluate its speech boundaries and added delay separately. Follow [Voice Focus tuning](/models/voice-focus/voice-focus-for-voice-ai-systems) and the [SDK quickstart](/models/get-started/sdk-quickstart) for the next step. # Voice Focus for voice AI systems Source: https://docs.ai-coustics.com/models/voice-focus/voice-focus-for-voice-ai-systems Tune primary-speaker isolation against transcription errors and speech retention. **Quail Voice Focus** is designed for voice agents that should follow one primary speaker. Evaluate it with your speech-to-text (STT) provider to determine whether suppressing competing speech improves the behavior your application needs. Use the [paired audio evaluation procedure](/guides/evaluate-audio) to establish a baseline, then rerun the same recordings after each tuning change. `ProcessorParameter.EnhancementLevel` accepts values from `0.0` to `1.0`. Higher values request stronger suppression. The starting value comes from the loaded model; read it through `processor.get_context().get_parameter(...)` in Python or `processor.getContext().getParameter(...)` in Node.js. > [accordion] How it works > > Voice Focus makes suppression decisions from audio context. Speech can be ambiguous, especially when speakers overlap or the target is quiet. Increasing the enhancement level changes suppression strength; it does not guarantee that every foreground word will remain or that every background voice will disappear. ## Recommended settings Use these as comparison points for an evaluation, not measured quality rankings: | Value | Evaluation purpose | Check | | - | - | - | | Current model default | Establish the baseline for the exact model artifact. | Speech retention, background leakage and startup behavior. | | `0.5` | Compare a lower setting with stronger suppression. | Whether quiet target speech is retained and whether competing speech reaches STT. | | `0.8` | Test increased suppression when competing speech causes errors. | Whether fewer background insertions justify any added target deletions. | | `1.0` | Test the strongest exposed setting. | Quiet speech, overlaps and speaker changes; do not assume this minimizes word error rate. | Keep the input recordings, STT version and decoding settings fixed. Change one setting at a time. No setting guarantees preservation of all foreground speech, and the best result can differ by provider and acoustic condition. ## Best practices * **Match the target-speaker task.** Use Voice Focus when background speech should be suppressed. Use [Quail's multi-speaker models](/models/speech-enhancement/quail-multi-speaker) when all participants matter. * **Measure insertions and deletions separately.** Lower overall word error rate can hide loss of a critical target utterance. * **Include startup and retargeting.** Test the beginning of a stream, quiet speech and a change in the most prominent speaker. Preserve state between consecutive frames. * **Check agent behavior.** Compare false interruptions, missed requests and end-of-turn latency alongside transcription quality. Use the [model reference](/reference/sdk/models#quail-voice-focus) to record the exact model ID and the [performance guide](/reference/concepts/performance) for reproducible resource measurements. # How to deploy the SDK Source: https://docs.ai-coustics.com/production/deployment Prepare model files, credentials, network access and runtime checks for a production deployment. Start with a working [SDK](/models/get-started/sdk-quickstart), [LiveKit](/models/get-started/livekit-quickstart) or [Pipecat](/models/get-started/pipecat-quickstart) integration and pin its dependencies. This guide covers the native SDK. Use the [WebAssembly guide](/reference/sdk/language-bindings/wasm) for browser-specific package and authentication requirements. ## Prepare the release 1. **Pin the version set.** Record the language binding, core SDK, framework plugin and model ID in your release. Keep the lockfile and check the [compatibility matrix](/reference/sdk/compatibility-matrix). 2. **Match the platform.** Select the package or native library for the target OS and CPU architecture. Test library loading inside the deployment image or host environment. 3. **Provision model files.** Download compatible `.aicmodel` files before deployment. Verify the service can read and load them, and retain the exact files with the release. 4. **Inject credentials at runtime.** Follow the [authentication guide](/models/get-started/authenticate-apps) with your secret manager. Keep keys out of images, build arguments, source control and logs. 5. **Retain a rollback bundle.** Keep the previous application, dependencies, models and configuration together so rollback restores a compatible combination. ## Configure network access Audio inference runs locally through [AirTen](/reference/concepts/airten). Review each network activity separately: ```mermaid theme={null} flowchart TB subgraph host["Your application host"] Input["Input audio"] --> SDK["SDK and local model"] SDK --> Output["Processed audio or analysis results"] Files["Provisioned model files"] --> SDK end Provision["Package and model distribution"] -. "Provisioning downloads" .-> Files SDK -. "Activation and usage metadata, per entitlement" .-> Service["ai-coustics services"] SDK -. "Optional error reports" .-> Errors["Error reporting service"] SDK -. "Configured metrics" .-> Collector["Your OpenTelemetry collector"] ``` Solid arrows show local processing; dotted arrows show downloads or metadata traffic. SDK inference does not upload input audio. Your application and downstream services may have separate audio flows. Entitlements and telemetry settings determine which network paths apply. | Activity | Deployment check | | :- | :- | | **Package and model download** | Allow access in the provisioning environment, or distribute the validated artifacts through your own deployment system. | | **SDK activation and usage reporting** | Verify connectivity under the deployed credential and entitlement. Test rejection and connectivity loss, as well as normal activation. | | **Client token issuance** | Keep the long-lived key on your backend. Test token retrieval, expiry and refresh from the client environment. | | **SDK error reporting** | Decide whether to use it; set `DO_NOT_TRACK=1` before SDK loading if disabled. | | **Customer OpenTelemetry export** | Configure the collector endpoint and authentication separately. Verify network access from the application container or host. | | **Framework and downstream services** | Review LiveKit, speech-to-text and other application dependencies independently. | See [telemetry](/reference/concepts/sdk-telemetry) for data categories and controls. For restricted egress, obtain the current destination requirements from ai-coustics. Disconnected deployment requires a suitable offline license and provisioned models. Test a cold start and the required operating period under your network restrictions, including entitlement expiry or renewal. An online session tolerating a network failure does not establish offline support. ## Separate startup from audio processing Create and initialize models, processors and voice activity detection (VAD) instances before accepting live audio. Keep downloads, credential retrieval, initialization and teardown outside real-time audio callbacks. Allocate an independent processor and VAD state for each independent stream. Process frames in order and follow the [streams and state](/reference/concepts/streams-and-state) guidance for reset, reconnect and concurrency. Match the sample rate, mono format and block size to the actual incoming stream using the [audio format reference](/reference/concepts/audio-format). Check readiness before accepting traffic: * **Load the deployed model.** Verify the file path and compatibility with the installed core SDK. * **Check a controlled audio fixture.** Process a non-silent recording with valid authorization, inspect errors and verify output length, format and expected processing behavior. * **Check framework activation.** Confirm the filter is active and not silently passing audio through. * **Measure under load.** Exercise the expected stream count under the deployed CPU and memory limits. Use controlled fixtures for readiness tests and keep production audio out of diagnostics and CI artifacts. ## Set a capacity and failure policy A 160-sample frame at 16 kHz represents 10 ms of audio. Sustained processing above 10 ms cannot keep pace on a serial path. Compare frame processing time against this budget. Record high-percentile processing time, queue depth, memory and CPU use at the intended concurrency. Include resampling and framework overhead. Use the [performance guide](/reference/concepts/performance) and [OpenTelemetry metrics](/models/get-started/opentelemetry) to track regressions. Bound queues and choose an overload policy: reject new sessions, stop the failing session or report a fallback. Test CPU throttling, credential rejection and token-refresh failure. Surface background-task errors. Report bypass and degraded processing separately from active enhancement, VAD or analysis. ## Shut down and upgrade Stop new streams and audio submissions, finish or cancel pending work and release SDK instances outside the audio callback. Stop token-refresh tasks too. Where exposed, `terminate_session()` requests termination and can block during cleanup. Processing may be disabled after it returns; submit no further frames and create a new instance for a new session. Before upgrading, compare the same fixtures, failure cases and settings on both versions. Check the [changelog](/changelog), [compatibility matrix](/reference/sdk/compatibility-matrix) and applicable migrations, then roll out gradually. ## Verify the deployment Record these results with the release: | Check | Evidence to retain | | :- | :- | | **Cold start** | Package/core/model versions, target OS/architecture and successful model loading | | **Active processing** | Controlled input, checked SDK return path and inspected output | | **Session isolation** | Independent streams, reset/reconnect behavior and clean shutdown | | **Capacity** | Hardware/resource limits, stream count, processing-duration distribution and queue behavior | | **Failure recovery** | Rejected credential, token expiry/refresh, lost connectivity and overload behavior | | **Observability** | Sanitized error record and confirmed metrics in the intended collector | | **Rollback** | Successful rerun using the retained previous release bundle | Use [troubleshooting](/production/troubleshooting) for failed checks. See your agreement and [pricing and support information](/models/get-started/pricing) for commercial terms. # How to troubleshoot an integration Source: https://docs.ai-coustics.com/production/troubleshooting Find the failing stage, apply a targeted recovery and verify that audio processing is active. Start with the first failing operation: installation, model loading, processor creation, initialization, processing or shutdown. Record the binding version, core SDK version, model ID and sanitized error. Keep credentials, authorization headers and private audio out of diagnostics. ## Versions and error references The recipes target the binding and core versions in the table below. Use your binding's error reference; exception names differ across languages. | Binding | Package or distribution | Core | Complete error reference | | :- | :- | :- | :- | | **Python** | `aic-sdk` 3.4.0 | 0.26.0 | [Python exceptions](/reference/sdk/api/python/errors) | | **Node.js** | `@ai-coustics/aic-sdk` 0.26.0 | 0.26.0 | [Node.js errors](/reference/sdk/api/node/errors) | | **C** | SDK 0.26.0 | 0.26.0 | [C status codes](/reference/sdk/api/c/errors-and-types) | | **C++** | Wrapper 0.26.0 | 0.26.0 | [C++ results and errors](/reference/sdk/api/cpp/results-and-errors) | | **Rust** | `aic-sdk` 0.25.2 | 0.25.2 | [Rust errors and features](/reference/sdk/api/rust/errors-and-features) | | **WebAssembly** | `@ai-coustics/aic-sdk-wasm` 0.26.0 | 0.26.0 | [WebAssembly errors](/reference/sdk/api/wasm/errors) | | First failing stage | Recovery recipe | | :- | :- | | **Package import or native loading** | [Installation](#installation-or-native-library-loading-fails) | | **Model download or creation** | [Model loading](#model-download-or-loading-fails) | | **Credential validation or refresh** | [Credentials](#credentials-are-missing-invalid-or-expired) | | **Authorization or terminated session** | [Disallowed processing](#processing-becomes-disallowed) | | **Initialization or audio length** | [Audio configuration](#audio-configuration-or-frame-size-is-rejected) | | **Unexpected audio or predictions** | [Output](#output-is-silent-distorted-or-unexpectedly-unchanged), [VAD](#voice-activity-detection-behaves-incorrectly) or [analysis](#analysis-fails-or-repeats-old-scores) | | **Missed audio deadlines or queue growth** | [Performance](#latency-or-cpu-use-increases) | | **No collector observations** | [Metrics](#metrics-are-missing) | ## Installation or native library loading fails **Applies to:** The native bindings listed above; WebAssembly 0.26.0 has a separate [initialization sequence](/reference/sdk/api/wasm/initialization). **Diagnostic:** Record the package-manager, import or loader error and your runtime, OS and architecture. With Rust's `runtime-linking` feature, `DynamicLoadingError::OpenLibrary` means the library could not be opened; automatic loading instead panics on failure. Check platform support in your [language guide](/reference/sdk/language-bindings), then install its pinned package in a fresh environment. For Python, run this in the environment that runs your application: ```bash theme={null} python -c 'import importlib.metadata, platform; import aic_sdk as aic; print("binding:", importlib.metadata.version("aic-sdk")); print("core:", aic.get_sdk_version()); print("platform:", platform.system(), platform.machine())' ``` For C and C++, check the include path, linked library and runtime loader path against the build example. Rebuild for the target architecture. **Verify:** Repeat the import or build in the deployment environment. Confirm the reported core SDK version before retrying audio. ## Model download or loading fails **Applies to:** The native bindings listed above; use the WebAssembly error reference for its 0.26.0 model-byte loader. **Diagnostic:** Python reports `ModelDownloadError`, `FileSystemError`, `ModelInvalidError` or `ModelVersionUnsupportedError` depending on the failing stage. In C/C++, native status `103` is a filesystem failure and `101` is an incompatible model format. Preserve the error category; redact private paths or URLs from details. Check the exact model ID in the [model catalog](/reference/sdk/models). Confirm it is supported by the installed core SDK; old model IDs are not aliases for current models. For a download failure, check connectivity, output-directory permissions and available disk space. For a local load failure, check the actual path and file contents. Redownload into a new directory instead of overwriting a model used by running sessions. A `ModelVersionUnsupportedError` requires a compatible SDK/model combination. **Verify:** Repeat the download or load, then run the language quickstart from the deployment path. Confirm model creation, initialization and processing succeed. ## Credentials are missing, invalid or expired **Applies to:** The native bindings listed above. Browser clients using WebAssembly 0.26.0 receive JWTs from their backend. **Diagnostic:** The native quickstart guard emits `Set AIC_SDK_LICENSE to your SDK key, then retry.` for missing or placeholder credentials. Python native failures include `LicenseFormatInvalidError`, `LicenseExpiredError` and `TokenUnsupportedError`; C/C++ use status `50`, `52` and `53`, respectively. Record the category, never the supplied credential. `AIC_SDK_LICENSE` must be available to the running service, not just your interactive shell. Check presence without printing its value: ```bash theme={null} python -c 'import os; print("AIC_SDK_LICENSE is set:", bool(os.environ.get("AIC_SDK_LICENSE")))' ``` Pass the complete SDK key to your server-side processor, including its signed contents. For JWT integrations, obtain a fresh token from your authenticated backend, check expiry and system time and follow the [refresh procedure](/models/get-started/authenticate-apps#refresh-before-the-token-expires). `LicenseFormatInvalidError` during construction means local credential validation failed before that session's online activation. During token refresh, the same error indicates a malformed replacement; the previous token remains installed. Check that the complete key was copied without truncation or added characters; do not edit its encoded contents. Test the key or token mode your application uses. `TokenUnsupportedError` during refresh means the original or replacement credential is not a JWT. A processor created with a plain SDK key cannot switch to JWT authentication in place. Use the [authentication guide](/models/get-started/authenticate-apps) for the supported key/token flow. **Verify:** Retry with a valid credential and check processing through the session lifecycle; construction can precede backend activation. ## Processing becomes disallowed **Applies to:** The native bindings listed above; WebAssembly 0.26.0 throws a JavaScript `Error` rather than a Python exception. **Diagnostic:** Python `ProcessingNotAllowedError`, C/C++ status `6` or Rust `AicError::ProcessingNotAllowed`. The native `usage.disallowed` metric measures disallowed audio duration. Check authorization, required usage reporting and whether your application called `terminate_session()`. Termination can finish after that call returns. * **Refresh a JWT** through its context when the session can continue; allow backend reactivation and observe errors during recovery. * **Replace a revoked or invalid SDK key** and create a new processor using the replacement. * **Create a new instance after termination.** A terminated session cannot be resumed by resetting stream state. * **Check outbound connectivity** for online operation. Disabling SDK error reporting does not remove authorization requirements. Catch the error and apply your fallback or stop policy. Python returns no enhanced array when processing raises. **Verify:** Process the controlled fixture, confirm valid output and check that disallowed usage stops increasing for the recovered session. See [deployment failure policy](/production/deployment#set-a-capacity-and-failure-policy). ## Audio configuration or frame size is rejected **Applies to:** The native bindings listed above. Use WebAssembly 0.26.0's own initialization and array signatures. **Diagnostic:** Python `NotInitializedError`, `AudioConfigUnsupportedError` or `AudioConfigMismatchError`; corresponding C/C++ statuses are `3`, `4` and `5`. Record sample rate, mono sample count, dtype and fixed/variable mode, without recording audio. The Python/Node.js quickstart rejects stereo input with `Export input.wav as mono, 16 kHz, 16-bit PCM WAV, then retry.` `NotInitializedError` means the processor needs initialization. `AudioConfigMismatchError` indicates that a call does not match the configured audio shape or block size. Use decoded mono `float32` samples at the configured rate and block size. Exclude file headers and count samples, not bytes: each `float32` sample occupies four bytes. Use `ProcessorConfig.optimal(model)` when the source matches the model's optimal rate, or explicitly configure the actual source rate. Handle the final partial block using the method shown in your [quickstart](/models/get-started/sdk-quickstart). See [audio format](/reference/concepts/audio-format) for variable blocks and channel handling. **Verify:** Resubmit a valid block, then rerun the quickstart. Check output shape, duration and playback speed. ## Output is silent, distorted or unexpectedly unchanged **Applies to:** The native bindings listed above and WebAssembly 0.26.0, using each binding's output contract. **Diagnostic:** Compare input/output sample counts and rate, finite-value checks and peak amplitude. Read the processor bypass and enhancement-level settings. Audio quality problems may produce no SDK error. Check input amplitude, finite values, channel conversion and sample rate, then inspect the model, enhancement strength and bypass setting. Account for startup delay and final buffered output when evaluating short recordings. Use [latency guidance](/reference/concepts/latency) to align input and output. For a framework integration, verify that the filter loaded and is active rather than assuming an audible call proves enhancement. **Verify:** Compare input and output from the same recording: check durations and listen at matched playback settings. ## Voice activity detection behaves incorrectly **Applies to:** The native bindings listed above and WebAssembly 0.26.0 dedicated VAD APIs. **Diagnostic:** Record the model ID, frame order, latest speech decision and parameter values on a controlled fixture. Python `ModelTypeUnsupportedError` or native status `105` indicates an incompatible model type. Incorrect timing or stale predictions can occur without an exception. Check that you use a supported dedicated VAD model and feed it the signal required by your integration. Reusing processor state across callers or processing frames out of order can invalidate the result. Follow the signal flow in the [VAD guide](/models/voice-activity-detection/vad) and your [LiveKit](/models/get-started/livekit-quickstart) or [Pipecat](/models/get-started/pipecat-quickstart) guide. Tune detection thresholds and speech/silence timing using representative recordings, including quiet speech and competing speakers. **Verify:** Compare detected speech intervals against labeled recordings and verify turn behavior in the full agent pipeline. ## Analysis fails or repeats old scores **Applies to:** The native bindings listed above; Node.js combines collection and analysis on `Analyzer`. WebAssembly 0.26.0 has its own analysis API. **Diagnostic:** Python `NotInitializedError` or C/C++ status `3` from buffering means the collector is uninitialized. Record buffered sample counts and analysis times. Repeated scores alone do not indicate a failure. Initialize collection before buffering. Analysis reads the latest retained window; repeated calls without new audio can inspect the same data. A reset makes analysis use zeros until collection applies the reset. Buffer fresh normalized mono samples under the configured block contract before expecting new observations. Use the [Python analysis reference](/reference/sdk/api/python/analysis) or your binding's analysis reference for collector ownership and window behavior. **Verify:** Buffer a known recording and check the analysis result and errors. Confirm new audio reached collection; scores need not change on every call. For complete files, follow [Tyto analysis](/models/audio-insight/batch-call-analysis). ## Latency or CPU use increases **Applies to:** The native bindings listed above. Measure WebAssembly 0.26.0 in its actual browser/runtime; native OTel metrics are unavailable there. **Diagnostic:** Record wall-clock processing percentiles, queue depth, stream count and the frame budget (`1000 * samples / sample_rate` ms). Native metrics include `experimental.processor.realtime_violations`, a count of calls that exceeded the frame budget, and `experimental.processor.process_duration_max`, a duration in ns. No SDK exception uniquely identifies overload. Separate SDK output delay from wall-clock processing time, buffering and downstream service latency. Check CPU throttling, growing queues, stream count and accidental model loading or network work on the audio thread. Run the [performance procedure](/reference/concepts/performance) under deployment resource limits. Reduce admitted concurrency or change model/configuration only after measuring the trade-off. **Verify:** Repeat the workload after one change. Confirm processing percentiles fit the frame budget at target concurrency and queue depth stays bounded. ## Metrics are missing **Applies to:** The native bindings listed above enhancement processors and VADs. WebAssembly 0.26.0 does not export SDK OTel metrics. Native analyzers and file analysis do not export optional OpenTelemetry metrics, even with `AIC_SDK_OTEL_ENABLE=1`. Use the [analysis result APIs](/reference/sdk/api/python/analysis) instead. SDK authorization and usage reporting still apply. **Diagnostic:** After processing and an export interval, look for service `aic-sdk`, meter `aic_usage` and `usage.processed` at the collector. Record enabled state, export interval and a sanitized endpoint. Exclude authentication headers and identifying attributes. Follow [OpenTelemetry troubleshooting](/models/get-started/opentelemetry#troubleshooting). Check that metrics are enabled before instance creation, a native build is in use, audio is actually processed and the collector accepts OTLP/HTTP Protobuf. Keep the session alive long enough to export. **Verify:** Restart the session with the corrected configuration and rerun the [local collector example](/models/get-started/opentelemetry#verify-with-a-local-collector). Find `service.name=aic-sdk`, `model.id` and increasing `usage.processed` after additional audio in the same session. ## Prepare a support report Include the failing stage, a minimal reproduction, package/core/model versions, OS/architecture, sanitized error, audio configuration and fixture result. Add session timing and a correlation ID where your data policy allows. Remove credentials, customer identifiers and private audio. Use the support route in the [developer platform](https://developers.ai-coustics.com/) or your support agreement. # MCP server and text export Source: https://docs.ai-coustics.com/reference/agents/mcp-server Connect a coding agent to canonical documentation and retrieve pages as Markdown. ## Overview The **ai-coustics documentation** is available through a Model Context Protocol (MCP) server. Connect an MCP-compatible tool to search the published site and retrieve pages while building your integration. ## Server URL ```text theme={null} https://docs.ai-coustics.com/mcp ``` ## What it exposes The hosted server supports documentation search, page retrieval and documentation feedback. Search returns matching pages; retrieval reads page content; feedback reports a documentation issue. These tools do not process audio or manage your SDK account. See [Mintlify's search MCP documentation](https://www.mintlify.com/docs/ai/model-context-protocol) for the tool contract. Do not include SDK keys, access tokens or private audio in searches or feedback. Use your client's approval controls before sending feedback. ## Read plain text Use the [documentation index](https://docs.ai-coustics.com/llms.txt) to discover canonical pages. It lists Markdown URLs, such as the [SDK quickstart as Markdown](https://docs.ai-coustics.com/models/get-started/sdk-quickstart.md). You can also use the page's copy menu. Mintlify generates these exports from the published documentation; a local edit does not update the hosted index. ## Find the canonical answer | Question | Source of truth | | - | - | | Which model fits my task? | [Model reference](/reference/sdk/models) and its model-specific guides | | How do I configure an SDK key? | [Authentication](/models/get-started/authenticate-apps) and the selected binding's quickstart | | What sample rate and frame size should I send? | [Audio format](/reference/concepts/audio-format) and the selected model's metadata | | What data leaves the process? | [SDK telemetry](/reference/concepts/sdk-telemetry) and [OpenTelemetry](/models/get-started/opentelemetry) | | How do I upgrade? | [Compatibility matrix](/reference/sdk/compatibility-matrix), [changelog](/changelog) and the migration guide for the installed version | | Can I process local files? | [SDK examples](/reference/sdk/examples) and [Tyto batch analysis](/models/audio-insight/batch-call-analysis) | Ask your tool to cite the page and state the package/model version it used. Historical migration examples apply to the versions in their titles. If search returns stale guidance, read the canonical page directly and check the changelog before changing code. ## Connect your tool > [tab] Claude > > 1. Go to [Settings → Connectors](https://claude.ai/settings/connectors) > 2. Click **Add custom connector** > 3. Name: `ai-coustics docs`, URL: `https://docs.ai-coustics.com/mcp` > 4. Click **Add** > 5. In a chat, click the attachments (+) button and select the connector > [tab] Claude Code > > ```bash theme={null} > claude mcp add --transport http ai-coustics-docs https://docs.ai-coustics.com/mcp > ``` > [tab] Codex > > Add the server to `~/.codex/config.toml`: > > ```toml theme={null} > [mcp_servers.ai-coustics-docs] > url = "https://docs.ai-coustics.com/mcp" > ``` > [tab] Cursor > > Open the command palette → **Open MCP settings** → **Add custom MCP**, then add to `mcp.json`: > > ```json theme={null} > { > "mcpServers": { > "ai-coustics-docs": { > "url": "https://docs.ai-coustics.com/mcp" > } > } > } > ``` > [tab] VS Code > > Create `.vscode/mcp.json` and add: > > ```json theme={null} > { > "servers": { > "ai-coustics-docs": { > "type": "http", > "url": "https://docs.ai-coustics.com/mcp" > } > } > } > ``` ## Check the connection Ask your tool to find the SDK quickstart and return its source URL, then compare the answer with that page. The MCP connection provides documentation access; SDK activation is separate. If the tool cannot connect, confirm the exact HTTPS endpoint above and that your client supports remote HTTP MCP servers. If retrieval is unavailable, use the Markdown index and page exports. If an answer cites an old version, state your installed version and request the corresponding migration guidance. # AirTen Source: https://docs.ai-coustics.com/reference/concepts/airten The CPU inference runtime used by the ai-coustics SDK. ## Overview AirTen executes ai-coustics models locally on the CPU. Applications use it through the SDK; they do not need to integrate a separate inference framework such as ONNX Runtime, PyTorch or TensorFlow. ## Characteristics * **CPU inference:** A GPU is not required for SDK audio processing. * **SDK-managed runtime:** Install the binding and its supported native library for your platform. See the [language bindings](/reference/sdk/language-bindings). * **Stateful processing:** Each independent audio stream needs its own processing state. See [streams and state](/reference/concepts/streams-and-state). Local inference describes where audio processing happens. Model downloads, authorization and telemetry have separate network requirements, described in [SDK telemetry](/reference/concepts/sdk-telemetry). ## Model support AirTen executes `.aicmodel` files. Match the model to the core SDK version using the [model catalog](/reference/sdk/models) and [compatibility matrix](/reference/sdk/compatibility-matrix). A language binding version and a core SDK version are different identifiers. ## Performance Processing time depends on the model, CPU, audio configuration and competing workload. A fixed algorithmic delay does not guarantee a fixed execution time or that every call finishes within its audio frame budget. Measure processing duration, memory use and concurrent-stream capacity on the hardware and resource limits you intend to deploy. Include resampling, application buffering and other pipeline stages in end-to-end measurements. Use the [latency guide](/reference/concepts/latency) to interpret SDK delay and the [performance guide](/reference/concepts/performance) to evaluate runtime cost. The [deployment guide](/production/deployment) connects these measurements to readiness and overload handling. # Audio format Source: https://docs.ai-coustics.com/reference/concepts/audio-format Prepare mono PCM audio for every audio entry point in the SDK. ## Audio requirements The SDK handles one **mono audio stream** per object. Each call accepts a contiguous block of decoded `float32` PCM samples. Provide: * One channel (mono) * Decoded PCM samples in `float32` format, normally scaled to `[-1.0, 1.0]`, with no NaN or infinite values * The same sample rate used to initialize the object * The configured block size, or a smaller block if variable block sizes are enabled > [!WARNING] > > Multi-channel buffers are not accepted. Mix multi-channel audio down to mono before processing, or use a separate processor for each channel that represents an independent stream. If you are upgrading from an SDK version with multi-channel processing methods, see [Migrate to mono processing](/reference/deprecated/multi-channel-to-mono). ### Audio entry points Three objects take audio, with the same mono requirements but different roles: | Object | Call | What it does | | - | - | - | | Processor | `process` | Enhances the audio samples. | | VAD | `process` | Updates the speech prediction without modifying the audio. | | Collector | `buffer` | Copies the audio into the analyzer's rolling window. | Make sure the VAD and collector receive the original input rather than the processor's enhanced output. See [Using VAD alongside enhancement](/models/voice-activity-detection/vad#using-vad-alongside-enhancement) and [Real-time analysis](/models/audio-insight/real-time-analysis#running-alongside-enhancement-and-vad). ## Block size Set the block size at initialization. It is the maximum number of mono samples per call. * For fixed-block mode (`variable_block_size = false`), every call must contain exactly the initialized `block_size`. * For variable-block mode (`variable_block_size = true`), every call may contain up to the initialized `block_size`. Larger calls are always rejected. * Use a positive block size at a supported sample rate (8,000–192,000 Hz for core SDK 0.26.0). The model's optimal block size is the one that avoids extra buffering, and therefore gives the lowest delay. Processor, VAD and collector each retain their own sample rate, `block_size` and `variable_block_size` configuration. Initialize objects sharing an input block for the same audio format, even if their model optima differ. Changing the sample rate or maximum block size requires reinitializing the object. Initialization allocates memory, so do not perform it on a real-time audio thread. To clear an object's history without changing its format, reset it instead. See [Streams and state](/reference/concepts/streams-and-state). ### Partial and empty input A final file chunk may be shorter than `block_size`. In fixed-block mode, pad it with zeros and track the original sample count, as the [Python quickstart](/reference/sdk/language-bindings/python) does. Variable-block mode accepts shorter calls but adds buffering. Avoid submitting empty frames in a live pipeline; they carry no new audio and are not an end-of-stream signal. For file enhancement, flush the delayed tail by processing sufficient silence, remove the leading SDK delay and trim the saved output to the original sample count. Query the initialized processor's delay instead of assuming a constant. Do not apply enhancement-tail handling to VAD as though it produced delayed audio. ### Host and model sample rates Configure the SDK with the sample rate of the samples you actually provide. The native model rate is not permission to relabel samples recorded at another rate. The core pipeline handles supported non-native host rates; conversion adds work and does not recover frequencies missing from the recording. See [non-native sample rates](/reference/sdk/models#non-native-sample-rates). `FileAnalyzer` accepts a complete decoded mono array and configures its collector internally. File decoding and channel selection remain your application's responsibility. ## Multi-channel input How you prepare multi-channel input depends on what its channels represent. ### One recording with multiple channels Mix the channels down to one mono stream in your application, then pass the mono samples to the SDK. Your application is also responsible for choosing the output channel layout, if a downstream system requires multi-channel audio. For a simple average mixdown with `N` channels: ```text theme={null} mono[frame] = (channel_0[frame] + ... + channel_N-1[frame]) / N ``` > [!NOTE] > > A simple average can reduce the level of signals that are out of phase. Use an appropriate downmix matrix or audio library when channel layout, gain or phase relationships matter. ### Independent streams stored as channels If each channel contains a distinct stream, e.g. two sides of a call, do not mix them together. Create and initialize one processor per channel, and pass each channel to its processor as a mono buffer. ## Codecs Decode MP3, AAC, Opus, G.711 or other encoded input to mono `float32` PCM in your application or media stack. The SDK does not decode files or network packets. Encode the enhanced output as needed for your application. ## Common pitfalls * Passing interleaved, sequential or planar multi-channel data directly to a process call * Treating the total number of samples in a multi-channel buffer as the mono block size * Processing distinct channel streams with one processor * Using a sample count that does not match the initialized block size (`AIC_ERROR_CODE_AUDIO_CONFIG_MISMATCH`) * Reinitializing a processor on a real-time audio thread * Feeding the VAD or the collector the processor's enhanced output instead of the original input * Initializing objects that share an input block for different sample rates or block sizes # Latency Source: https://docs.ai-coustics.com/reference/concepts/latency Separate SDK output delay from execution time, queueing and end-to-end application latency. Measure audio alignment and application response time separately. The SDK's delay query describes where enhanced samples belong on the input timeline; it is not a measurement of the full voice agent. ## Terminology | Term | Meaning | How to measure | | :- | :- | :- | | **Inference latency** | Time spent executing the model | Profile model execution on the deployed CPU. | | **Processing-call duration** | Time around the binding's processing call, including wrapper and scheduling overhead | Use a monotonic clock around each call or await. | | **Audio latency** | Output sample offset caused by SDK processing and buffering | Query the initialized processor's audio delay. | | **Application latency** | Capture, transport, queueing, SDK work and downstream response time | Instrument the full pipeline with consistent timestamps. | For example, computing audio could take 2 ms while the output is delayed by 30 ms. These are illustrative figures, not model measurements. ## Understanding audio delay Use `aic_processor_context_get_audio_delay` in C or your binding's equivalent, such as `processor.get_context().get_audio_delay()` in Python. Query after initialization so the result reflects the configured sample rate and buffering. The value is in samples at the configured host rate: $$ \text{delay\_ms} = \frac{\text{delay\_samples}}{\text{configured\_sample\_rate}} \times 1000 $$ It excludes capture hardware, network transport, application queues, downstream speech-to-text and playback buffering. Do not call it the total end-to-end delay of your application. ### Components of audio delay | Component | When it applies | Action | | :- | :- | :- | | **Algorithmic delay** | Model framing and lookahead | Compare model specifications for your task. | | **Adapter delay** | Host blocks differ from the model's processing window | Query the optimal block size for the actual host sample rate. | | **Buffering delay** | Variable-size calls require additional buffering | Use fixed optimal blocks when the host pipeline supports them. | Requery after changing the rate, block size or model. ## Factors affecting delay ### 1. Algorithmic delay (model choice) Model architectures differ. Use the [model catalog](/reference/sdk/models) and runtime query rather than assuming every model has a 30 ms delay. VAD prediction delay and Tyto's analysis window are separate quantities. ### 2. Adapter delay (block size) Call `aic_model_get_optimal_block_size` with the host sample rate, or the corresponding binding method. This gives the number of samples that matches the model's processing window at that rate. Non-optimal blocks require adaptation and can increase delay. Choose the host block size with the capture/playback pipeline in mind: avoiding SDK buffering is only one part of the full system. ### 3. Buffering delay (variable block sizes) With `variable_block_size = false`, each call must contain exactly the configured block size. With `true`, shorter calls are accepted at the cost of additional buffering. Larger calls are rejected in both modes. Collector and VAD configuration uses the same host-audio fields, but neither returns enhanced audio. Their buffering affects when analysis input or speech decisions become available. See [audio format](/reference/concepts/audio-format#block-size). ## VAD prediction delay A dedicated voice activity detector (VAD) exposes `aic_vad_context_get_prediction_delay`. It describes how far a published decision trails the VAD's input. VAD does not shift or modify the audio samples. When enhancement and VAD run on the same original input, align enhanced audio using processor delay and align speech decisions using VAD prediction delay. Framework speech/silence thresholds and end-of-turn logic can add further decision latency. Before core SDK 0.22.0, the processor drove VAD and a shared output-delay query covered both. See [dedicated VAD migration](/reference/deprecated/energy-vad-to-dedicated-vad#delay-queries). ## Align file comparisons For file enhancement, retain the original sample count, flush the processor's delayed tail with silence and remove the leading delay from the concatenated output. Then trim to the original duration. The [Python quickstart](/reference/sdk/language-bindings/python) demonstrates this procedure. Compare recordings at the same rate and on the same timeline. Do not mistake a shifted waveform for lost speech or compare differently trimmed transcripts. Use the [evaluation guide](/guides/evaluate-audio) for quality comparisons and [performance guide](/reference/concepts/performance) for timing measurements. # Performance Source: https://docs.ai-coustics.com/reference/concepts/performance Measure processing time, capacity and queue behavior on your deployment hardware. Measure the model and integration on the CPU, operating system and resource limits you will deploy. Throughput measured on a quiet development machine is not a production capacity guarantee. ## CPU requirements The SDK runs inference on the CPU. Available operating-system and architecture builds vary by binding; check your [language guide](/reference/sdk/language-bindings) and the [compatibility matrix](/reference/sdk/compatibility-matrix). Model complexity, host-rate conversion, block adaptation, wrapper copies, concurrent streams and other workloads all contribute to CPU cost. Test smaller models if the larger variant exceeds your capacity budget. Choose by task quality as well as runtime cost using the [evaluation guide](/guides/evaluate-audio). ## Real-time guarantees A serial processing path must keep pace with incoming audio. Define the frame budget and processing ratio as: $$ \text{frame\_duration} = \frac{\text{block\_size}}{\text{sample\_rate}},\qquad \text{ratio} = \frac{\text{processing\_call\_duration}}{\text{frame\_duration}} $$ A sustained ratio above 1 means that path cannot keep up. A ratio below 1 on average does not rule out deadline misses: inspect high percentiles, maximum duration and queue growth. Reserve capacity for capture, resampling, transport and downstream work. For example, 160 samples at 16 kHz represent 10 ms. This is an illustrative budget calculation, not a measured inference time. ## Performance (CPU usage) Changing the host sample rate can change conversion cost even when the model stays the same. Changing block size can change buffering and scheduling overhead. Keep both fixed when comparing model variants, then measure the actual production configuration separately. Distinguish [audio delay](/reference/concepts/latency) from time spent computing a block. Reducing one does not prove that the other improved. ## Parallel processing Python only (This behavior applies to the Python SDK bindings. Other bindings can use a different threading model.) In Python SDK 3.4.0, `Processor.process()` blocks its calling thread while native processing releases the Python interpreter lock. `ProcessorAsync.process_async()` schedules work on the native blocking pool so the event loop can continue. Use one instance per stream and await frames sequentially within each stream. More concurrent instances improve capacity only while the machine has resources to run them. Reuse loaded model weights where supported; each stream still owns processing state. ## Async execution footguns Python only (This behavior applies to the Python SDK bindings. Other bindings can use a different threading model.) * **Submitting one stream concurrently:** A mutex prevents simultaneous mutation but does not make submission order an audio-order guarantee. Await one frame before sending the next. * **Unbounded work queues:** Pending calls retain audio buffers and add waiting time. Bound admission and measure queue depth. * **Reinitializing during processing:** Stop input and settle in-flight work before changing configuration or resetting state. * **Blocking the event loop with control calls:** Create contexts during setup and keep initialization, synchronous teardown and other blocking work off the loop. * **Treating cancellation as rollback:** A cancelled await does not prove native work stopped. Follow the [lifecycle guidance](/reference/concepts/streams-and-state#ordering-cancellation-and-teardown). ## Run a bounded comparison Use Python 3.12 or newer, an SDK key and a finite, non-silent mono WAV recording. The script below targets Python SDK 3.4.0/core 0.26.0 and compares one stream with two independent streams by running it twice. It measures call duration, scheduling lateness and process memory/CPU; it does not measure enhancement quality. ```bash theme={null} python -m venv .venv source .venv/bin/activate python -m pip install 'aic-sdk==3.4.0' 'numpy==2.5.3' 'soundfile==0.13.1' 'psutil==7.2.2' ``` Set `AIC_SDK_LICENSE` through your normal secret mechanism. Save this as `measure_runtime.py`: ```python theme={null} import argparse import asyncio import hashlib import importlib.metadata import json import os import platform import time from pathlib import Path import aic_sdk as aic import numpy as np import psutil import soundfile as sf MODEL = "quail-vf-2.3-l-16khz" async def measure(model, audio, config, seconds): processor = aic.ProcessorAsync(model, os.environ["AIC_SDK_LICENSE"], config) size = config.block_size period = size / config.sample_rate frames = len(audio) // size durations, late = [], [] try: for i in range(10): await processor.process_async(audio[(i % frames) * size:((i % frames) + 1) * size]) start = time.monotonic() index = 0 while time.monotonic() - start < seconds: due = start + index * period await asyncio.sleep(max(0, due - time.monotonic())) before = time.monotonic() frame = index % frames output = await processor.process_async(audio[frame * size:(frame + 1) * size]) after = time.monotonic() if len(output) != size or not np.isfinite(output).all(): raise RuntimeError("Invalid processor output") durations.append(after - before) late.append(max(0, after - (due + period))) index += 1 return { "frames": index, "call_ms_p50_p95_p99_max": np.percentile(durations, [50, 95, 99, 100]).tolist(), "max_scheduling_lateness_ms": max(late) * 1000, "deadline_misses": sum(value > 0 for value in late), "max_call_frame_ratio": max(durations) / period, } finally: await processor.terminate_session_async() async def main(args): if not os.environ.get("AIC_SDK_LICENSE"): raise ValueError("Set AIC_SDK_LICENSE before running") audio, rate = sf.read(args.input, dtype="float32") if audio.ndim != 1 or not np.isfinite(audio).all() or not np.any(audio): raise ValueError("Use finite, non-silent mono audio") model = aic.Model.from_file(aic.Model.download(MODEL, "./models")) config = aic.ProcessorConfig(rate, model.get_optimal_block_size(rate)) if len(audio) < config.block_size: raise ValueError("Input must contain at least one complete frame") process = psutil.Process() process.cpu_percent(None) rss_before = process.memory_info().rss tasks = [measure(model, audio, config, args.seconds) for _ in range(args.streams)] results = await asyncio.gather(*tasks, return_exceptions=True) failures = [type(result).__name__ for result in results if isinstance(result, BaseException)] if failures: raise RuntimeError(f"Run failed: {failures}") for result in results: result["call_ms_p50_p95_p99_max"] = [value * 1000 for value in result["call_ms_p50_p95_p99_max"]] print(json.dumps({ "binding": importlib.metadata.version("aic-sdk"), "core": aic.get_sdk_version(), "model": MODEL, "platform": platform.platform(), "machine": platform.machine(), "input_sha256": hashlib.sha256(Path(args.input).read_bytes()).hexdigest(), "sample_rate": rate, "block_size": config.block_size, "seconds_per_stream": args.seconds, "streams": args.streams, "process_cpu_percent": process.cpu_percent(None), "rss_before_bytes": rss_before, "rss_after_bytes": process.memory_info().rss, "results": results, }, indent=2)) if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("input") parser.add_argument("--streams", type=int, choices=[1, 2], default=1) parser.add_argument("--seconds", type=int, choices=range(1, 121), default=10) asyncio.run(main(parser.parse_args())) ``` Run with a controlled recording, then compare the JSON results: ```bash theme={null} python measure_runtime.py input.wav --streams 1 --seconds 10 > one-stream.json python measure_runtime.py input.wav --streams 2 --seconds 10 > two-streams.json ``` The file is repeated to fill the requested duration; the final incomplete input block is excluded. Warmup and model download are outside per-call timing. CPU percentage covers the process and can exceed 100% across cores; before/after resident memory is not peak memory. Record the CPU model and deployment CPU/memory limits alongside the output. For sustained-load validation, test your pipeline under deployment resource limits at the intended concurrency. This script holds at most one call per stream; measure queueing, drops, bypass and processing errors in your application. Stop runs that fall behind; their nominal stream count is not supported capacity. ## Record and compare results Retain the fixture hash, exact package/core/model versions, settings, hardware, resource limits and repetitions with each result. Report p50/p95/p99 and maximum call duration, deadline misses, queue depth, peak memory and output/error checks. Compare the same fixtures before and after an upgrade. Use the [SDK benchmark example](/reference/sdk/examples) for further experiments and [deployment verification](/production/deployment#verify-the-deployment) for the release checklist. Every published number should identify what was measured and what the measurement excludes. # SDK telemetry Source: https://docs.ai-coustics.com/reference/concepts/sdk-telemetry Separate local inference, authorization, usage reporting, error reporting and optional metrics export. ## Overview The ai-coustics SDK processes audio locally. In core SDK 0.26.0, the authorization, usage and SDK error-reporting payloads described here do not include audio samples, recordings, transcripts or model input/output features. Each network channel is controlled separately: | Activity | Destination and data | Control | | :- | :- | :- | | Model provisioning | Model download service; model identifier and download request | Provision compatible model files before deployment, then load them from a local path. | | Authorization and metering | ai-coustics backend; credentials, session identity, SDK/model/system metadata and usage | Governed by the credential and entitlement. Self-service keys use online authorization and usage reporting. | | SDK error reporting | ai-coustics error tracking; error category and SDK/model/system/account metadata | Set `DO_NOT_TRACK=1` before loading the SDK to disable this channel. | | OpenTelemetry metrics | Your configured collector; processing metrics and session attributes | Disabled by default; enable through `AIC_SDK_OTEL_ENABLE=1` or the binding's per-instance configuration. | This description covers SDK traffic. Your application, speech-to-text provider and agent framework may send audio or other data independently. ## What we collect Product and usage records include: * Core SDK version and wrapper type, such as Python or Node.js * Model identifier, such as `quail-vf-2.2-l-16khz` * Operating system and CPU architecture * Processing-session identity and processed or disallowed audio duration * Whether the session uses a dedicated voice activity detection (VAD) model ## Authentication and metering A session associates processing activity with the authorized account. Treat SDK keys, decoded API keys and bearer tokens as secrets. Network failure behavior depends on the credential and session requirements. Core SDK 0.26.0 requires activation for JWT credentials; failed activation can disable processing. Explicit authorization rejection can also disable processing. Where usage reporting is required, sustained reporting failure can disable processing too. Do not use a temporary grace period or tolerated failure as an offline deployment contract. For disconnected operation, contact ai-coustics about an appropriate offline license and verify its validity period and deployment conditions. Preprovision model files as well. An offline entitlement does not automatically prevent your application or an enabled customer metrics exporter from making network requests. See [authentication](/models/get-started/authenticate-apps) for token handling and [deployment](/production/deployment) for restricted-network validation. ## Error reporting SDK error reporting was added in [core SDK 0.24.0](/changelog). It covers failed session activations, failed usage reports and rejected bearer-token updates. Reports contain the error class and message, core SDK version, wrapper type, model identifier, operating system and CPU architecture. Account identity is included when available and trusted. The reporting path excludes credential material and audio. To disable SDK error reporting: ```bash theme={null} export DO_NOT_TRACK=1 ``` Set this before your process loads the SDK. The setting is read once per process. Licenses with an offline entitlement and WebAssembly builds do not use this error-reporting channel. > [!NOTE] > > `DO_NOT_TRACK=1` does not turn off authorization or usage reporting, grant an offline entitlement or disable your OpenTelemetry exporter. ## What we do not collect The SDK reporting channels to ai-coustics described above do not send: * Audio samples, recordings or buffered audio * Transcripts or speech content * Model input/output feature data Customer-controlled [OpenTelemetry export](/models/get-started/opentelemetry) includes derived processing and audio metrics. Hashes and session IDs remain correlatable identifiers: apply access controls, retention limits and appropriate redaction in your own observability system. ## Network review and contractual sources For a deployment with restricted outbound access, validate model provisioning, activation, usage reporting and optional exporters independently. Obtain the current destination requirements for your SDK release and entitlement from ai-coustics before finalizing firewall rules. This page is not an exhaustive hostname allowlist. The [Privacy Policy](https://ai-coustics.com/legal/privacy-policy) and your applicable license agreement govern data and privacy terms. This technical reference does not establish retention periods, certifications, service levels or contractual offline rights. # Streams and state Source: https://docs.ai-coustics.com/reference/concepts/streams-and-state How SDK objects hold per-stream state, when to reset it and which calls are real-time safe. SDK audio objects retain history: enhancement state, voice activity detection (VAD) history or an analysis window. Manage each object's state across processing, resets and teardown. ## One object per stream Create one processor, VAD or collector/analyzer pair per stream and pass its blocks in order. Objects can share a [model handle](/reference/sdk/models#loading-and-reusing-models), but each owns its processing state. Interleaving streams mixes their history and produces unstable output. Give each side of a call or other independent channel its own object. See [audio format](/reference/concepts/audio-format#independent-streams-stored-as-channels). ## Resetting state Reset clears history and internal buffers while preserving audio configuration. The object stays initialized. | Object | Call | What it clears | | - | - | - | | Processor | `processor.get_context().reset()` `aic_processor_context_reset` | The processor's internal buffers and enhancement state. It does not touch a VAD. | | VAD | `vad.get_context().reset()` `aic_vad_context_reset` | The VAD's state, plus the published speech decision and raw probability, which drop to `false` and `0.0` immediately rather than returning stale values. | | Analyzer pair | `analyzer.reset()` `aic_analyzer_reset` | The analyzer's state **and** the audio buffered by its paired collector. The collector stays initialized. | Reset at a discontinuity: * The stream was interrupted, or a caller reconnected * You are seeking in a file or a recording * You are reusing the object for a new call or a new stream * A long gap in the audio makes the previous content irrelevant Skipping reset carries unrelated history into the next stream and can cause enhancement artifacts or incorrect VAD and analysis results. > [!NOTE] > > Resetting is per object. If you run enhancement, VAD and analysis side by side on one stream, reset all of them when that stream is interrupted. Reset is not a replacement for reinitialization. Changing the sample rate or the maximum block size requires initializing the object again, which allocates memory and must not happen on a real-time audio thread. See [Block size](/reference/concepts/audio-format#block-size). ## Real-time safety The native core audio path is designed for a real-time callback. The table describes core operations; language bindings and application code add their own allocation, locking and scheduling behavior. Python `Processor.process()` copies its input and creates an output array, so the native guarantee does not make the Python call allocation-free. Keep setup, analysis and network operations off a real-time callback. | Call | Real-time safe | | - | - | | `process` on a processor or VAD, `buffer` on a collector | Yes | | Reset, on any object | Yes | | Reading or writing parameters through a context | Yes | | Reading the audio delay or the prediction delay | Yes | | Creating an object, or `initialize` | No, it allocates memory | | `analyze_buffered` on an analyzer | No, it runs an expensive model | | `update_bearer_token` | No, it locks a mutex and allocates | | `terminate_session` | No, termination can block during cleanup | > [!WARNING] > > Analysis work can exceed a real-time frame budget. The collector and analyzer are separate so you can schedule analysis away from the audio callback. See [Real-time analysis](/models/audio-insight/real-time-analysis#two-objects-two-threads). Each object is also single-threaded with respect to itself: do not call `process` on one processor from two threads at once. Parallelize across streams with one object per stream instead. See [Performance](/reference/concepts/performance#parallel-processing). ## Contexts Use a context handle to control and query an object from a different thread than the audio thread: ```python theme={null} proc_ctx = processor.get_context() vad_ctx = vad.get_context() proc_ctx.set_parameter(aic.ProcessorParameter.EnhancementLevel, 0.8) print(vad_ctx.is_speech_detected()) ``` Create a context once during setup and keep it for as long as you need it. In C, contexts are independent handles: `aic_processor_context_destroy` does not destroy the processor, and a context may be destroyed before or after the object it controls, in any order. ## Ordering, cancellation and teardown For asynchronous bindings, await each stream's processing call before submitting its next frame. A per-instance lock prevents concurrent mutation; it does not promise that concurrently submitted frames execute in audio order. Use separate instances to parallelize independent streams. Keep queues bounded. Cancelling a Python await does not establish that already-running native work has stopped or that its state changes were rolled back. Stop admitting frames, resolve in-flight work and then reset, reinitialize or dispose of the stream. Prefer a new instance when the processing boundary is uncertain. Reset clears audio history; it does not create a new authorization session or reverse `terminate_session()`. Stop submitting audio before requesting termination. Processing may be disabled after the termination call returns, so its return is not permission to submit another frame. Termination and object destruction may block while session work drains, so perform them on a control thread. Stop refresh and analysis tasks during shutdown and release contexts according to your binding's ownership rules. For reconnects, choose one owner to coordinate stopping input, settling work, clearing each object's state and restarting the warmup/sample counters. Avoid resetting while another application task is still submitting frames from the previous call. ## Verify stream isolation Using the same fixed fixtures and configuration, compare two independent instances run separately with the same two instances scheduled concurrently. Each output should match its own reference within your chosen numerical tolerance; one stream's reset must not alter the other. Include repeated reset, a reconnect, a final partial block and cancellation in your integration checks. Check errors and teardown completion as well as sample counts. See [deployment verification](/production/deployment#verify-the-deployment). # Migrate to the Dedicated VAD Source: https://docs.ai-coustics.com/reference/deprecated/energy-vad-to-dedicated-vad Move voice activity detection off the processor and onto a dedicated VAD object backed by a VAD model. > [!NOTE] > > Migration introduced in core SDK 0.22.0 and Python 3.0.0. The before/after examples target that API transition. For a current upgrade, start with the [upgrade guide](/reference/sdk/upgrading) and [compatibility matrix](/reference/sdk/compatibility-matrix). > [!WARNING] > > Core SDK 0.25.0 reintroduced energy-based VAD under a new API, so this page no longer describes a removed feature. It documents the 0.22.0 transition, when energy VAD was unavailable and a dedicated VAD model was the only option. > > On 0.25.0 and later you can detect speech from an enhancement processor again, through `EnergyVadContext`: [Python](/reference/sdk/api/python/vad#energyvadcontext), [Node.js](/reference/sdk/api/node/vad#node-energyvadcontext), [C](/reference/sdk/api/c/vad#aic_energy_vad_context_create), [C++](/reference/sdk/api/cpp/vad#aic-EnergyVadContext), [Rust](/reference/sdk/api/rust/vad#rust-aic_sdk-EnergyVadContext) and [WebAssembly](/reference/sdk/api/wasm/vad#wasm-energyvadcontext). It is not the pre-0.22.0 detector restored unchanged: it detects quiet and distant speech far more reliably and triggers more often on background noise and voices. Sensitivity is again an energy threshold from `1.0` to `15.0`, defaulting to `6.0`; around `4.0` gives a false-activation rate close to the pre-0.22.0 behavior. > > A dedicated VAD model remains the more accurate option and is still what the rest of this page migrates you to. **Before:** the VAD was a side effect of enhancement. It inferred speech from how much energy was left after the enhancement model suppressed non-speech, so its accuracy depended on which model you ran. **Now:** the VAD is its own object, running a model trained for the task. You create it from a dedicated VAD model and drive it yourself. > [!WARNING] > > This is not a drop-in replacement. Sensitivity changed from an energy threshold to a probability, so your old value cannot be carried across. See [Retune sensitivity](#retune-sensitivity). ## What changed > [tab] Python > > | | Before | Now | > | - | - | - | > | Model | Any enhancement model | A dedicated VAD model only | > | Create | `processor.get_vad_context()` | `aic.Vad(vad_model, license_key, config)`, then `vad.get_context()` | > | Advance | Implicit, via `processor.process()` | `vad.process(audio)` | > | Sensitivity | `1.0` to `15.0`, an energy threshold | `0.0` to `1.0`, a probability threshold | > | Reset | `processor_context.reset()` reset both | `vad_context.reset()` resets only the VAD | > | Delay | `processor_context.get_output_delay()` | `vad_context.get_prediction_delay()` | > | Async | Not available separately | `aic.VadAsync`, `await vad.process_async(audio)` | > [tab] C > > | | Before | Now | > | - | - | - | > | Model | Any enhancement model | A dedicated VAD model only | > | Create | `aic_vad_context_create(&ctx, processor)` | `aic_vad_create` → `aic_vad_initialize` → `aic_vad_context_create(&ctx, vad)` | > | Advance | Implicit, via `aic_processor_process_*` | `aic_vad_process(vad, audio, block_size)` | > | Sensitivity | `1.0` to `15.0`, an energy threshold | `0.0` to `1.0`, a probability threshold | > | Reset | `aic_processor_context_reset` reset both | `aic_vad_context_reset(ctx)` | > | Delay | `aic_processor_context_get_output_delay` | `aic_vad_context_get_prediction_delay` | > | Destroy | `aic_vad_context_destroy` | `aic_vad_context_destroy`, then `aic_vad_destroy` | Use `vad-ms-2.1-xxs-16khz` for general speech detection, or `vad-vf-2.0-s-16khz` to detect the primary speaker only. ## Migrate the setup > [tab] Python > > ```python Before theme={null} > # One model, one processor: enhancement and VAD were coupled. > processor = aic.Processor(model, license_key, config) > > vad_context = processor.get_vad_context() > vad_context.set_parameter(aic.VadParameter.Sensitivity, 5.0) # energy threshold > > enhanced = processor.process(audio) # also advanced the VAD > > print(vad_context.is_speech_detected()) > ``` > > ```python Now theme={null} > # Two models, two objects. > vad_model = aic.Model.from_file( > aic.Model.download("vad-ms-2.1-xxs-16khz", "./models") > ) > # Raises ModelTypeUnsupportedError if the model is not a VAD model. > vad = aic.Vad(vad_model, license_key, aic.ProcessorConfig.optimal(vad_model)) > > vad_context = vad.get_context() > vad_context.set_parameter(aic.VadParameter.Sensitivity, 0.8) # probability > > vad.process(audio) # returns None, does not modify the audio > > print(vad_context.is_speech_detected()) > print(vad_context.raw_vad_probability()) > ``` > [tab] C > > ```c Before theme={null} > aic_processor_create(&processor, enhancement_model, license, NULL); > aic_processor_initialize(processor, sample_rate, 1, num_frames, false); > > aic_vad_context_create(&vad_context, processor); > aic_vad_context_set_parameter( > vad_context, AIC_VAD_PARAMETER_SENSITIVITY, 5.0f); // energy threshold > > aic_processor_process_interleaved(processor, audio, 1, num_frames); > > bool is_speech_detected = false; > aic_vad_context_is_speech_detected(vad_context, &is_speech_detected); > ``` > > ```c Now theme={null} > aic_model_create_from_file(&vad_model, "path/to/vad-model.aicmodel"); > > // Returns AIC_ERROR_CODE_MODEL_TYPE_UNSUPPORTED if the model is not a VAD model. > aic_vad_create(&vad, vad_model, license, NULL); > > aic_model_get_optimal_sample_rate(vad_model, &sample_rate); > aic_model_get_optimal_block_size(vad_model, sample_rate, &block_size); > aic_vad_initialize(vad, sample_rate, block_size, false); > > aic_vad_context_create(&vad_context, vad); > aic_vad_context_set_parameter( > vad_context, AIC_VAD_PARAMETER_SENSITIVITY, 0.8f); // probability > > aic_vad_process(vad, audio, block_size); > > bool is_speech_detected = false; > aic_vad_context_is_speech_detected(vad_context, &is_speech_detected); > > aic_vad_context_destroy(vad_context); > aic_vad_destroy(vad); > aic_model_destroy(vad_model); > ``` > > See `examples/vad.c` in the SDK distribution for a complete, error-checked version. ## Feed the VAD your original audio If you run enhancement and VAD together, give both the same original input block. Do not chain them. > [tab] Python > > ```python theme={null} > vad.process(audio) # reads the block, does not modify it > enhanced = processor.process(audio) > ``` > [tab] C > > ```c theme={null} > aic_vad_process(vad, input, block_size); // const float *, leaves the buffer untouched > aic_processor_process(processor, input, block_size); // enhances the block in place > ``` Enhancement changes the signal on purpose, so running the VAD on its output means detecting speech in audio the VAD model was not trained on. It also stacks the processor's delay on top of the VAD's own. > [!NOTE] > > The two models can have different optimal block sizes and sample rates. If yours disagree, initialize both to the configuration your stream already uses, or keep separate block sizes and feed each object from your own buffer. ## Retune sensitivity This is the step most likely to change your application's behavior. | | Before | Now | | - | - | - | | Meaning | An energy threshold, $10^{-\text{sensitivity}}$ | A probability threshold | | Range | `1.0` to `15.0` | `0.0` to `1.0` | | Direction | Higher detected speech more aggressively | Higher requires more confidence, so it fires less | There is no conversion formula. The old value described leftover energy after enhancement, the new one describes model confidence, and the direction is inverted. > [!WARNING] > > An old value like `5.0` is out of range and raises a parameter error. One that happens to be in range, like `1.0`, is valid but means "only at maximum confidence", which looks like a VAD that never fires. Start from the model default and adjust against representative production audio. `raw_vad_probability()` gives the model's probability before thresholding, which is the practical way to pick a threshold from recordings. `SpeechHoldDuration` and `MinimumSpeechDuration` keep their previous meaning and units. ## Delay queries The processor delays audio, the VAD does not, so there is no single output delay any more. The VAD's prediction delay tells you how far behind its input the published decision is, so you can align speech decisions with the audio timeline. Fed from the same block, the two are independent. | Binding | Audio delay | Prediction delay | | - | - | - | | C | `aic_processor_context_get_audio_delay` | `aic_vad_context_get_prediction_delay` | | Python | `processor_context.get_audio_delay()` | `vad_context.get_prediction_delay()` | | Rust | `processor_context.audio_delay()` | `vad_context.prediction_delay()` | | Node.js | `processorContext.getOutputDelay()` | `vadContext.getOutputDelay()` | > [!NOTE] > > Node.js has not adopted the rename yet. Its `VadContext.getOutputDelay()` returns the prediction delay, so only the name differs. If you previously compensated for VAD timing using the processor's delay, read the VAD's own delay instead. ## Also worth knowing * **Model types are enforced.** A processor takes enhancement and bypass models, a VAD takes VAD models, an analyzer takes analysis models. A mismatch fails at creation with `AIC_ERROR_CODE_MODEL_TYPE_UNSUPPORTED`, or `ModelTypeUnsupportedError` in Python, instead of silently doing something else. * **Reset clears published values immediately.** After a reset, the speech decision is false and the raw probability is `0.0`, so queries no longer return stale values from the previous stream. * **Close sessions explicitly** with `aic_vad_terminate_session` or `terminate_session()` in Python when deallocation may be delayed. Stop submitting audio first and treat the object as closed afterward. Processing can become disallowed asynchronously, and native termination may block while the final session drains. ## Related migrations > [card] [Multi-channel to mono](/reference/deprecated/multi-channel-to-mono) > > The same release removed multi-channel processing and buffering. > [card] [Python SDK 2.5 to 3.0](/reference/deprecated/python-2-5-to-3-0) > > Every Python-specific rename in this release. # Migrate to Mono Processing Source: https://docs.ai-coustics.com/reference/deprecated/multi-channel-to-mono Update SDK integrations from the multi-channel buffer APIs to the mono processing and buffering API. > [!NOTE] > > Migration introduced in core SDK 0.22.0 and Python 3.0.0. The before/after examples target that API transition. For a current upgrade, start with the [upgrade guide](/reference/sdk/upgrading) and [compatibility matrix](/reference/sdk/compatibility-matrix). **Before:** you passed a multi-channel buffer. The SDK mixed it down to mono internally, enhanced it and mixed the result back into your channels. That mixback was hard to predict per channel, so the output level and spatial presentation could surprise you. **Now:** every audio API takes one mono buffer. Your application controls downmixing and output channel layout. > [!WARNING] > > The same release also moves voice activity detection into a dedicated `Vad` object and removes energy-based VAD. If you read a VAD signal from a processor, see [Migrate to the dedicated VAD](/reference/deprecated/energy-vad-to-dedicated-vad). ## What changed > [tab] Python > > | Before | Now | > | - | - | > | `ProcessorConfig(sample_rate, num_channels, num_frames, allow_variable_frames)` | `ProcessorConfig(sample_rate, block_size, variable_block_size)` | > | `ProcessorConfig.optimal(model, num_channels=2)` | `ProcessorConfig.optimal(model)` | > | `model.get_optimal_num_frames(sample_rate)` | `model.get_optimal_block_size(sample_rate)` | > | `processor.process(audio)` with a 2D `(channels, frames)` array | `processor.process(audio)` with a 1D mono array | > | `collector.buffer(audio)` with a 2D array | `collector.buffer(audio)` with a 1D mono array | > [tab] C > > | Before | Now | > | - | - | > | `aic_processor_initialize(processor, sample_rate, num_channels, num_frames, allow_variable_frames)` | `aic_processor_initialize(processor, sample_rate, block_size, variable_block_size)` | > | `aic_model_get_optimal_num_frames` | `aic_model_get_optimal_block_size` | > | `aic_processor_process_planar` / `_interleaved` / `_sequential` | `aic_processor_process(processor, audio_ptr, audio_len)` | > | `aic_collector_buffer_planar` / `_interleaved` / `_sequential` | `aic_collector_buffer(collector, audio_ptr, audio_len)` | Your old `num_frames` value is your new `block_size`, because it already meant samples per channel. Error codes were renamed too, see the [changelog](/changelog). > [!WARNING] > > Do not pass the total length of a multi-channel buffer. A stereo block of 480 frames holds 960 samples, but the mono block size is still 480. A mismatch returns `AIC_ERROR_CODE_AUDIO_CONFIG_MISMATCH`. ## If you still want multi-channel output Two steps: downmix to mono, then distribute the enhanced mono back across your channels. ### 1. Downmix to mono > [tab] Python > > ```python theme={null} > # audio is (frames, channels), as returned by soundfile.read > mono = np.ascontiguousarray(audio.mean(axis=1), dtype=np.float32) > > enhanced = processor.process(mono) > ``` > > Pass a contiguous `float32` array to `process()`. NumPy preserves `float32` when averaging `float32` input, but integer input defaults to `float64`; the explicit cast handles either case. > [tab] C > > ```c theme={null} > // interleaved stereo in, mono out > for (size_t i = 0; i < block_size; ++i) { > mono[i] = 0.5f * (interleaved[i * 2] + interleaved[i * 2 + 1]); > } > > aic_processor_process(processor, mono, block_size); > ``` > > Allocate `mono` once outside the processing loop, because allocation is not real-time safe. ### 2. Copy the enhanced mono into each channel > [tab] Python > > ```python theme={null} > # Back to (frames, channels), same enhanced signal in every channel > out = np.repeat(enhanced[:, None], num_channels, axis=1) > ``` > [tab] C > > ```c theme={null} > // aic_processor_process enhanced mono in place > for (size_t i = 0; i < block_size; ++i) { > for (uint16_t ch = 0; ch < num_channels; ++ch) { > interleaved[i * num_channels + ch] = mono[i]; > } > } > ``` > [!WARNING] > > This does not reproduce the old mixback. Every channel now carries the identical enhanced signal, so any stereo image in the input is gone and the perceived level may differ. Check loudness and enhancement level against representative audio. See [Audio format](/reference/concepts/audio-format) for downmix caveats when channel gain or phase matters. ## If your channels are independent streams Do not downmix. Two sides of a call, or two speakers on separate mics, are separate streams. Create one processor per stream, each with its own state: ```python theme={null} left_processor = aic.Processor(model, license_key, config) right_processor = aic.Processor(model, license_key, config) enhanced_left = left_processor.process(left) enhanced_right = right_processor.process(right) ``` The processors can share one model. The old 16-channel limit is gone, since concurrency is now bounded only by how many instances you create. The same applies to the analyzer: one collector and analyzer pair per stream. ## Related migrations > [card] [Migrate to the dedicated VAD](/reference/deprecated/energy-vad-to-dedicated-vad) > > Move voice activity detection onto a dedicated VAD model. > [card] [Python SDK 2.5 to 3.0](/reference/deprecated/python-2-5-to-3-0) > > Every Python-specific rename in this release. # Migrate Python SDK 2.5 to 3.0 Source: https://docs.ai-coustics.com/reference/deprecated/python-2-5-to-3-0 Upgrade to ai-coustics Python SDK 3.0 with mono-only processing, a dedicated Vad class and renamed configuration fields and errors. > [!NOTE] > > Historical migration: Python 2.5 to 3.0 (core 0.21 to 0.22). For a current upgrade, start with the [upgrade guide](/reference/sdk/upgrading) and [compatibility matrix](/reference/sdk/compatibility-matrix). Python SDK 3.0 tracks core SDK 0.22.0. It contains two breaking changes that affect every integration, plus a set of renames. > [card] [Audio is mono only](/reference/deprecated/multi-channel-to-mono) > > `process()` and `buffer()` take a 1D array. The internal mixdown is gone. > [card] [VAD is its own object](/reference/deprecated/energy-vad-to-dedicated-vad) > > `Vad` runs a dedicated VAD model. Energy-based VAD is removed. This page is the Python-specific reference. The two guides above explain the reasoning and the audio-handling changes in more detail. > [!WARNING] > > No key regeneration is needed for this upgrade. Re-download compatible model files: core 0.21 uses file format 5, while core 0.22 uses format 6. Keep the previous files separately if you need to roll back. ## Quick migration checklist **1. Downmix to mono** Pass a 1D `float32` array to `process()`, `process_async()` and `buffer()`. A 2D array now raises `AudioConfigMismatchError`. **2. Rename the config fields** `num_frames` is `block_size`, `allow_variable_frames` is `variable_block_size` and `num_channels` is gone. **3. Rename get\_processor\_context** It is now `get_context()` on both `Processor` and `ProcessorAsync`. **4. Replace the processor-owned VAD** Create a `Vad` or `VadAsync` from a dedicated VAD model. `get_vad_context()` no longer exists. **5. Update the three renamed error classes** `NotInitializedError`, `ProcessingNotAllowedError` and `FilePathInvalidError`. **6. Keep model types in the right objects** `Processor` takes enhancement and bypass models only. `Vad` takes VAD models only. ## Renames ### `ProcessorConfig` `ProcessorConfig` is shared by `Processor`, `Vad` and `Collector`. | 2.5 | 3.0 | | - | - | | `ProcessorConfig(sample_rate, num_channels, num_frames, allow_variable_frames)` | `ProcessorConfig(sample_rate, block_size, variable_block_size)` | | `config.num_frames` | `config.block_size` | | `config.allow_variable_frames` | `config.variable_block_size` | | `config.num_channels` | Removed | | `ProcessorConfig.optimal(model, num_channels=2)` | `ProcessorConfig.optimal(model)` | ```python 2.5 theme={null} config = aic.ProcessorConfig( sample_rate=48000, num_channels=2, num_frames=480, allow_variable_frames=False, ) ``` ```python 3.0 theme={null} config = aic.ProcessorConfig( sample_rate=48000, block_size=480, variable_block_size=False, ) ``` ### `Model` | 2.5 | 3.0 | | - | - | | `model.get_optimal_num_frames(sample_rate)` | `model.get_optimal_block_size(sample_rate)` | ### `Processor` and `ProcessorAsync` | 2.5 | 3.0 | | - | - | | `processor.get_processor_context()` | `processor.get_context()` | | `processor.get_vad_context()` | Removed, create a `Vad` instead | | `processor.process(audio)` with a 2D array | `processor.process(audio)` with a 1D mono array | | (not available) | `processor.terminate_session()` | ### `ProcessorContext` | 2.5 | 3.0 | | - | - | | `proc_ctx.get_output_delay()` | `proc_ctx.get_audio_delay()` | The rename says what the value delays. `get_audio_delay()` reports how far the enhanced samples lag their input. It no longer covers VAD timing, because the VAD has its own `get_prediction_delay()`. `ProcessorContext.reset()` now affects enhancement state only. Reset a VAD through its own `VadContext`. ### Errors | 2.5 | 3.0 | | - | - | | `ModelNotInitializedError` | `NotInitializedError` | | `EnhancementNotAllowedError` | `ProcessingNotAllowedError` | | `ModelFilePathInvalidError` | `FilePathInvalidError` | ## Migrate enhancement ```python 2.5 theme={null} import aic_sdk as aic import numpy as np model = aic.Model.from_file(model_path) config = aic.ProcessorConfig.optimal(model, num_channels=2) processor = aic.Processor(model, license_key, config) proc_ctx = processor.get_processor_context() print(f"Delay: {proc_ctx.get_output_delay()} samples") # Stereo in, stereo out. The SDK mixed both channels down internally. audio = np.zeros((config.num_channels, config.num_frames), dtype=np.float32) enhanced = processor.process(audio) ``` ```python 3.0 theme={null} import aic_sdk as aic import numpy as np model = aic.Model.from_file(model_path) config = aic.ProcessorConfig.optimal(model) processor = aic.Processor(model, license_key, config) proc_ctx = processor.get_context() print(f"Delay: {proc_ctx.get_audio_delay()} samples") # Mono in, mono out. Downmix in your application first. audio = np.zeros(config.block_size, dtype=np.float32) enhanced = processor.process(audio) ``` To downmix a file loaded with `soundfile`: ```python theme={null} import numpy as np import soundfile as sf audio, sample_rate = sf.read(path, dtype="float32") # audio is (frames,) for mono or (frames, channels) for multi-channel. if audio.ndim > 1: audio = audio.mean(axis=1) audio = np.ascontiguousarray(audio, dtype=np.float32) ``` > [!NOTE] > > `mean(axis=1)` preserves the `float32` dtype used here. The explicit cast also handles inputs such as integers, whose mean defaults to `float64`. `process()` requires a contiguous array; use `np.ascontiguousarray` for non-contiguous slices. To keep channels separate, create one `Processor` per channel. Each one holds the state for exactly one stream. ## Migrate VAD ```python 2.5 theme={null} # The VAD came from the enhancement processor. processor = aic.Processor(model, license_key, config) vad_ctx = processor.get_vad_context() vad_ctx.set_parameter(aic.VadParameter.Sensitivity, 5.0) # energy threshold enhanced = processor.process(audio) # also advanced the VAD if vad_ctx.is_speech_detected(): print("Speech detected") ``` ```python 3.0 theme={null} # The VAD is its own object, backed by a dedicated VAD model. vad_model = aic.Model.from_file( aic.Model.download("vad-2.1-xxs-16khz", "./models") ) vad = aic.Vad(vad_model, license_key, aic.ProcessorConfig.optimal(vad_model)) vad_ctx = vad.get_context() vad_ctx.set_parameter(aic.VadParameter.Sensitivity, 0.8) # probability vad.process(audio) # returns None, does not modify the audio if vad_ctx.is_speech_detected(): print("Speech detected") ``` > [!WARNING] > > `VadParameter.Sensitivity` is now a probability threshold from `0.0` to `1.0`, and the direction is inverted: higher values require more confidence and therefore fire less often. Old energy-threshold values above `1.0` raise `ParameterOutOfRangeError`. Retune against real audio and start from the model default. See [Retune sensitivity](/reference/deprecated/energy-vad-to-dedicated-vad#retune-sensitivity). Running both together, on the same original input block: ```python theme={null} vad.process(audio) # reads the block enhanced = processor.process(audio) # returns the enhanced block ``` Feed the VAD the original input rather than the enhanced output. Enhancement changes the signal the VAD model was trained on, and it adds the processor's delay on top of the VAD's own. ### Async VAD `VadAsync` mirrors `ProcessorAsync`: ```python theme={null} vad = aic.VadAsync(vad_model, license_key) await vad.initialize_async(config) await vad.process_async(audio) print(vad.get_context().is_speech_detected()) await vad.terminate_session_async() ``` ### `VadContext` `VadContext` gained the methods the processor context already had: | Method | Notes | | - | - | | `is_speech_detected()` | Unchanged | | `raw_vad_probability()` | Unchanged. The model's probability before thresholding, useful for picking a sensitivity value | | `get_prediction_delay()` | New on the VAD. How far the published prediction lags its input, independent of the processor's audio delay | | `reset()` | New. Clears VAD state and immediately clears the published decision and probability | | `update_bearer_token(token)` | New. Same JWT rules as the processor context | > [!NOTE] > > These names match the C API's `aic_processor_context_get_audio_delay` and `aic_vad_context_get_prediction_delay`. ## Model types are enforced | Object | Accepts | | - | - | | `Processor`, `ProcessorAsync` | Enhancement and bypass models | | `Vad`, `VadAsync` | Dedicated VAD models | | `Analyzer`, `FileAnalyzer` | Analysis models | A mismatch raises `ModelTypeUnsupportedError` at creation time. ## Session termination `Processor`, `Vad` and `Analyzer` can now close their telemetry session explicitly, instead of waiting for garbage collection: ```python theme={null} processor.terminate_session() vad.terminate_session() # Async variants await processor.terminate_session_async() await vad.terminate_session_async() ``` Stop submitting audio before termination and treat the object as closed afterward. Processing can become disallowed asynchronously; the method returning does not guarantee immediate cutoff. Native termination may block while the final session drains. Destruction also terminates the session, but explicit termination avoids waiting for garbage collection. ## Validation * Confirm every `process()`, `process_async()` and `buffer()` call receives a contiguous 1D `float32` array. * Confirm no code still reads `config.num_frames`, `config.num_channels` or `config.allow_variable_frames`. * Search for `get_processor_context` and `get_vad_context`. * Search for the three renamed error classes, including in `except` clauses. * Compare speech detection against representative audio after retuning sensitivity. * Compare enhancement output level against representative recordings if you previously relied on the internal mixdown and mixback. ## Need help? * See the [GitHub repository](https://github.com/ai-coustics/aic-sdk-py) and the [type stubs file](https://github.com/ai-coustics/aic-sdk-py/blob/3.4.0/aic_sdk.pyi). * Browse available models at [artifacts.ai-coustics.io](https://artifacts.ai-coustics.io). * Check the [compatibility matrix](/reference/sdk/compatibility-matrix) for binding, core and model file versions. # Migrate from livekit-plugins to livekit-extras Source: https://docs.ai-coustics.com/reference/livekit/migrate-to-livekit-extras Move dedicated VAD and Audio Insight from the ai-coustics-maintained plugin 0.2.0 to the ai-coustics LiveKit extras plugin 0.25.2. The ai-coustics LiveKit extras plugin replaces the ai-coustics-maintained LiveKit plugin. It keeps the dedicated `VAD`, the Tyto `Analyzer` and `FrameProcessorChain`. It does not include speech enhancement. Use the official LiveKit plugin for speech enhancement. This guide compares plugin 0.2.0 with the LiveKit extras plugin 0.25.2. The LiveKit extras plugin version matches the version of the ai-coustics core SDK that it uses. | | Old package | New package | | - | - | - | | Python distribution | `ai-coustics-livekit-plugin` | `ai-coustics-livekit-extras` | | Python import | `livekit.plugins.ai_coustics` | `ai_coustics.livekit` | | Node.js package | `@ai-coustics/livekit-plugin` | `@ai-coustics/livekit-extras` | | SDK dependency | `aic-sdk>=3.2.0,<4` / `@ai-coustics/aic-sdk@^0.24.0` | `aic-sdk==3.3.2` / `@ai-coustics/aic-sdk@0.25.2` | | Source | [ai-coustics/livekit-plugins](https://github.com/ai-coustics/livekit-plugins) | [ai-coustics/livekit-extras](https://github.com/ai-coustics/livekit-extras) | ## What changes | Feature | Plugin 0.2.0 | LiveKit extras plugin 0.25.2 | | - | - | - | | Speech enhancement (`Processor`) | Yes | Removed. Use the official plugin. | | Dedicated VAD (`VAD`) | Yes | Yes, same API | | Audio Insight (`Analyzer`) | Yes | Yes, same API | | `FrameProcessorChain` | Yes | Yes, same API | | Install next to the official plugin | Not in Python | Yes, in both runtimes | These public names are removed: * `Processor`, `ProcessorContext` and `ProcessorParameter` * Node.js only: `ProcessorOptions`, `float32ToPcm16` and `pcm16ToFloat32` The constructor options of `VAD` and `Analyzer` do not change. VAD defaults, VAD events, analysis events and the OpenTelemetry instrument names do not change. Authentication with `AIC_SDK_LICENSE` or `license_key` / `licenseKey` does not change. ## Migration steps **1. Replace the package** ```bash Python theme={null} pip uninstall ai-coustics-livekit-plugin pip install ai-coustics-livekit-extras==0.25.2 ``` ```bash Node.js theme={null} npm uninstall @ai-coustics/livekit-plugin npm install --save-exact @ai-coustics/livekit-extras@0.25.2 ``` In Python, remove the old distribution before you install the LiveKit extras plugin. The old distribution and the official `livekit-plugins-ai-coustics` package write to the same directory. The LiveKit extras plugin uses a different import path, so it can share an environment with the official plugin. The LiveKit extras plugin pins an exact SDK version. If your project also pins `aic-sdk` or `@ai-coustics/aic-sdk`, change that pin to `3.3.2` or `0.25.2`. **2. Update the imports** Python code that used the `ai_coustics` module object must import names from `ai_coustics.livekit`. ```python Python (before) theme={null} from livekit.plugins import ai_coustics vad_model = ai_coustics.Model.from_file(vad_path) vad = ai_coustics.VAD(model=vad_model) analyzer = ai_coustics.Analyzer(model=analysis_model) frame_processor = ai_coustics.FrameProcessorChain(vad.processor, analyzer.collector) ``` ```python Python (after) theme={null} from ai_coustics.livekit import VAD, Analyzer, FrameProcessorChain, Model vad_model = Model.from_file(vad_path) vad = VAD(model=vad_model) analyzer = Analyzer(model=analysis_model) frame_processor = FrameProcessorChain(vad.processor, analyzer.collector) ``` To keep the module-object style, use `from ai_coustics import livekit as ai_coustics`. In Node.js, change only the package name: ```ts theme={null} import { Analyzer, FrameProcessorChain, Model, VAD } from "@ai-coustics/livekit-extras"; ``` **3. Move speech enhancement to the official plugin** Skip this step if you do not use `Processor`. Follow LiveKit's [noise cancellation documentation](https://docs.livekit.io/transport/media/noise-cancellation/) to install and configure the official plugin. Its `audio_enhancement()` / `audioEnhancement()` factory replaces `Processor`. The official plugin selects the model and does not use your provisioned enhancement `.aicmodel` file. Model names do not guarantee identical weights across versions. Compare the output on your own recordings. Remove the enhancement model download from your deployment. Keep the VAD and Tyto model downloads. **4. Rebuild the RoomIO audio path** RoomIO has one `noise_cancellation` / `noiseCancellation` slot. The dedicated VAD needs `vad.processor` in that slot, and the Analyzer needs `analyzer.collector` in that slot. The authentication mode of the official plugin controls if the official enhancement can also go in that slot. **Explicit ai-coustics authentication.** With `Auth.ai_coustics_api(...)` / `Auth.aiCousticsApi(...)`, the official enhancement does not need LiveKit Cloud credentials or stream information from RoomIO. Put it in the chain after `vad.processor` and `analyzer.collector`. VAD and Tyto then receive the original audio. Self-hosted LiveKit deployments have no LiveKit Cloud credentials, so they require this mode. ```python Python theme={null} import os from livekit.plugins.ai_coustics import Auth, audio_enhancement from ai_coustics.livekit import FrameProcessorChain enhancement = audio_enhancement( auth=Auth.ai_coustics_api(license_key=os.environ["AIC_SDK_LICENSE"]), ) frame_processor = FrameProcessorChain(vad.processor, analyzer.collector, enhancement) ``` ```ts Node.js theme={null} import { Auth, audioEnhancement } from "@livekit/plugins-ai-coustics"; import { FrameProcessorChain } from "@ai-coustics/livekit-extras"; const enhancement = audioEnhancement({ auth: Auth.aiCousticsApi(process.env.AIC_SDK_LICENSE!), }); const frameProcessor = new FrameProcessorChain(vad.processor, analyzer.collector, enhancement); ``` Omit `analyzer.collector` if you do not use Tyto. ai-coustics bills this enhancement to your SDK key, not through LiveKit Cloud. **Default LiveKit Cloud authentication.** The official enhancement needs the LiveKit Cloud credentials that RoomIO gives to the slot. `FrameProcessorChain` does not forward these credentials to its processors. Install the official enhancement in the slot on its own. Thus one session cannot use this mode and the dedicated VAD together. Select one configuration for each session: | Old chain | New configuration with LiveKit Cloud authentication | | - | - | | `vad.processor`, `analyzer.collector`, `processor` | Official enhancement with the official VAD adapter, or the LiveKit extras plugin `FrameProcessorChain(vad.processor, analyzer.collector)` without enhancement | | `vad.processor`, `processor` | Official enhancement with the official VAD adapter, or the LiveKit extras plugin `vad.processor` without enhancement | | `processor` | Official enhancement only | | `vad.processor`, `analyzer.collector` | No change | The official VAD adapter is not interchangeable with the dedicated `VAD`. Do not copy the dedicated VAD sensitivity values to the adapter without a review of their ranges. Refer to [Which LiveKit plugin to use](/reference/livekit/plugin-scope) for the differences. **5. Update logs and metrics filters** In Python, the logger name changes from `livekit.plugins.ai_coustics` to `ai_coustics.livekit`. Update log level configuration and log filters that use the old name. The OpenTelemetry meter name changes from `ai-coustics-livekit-plugin` to `ai-coustics-livekit-extras` in both runtimes. The instrument names stay the same. Update dashboards that filter on the instrumentation scope. **6. Check Analyzer shutdown in Node.js** `Analyzer.close()` now returns `void`, not a promise. Existing `await analyzer.close()` calls still work. The SDK session ends after an in-flight analysis completes. ## Verify the migration 1. Start a room and confirm that VAD events and `analysisResult` / `analysis_result` events arrive. 2. Disconnect and reconnect, then confirm that a new room produces events again. ## Questions For the LiveKit extras plugin, open an issue in [ai-coustics/livekit-extras](https://github.com/ai-coustics/livekit-extras/issues). Include package versions, runtime, operating system, model IDs, audio geometry and a redacted error. For the official integration, use [LiveKit's documentation and community](https://docs.livekit.io/home/get-started/intro-to-livekit/). # Which LiveKit plugin to use Source: https://docs.ai-coustics.com/reference/livekit/plugin-scope Choose the official plugin for speech enhancement or the ai-coustics LiveKit extras plugin for dedicated VAD and Tyto. **ai-coustics** models are available through two LiveKit integrations with different APIs and authentication paths. The official LiveKit plugin is the primary path for speech enhancement. Follow LiveKit's [noise cancellation documentation](https://docs.livekit.io/transport/media/noise-cancellation/) for installation and configuration. The ai-coustics LiveKit extras plugin provides standalone voice activity detection (VAD) and Tyto audio-quality analysis, billed through ai-coustics. These capabilities are unavailable in the compared official-plugin release. ## Which plugin for what This comparison covers the official plugin 0.3.2 and the ai-coustics LiveKit extras plugin 0.26.0. | Need | Integration | Next step | | - | - | - | | Speech enhancement with Quail Multi Speaker or Quail Voice Focus | Official `livekit-plugins-ai-coustics` / `@livekit/plugins-ai-coustics` | [LiveKit noise cancellation](https://docs.livekit.io/transport/media/noise-cancellation/) | | Voice activity detection coupled to the official enhancement path | Official plugin's VAD adapter, with its accompanying enhancement component | Keep the official components together. | | Standalone voice activity detection with a dedicated model | `ai-coustics-livekit-extras` / `@ai-coustics/livekit-extras` | [Complete VAD quickstart](/models/get-started/livekit-quickstart) | | Tyto audio-quality analysis | ai-coustics LiveKit extras plugin `Analyzer` and `collector` | [Add Tyto](/models/get-started/livekit-quickstart#audio-quality-analysis) | The official plugin's VAD adapter in this release consumes metadata from its accompanying enhancement component. It is not interchangeable with the dedicated `VAD(model=...)` / `new VAD({ model })` API. The LiveKit extras plugin does not include `Processor`. Use the official plugin for speech enhancement. ## Running both packages In Python, the LiveKit extras plugin uses the `ai_coustics.livekit` import path. It can share an environment with the official plugin in Python and Node.js. Different import names do not make the objects interchangeable. Each VAD expects metadata from its own audio processing path. The [ai-coustics quickstart](/models/get-started/livekit-quickstart) uses only LiveKit extras plugin components in its RoomIO chain. To chain the official enhancement with the LiveKit extras plugin components, see the [migration guide](/reference/livekit/migrate-to-livekit-extras). ## Authentication and provisioning | Concern | Official plugin | ai-coustics LiveKit extras plugin | | - | - | - | | LiveKit Cloud authentication | Default Cloud authentication and metering | Uses a separate ai-coustics SDK key for SDK usage | | Explicit ai-coustics key | `Auth.ai_coustics_api(...)` / `Auth.aiCousticsApi(...)` | `AIC_SDK_LICENSE`, `license_key` / `licenseKey` | | Models | Select from the official plugin's exposed model choices | Provision `.aicmodel` files and load matching `Model` objects | | VAD activation | Use the adapter with its accompanying enhancement path | Pass `vad` to the session and `vad.processor` to RoomIO | | Tyto activation | No `Analyzer` API in the compared release | Add `analyzer.collector` to RoomIO and handle result events | Keep all SDK and LiveKit keys on the server. Downloading a model is separate from authorizing a processing session. See [authentication](/models/get-started/authenticate-apps). ## If you use Processor today Plugin 0.2.0 `Processor` is not in the LiveKit extras plugin. Use the [migration guide](/reference/livekit/migrate-to-livekit-extras) to move speech enhancement to the official plugin. Keep your deployment and lockfile while you evaluate the change. 1. **Record your baseline.** Save the package versions, model ID, enhancement parameters, audio format and authentication configuration. 2. **Compare and recover.** Use the same recordings and downstream providers to compare enhancement, speech boundaries and response latency. Test room disconnect and reconnect. Restore the previous deployment and its lockfile if the new combination fails acceptance. Do not combine a package change, model change and VAD tuning into one unmeasured rollout. The [dedicated VAD migration reference](/reference/deprecated/energy-vad-to-dedicated-vad) explains the difference between legacy energy thresholds and probability thresholds. ## Questions For the ai-coustics LiveKit extras plugin, open an issue in [ai-coustics/livekit-extras](https://github.com/ai-coustics/livekit-extras/issues). Include package versions, runtime, operating system, model IDs, audio geometry and a redacted error. For the official integration, use [LiveKit's documentation and community](https://docs.livekit.io/home/get-started/intro-to-livekit/). # C audio analysis Source: https://docs.ai-coustics.com/reference/sdk/api/c/analysis Collect audio features and run analysis on a separate thread. All functions on this page are from C SDK **0.26.0**, core **0.26.0**. Include `aic.h` and link the matching native library. Start with the [C integration guide](/reference/sdk/language-bindings/c). The [pointer and error contract](/reference/sdk/api/c/errors-and-types#pointer-contract) applies to every signature below. Error names in prose omit the `AIC_ERROR_CODE_` prefix. There are no default C arguments; optional pointers are stated explicitly. Use a compatible [Tyto model](/models/audio-insight/tyto). The collector accepts mono float32 samples; the analyzer reads a snapshot of the collected features. A successful buffering call is not a completed model inference. Read [analysis fields](/reference/sdk/api/c/errors-and-types#AicAnalysisResult) only after a successful analysis call. ## `aic_analyzer_pair_create` ```c theme={null} enum AicErrorCode aic_analyzer_pair_create(struct AicCollector **collector, struct AicAnalyzer **analyzer, const struct AicModel *model, const char *license_key); ``` `collector` and `analyzer` are distinct writable output slots. `model` must be an analysis model; `license_key` is a null-terminated SDK key or supported bearer token. On success, each output is independently owned and must be destroyed. The analyzer retains the model data. Creation allocates; it does not initialize the collector. Returns `SUCCESS`, `NULL_POINTER`, `MODEL_TYPE_UNSUPPORTED`, license errors or `INTERNAL_ERROR`. This API has no OTel configuration parameter and disables optional OTel export for this pair; SDK session requirements remain separate. ## `aic_collector_initialize` ```c theme={null} enum AicErrorCode aic_collector_initialize(struct AicCollector *collector, uint32_t sample_rate, size_t block_size, bool variable_block_size); ``` Configures `collector` with `sample_rate` in Hz (8,000–192,000), positive `block_size` in mono samples and fixed (`false`) or variable (`true`) block sizing. Fixed input must match the block size; variable input cannot exceed it. Returns `SUCCESS`, `NULL_POINTER` or `AUDIO_CONFIG_UNSUPPORTED`. Failure leaves the collector uninitialized. Allocate and initialize before starting audio collection; do not reinitialize while collecting. ## `aic_collector_buffer` ```c theme={null} enum AicErrorCode aic_collector_buffer(struct AicCollector *collector, const float *audio_ptr, size_t audio_len); ``` Copies/accumulates `audio_len` mono float32 samples from the readable `audio_ptr` into the collection pipeline without modifying input. Returns `SUCCESS`, `NULL_POINTER`, `NOT_INITIALIZED` or `AUDIO_CONFIG_MISMATCH`. This collects features; it does not run analysis or return scores. One thread may feed the collector while a separate thread calls the paired analyzer; do not call this function concurrently on one collector. ## `aic_collector_destroy` ```c theme={null} void aic_collector_destroy(struct AicCollector *collector); ``` Releases `collector`; `NULL` is a no-op. Stop calls using that handle first. The analyzer is owned separately and is not destroyed by this call. Teardown is outside the audio callback. No return value. ## `aic_analyzer_reset` ```c theme={null} enum AicErrorCode aic_analyzer_reset(const struct AicAnalyzer *analyzer); ``` Requests a reset of the paired collector through `analyzer`. The next collection call clears pending stream state; analysis while the reset is pending uses an empty, padded window. Returns `SUCCESS` or `NULL_POINTER`. Parameters and collector audio configuration are retained. Coordinate unrelated recordings so they do not share a window. ## `aic_analyzer_analyze_buffered` ```c theme={null} enum AicErrorCode aic_analyzer_analyze_buffered(struct AicAnalyzer *analyzer, struct AicAnalysisResult *result); ``` Runs the model on the latest fixed-size feature window from `analyzer` and writes all seven fields of writable `result` only on success. Early windows are silence-padded; repeated calls without new input can score the same window. This does not consume a caller-owned audio buffer. Returns `SUCCESS`, `NULL_POINTER`, `PROCESSING_NOT_ALLOWED` or `INTERNAL_ERROR` (for example, no usable snapshot). Call off the audio thread and serialize analysis calls. The paired collector can continue feeding from another thread. ## `aic_analyzer_terminate_session` ```c theme={null} enum AicErrorCode aic_analyzer_terminate_session(struct AicAnalyzer *analyzer); ``` Requests session termination through `analyzer`. Returns `SUCCESS` or `NULL_POINTER`; it does not destroy either handle. Termination is asynchronous and is a no-op if no session exists. Stop analysis explicitly and release both handles when finished. On native targets, terminating the final active session may wait for the shared telemetry tasks to finish. Call it outside the audio callback. ## `aic_analyzer_update_bearer_token` ```c theme={null} enum AicErrorCode aic_analyzer_update_bearer_token(const struct AicAnalyzer *analyzer, const char *token); ``` Updates the analyzer session with null-terminated UTF-8 `token`. Both original and new credentials must use supported JWT form. Returns `SUCCESS`, `NULL_POINTER`, `LICENSE_FORMAT_INVALID`, other license errors or `TOKEN_UPDATE_UNSUPPORTED`. Call on a control thread. Success means local credential replacement, not backend acknowledgment. ## `aic_analyzer_destroy` ```c theme={null} void aic_analyzer_destroy(struct AicAnalyzer *analyzer); ``` Releases `analyzer`, its model reference and its associated session. `NULL` is a no-op. The collector must be destroyed separately. Stop calls using the analyzer first; destruction can block. No return value. ## Related [C API index](/reference/sdk/api/c/index) · [C examples](/reference/sdk/examples#c) · [Compatibility](/reference/sdk/compatibility-matrix) ## Example: check an analysis result Run this helper on the analysis thread after initializing and feeding the paired collector. It copies the headline score only on success. ```c theme={null} #include "aic.h" AicErrorCode read_risk(AicAnalyzer *analyzer, float *risk) { if (risk == NULL) return AIC_ERROR_CODE_NULL_POINTER; AicAnalysisResult result; AicErrorCode error = aic_analyzer_analyze_buffered(analyzer, &result); if (error == AIC_ERROR_CODE_SUCCESS) *risk = result.risk_score; return error; } ``` # C errors and types Source: https://docs.ai-coustics.com/reference/sdk/api/c/errors-and-types Look up public error codes, pointer ownership and every analysis field. C SDK **0.26.0**, core **0.26.0**. The declarations are in `aic.h`. ## Pointer and error contract Initialize handle output slots to `NULL`. Creation writes an output only on success; failure does not promise to clear the slot. Check the return code before using outputs. Do not pass an already owned handle as an output slot without first managing its lifetime. Non-null pointers must still point to valid storage of the declared type and size. Null checks do not make dangling, misaligned or undersized pointers safe. Pass only declared enum values. Output storage must be writable and unaliased for the call. Strings are null-terminated; paths and credentials require UTF-8. Audio length is a count of mono float32 samples, not bytes. Do not mutate, destroy or call a mutable processing object concurrently. Shared context parameter reads/writes and reset requests can run alongside processing while both handles remain valid. They do not make destruction concurrent-safe. Use one stateful object per stream. Create, initialize, update credentials and destroy outside the audio callback; run analysis off the callback too. ## `AicErrorCode` Every member below is prefixed with `AIC_ERROR_CODE_` in C. Error-returning functions use this enum, with success equal to zero. A `void` destroy function and the direct metadata getters do not return it. | Constant | Value | Meaning and recovery | | - | - | - | | `AIC_ERROR_CODE_SUCCESS` | 0 | The operation succeeded. Output slots are usable. | | `AIC_ERROR_CODE_NULL_POINTER` | 1 | A required pointer is NULL. Supply valid objects and writable output storage. | | `AIC_ERROR_CODE_PARAMETER_OUT_OF_RANGE` | 2 | A parameter is outside its accepted range or is NaN. Check the parameter table. | | `AIC_ERROR_CODE_NOT_INITIALIZED` | 3 | Initialize the processor, VAD or collector successfully before supplying audio. | | `AIC_ERROR_CODE_AUDIO_CONFIG_UNSUPPORTED` | 4 | The initialization rate or block configuration is unsupported. Use 8,000–192,000 Hz and a positive block size. | | `AIC_ERROR_CODE_AUDIO_CONFIG_MISMATCH` | 5 | The input length violates the fixed block size or variable maximum. Correct the buffer length. | | `AIC_ERROR_CODE_PROCESSING_NOT_ALLOWED` | 6 | The session currently disallows processing. Check credentials, activation and session state; do not treat the output as enhanced audio. | | `AIC_ERROR_CODE_INTERNAL_ERROR` | 7 | The operation could not complete internally. Preserve a safe diagnostic and contact support if a valid configuration reproduces it. | | `AIC_ERROR_CODE_LICENSE_FORMAT_INVALID` | 50 | The credential cannot be parsed. Check the supplied key/token and string encoding without logging it. | | `AIC_ERROR_CODE_LICENSE_VERSION_UNSUPPORTED` | 51 | This SDK does not support the credential version. Check SDK/account compatibility. | | `AIC_ERROR_CODE_LICENSE_EXPIRED` | 52 | The credential has expired. Obtain a valid credential through the approved account flow. | | `AIC_ERROR_CODE_TOKEN_UPDATE_UNSUPPORTED` | 53 | In-place token replacement requires JWT-form original and replacement credentials. | | `AIC_ERROR_CODE_MODEL_INVALID` | 100 | The model data cannot be parsed. Download the complete compatible model again. | | `AIC_ERROR_CODE_MODEL_VERSION_UNSUPPORTED` | 101 | The model file format does not match this SDK. Obtain the matching format. | | `AIC_ERROR_CODE_FILE_PATH_INVALID` | 102 | The model path is not valid UTF-8. | | `AIC_ERROR_CODE_FILE_SYSTEM_ERROR` | 103 | The model file cannot be opened or mapped. Check its path, permissions and integrity. | | `AIC_ERROR_CODE_MODEL_DATA_UNALIGNED` | 104 | The model buffer does not meet 64-byte alignment. | | `AIC_ERROR_CODE_MODEL_TYPE_UNSUPPORTED` | 105 | This object cannot run the selected model type. Match enhancement, VAD or analysis to its dedicated API. | ## Opaque handles Do not allocate these structs yourself or read their layout. Each factory returns an owned handle; use the matching destroy function exactly once. A `NULL` argument to a destroy function is a no-op. | Type | Created by | Released by | | - | - | - | | `AicModel` | [`aic_model_create_from_file`](/reference/sdk/api/c/models-and-config#aic_model_create_from_file) | [`aic_model_destroy`](/reference/sdk/api/c/models-and-config#aic_model_destroy) | | `AicProcessor` | [`aic_processor_create`](/reference/sdk/api/c/processing#aic_processor_create) | [`aic_processor_destroy`](/reference/sdk/api/c/processing#aic_processor_destroy) | | `AicProcessorContext` | [`aic_processor_context_create`](/reference/sdk/api/c/processing#aic_processor_context_create) | [`aic_processor_context_destroy`](/reference/sdk/api/c/processing#aic_processor_context_destroy) | | `AicVad` | [`aic_vad_create`](/reference/sdk/api/c/vad#aic_vad_create) | [`aic_vad_destroy`](/reference/sdk/api/c/vad#aic_vad_destroy) | | `AicVadContext` | [`aic_vad_context_create`](/reference/sdk/api/c/vad#aic_vad_context_create) | [`aic_vad_context_destroy`](/reference/sdk/api/c/vad#aic_vad_context_destroy) | | `AicEnergyVadContext` | [`aic_energy_vad_context_create`](/reference/sdk/api/c/vad#aic_energy_vad_context_create) | [`aic_energy_vad_context_destroy`](/reference/sdk/api/c/vad#aic_energy_vad_context_destroy) | | `AicCollector` | [`aic_analyzer_pair_create`](/reference/sdk/api/c/analysis#aic_analyzer_pair_create) | [`aic_collector_destroy`](/reference/sdk/api/c/analysis#aic_collector_destroy) | | `AicAnalyzer` | [`aic_analyzer_pair_create`](/reference/sdk/api/c/analysis#aic_analyzer_pair_create) | [`aic_analyzer_destroy`](/reference/sdk/api/c/analysis#aic_analyzer_destroy) | `AicModel` can also be created from a buffer. Derived objects retain the model data, but the caller must keep any borrowed buffer or mapped file valid. Context handles retain shared controls and can outlive their source object; they do not keep processing audio after its destruction. ## `AicAnalysisResult` ```c theme={null} typedef struct AicAnalysisResult { float risk_score; float speaker_reverb; float speaker_loudness; float interfering_speech; float noise; float codec_degradation; float packet_loss; } AicAnalysisResult; ``` Caller-owned value storage. `aic_analyzer_analyze_buffered` writes it on success. All fields are `float`; no field has a C default. Read the [Tyto dimension interpretation](/models/audio-insight/tyto#tyto-dimensions) before setting application thresholds. Scores are model estimates, not a measured word error rate or a guarantee about downstream behavior. | Field | Meaning | | - | - | | `risk_score` | Combined risk score from the model output and its weighting metadata. Lower values indicate less problematic audio. | | `speaker_reverb` | Main-speaker distance/reverberation indicator. | | `speaker_loudness` | Main-speaker level indicator; a larger value is not automatically worse. | | `interfering_speech` | The maximum of background-speaker and background-media interference outputs. | | `noise` | Background-noise indicator. | | `codec_degradation` | Speech-codec artifact indicator. | | `packet_loss` | Dropout/discontinuity indicator. | ## Related [C API index](/reference/sdk/api/c/index) · [OpenTelemetry configuration](/reference/sdk/api/c/models-and-config#AicOtelConfig) · [Troubleshooting](/production/troubleshooting) ## Example: initialize output handles This helper leaves the output slot null when loading fails. It is an application convention; the SDK factory itself does not clear an existing slot. ```c theme={null} #include "aic.h" AicErrorCode load_model(const char *path, AicModel **output) { if (output == NULL) return AIC_ERROR_CODE_NULL_POINTER; *output = NULL; /* Pass a fresh output slot, not an owned model. */ return aic_model_create_from_file(output, path); } ``` # C API reference Source: https://docs.ai-coustics.com/reference/sdk/api/c/index Complete public C SDK functions, handles, structures and enums. C SDK **0.26.0** uses core **0.26.0** and model file format **8**. This reference covers the public `aic.h` surface: 50 functions, eight opaque handle types, two value structs and three enums, including every field and enum member. For installation and a complete runnable audio example, start with the [C integration guide](/reference/sdk/language-bindings/c). This reference has no automatic model downloader or file-decoding API: download a model separately and decode audio in your application. Internal wrapper-registration exports are not part of the public header contract. ## Browse by task | Task | Reference | | - | - | | Load a model, inspect its rate or configure OTel | [Models and configuration](/reference/sdk/api/c/models-and-config) | | Enhance audio and control stream state | [Processing](/reference/sdk/api/c/processing) | | Detect speech with a dedicated model, or from an enhancement processor | [VAD](/reference/sdk/api/c/vad) | | Collect audio and compute Tyto scores | [Analysis](/reference/sdk/api/c/analysis) | | Interpret an error or inspect a struct field | [Errors and types](/reference/sdk/api/c/errors-and-types) | ## Alphabetical symbol index | Public symbol | Definition | | - | - | | `aic_analyzer_analyze_buffered` | [Reference](/reference/sdk/api/c/analysis#aic_analyzer_analyze_buffered) | | `aic_analyzer_destroy` | [Reference](/reference/sdk/api/c/analysis#aic_analyzer_destroy) | | `aic_analyzer_pair_create` | [Reference](/reference/sdk/api/c/analysis#aic_analyzer_pair_create) | | `aic_analyzer_reset` | [Reference](/reference/sdk/api/c/analysis#aic_analyzer_reset) | | `aic_analyzer_terminate_session` | [Reference](/reference/sdk/api/c/analysis#aic_analyzer_terminate_session) | | `aic_analyzer_update_bearer_token` | [Reference](/reference/sdk/api/c/analysis#aic_analyzer_update_bearer_token) | | `aic_collector_buffer` | [Reference](/reference/sdk/api/c/analysis#aic_collector_buffer) | | `aic_collector_destroy` | [Reference](/reference/sdk/api/c/analysis#aic_collector_destroy) | | `aic_collector_initialize` | [Reference](/reference/sdk/api/c/analysis#aic_collector_initialize) | | `AIC_ERROR_CODE_AUDIO_CONFIG_MISMATCH` | [Reference](/reference/sdk/api/c/errors-and-types#AIC_ERROR_CODE_AUDIO_CONFIG_MISMATCH) | | `AIC_ERROR_CODE_AUDIO_CONFIG_UNSUPPORTED` | [Reference](/reference/sdk/api/c/errors-and-types#AIC_ERROR_CODE_AUDIO_CONFIG_UNSUPPORTED) | | `AIC_ERROR_CODE_FILE_PATH_INVALID` | [Reference](/reference/sdk/api/c/errors-and-types#AIC_ERROR_CODE_FILE_PATH_INVALID) | | `AIC_ERROR_CODE_FILE_SYSTEM_ERROR` | [Reference](/reference/sdk/api/c/errors-and-types#AIC_ERROR_CODE_FILE_SYSTEM_ERROR) | | `AIC_ERROR_CODE_INTERNAL_ERROR` | [Reference](/reference/sdk/api/c/errors-and-types#AIC_ERROR_CODE_INTERNAL_ERROR) | | `AIC_ERROR_CODE_LICENSE_EXPIRED` | [Reference](/reference/sdk/api/c/errors-and-types#AIC_ERROR_CODE_LICENSE_EXPIRED) | | `AIC_ERROR_CODE_LICENSE_FORMAT_INVALID` | [Reference](/reference/sdk/api/c/errors-and-types#AIC_ERROR_CODE_LICENSE_FORMAT_INVALID) | | `AIC_ERROR_CODE_LICENSE_VERSION_UNSUPPORTED` | [Reference](/reference/sdk/api/c/errors-and-types#AIC_ERROR_CODE_LICENSE_VERSION_UNSUPPORTED) | | `AIC_ERROR_CODE_MODEL_DATA_UNALIGNED` | [Reference](/reference/sdk/api/c/errors-and-types#AIC_ERROR_CODE_MODEL_DATA_UNALIGNED) | | `AIC_ERROR_CODE_MODEL_INVALID` | [Reference](/reference/sdk/api/c/errors-and-types#AIC_ERROR_CODE_MODEL_INVALID) | | `AIC_ERROR_CODE_MODEL_TYPE_UNSUPPORTED` | [Reference](/reference/sdk/api/c/errors-and-types#AIC_ERROR_CODE_MODEL_TYPE_UNSUPPORTED) | | `AIC_ERROR_CODE_MODEL_VERSION_UNSUPPORTED` | [Reference](/reference/sdk/api/c/errors-and-types#AIC_ERROR_CODE_MODEL_VERSION_UNSUPPORTED) | | `AIC_ERROR_CODE_NOT_INITIALIZED` | [Reference](/reference/sdk/api/c/errors-and-types#AIC_ERROR_CODE_NOT_INITIALIZED) | | `AIC_ERROR_CODE_NULL_POINTER` | [Reference](/reference/sdk/api/c/errors-and-types#AIC_ERROR_CODE_NULL_POINTER) | | `AIC_ERROR_CODE_PARAMETER_OUT_OF_RANGE` | [Reference](/reference/sdk/api/c/errors-and-types#AIC_ERROR_CODE_PARAMETER_OUT_OF_RANGE) | | `AIC_ERROR_CODE_PROCESSING_NOT_ALLOWED` | [Reference](/reference/sdk/api/c/errors-and-types#AIC_ERROR_CODE_PROCESSING_NOT_ALLOWED) | | `AIC_ERROR_CODE_SUCCESS` | [Reference](/reference/sdk/api/c/errors-and-types#AIC_ERROR_CODE_SUCCESS) | | `AIC_ERROR_CODE_TOKEN_UPDATE_UNSUPPORTED` | [Reference](/reference/sdk/api/c/errors-and-types#AIC_ERROR_CODE_TOKEN_UPDATE_UNSUPPORTED) | | `aic_energy_vad_context_create` | [Reference](/reference/sdk/api/c/vad#aic_energy_vad_context_create) | | `aic_energy_vad_context_destroy` | [Reference](/reference/sdk/api/c/vad#aic_energy_vad_context_destroy) | | `aic_energy_vad_context_get_parameter` | [Reference](/reference/sdk/api/c/vad#aic_energy_vad_context_get_parameter) | | `aic_energy_vad_context_get_prediction_delay` | [Reference](/reference/sdk/api/c/vad#aic_energy_vad_context_get_prediction_delay) | | `aic_energy_vad_context_is_speech_detected` | [Reference](/reference/sdk/api/c/vad#aic_energy_vad_context_is_speech_detected) | | `aic_energy_vad_context_reset` | [Reference](/reference/sdk/api/c/vad#aic_energy_vad_context_reset) | | `aic_energy_vad_context_set_parameter` | [Reference](/reference/sdk/api/c/vad#aic_energy_vad_context_set_parameter) | | `aic_get_compatible_model_version` | [Reference](/reference/sdk/api/c/models-and-config#aic_get_compatible_model_version) | | `aic_get_sdk_version` | [Reference](/reference/sdk/api/c/models-and-config#aic_get_sdk_version) | | `aic_model_create_from_buffer` | [Reference](/reference/sdk/api/c/models-and-config#aic_model_create_from_buffer) | | `aic_model_create_from_file` | [Reference](/reference/sdk/api/c/models-and-config#aic_model_create_from_file) | | `aic_model_destroy` | [Reference](/reference/sdk/api/c/models-and-config#aic_model_destroy) | | `aic_model_get_id` | [Reference](/reference/sdk/api/c/models-and-config#aic_model_get_id) | | `aic_model_get_optimal_block_size` | [Reference](/reference/sdk/api/c/models-and-config#aic_model_get_optimal_block_size) | | `aic_model_get_optimal_sample_rate` | [Reference](/reference/sdk/api/c/models-and-config#aic_model_get_optimal_sample_rate) | | `aic_processor_context_create` | [Reference](/reference/sdk/api/c/processing#aic_processor_context_create) | | `aic_processor_context_destroy` | [Reference](/reference/sdk/api/c/processing#aic_processor_context_destroy) | | `aic_processor_context_get_audio_delay` | [Reference](/reference/sdk/api/c/processing#aic_processor_context_get_audio_delay) | | `aic_processor_context_get_parameter` | [Reference](/reference/sdk/api/c/processing#aic_processor_context_get_parameter) | | `aic_processor_context_reset` | [Reference](/reference/sdk/api/c/processing#aic_processor_context_reset) | | `aic_processor_context_set_parameter` | [Reference](/reference/sdk/api/c/processing#aic_processor_context_set_parameter) | | `aic_processor_context_update_bearer_token` | [Reference](/reference/sdk/api/c/processing#aic_processor_context_update_bearer_token) | | `aic_processor_create` | [Reference](/reference/sdk/api/c/processing#aic_processor_create) | | `aic_processor_destroy` | [Reference](/reference/sdk/api/c/processing#aic_processor_destroy) | | `aic_processor_initialize` | [Reference](/reference/sdk/api/c/processing#aic_processor_initialize) | | `AIC_PROCESSOR_PARAMETER_BYPASS` | [Reference](/reference/sdk/api/c/processing#AIC_PROCESSOR_PARAMETER_BYPASS) | | `AIC_PROCESSOR_PARAMETER_ENHANCEMENT_LEVEL` | [Reference](/reference/sdk/api/c/processing#AIC_PROCESSOR_PARAMETER_ENHANCEMENT_LEVEL) | | `aic_processor_process` | [Reference](/reference/sdk/api/c/processing#aic_processor_process) | | `aic_processor_terminate_session` | [Reference](/reference/sdk/api/c/processing#aic_processor_terminate_session) | | `aic_vad_context_create` | [Reference](/reference/sdk/api/c/vad#aic_vad_context_create) | | `aic_vad_context_destroy` | [Reference](/reference/sdk/api/c/vad#aic_vad_context_destroy) | | `aic_vad_context_get_parameter` | [Reference](/reference/sdk/api/c/vad#aic_vad_context_get_parameter) | | `aic_vad_context_get_prediction_delay` | [Reference](/reference/sdk/api/c/vad#aic_vad_context_get_prediction_delay) | | `aic_vad_context_get_raw_vad_probability` | [Reference](/reference/sdk/api/c/vad#aic_vad_context_get_raw_vad_probability) | | `aic_vad_context_is_speech_detected` | [Reference](/reference/sdk/api/c/vad#aic_vad_context_is_speech_detected) | | `aic_vad_context_reset` | [Reference](/reference/sdk/api/c/vad#aic_vad_context_reset) | | `aic_vad_context_set_parameter` | [Reference](/reference/sdk/api/c/vad#aic_vad_context_set_parameter) | | `aic_vad_context_update_bearer_token` | [Reference](/reference/sdk/api/c/vad#aic_vad_context_update_bearer_token) | | `aic_vad_create` | [Reference](/reference/sdk/api/c/vad#aic_vad_create) | | `aic_vad_destroy` | [Reference](/reference/sdk/api/c/vad#aic_vad_destroy) | | `aic_vad_initialize` | [Reference](/reference/sdk/api/c/vad#aic_vad_initialize) | | `AIC_VAD_PARAMETER_MINIMUM_SPEECH_DURATION` | [Reference](/reference/sdk/api/c/vad#AIC_VAD_PARAMETER_MINIMUM_SPEECH_DURATION) | | `AIC_VAD_PARAMETER_SENSITIVITY` | [Reference](/reference/sdk/api/c/vad#AIC_VAD_PARAMETER_SENSITIVITY) | | `AIC_VAD_PARAMETER_SPEECH_HOLD_DURATION` | [Reference](/reference/sdk/api/c/vad#AIC_VAD_PARAMETER_SPEECH_HOLD_DURATION) | | `aic_vad_process` | [Reference](/reference/sdk/api/c/vad#aic_vad_process) | | `aic_vad_terminate_session` | [Reference](/reference/sdk/api/c/vad#aic_vad_terminate_session) | | `AicAnalysisResult` | [Reference](/reference/sdk/api/c/errors-and-types#AicAnalysisResult) | | `AicAnalysisResult.codec_degradation` | [Reference](/reference/sdk/api/c/errors-and-types#AicAnalysisResult.codec_degradation) | | `AicAnalysisResult.interfering_speech` | [Reference](/reference/sdk/api/c/errors-and-types#AicAnalysisResult.interfering_speech) | | `AicAnalysisResult.noise` | [Reference](/reference/sdk/api/c/errors-and-types#AicAnalysisResult.noise) | | `AicAnalysisResult.packet_loss` | [Reference](/reference/sdk/api/c/errors-and-types#AicAnalysisResult.packet_loss) | | `AicAnalysisResult.risk_score` | [Reference](/reference/sdk/api/c/errors-and-types#AicAnalysisResult.risk_score) | | `AicAnalysisResult.speaker_loudness` | [Reference](/reference/sdk/api/c/errors-and-types#AicAnalysisResult.speaker_loudness) | | `AicAnalysisResult.speaker_reverb` | [Reference](/reference/sdk/api/c/errors-and-types#AicAnalysisResult.speaker_reverb) | | `AicAnalyzer` | [Reference](/reference/sdk/api/c/errors-and-types#AicAnalyzer) | | `AicCollector` | [Reference](/reference/sdk/api/c/errors-and-types#AicCollector) | | `AicEnergyVadContext` | [Reference](/reference/sdk/api/c/errors-and-types#AicEnergyVadContext) | | `AicErrorCode` | [Reference](/reference/sdk/api/c/errors-and-types#AicErrorCode) | | `AicModel` | [Reference](/reference/sdk/api/c/errors-and-types#AicModel) | | `AicOtelConfig` | [Reference](/reference/sdk/api/c/models-and-config#AicOtelConfig) | | `AicOtelConfig.enable` | [Reference](/reference/sdk/api/c/models-and-config#AicOtelConfig.enable) | | `AicOtelConfig.export_interval_ms` | [Reference](/reference/sdk/api/c/models-and-config#AicOtelConfig.export_interval_ms) | | `AicOtelConfig.session_id` | [Reference](/reference/sdk/api/c/models-and-config#AicOtelConfig.session_id) | | `AicProcessor` | [Reference](/reference/sdk/api/c/errors-and-types#AicProcessor) | | `AicProcessorContext` | [Reference](/reference/sdk/api/c/errors-and-types#AicProcessorContext) | | `AicProcessorParameter` | [Reference](/reference/sdk/api/c/processing#AicProcessorParameter) | | `AicVad` | [Reference](/reference/sdk/api/c/errors-and-types#AicVad) | | `AicVadContext` | [Reference](/reference/sdk/api/c/errors-and-types#AicVadContext) | | `AicVadParameter` | [Reference](/reference/sdk/api/c/vad#AicVadParameter) | ## Update this reference Compare API changes against the released header and implementation, preserving correct text and anchors. Check [compatibility](/reference/sdk/compatibility-matrix) before changing package or model versions. # C models and configuration Source: https://docs.ai-coustics.com/reference/sdk/api/c/models-and-config Load model data, inspect native audio metadata and configure optional OpenTelemetry. All functions on this page are from C SDK **0.26.0**, core **0.26.0**. Include `aic.h` and link the matching native library. Start with the [C integration guide](/reference/sdk/language-bindings/c). The [pointer and error contract](/reference/sdk/api/c/errors-and-types#pointer-contract) applies to every signature below. Error names in prose omit the `AIC_ERROR_CODE_` prefix. There are no default C arguments; optional pointers are stated explicitly. ## `AicOtelConfig` ```c theme={null} typedef struct AicOtelConfig { bool enable; const char *session_id; uint32_t export_interval_ms; } AicOtelConfig; ``` | Field | Meaning | | - | - | | `enable` | Overrides `AIC_SDK_OTEL_ENABLE` when a config is supplied. `false` disables optional OTel export; it does not disable SDK session telemetry. | | `session_id` | Optional null-terminated session label. `NULL` requests a generated ID. The creation call copies a supplied string; keep it valid during that call. | | `export_interval_ms` | Positive export interval in milliseconds. Zero keeps the default 60,000 ms interval. | Passing `NULL` as the entire config uses environment defaults. Supplying `{false, NULL, 0}` explicitly disables OTel even if the environment enables it. See [OpenTelemetry](/models/get-started/opentelemetry) and [SDK telemetry](/reference/concepts/sdk-telemetry). ## `aic_get_sdk_version` ```c theme={null} const char *aic_get_sdk_version(void); ``` Returns a borrowed, null-terminated core SDK version string. It has static lifetime: do not modify or free it. This function has no arguments or error return. ## `aic_get_compatible_model_version` ```c theme={null} uint32_t aic_get_compatible_model_version(void); ``` Returns the model file format version accepted by this core build: 8 for 0.26.0. This is not a model product version. No arguments or error return. ## `aic_model_create_from_file` ```c theme={null} enum AicErrorCode aic_model_create_from_file(struct AicModel **model, const char *file_path); ``` `model` is a writable output slot; `file_path` is a null-terminated UTF-8 path. On success, the slot receives an owned handle. The file is memory-mapped: keep it present and unchanged until the model and every processor, VAD or analyzer derived from it are destroyed. Errors include `NULL_POINTER`, `FILE_PATH_INVALID`, `FILE_SYSTEM_ERROR`, `MODEL_INVALID`, `MODEL_VERSION_UNSUPPORTED` and `MODEL_DATA_UNALIGNED`. Model loading allocates and performs file I/O. ## `aic_model_create_from_buffer` ```c theme={null} enum AicErrorCode aic_model_create_from_buffer(struct AicModel **model, const uint8_t *buffer, size_t buffer_len); ``` `model` is a writable output slot. `buffer` points to `buffer_len` bytes of complete model data, aligned to 64 bytes. Loading borrows the bytes without copying or taking ownership. Keep the allocation alive and unchanged until the model and all derived objects are destroyed, even if you destroy the model handle first. Errors include `NULL_POINTER`, `MODEL_INVALID`, `MODEL_VERSION_UNSUPPORTED` and `MODEL_DATA_UNALIGNED`. Allocates the handle and parses model metadata. ## `aic_model_destroy` ```c theme={null} void aic_model_destroy(struct AicModel *model); ``` Releases `model`; `NULL` is a no-op. Do not use the handle afterward. Derived processors, VADs and analyzers retain the underlying model through reference counting. A borrowed buffer still belongs to the caller and must outlive those objects. Stop all users of this handle before destroying it. No return value. ## `aic_model_get_id` ```c theme={null} const char *aic_model_get_id(const struct AicModel *model); ``` Returns the borrowed, null-terminated UTF-8 model ID for `model`, or `NULL` for a null handle. The string belongs to the model handle and becomes invalid when that handle is destroyed. Copy it if you need it afterward; do not free or modify it. ## `aic_model_get_optimal_sample_rate` ```c theme={null} enum AicErrorCode aic_model_get_optimal_sample_rate(const struct AicModel *model, uint32_t *sample_rate); ``` Writes the native model sample rate in Hz to `sample_rate`. `model` and the writable output pointer must be non-null. Returns `SUCCESS` or `NULL_POINTER`. This is a metadata query, not initialization. ## `aic_model_get_optimal_block_size` ```c theme={null} enum AicErrorCode aic_model_get_optimal_block_size(const struct AicModel *model, uint32_t sample_rate, size_t *block_size); ``` Writes the model hop size converted to the requested `sample_rate` in Hz into `block_size`, measured in mono samples. `model` and the writable output pointer must be non-null. Returns `SUCCESS` or `NULL_POINTER`; this query does not validate whether the requested rate is supported. Validate rates during initialization. The native rate and optimal block size avoid unnecessary resampling and block buffering. ## Related [C API index](/reference/sdk/api/c/index) · [C examples](/reference/sdk/examples#c) · [Compatibility](/reference/sdk/compatibility-matrix) ## Example: read model metadata This helper loads a model and returns its native rate. It does not create a licensed processing session. ```c theme={null} #include "aic.h" AicErrorCode read_native_rate(const char *path, uint32_t *rate) { AicModel *model = NULL; AicErrorCode error = aic_model_create_from_file(&model, path); if (error != AIC_ERROR_CODE_SUCCESS) return error; error = aic_model_get_optimal_sample_rate(model, rate); aic_model_destroy(model); return error; } ``` # C enhancement and processor control Source: https://docs.ai-coustics.com/reference/sdk/api/c/processing Create and initialize an enhancement processor, process mono audio and control stream state. All functions on this page are from C SDK **0.26.0**, core **0.26.0**. Include `aic.h` and link the matching native library. Start with the [C integration guide](/reference/sdk/language-bindings/c). The [pointer and error contract](/reference/sdk/api/c/errors-and-types#pointer-contract) applies to every signature below. Error names in prose omit the `AIC_ERROR_CODE_` prefix. There are no default C arguments; optional pointers are stated explicitly. ## `AicProcessorParameter` | Constant | Value | Range and default | | - | - | - | | `AIC_PROCESSOR_PARAMETER_BYPASS` | 0 | Value 0 disables bypass; any value greater than 0 and at most 1 enables it. Default: off. Getter returns 0 or 1. Bypass keeps delay alignment. | | `AIC_PROCESSOR_PARAMETER_ENHANCEMENT_LEVEL` | 1 | 0–1 inclusive. Default comes from model metadata, falling back to 1. The model can also scale the effective strength. | Use normalized mono float32 samples, nominally -1.0 to 1.0. Keep audio storage valid during each call. [Audio format](/reference/concepts/audio-format) explains block sizing; [streams and state](/reference/concepts/streams-and-state) explains discontinuities. ## `aic_processor_create` ```c theme={null} enum AicErrorCode aic_processor_create(struct AicProcessor **processor, const struct AicModel *model, const char *license_key, const struct AicOtelConfig *otel_config); ``` `processor` is a writable output slot. `model` must be an enhancement or bypass model; `license_key` is a null-terminated SDK key or supported bearer token. `otel_config` may be `NULL` to use environment defaults, or point to [AicOtelConfig](/reference/sdk/api/c/models-and-config#AicOtelConfig). The function copies configuration strings and retains model data internally. On success, destroy the owned processor handle separately. Errors include `NULL_POINTER`, `MODEL_TYPE_UNSUPPORTED`, license errors and `INTERNAL_ERROR`. Construction allocates resources and may start session work; keep it outside an audio callback. ## `aic_processor_destroy` ```c theme={null} void aic_processor_destroy(struct AicProcessor *processor); ``` Releases `processor` and its model reference and ends its associated session. `NULL` is a no-op. Stop processing and other calls that use this handle first. Context handles are independent and must be destroyed separately. Teardown can block; keep it outside an audio callback. No return value. ## `aic_processor_initialize` ```c theme={null} enum AicErrorCode aic_processor_initialize(struct AicProcessor *processor, uint32_t sample_rate, size_t block_size, bool variable_block_size); ``` Configures `processor` for `sample_rate` in Hz (8,000–192,000 inclusive), a positive `block_size` in mono samples and `variable_block_size`. With `false`, every call must supply exactly `block_size`; with `true`, that value is the maximum per call. Reinitialization resets processing state. Returns `SUCCESS`, `NULL_POINTER` or `AUDIO_CONFIG_UNSUPPORTED`. A failed initialization leaves the object uninitialized; initialize successfully before processing again. Allocates internal buffers; do not call concurrently with processing. ## `aic_processor_process` ```c theme={null} enum AicErrorCode aic_processor_process(struct AicProcessor *processor, float *audio_ptr, size_t audio_len); ``` `audio_ptr` points to `audio_len` writable contiguous mono float32 samples. Processing modifies the buffer in place, retains stream state and returns only after using the buffer. Keep one processor per independent stream. Returns `SUCCESS`, `NULL_POINTER`, `NOT_INITIALIZED`, `AUDIO_CONFIG_MISMATCH` or `PROCESSING_NOT_ALLOWED` (and internal failures). A disallowed call can already have advanced buffering or written delayed input; do not treat error output as enhanced audio. Do not process the same object concurrently. ## `aic_processor_terminate_session` ```c theme={null} enum AicErrorCode aic_processor_terminate_session(struct AicProcessor *processor); ``` Requests termination of the session associated with `processor`. Returns `SUCCESS` after requesting it, or `NULL_POINTER`. Termination is handled asynchronously; a successful return does not prove remote acknowledgment or immediate processing denial. For credentials with no telemetry session, this is a no-op. It does not destroy the handle. Stop application processing explicitly and destroy the object when finished. On native targets, terminating the final active session may wait for the shared telemetry tasks to finish. Call it outside the audio callback. ## `aic_processor_context_create` ```c theme={null} enum AicErrorCode aic_processor_context_create(struct AicProcessorContext **context, const struct AicProcessor *processor); ``` `context` is a writable output slot; `processor` is the source object. Returns a separately owned context with shared control state. It can outlive the source object, but no new audio is processed after the source is destroyed. Returns `SUCCESS` or `NULL_POINTER`. Allocate outside the callback and destroy the context separately. ## `aic_processor_context_destroy` ```c theme={null} void aic_processor_context_destroy(struct AicProcessorContext *context); ``` Releases `context`; `NULL` is a no-op. Stop users of this context handle first. This does not destroy the processing object. No return value. ## `aic_processor_context_reset` ```c theme={null} enum AicErrorCode aic_processor_context_reset(const struct AicProcessorContext *context); ``` Requests a reset of the stream buffers and model state, applied at the next processing call. Audio configuration and parameter values remain in place. Any energy VAD on the same processor is reset as well. `context` must be valid. Returns `SUCCESS` or `NULL_POINTER`. The shared control operation can run alongside processing; coordinate a stream boundary if you need a precise reset position. ## `aic_processor_context_set_parameter` ```c theme={null} enum AicErrorCode aic_processor_context_set_parameter(const struct AicProcessorContext *context, enum AicProcessorParameter parameter, float value); ``` Sets `parameter` to `value` through shared control state. Use only the declared [AicProcessorParameter](/reference/sdk/api/c/processing#AicProcessorParameter) values and documented ranges. Returns `SUCCESS`, `NULL_POINTER` or `PARAMETER_OUT_OF_RANGE`; NaN is out of range. Updates may run alongside processing. No ownership transfer. ## `aic_processor_context_get_parameter` ```c theme={null} enum AicErrorCode aic_processor_context_get_parameter(const struct AicProcessorContext *context, enum AicProcessorParameter parameter, float *value); ``` Writes the current `parameter` value to the non-null writable `value` pointer. Use a declared enum value. Returns `SUCCESS` or `NULL_POINTER`. Shared control reads can run alongside processing. ## `aic_processor_context_get_audio_delay` ```c theme={null} enum AicErrorCode aic_processor_context_get_audio_delay(const struct AicProcessorContext *context, size_t *delay); ``` Writes the current audio delay to `delay`, measured in samples at the initialized host rate. Query after successful initialization and again if you reinitialize. Both `context` and writable `delay` must be non-null. Returns `SUCCESS` or `NULL_POINTER`. This shared metadata read can run alongside processing; it is not elapsed CPU time. ## `aic_processor_context_update_bearer_token` ```c theme={null} enum AicErrorCode aic_processor_context_update_bearer_token(const struct AicProcessorContext *context, const char *token); ``` Updates credentials through `context` using null-terminated UTF-8 `token`. Both the original credential and replacement must use the supported JWT form. Returns `SUCCESS`, `NULL_POINTER`, `LICENSE_FORMAT_INVALID`, other license errors or `TOKEN_UPDATE_UNSUPPORTED`. Success updates local credential state; it does not prove backend acceptance. This is a control-thread operation, not an audio-callback operation. See [authentication](/models/get-started/authenticate-apps). ## Related [C API index](/reference/sdk/api/c/index) · [C examples](/reference/sdk/examples#c) · [Compatibility](/reference/sdk/compatibility-matrix) ## Example: process one initialized stream block Call this helper repeatedly with an initialized processor and its context. Each successful call modifies the audio buffer. Read the delay after initialization to align output. ```c theme={null} #include "aic.h" AicErrorCode process_block(AicProcessor *processor, AicProcessorContext *context, float *audio, size_t count, size_t *delay) { AicErrorCode error = aic_processor_context_get_audio_delay(context, delay); if (error != AIC_ERROR_CODE_SUCCESS) return error; return aic_processor_process(processor, audio, count); } ``` # C voice activity detection Source: https://docs.ai-coustics.com/reference/sdk/api/c/vad Process a dedicated VAD model and read its probability and filtered speech decision. All functions on this page are from C SDK **0.26.0**, core **0.26.0**. Include `aic.h` and link the matching native library. Start with the [C integration guide](/reference/sdk/language-bindings/c). The [pointer and error contract](/reference/sdk/api/c/errors-and-types#pointer-contract) applies to every signature below. Error names in prose omit the `AIC_ERROR_CODE_` prefix. There are no default C arguments; optional pointers are stated explicitly. ## `AicVadParameter` All defaults are model-specific. Read the current values through `aic_vad_context_get_parameter` or `aic_energy_vad_context_get_parameter` after creation. | Constant | Value | Units and constraints | | - | - | - | | `AIC_VAD_PARAMETER_SPEECH_HOLD_DURATION` | 0 | Seconds, from zero to the model/window-dependent maximum. Holds the speech decision through short gaps; internal decisions are quantized to model frames. | | `AIC_VAD_PARAMETER_SENSITIVITY` | 1 | Meaning depends on the detector. On a dedicated VAD model, a probability threshold, 0–1 inclusive, where a higher threshold requires stronger evidence of speech. On an energy VAD (`AicEnergyVadContext`), the energy threshold of the enhanced signal, computed as `10 ^ (-sensitivity)` over 1–15 inclusive, where higher values detect quieter speech. | | `AIC_VAD_PARAMETER_MINIMUM_SPEECH_DURATION` | 2 | Seconds, 0–1 inclusive. Requires sustained speech before the decision becomes true. | Use a dedicated [ai-coustics VAD model](/models/voice-activity-detection/vad) and mono float32 audio. An enhancement model is not accepted by `aic_vad_create`; to detect speech with an enhancement model, create an energy VAD handle with [`aic_energy_vad_context_create`](/reference/sdk/api/c/vad#aic_energy_vad_context_create) instead. ## `aic_vad_create` ```c theme={null} enum AicErrorCode aic_vad_create(struct AicVad **vad, const struct AicModel *model, const char *license_key, const struct AicOtelConfig *otel_config); ``` `vad` is a writable output slot. `model` must be a VAD model; `license_key` is a null-terminated SDK key or supported bearer token. `otel_config` may be `NULL` to use environment defaults, or point to [AicOtelConfig](/reference/sdk/api/c/models-and-config#AicOtelConfig). The function copies configuration strings and retains model data internally. On success, destroy the owned VAD handle separately. Errors include `NULL_POINTER`, `MODEL_TYPE_UNSUPPORTED`, license errors and `INTERNAL_ERROR`. Construction allocates resources and may start session work; keep it outside an audio callback. ## `aic_vad_destroy` ```c theme={null} void aic_vad_destroy(struct AicVad *vad); ``` Releases `vad` and its model reference and ends its associated session. `NULL` is a no-op. Stop processing and other calls that use this handle first. Context handles are independent and must be destroyed separately. Teardown can block; keep it outside an audio callback. No return value. ## `aic_vad_initialize` ```c theme={null} enum AicErrorCode aic_vad_initialize(struct AicVad *vad, uint32_t sample_rate, size_t block_size, bool variable_block_size); ``` Configures `vad` for `sample_rate` in Hz (8,000–192,000 inclusive), a positive `block_size` in mono samples and `variable_block_size`. With `false`, every call must supply exactly `block_size`; with `true`, that value is the maximum per call. Reinitialization resets processing state. Returns `SUCCESS`, `NULL_POINTER` or `AUDIO_CONFIG_UNSUPPORTED`. A failed initialization leaves the object uninitialized; initialize successfully before processing again. Allocates internal buffers; do not call concurrently with processing. ## `aic_vad_process` ```c theme={null} enum AicErrorCode aic_vad_process(struct AicVad *vad, const float *audio_ptr, size_t audio_len); ``` `audio_ptr` points to `audio_len` readable contiguous mono float32 samples. The binding copies them to its internal buffer; the caller's input is unchanged. Processing updates the context's latest decision and probability. Returns `SUCCESS`, `NULL_POINTER`, `NOT_INITIALIZED`, `AUDIO_CONFIG_MISMATCH` or `PROCESSING_NOT_ALLOWED` (and internal failures). Read a fresh decision only after a successful call. Do not process the same object concurrently. ## `aic_vad_terminate_session` ```c theme={null} enum AicErrorCode aic_vad_terminate_session(struct AicVad *vad); ``` Requests termination of the session associated with `vad`. Returns `SUCCESS` after requesting it, or `NULL_POINTER`. Termination is handled asynchronously; a successful return does not prove remote acknowledgment or immediate processing denial. For credentials with no telemetry session, this is a no-op. It does not destroy the handle. Stop application processing explicitly and destroy the object when finished. On native targets, terminating the final active session may wait for the shared telemetry tasks to finish. Call it outside the audio callback. ## `aic_vad_context_create` ```c theme={null} enum AicErrorCode aic_vad_context_create(struct AicVadContext **context, const struct AicVad *vad); ``` `context` is a writable output slot; `vad` is the source object. Returns a separately owned context with shared control state. It can outlive the source object, but no new audio is processed after the source is destroyed. Returns `SUCCESS` or `NULL_POINTER` (or `INTERNAL_ERROR` if the VAD context is unavailable). Allocate outside the callback and destroy the context separately. ## `aic_vad_context_destroy` ```c theme={null} void aic_vad_context_destroy(struct AicVadContext *context); ``` Releases `context`; `NULL` is a no-op. Stop users of this context handle first. This does not destroy the processing object. No return value. ## `aic_vad_context_reset` ```c theme={null} enum AicErrorCode aic_vad_context_reset(const struct AicVadContext *context); ``` Requests processing-state reset for the next call and immediately clears the published speech decision to false and raw probability to zero. Audio configuration and parameter values remain in place. `context` must be valid. Returns `SUCCESS` or `NULL_POINTER`. The shared control operation can run alongside processing; coordinate a stream boundary if you need a precise reset position. ## `aic_vad_context_set_parameter` ```c theme={null} enum AicErrorCode aic_vad_context_set_parameter(const struct AicVadContext *context, enum AicVadParameter parameter, float value); ``` Sets `parameter` to `value` through shared control state. Use only the declared [AicVadParameter](/reference/sdk/api/c/vad#AicVadParameter) values and documented ranges. Returns `SUCCESS`, `NULL_POINTER` or `PARAMETER_OUT_OF_RANGE`; NaN is out of range. Updates may run alongside processing. No ownership transfer. ## `aic_vad_context_get_parameter` ```c theme={null} enum AicErrorCode aic_vad_context_get_parameter(const struct AicVadContext *context, enum AicVadParameter parameter, float *value); ``` Writes the current `parameter` value to the non-null writable `value` pointer. Use a declared enum value. Returns `SUCCESS` or `NULL_POINTER`. Shared control reads can run alongside processing. VAD duration values are stored in seconds; model-frame quantization affects decisions. ## `aic_vad_context_get_prediction_delay` ```c theme={null} enum AicErrorCode aic_vad_context_get_prediction_delay(const struct AicVadContext *context, size_t *delay); ``` Writes the current prediction delay to `delay`, measured in samples at the initialized host rate. Query after successful initialization and again if you reinitialize. Both `context` and writable `delay` must be non-null. Returns `SUCCESS` or `NULL_POINTER`. This shared metadata read can run alongside processing; it is not elapsed CPU time. ## `aic_vad_context_update_bearer_token` ```c theme={null} enum AicErrorCode aic_vad_context_update_bearer_token(const struct AicVadContext *context, const char *token); ``` Updates credentials through `context` using null-terminated UTF-8 `token`. Both the original credential and replacement must use the supported JWT form. Returns `SUCCESS`, `NULL_POINTER`, `LICENSE_FORMAT_INVALID`, other license errors or `TOKEN_UPDATE_UNSUPPORTED`. Success updates local credential state; it does not prove backend acceptance. This is a control-thread operation, not an audio-callback operation. See [authentication](/models/get-started/authenticate-apps). ## `aic_vad_context_is_speech_detected` ```c theme={null} enum AicErrorCode aic_vad_context_is_speech_detected(const struct AicVadContext *context, bool *value); ``` Writes the latest filtered speech decision into the writable `value` pointer. Returns `SUCCESS` or `NULL_POINTER`. This does not process audio; call `aic_vad_process` first and check its result. It combines model probability, sensitivity, minimum speech duration and hold behavior. Safe to read alongside processing while the context remains alive. ## `aic_vad_context_get_raw_vad_probability` ```c theme={null} enum AicErrorCode aic_vad_context_get_raw_vad_probability(const struct AicVadContext *context, float *value); ``` Writes the latest model speech probability into the writable `value` pointer. Returns `SUCCESS` or `NULL_POINTER`. This is the probability before duration filtering, not the final speech decision. It does not process audio. Safe to read alongside processing while the context remains alive. ## `aic_energy_vad_context_create` ```c theme={null} enum AicErrorCode aic_energy_vad_context_create(struct AicEnergyVadContext **context, const struct AicProcessor *processor); ``` `context` is a writable output slot; `processor` is an enhancement processor. Returns a separately owned handle to that processor's energy VAD, which detects speech from the enhanced signal before output mixing and runs no separate model. Detection advances with `aic_processor_process`; there is no separate process call. Every handle from one processor refers to the same energy VAD. Creating a handle keeps enhancement inference active even when the processor is bypassed or its enhancement level is zero, and it stays active for the processor's lifetime after all handles are destroyed. The handle can outlive the processor, but publishes no new predictions once the processor is destroyed. Returns `SUCCESS`, `NULL_POINTER` or `MODEL_TYPE_UNSUPPORTED` when the processor does not support energy VAD. Allocates memory; keep it outside an audio callback and do not use or destroy the processor from another thread during the call. ## `aic_energy_vad_context_destroy` ```c theme={null} void aic_energy_vad_context_destroy(struct AicEnergyVadContext *context); ``` Releases `context`; `NULL` is a no-op. This does not destroy the backing processor or disable its energy VAD; call `aic_processor_destroy` separately. Stop users of this handle first. Deallocates memory, so keep it outside an audio callback. No return value. ## `aic_energy_vad_context_reset` ```c theme={null} enum AicErrorCode aic_energy_vad_context_reset(const struct AicEnergyVadContext *context); ``` Clears the energy VAD state and the published speech decision. Use it when the stream is interrupted or when seeking. Parameter values are retained and the backing processor is not reset; `aic_processor_context_reset` also resets the energy VAD. `context` must be valid. Returns `SUCCESS` or `NULL_POINTER`. Real-time safe and callable from any thread. ## `aic_energy_vad_context_set_parameter` ```c theme={null} enum AicErrorCode aic_energy_vad_context_set_parameter(const struct AicEnergyVadContext *context, enum AicVadParameter parameter, float value); ``` Sets `parameter` to `value`. Use the declared [AicVadParameter](/reference/sdk/api/c/vad#AicVadParameter) values; `AIC_VAD_PARAMETER_SENSITIVITY` takes the energy range, 1.0 to 15.0, on this handle. Returns `SUCCESS`, `NULL_POINTER` or `PARAMETER_OUT_OF_RANGE`. All parameters can be changed during processing, from any thread. ## `aic_energy_vad_context_get_parameter` ```c theme={null} enum AicErrorCode aic_energy_vad_context_get_parameter(const struct AicEnergyVadContext *context, enum AicVadParameter parameter, float *value); ``` Writes the current `parameter` value to the non-null writable `value` pointer. Use a declared enum value. Returns `SUCCESS` or `NULL_POINTER`. Real-time safe and callable from any thread. ## `aic_energy_vad_context_is_speech_detected` ```c theme={null} enum AicErrorCode aic_energy_vad_context_is_speech_detected(const struct AicEnergyVadContext *context, bool *value); ``` Writes the energy VAD's prediction into the writable `value` pointer. It is false before audio is processed and after a reset, and stops updating if the backing processor stops being processed. The decision lags its input by `aic_energy_vad_context_get_prediction_delay` samples; speech hold and minimum speech duration affect its timing further. Returns `SUCCESS` or `NULL_POINTER`. Real-time safe and callable from any thread. ## `aic_energy_vad_context_get_prediction_delay` ```c theme={null} enum AicErrorCode aic_energy_vad_context_get_prediction_delay(const struct AicEnergyVadContext *context, size_t *delay); ``` Writes the prediction delay in samples to `delay`, covering input reblocking, STFT and enhancement model processing. It equals `aic_processor_context_get_audio_delay` for the backing processor; energy detection adds no audio delay. Speech hold and minimum speech duration affect decision timing and are not included. Before initialization the value uses the processor's optimal block size at its native sample rate. After initialization it is expressed in samples at the rate given to `aic_processor_initialize` and includes input-buffering latency for the configured block size, which a non-optimal or variable block size increases. Convert with `delay_ms = (delay_samples * 1000) / sample_rate`. Both pointers must be non-null. Returns `SUCCESS` or `NULL_POINTER`. Real-time safe and callable from any thread. ## Related [C API index](/reference/sdk/api/c/index) · [C examples](/reference/sdk/examples#c) · [Compatibility](/reference/sdk/compatibility-matrix) ## Example: read a fresh decision Use an initialized VAD and its context. The input is read-only; the decision is written only after successful processing. ```c theme={null} #include "aic.h" AicErrorCode detect_block(AicVad *vad, AicVadContext *context, const float *audio, size_t count, bool *speech) { AicErrorCode error = aic_vad_process(vad, audio, count); if (error != AIC_ERROR_CODE_SUCCESS) return error; return aic_vad_context_is_speech_detected(context, speech); } ``` # C++ audio analysis Source: https://docs.ai-coustics.com/reference/sdk/api/cpp/analysis Collect mono audio and compute a checked Tyto analysis result. C++ wrapper **0.26.0**, core **0.26.0**, C++11 or newer. Include `aic.hpp` and link the matching wrapper/native libraries. Start with the [C++ integration guide](/reference/sdk/language-bindings/cpp). All names below are in namespace `aic`. Check [Result and error handling](/reference/sdk/api/cpp/results-and-errors) before extracting a factory result. Ordinary C++ allocation or string operations can still throw; SDK status failures use the declared return values. ## `aic::AnalyzerPair` Owns a `Collector` and `Analyzer` created together. The members are move-only, so the pair is move-only too. Its implicit destructor destroys both members. The wrapper supplies a static factory, not a public default factory. Use a [Tyto analysis model](/models/audio-insight/tyto). | Public field | Type | Ownership | | - | - | - | | `collector` | `Collector` | Owned value. Can be moved to its processing thread; arrange shutdown before destruction. | | `analyzer` | `Analyzer` | Owned value. Can be moved to its processing thread; arrange shutdown before destruction. | ### `aic::AnalyzerPair::create` ```cpp theme={null} static Result create(const Model& model, const std::string& license_key); ``` Creates the pair from an analysis `model` and SDK key or supported bearer token in `license_key`. The analyzer retains model data. Check the result before taking the pair. Errors include `ModelTypeUnsupported`, license errors and `InternalError`. The collector still needs initialization. There is no `OtelConfig` argument: this creation path disables optional OTel export; SDK session requirements remain separate. ## `aic::Collector` Owns one native handle. Its destructor releases that handle; do not destroy or move the object while another thread uses it. Construction/destruction can allocate or block, so keep them outside the audio callback. The default constructor and raw-handle constructor are private: use the documented factory. | Member | Contract | | - | - | | `~Collector()` | Releases the native handle if non-null. | | `Collector(Collector&& other) noexcept` | Transfers the handle and clears the source. Do not call processing/getter methods on the moved-from object. | | `Collector& operator=(Collector&& other) noexcept` | Releases the destination's old handle, transfers ownership and clears the source. Self-move is guarded; returns `*this`. | | `Collector(const Collector&) = delete` | Copy construction is unavailable. | | `Collector& operator=(const Collector&) = delete` | Copy assignment is unavailable. | ### `aic::Collector::initialize` ```cpp theme={null} ErrorCode initialize(uint32_t sample_rate, size_t block_size, bool variable_block_size); ``` Sets the host rate (8,000–192,000 Hz), positive mono block size and fixed/variable mode. Fixed input must match the block size; variable input cannot exceed it. Returns `Success`, `AudioConfigUnsupported` or `NullPointer`. Failure leaves the collector uninitialized. Initializes buffers outside the callback; do not reinitialize concurrently with collection. ### `aic::Collector::buffer` ```cpp theme={null} ErrorCode buffer(const float* audio, size_t audio_len); ``` Collects `audio_len` mono float32 samples from `audio`, without modifying caller input. Returns `Success`, `NullPointer`, `NotInitialized` or `AudioConfigMismatch`. Collection updates the analysis window; it does not return scores. One thread may collect while another runs the paired analyzer. Serialize calls on the collector itself. ## `aic::Analyzer` Owns one native handle. Its destructor releases that handle; do not destroy or move the object while another thread uses it. Construction/destruction can allocate or block, so keep them outside the audio callback. The default constructor and raw-handle constructor are private: use the documented factory. | Member | Contract | | - | - | | `~Analyzer()` | Releases the native handle if non-null. | | `Analyzer(Analyzer&& other) noexcept` | Transfers the handle and clears the source. Do not call processing/getter methods on the moved-from object. | | `Analyzer& operator=(Analyzer&& other) noexcept` | Releases the destination's old handle, transfers ownership and clears the source. Self-move is guarded; returns `*this`. | | `Analyzer(const Analyzer&) = delete` | Copy construction is unavailable. | | `Analyzer& operator=(const Analyzer&) = delete` | Copy assignment is unavailable. | ### `aic::Analyzer::reset` ```cpp theme={null} ErrorCode reset() const; ``` Requests a reset of the paired collection pipeline. The next collection call clears stream state; analysis while reset is pending uses an empty padded window. Returns `Success` or `NullPointer`. Coordinate boundaries between unrelated recordings; audio configuration remains in place. ### `aic::Analyzer::analyze_buffered` ```cpp theme={null} Result analyze_buffered(); ``` Analyzes the latest fixed-size feature snapshot. Early windows are silence-padded; repeated calls without new input can score the same window. On success, returns all seven fields. On failure, `error` identifies `ProcessingNotAllowed`, `InternalError` or `NullPointer` and `value` is zero-initialized; those zeros are not valid scores. Analyze off the audio thread and serialize analyzer calls. The paired collector may continue feeding on another thread. ### `aic::Analyzer::terminate_session` ```cpp theme={null} ErrorCode terminate_session(); ``` Requests asynchronous session termination. Returns `Success` or `NullPointer`; no-op when no session exists. Does not destroy the pair or prove backend acknowledgment. Stop application analysis and destroy both objects when finished. On native targets, terminating the final active session may wait for the shared telemetry tasks to finish. Call it outside the audio callback. ### `aic::Analyzer::update_bearer_token` ```cpp theme={null} ErrorCode update_bearer_token(const std::string& token) const; ``` Uses `token.c_str()` to replace local JWT-form credentials. The original credential must also be JWT-form. Returns `Success`, `LicenseFormatInvalid`, other license errors or `TokenUpdateUnsupported` (and `NullPointer` for an invalid handle). Run on a control thread. Success is local replacement, not backend acknowledgment. ## `aic::AnalysisResult` A value struct returned inside `Result`. Read it only after `ok()` succeeds. All seven fields are `float`. Default initialization does not initialize built-in fields; value initialization with `{}` zeros them. Neither form proves an analysis ran. ```cpp theme={null} struct AnalysisResult { float risk_score; float speaker_reverb; float speaker_loudness; float interfering_speech; float noise; float codec_degradation; float packet_loss; }; ``` | Field | Meaning | | - | - | | `risk_score` | Combined model risk score weighted by model metadata. Lower indicates less problematic audio. | | `speaker_reverb` | Main-speaker distance/reverberation indicator. | | `speaker_loudness` | Main-speaker level indicator; a higher value is not automatically worse. | | `interfering_speech` | Maximum of the background-speaker and background-media interference outputs. | | `noise` | Background-noise indicator. | | `codec_degradation` | Speech-codec artifact indicator. | | `packet_loss` | Dropout/discontinuity indicator. | Read [Tyto dimensions](/models/audio-insight/tyto#tyto-dimensions) before choosing thresholds. Model scores are estimates, not a measured word error rate. [C++ API index](/reference/sdk/api/cpp/index) · [Released analysis example](https://github.com/ai-coustics/aic-sdk-cpp/blob/0.26.0/example/analyzer.cpp) ## Example: check before reading a score Run this helper off the audio thread with an analyzer whose paired collector has been initialized and fed. ```cpp theme={null} #include "aic.hpp" aic::ErrorCode read_risk(aic::Analyzer& analyzer, float& risk) { auto result = analyzer.analyze_buffered(); if (!result.ok()) return result.error; risk = result.value.risk_score; return aic::ErrorCode::Success; } ``` # C++ API reference Source: https://docs.ai-coustics.com/reference/sdk/api/cpp/index Complete C++11 wrapper types, members, factories and ownership contracts. C++ wrapper **0.26.0** uses core **0.26.0** and model file format **8**. This reference covers the 16 public named types and two free functions in namespace `aic`, including fields, enum members, constructor overloads, moves and deleted copies. Start with the [C++ integration guide](/reference/sdk/language-bindings/cpp) for installation and a complete audio example. The wrapper has no model-downloader, file-decoder, async-processing or `initialize(ProcessorConfig)` overload. Use the three-argument initializers and arrange application threads explicitly. Private constructors, native handle fields and wrapper-registration helpers are not public API. ## Browse by task | Task | Reference | | - | - | | Load a model or inspect configuration | [Models and configuration](/reference/sdk/api/cpp/models-and-config) | | Enhance audio and control a stream | [Processing](/reference/sdk/api/cpp/processing) | | Detect speech with a dedicated model, or from an enhancement processor | [VAD](/reference/sdk/api/cpp/vad) | | Collect audio and analyze Tyto scores | [Analysis](/reference/sdk/api/cpp/analysis) | | Extract a factory result or handle an error | [Results and errors](/reference/sdk/api/cpp/results-and-errors) | ## Alphabetical symbol index Constructor and assignment suffixes distinguish move and deleted copy overloads. All names refer to namespace `aic`. | Public symbol | Definition | | - | - | | `aic::AnalysisResult` | [Reference](/reference/sdk/api/cpp/analysis#aic-AnalysisResult) | | `aic::AnalysisResult::codec_degradation` | [Reference](/reference/sdk/api/cpp/analysis#aic-AnalysisResult-codec_degradation) | | `aic::AnalysisResult::interfering_speech` | [Reference](/reference/sdk/api/cpp/analysis#aic-AnalysisResult-interfering_speech) | | `aic::AnalysisResult::noise` | [Reference](/reference/sdk/api/cpp/analysis#aic-AnalysisResult-noise) | | `aic::AnalysisResult::packet_loss` | [Reference](/reference/sdk/api/cpp/analysis#aic-AnalysisResult-packet_loss) | | `aic::AnalysisResult::risk_score` | [Reference](/reference/sdk/api/cpp/analysis#aic-AnalysisResult-risk_score) | | `aic::AnalysisResult::speaker_loudness` | [Reference](/reference/sdk/api/cpp/analysis#aic-AnalysisResult-speaker_loudness) | | `aic::AnalysisResult::speaker_reverb` | [Reference](/reference/sdk/api/cpp/analysis#aic-AnalysisResult-speaker_reverb) | | `aic::Analyzer` | [Reference](/reference/sdk/api/cpp/analysis#aic-Analyzer) | | `aic::Analyzer::analyze_buffered` | [Reference](/reference/sdk/api/cpp/analysis#aic-Analyzer-analyze_buffered) | | `aic::Analyzer::Analyzer-copy` | [Reference](/reference/sdk/api/cpp/analysis#aic-Analyzer-Analyzer-copy) | | `aic::Analyzer::Analyzer-move` | [Reference](/reference/sdk/api/cpp/analysis#aic-Analyzer-Analyzer-move) | | `aic::Analyzer::operator=-copy` | [Reference](/reference/sdk/api/cpp/analysis#aic-Analyzer-operatorassign-copy) | | `aic::Analyzer::operator=-move` | [Reference](/reference/sdk/api/cpp/analysis#aic-Analyzer-operatorassign-move) | | `aic::Analyzer::reset` | [Reference](/reference/sdk/api/cpp/analysis#aic-Analyzer-reset) | | `aic::Analyzer::terminate_session` | [Reference](/reference/sdk/api/cpp/analysis#aic-Analyzer-terminate_session) | | `aic::Analyzer::update_bearer_token` | [Reference](/reference/sdk/api/cpp/analysis#aic-Analyzer-update_bearer_token) | | `aic::Analyzer::~Analyzer` | [Reference](/reference/sdk/api/cpp/analysis#aic-Analyzer-destructor-Analyzer) | | `aic::AnalyzerPair` | [Reference](/reference/sdk/api/cpp/analysis#aic-AnalyzerPair) | | `aic::AnalyzerPair::analyzer` | [Reference](/reference/sdk/api/cpp/analysis#aic-AnalyzerPair-analyzer) | | `aic::AnalyzerPair::collector` | [Reference](/reference/sdk/api/cpp/analysis#aic-AnalyzerPair-collector) | | `aic::AnalyzerPair::create` | [Reference](/reference/sdk/api/cpp/analysis#aic-AnalyzerPair-create) | | `aic::Collector` | [Reference](/reference/sdk/api/cpp/analysis#aic-Collector) | | `aic::Collector::buffer` | [Reference](/reference/sdk/api/cpp/analysis#aic-Collector-buffer) | | `aic::Collector::Collector-copy` | [Reference](/reference/sdk/api/cpp/analysis#aic-Collector-Collector-copy) | | `aic::Collector::Collector-move` | [Reference](/reference/sdk/api/cpp/analysis#aic-Collector-Collector-move) | | `aic::Collector::initialize` | [Reference](/reference/sdk/api/cpp/analysis#aic-Collector-initialize) | | `aic::Collector::operator=-copy` | [Reference](/reference/sdk/api/cpp/analysis#aic-Collector-operatorassign-copy) | | `aic::Collector::operator=-move` | [Reference](/reference/sdk/api/cpp/analysis#aic-Collector-operatorassign-move) | | `aic::Collector::~Collector` | [Reference](/reference/sdk/api/cpp/analysis#aic-Collector-destructor-Collector) | | `aic::EnergyVadContext` | [Reference](/reference/sdk/api/cpp/vad#aic-EnergyVadContext) | | `aic::EnergyVadContext::EnergyVadContext-copy` | [Reference](/reference/sdk/api/cpp/vad#aic-EnergyVadContext-EnergyVadContext-copy) | | `aic::EnergyVadContext::EnergyVadContext-move` | [Reference](/reference/sdk/api/cpp/vad#aic-EnergyVadContext-EnergyVadContext-move) | | `aic::EnergyVadContext::get_parameter` | [Reference](/reference/sdk/api/cpp/vad#aic-EnergyVadContext-get_parameter) | | `aic::EnergyVadContext::get_prediction_delay` | [Reference](/reference/sdk/api/cpp/vad#aic-EnergyVadContext-get_prediction_delay) | | `aic::EnergyVadContext::is_speech_detected` | [Reference](/reference/sdk/api/cpp/vad#aic-EnergyVadContext-is_speech_detected) | | `aic::EnergyVadContext::operator=-copy` | [Reference](/reference/sdk/api/cpp/vad#aic-EnergyVadContext-operatorassign-copy) | | `aic::EnergyVadContext::operator=-move` | [Reference](/reference/sdk/api/cpp/vad#aic-EnergyVadContext-operatorassign-move) | | `aic::EnergyVadContext::reset` | [Reference](/reference/sdk/api/cpp/vad#aic-EnergyVadContext-reset) | | `aic::EnergyVadContext::set_parameter` | [Reference](/reference/sdk/api/cpp/vad#aic-EnergyVadContext-set_parameter) | | `aic::EnergyVadContext::~EnergyVadContext` | [Reference](/reference/sdk/api/cpp/vad#aic-EnergyVadContext-destructor-EnergyVadContext) | | `aic::ErrorCode` | [Reference](/reference/sdk/api/cpp/results-and-errors#aic-ErrorCode) | | `aic::ErrorCode::AudioConfigMismatch` | [Reference](/reference/sdk/api/cpp/results-and-errors#aic-ErrorCode-AudioConfigMismatch) | | `aic::ErrorCode::AudioConfigUnsupported` | [Reference](/reference/sdk/api/cpp/results-and-errors#aic-ErrorCode-AudioConfigUnsupported) | | `aic::ErrorCode::FilePathInvalid` | [Reference](/reference/sdk/api/cpp/results-and-errors#aic-ErrorCode-FilePathInvalid) | | `aic::ErrorCode::FileSystemError` | [Reference](/reference/sdk/api/cpp/results-and-errors#aic-ErrorCode-FileSystemError) | | `aic::ErrorCode::InternalError` | [Reference](/reference/sdk/api/cpp/results-and-errors#aic-ErrorCode-InternalError) | | `aic::ErrorCode::LicenseExpired` | [Reference](/reference/sdk/api/cpp/results-and-errors#aic-ErrorCode-LicenseExpired) | | `aic::ErrorCode::LicenseFormatInvalid` | [Reference](/reference/sdk/api/cpp/results-and-errors#aic-ErrorCode-LicenseFormatInvalid) | | `aic::ErrorCode::LicenseVersionUnsupported` | [Reference](/reference/sdk/api/cpp/results-and-errors#aic-ErrorCode-LicenseVersionUnsupported) | | `aic::ErrorCode::ModelDataUnaligned` | [Reference](/reference/sdk/api/cpp/results-and-errors#aic-ErrorCode-ModelDataUnaligned) | | `aic::ErrorCode::ModelInvalid` | [Reference](/reference/sdk/api/cpp/results-and-errors#aic-ErrorCode-ModelInvalid) | | `aic::ErrorCode::ModelTypeUnsupported` | [Reference](/reference/sdk/api/cpp/results-and-errors#aic-ErrorCode-ModelTypeUnsupported) | | `aic::ErrorCode::ModelVersionUnsupported` | [Reference](/reference/sdk/api/cpp/results-and-errors#aic-ErrorCode-ModelVersionUnsupported) | | `aic::ErrorCode::NotInitialized` | [Reference](/reference/sdk/api/cpp/results-and-errors#aic-ErrorCode-NotInitialized) | | `aic::ErrorCode::NullPointer` | [Reference](/reference/sdk/api/cpp/results-and-errors#aic-ErrorCode-NullPointer) | | `aic::ErrorCode::ParameterOutOfRange` | [Reference](/reference/sdk/api/cpp/results-and-errors#aic-ErrorCode-ParameterOutOfRange) | | `aic::ErrorCode::ProcessingNotAllowed` | [Reference](/reference/sdk/api/cpp/results-and-errors#aic-ErrorCode-ProcessingNotAllowed) | | `aic::ErrorCode::Success` | [Reference](/reference/sdk/api/cpp/results-and-errors#aic-ErrorCode-Success) | | `aic::ErrorCode::TokenUpdateUnsupported` | [Reference](/reference/sdk/api/cpp/results-and-errors#aic-ErrorCode-TokenUpdateUnsupported) | | `aic::get_compatible_model_version` | [Reference](/reference/sdk/api/cpp/models-and-config#aic-get_compatible_model_version) | | `aic::get_sdk_version` | [Reference](/reference/sdk/api/cpp/models-and-config#aic-get_sdk_version) | | `aic::Model` | [Reference](/reference/sdk/api/cpp/models-and-config#aic-Model) | | `aic::Model::create_from_buffer` | [Reference](/reference/sdk/api/cpp/models-and-config#aic-Model-create_from_buffer) | | `aic::Model::create_from_file` | [Reference](/reference/sdk/api/cpp/models-and-config#aic-Model-create_from_file) | | `aic::Model::get_id` | [Reference](/reference/sdk/api/cpp/models-and-config#aic-Model-get_id) | | `aic::Model::get_optimal_block_size` | [Reference](/reference/sdk/api/cpp/models-and-config#aic-Model-get_optimal_block_size) | | `aic::Model::get_optimal_sample_rate` | [Reference](/reference/sdk/api/cpp/models-and-config#aic-Model-get_optimal_sample_rate) | | `aic::Model::Model-copy` | [Reference](/reference/sdk/api/cpp/models-and-config#aic-Model-Model-copy) | | `aic::Model::Model-move` | [Reference](/reference/sdk/api/cpp/models-and-config#aic-Model-Model-move) | | `aic::Model::operator=-copy` | [Reference](/reference/sdk/api/cpp/models-and-config#aic-Model-operatorassign-copy) | | `aic::Model::operator=-move` | [Reference](/reference/sdk/api/cpp/models-and-config#aic-Model-operatorassign-move) | | `aic::Model::~Model` | [Reference](/reference/sdk/api/cpp/models-and-config#aic-Model-destructor-Model) | | `aic::OtelConfig` | [Reference](/reference/sdk/api/cpp/models-and-config#aic-OtelConfig) | | `aic::OtelConfig::enable` | [Reference](/reference/sdk/api/cpp/models-and-config#aic-OtelConfig-enable) | | `aic::OtelConfig::export_interval_ms` | [Reference](/reference/sdk/api/cpp/models-and-config#aic-OtelConfig-export_interval_ms) | | `aic::OtelConfig::OtelConfig` | [Reference](/reference/sdk/api/cpp/models-and-config#aic-OtelConfig-OtelConfig) | | `aic::OtelConfig::session_id` | [Reference](/reference/sdk/api/cpp/models-and-config#aic-OtelConfig-session_id) | | `aic::Processor` | [Reference](/reference/sdk/api/cpp/processing#aic-Processor) | | `aic::Processor::create` | [Reference](/reference/sdk/api/cpp/processing#aic-Processor-create) | | `aic::Processor::create_context` | [Reference](/reference/sdk/api/cpp/processing#aic-Processor-create_context) | | `aic::Processor::create_energy_vad_context` | [Reference](/reference/sdk/api/cpp/processing#aic-Processor-create_energy_vad_context) | | `aic::Processor::initialize` | [Reference](/reference/sdk/api/cpp/processing#aic-Processor-initialize) | | `aic::Processor::operator=-copy` | [Reference](/reference/sdk/api/cpp/processing#aic-Processor-operatorassign-copy) | | `aic::Processor::operator=-move` | [Reference](/reference/sdk/api/cpp/processing#aic-Processor-operatorassign-move) | | `aic::Processor::process` | [Reference](/reference/sdk/api/cpp/processing#aic-Processor-process) | | `aic::Processor::Processor-copy` | [Reference](/reference/sdk/api/cpp/processing#aic-Processor-Processor-copy) | | `aic::Processor::Processor-move` | [Reference](/reference/sdk/api/cpp/processing#aic-Processor-Processor-move) | | `aic::Processor::terminate_session` | [Reference](/reference/sdk/api/cpp/processing#aic-Processor-terminate_session) | | `aic::Processor::~Processor` | [Reference](/reference/sdk/api/cpp/processing#aic-Processor-destructor-Processor) | | `aic::ProcessorConfig` | [Reference](/reference/sdk/api/cpp/models-and-config#aic-ProcessorConfig) | | `aic::ProcessorConfig::block_size` | [Reference](/reference/sdk/api/cpp/models-and-config#aic-ProcessorConfig-block_size) | | `aic::ProcessorConfig::ProcessorConfig` | [Reference](/reference/sdk/api/cpp/models-and-config#aic-ProcessorConfig-ProcessorConfig) | | `aic::ProcessorConfig::sample_rate` | [Reference](/reference/sdk/api/cpp/models-and-config#aic-ProcessorConfig-sample_rate) | | `aic::ProcessorConfig::variable_block_size` | [Reference](/reference/sdk/api/cpp/models-and-config#aic-ProcessorConfig-variable_block_size) | | `aic::ProcessorContext` | [Reference](/reference/sdk/api/cpp/processing#aic-ProcessorContext) | | `aic::ProcessorContext::get_audio_delay` | [Reference](/reference/sdk/api/cpp/processing#aic-ProcessorContext-get_audio_delay) | | `aic::ProcessorContext::get_parameter` | [Reference](/reference/sdk/api/cpp/processing#aic-ProcessorContext-get_parameter) | | `aic::ProcessorContext::operator=-copy` | [Reference](/reference/sdk/api/cpp/processing#aic-ProcessorContext-operatorassign-copy) | | `aic::ProcessorContext::operator=-move` | [Reference](/reference/sdk/api/cpp/processing#aic-ProcessorContext-operatorassign-move) | | `aic::ProcessorContext::ProcessorContext-copy` | [Reference](/reference/sdk/api/cpp/processing#aic-ProcessorContext-ProcessorContext-copy) | | `aic::ProcessorContext::ProcessorContext-move` | [Reference](/reference/sdk/api/cpp/processing#aic-ProcessorContext-ProcessorContext-move) | | `aic::ProcessorContext::reset` | [Reference](/reference/sdk/api/cpp/processing#aic-ProcessorContext-reset) | | `aic::ProcessorContext::set_parameter` | [Reference](/reference/sdk/api/cpp/processing#aic-ProcessorContext-set_parameter) | | `aic::ProcessorContext::update_bearer_token` | [Reference](/reference/sdk/api/cpp/processing#aic-ProcessorContext-update_bearer_token) | | `aic::ProcessorContext::~ProcessorContext` | [Reference](/reference/sdk/api/cpp/processing#aic-ProcessorContext-destructor-ProcessorContext) | | `aic::ProcessorParameter` | [Reference](/reference/sdk/api/cpp/processing#aic-ProcessorParameter) | | `aic::ProcessorParameter::Bypass` | [Reference](/reference/sdk/api/cpp/processing#aic-ProcessorParameter-Bypass) | | `aic::ProcessorParameter::EnhancementLevel` | [Reference](/reference/sdk/api/cpp/processing#aic-ProcessorParameter-EnhancementLevel) | | `aic::Result` | [Reference](/reference/sdk/api/cpp/results-and-errors#aic-Result-T) | | `aic::Result::error` | [Reference](/reference/sdk/api/cpp/results-and-errors#aic-Result-T-error) | | `aic::Result::ok` | [Reference](/reference/sdk/api/cpp/results-and-errors#aic-Result-T-ok) | | `aic::Result::Result-copy` | [Reference](/reference/sdk/api/cpp/results-and-errors#aic-Result-T-Result-copy) | | `aic::Result::Result-move` | [Reference](/reference/sdk/api/cpp/results-and-errors#aic-Result-T-Result-move) | | `aic::Result::take` | [Reference](/reference/sdk/api/cpp/results-and-errors#aic-Result-T-take) | | `aic::Result::value` | [Reference](/reference/sdk/api/cpp/results-and-errors#aic-Result-T-value) | | `aic::Vad` | [Reference](/reference/sdk/api/cpp/vad#aic-Vad) | | `aic::Vad::create` | [Reference](/reference/sdk/api/cpp/vad#aic-Vad-create) | | `aic::Vad::create_context` | [Reference](/reference/sdk/api/cpp/vad#aic-Vad-create_context) | | `aic::Vad::initialize` | [Reference](/reference/sdk/api/cpp/vad#aic-Vad-initialize) | | `aic::Vad::operator=-copy` | [Reference](/reference/sdk/api/cpp/vad#aic-Vad-operatorassign-copy) | | `aic::Vad::operator=-move` | [Reference](/reference/sdk/api/cpp/vad#aic-Vad-operatorassign-move) | | `aic::Vad::process` | [Reference](/reference/sdk/api/cpp/vad#aic-Vad-process) | | `aic::Vad::terminate_session` | [Reference](/reference/sdk/api/cpp/vad#aic-Vad-terminate_session) | | `aic::Vad::Vad-copy` | [Reference](/reference/sdk/api/cpp/vad#aic-Vad-Vad-copy) | | `aic::Vad::Vad-move` | [Reference](/reference/sdk/api/cpp/vad#aic-Vad-Vad-move) | | `aic::Vad::~Vad` | [Reference](/reference/sdk/api/cpp/vad#aic-Vad-destructor-Vad) | | `aic::VadContext` | [Reference](/reference/sdk/api/cpp/vad#aic-VadContext) | | `aic::VadContext::get_parameter` | [Reference](/reference/sdk/api/cpp/vad#aic-VadContext-get_parameter) | | `aic::VadContext::get_prediction_delay` | [Reference](/reference/sdk/api/cpp/vad#aic-VadContext-get_prediction_delay) | | `aic::VadContext::get_raw_vad_probability` | [Reference](/reference/sdk/api/cpp/vad#aic-VadContext-get_raw_vad_probability) | | `aic::VadContext::is_speech_detected` | [Reference](/reference/sdk/api/cpp/vad#aic-VadContext-is_speech_detected) | | `aic::VadContext::operator=-copy` | [Reference](/reference/sdk/api/cpp/vad#aic-VadContext-operatorassign-copy) | | `aic::VadContext::operator=-move` | [Reference](/reference/sdk/api/cpp/vad#aic-VadContext-operatorassign-move) | | `aic::VadContext::reset` | [Reference](/reference/sdk/api/cpp/vad#aic-VadContext-reset) | | `aic::VadContext::set_parameter` | [Reference](/reference/sdk/api/cpp/vad#aic-VadContext-set_parameter) | | `aic::VadContext::update_bearer_token` | [Reference](/reference/sdk/api/cpp/vad#aic-VadContext-update_bearer_token) | | `aic::VadContext::VadContext-copy` | [Reference](/reference/sdk/api/cpp/vad#aic-VadContext-VadContext-copy) | | `aic::VadContext::VadContext-move` | [Reference](/reference/sdk/api/cpp/vad#aic-VadContext-VadContext-move) | | `aic::VadContext::~VadContext` | [Reference](/reference/sdk/api/cpp/vad#aic-VadContext-destructor-VadContext) | | `aic::VadParameter` | [Reference](/reference/sdk/api/cpp/vad#aic-VadParameter) | | `aic::VadParameter::MinimumSpeechDuration` | [Reference](/reference/sdk/api/cpp/vad#aic-VadParameter-MinimumSpeechDuration) | | `aic::VadParameter::Sensitivity` | [Reference](/reference/sdk/api/cpp/vad#aic-VadParameter-Sensitivity) | | `aic::VadParameter::SpeechHoldDuration` | [Reference](/reference/sdk/api/cpp/vad#aic-VadParameter-SpeechHoldDuration) | ## Update this reference Compare API changes against the released header and implementation, preserving correct text and anchors. Check overloads and move/copy behavior directly; convenience types do not imply additional overloads. # C++ models and configuration Source: https://docs.ai-coustics.com/reference/sdk/api/cpp/models-and-config Load model data and inspect audio metadata and configuration values. C++ wrapper **0.26.0**, core **0.26.0**, C++11 or newer. Include `aic.hpp` and link the matching wrapper/native libraries. Start with the [C++ integration guide](/reference/sdk/language-bindings/cpp). All names below are in namespace `aic`. Check [Result and error handling](/reference/sdk/api/cpp/results-and-errors) before extracting a factory result. Ordinary C++ allocation or string operations can still throw; SDK status failures use the declared return values. ## `aic::Model` Owns one native handle. Its destructor releases that handle; do not destroy or move the object while another thread uses it. Construction/destruction can allocate or block, so keep them outside the audio callback. The default constructor and raw-handle constructor are private: use the documented factory. | Member | Contract | | - | - | | `~Model()` | Releases the native handle if non-null. | | `Model(Model&& other) noexcept` | Transfers the handle and clears the source. Do not call processing/getter methods on the moved-from object. | | `Model& operator=(Model&& other) noexcept` | Releases the destination's old handle, transfers ownership and clears the source. Self-move is guarded; returns `*this`. | | `Model(const Model&) = delete` | Copy construction is unavailable. | | `Model& operator=(const Model&) = delete` | Copy assignment is unavailable. | Model bytes are shared internally with derived processors, VADs and analyzers. Destroying this wrapper does not release their model reference. Keep a mapped file or borrowed model buffer valid until every derived object has been destroyed. ### `aic::Model::create_from_file` ```cpp theme={null} static Result create_from_file(const std::string& file_path); ``` Loads and memory-maps the UTF-8 path `file_path`. Returns an owned model on success. Do not change or delete the file while the model or derived objects remain alive. Errors include `FilePathInvalid`, `FileSystemError`, `ModelInvalid`, `ModelVersionUnsupported` and `ModelDataUnaligned`. The factory forwards `file_path.c_str()` to C; embedded NUL characters terminate the path. Perform file I/O outside the audio callback. ### `aic::Model::create_from_buffer` ```cpp theme={null} static Result create_from_buffer(const uint8_t* buffer, size_t buffer_len); ``` Borrows `buffer_len` bytes at `buffer`, aligned to 64 bytes. It does not copy or own the allocation. Keep it alive and unchanged through the lifetimes of this model and every derived object. Returns a checked model or errors such as `NullPointer`, `ModelInvalid`, `ModelVersionUnsupported` or `ModelDataUnaligned`. Destroying a model does not free the caller's buffer. ### `aic::Model::get_id` ```cpp theme={null} std::string get_id() const; ``` Returns a copy of the model ID. Unlike the C pointer getter, this string remains valid independently of the model. A null underlying handle returns an empty string. Copying can allocate. ### `aic::Model::get_optimal_sample_rate` ```cpp theme={null} uint32_t get_optimal_sample_rate() const; ``` Returns the native sample rate in Hz. The wrapper asserts that the C call succeeded; it does not return an error object. Use a valid, successfully created model. In assertion-disabled builds, the initialized fallback value is zero if the C call fails. ### `aic::Model::get_optimal_block_size` ```cpp theme={null} size_t get_optimal_block_size(uint32_t sample_rate) const; ``` Returns the model hop size converted to `sample_rate` in Hz, in mono samples. The query does not validate supported rates; initialization performs that check. The wrapper asserts on C errors and has a zero fallback in assertion-disabled builds. Keep the model valid. ## `aic::ProcessorConfig` Stores audio configuration values. This is a convenience value type; wrapper 0.26.0 has no `initialize(ProcessorConfig)` overload. Pass its three fields to the object's three-argument `initialize` method. ### `aic::ProcessorConfig::ProcessorConfig` ```cpp theme={null} ProcessorConfig(uint32_t sample_rate, size_t block_size, bool variable_block_size = false); ``` Stores the arguments without validating them. Validation happens when you initialize a processor, VAD or collector. This constructor is not a default constructor: the rate and block size are required. | Field | Type | Meaning | | - | - | - | | `sample_rate` | `uint32_t` | Input rate in Hz. Initialization supports 8,000–192,000 inclusive. | | `block_size` | `size_t` | Positive mono sample count. Fixed size, or maximum when variable sizing is enabled. | | `variable_block_size` | `bool` | Defaults to false through the constructor. True allows each call to provide at most `block_size` samples. | ## `aic::OtelConfig` ### `aic::OtelConfig::OtelConfig` ```cpp theme={null} OtelConfig(bool enable = false, const char* session_id = nullptr, uint32_t export_interval_ms = 0); ``` Stores the arguments. Passing no config pointer to a factory preserves environment defaults; passing an `OtelConfig{}` explicitly disables optional OTel export. This does not disable SDK session telemetry. The struct does not own `session_id`; keep it valid through the factory call, which copies it. | Field | Type and default | Meaning | | - | - | - | | `enable` | `bool = false` | Overrides `AIC_SDK_OTEL_ENABLE` when a config is supplied. | | `session_id` | `const char* = nullptr` | Optional null-terminated session label; nullptr requests a generated ID. | | `export_interval_ms` | `uint32_t = 0` | Positive export interval in milliseconds. Zero keeps the 60,000 ms default. | See [OpenTelemetry](/models/get-started/opentelemetry) and [SDK telemetry](/reference/concepts/sdk-telemetry). ### `aic::get_sdk_version` ```cpp theme={null} inline std::string get_sdk_version(); ``` Returns a copied core SDK version string. It wraps `aic_get_sdk_version`; a null C result would produce an empty string. No arguments. ### `aic::get_compatible_model_version` ```cpp theme={null} inline uint32_t get_compatible_model_version(); ``` Returns the accepted model file format version, 8 for core 0.26.0. This is not the model product version. No arguments. ## Example: pass configuration fields explicitly Use a successfully created processor. `ProcessorConfig` stores values; `initialize` validates them. ```cpp theme={null} #include "aic.hpp" aic::ErrorCode configure(aic::Processor& processor) { aic::ProcessorConfig config(16000, 240); return processor.initialize(config.sample_rate, config.block_size, config.variable_block_size); } ``` # C++ enhancement and processor control Source: https://docs.ai-coustics.com/reference/sdk/api/cpp/processing Create a dedicated enhancement object and manage its stream state. C++ wrapper **0.26.0**, core **0.26.0**, C++11 or newer. Include `aic.hpp` and link the matching wrapper/native libraries. Start with the [C++ integration guide](/reference/sdk/language-bindings/cpp). All names below are in namespace `aic`. Check [Result and error handling](/reference/sdk/api/cpp/results-and-errors) before extracting a factory result. Ordinary C++ allocation or string operations can still throw; SDK status failures use the declared return values. ## `aic::Processor` Owns one native handle. Its destructor releases that handle; do not destroy or move the object while another thread uses it. Construction/destruction can allocate or block, so keep them outside the audio callback. The default constructor and raw-handle constructor are private: use the documented factory. | Member | Contract | | - | - | | `~Processor()` | Releases the native handle if non-null. | | `Processor(Processor&& other) noexcept` | Transfers the handle and clears the source. Do not call processing/getter methods on the moved-from object. | | `Processor& operator=(Processor&& other) noexcept` | Releases the destination's old handle, transfers ownership and clears the source. Self-move is guarded; returns `*this`. | | `Processor(const Processor&) = delete` | Copy construction is unavailable. | | `Processor& operator=(const Processor&) = delete` | Copy assignment is unavailable. | ### `aic::Processor::create` ```cpp theme={null} static Result create(const Model& model, const std::string& license_key, const OtelConfig* otel_config = nullptr); ``` Creates an owned `Processor` using an enhancement or bypass model and the null-terminated representation of `license_key` (SDK key or supported bearer token). The object retains model data; no ownership of the `Model` wrapper is transferred. `otel_config` is optional and is copied during creation. Returns a checked result; errors include `ModelTypeUnsupported`, license errors and `InternalError`. Construction does not initialize audio configuration. Keep it outside the audio callback. ### `aic::Processor::initialize` ```cpp theme={null} ErrorCode initialize(uint32_t sample_rate, size_t block_size, bool variable_block_size); ``` Initializes or reinitializes the object. `sample_rate` is the host rate in Hz (8,000–192,000); `block_size` is a positive mono sample count. With `variable_block_size=false`, input must match exactly; with `true`, it is the maximum per call. All three arguments are required: there is no config-object overload. Returns `Success` or `AudioConfigUnsupported` (or `NullPointer` for an invalid underlying handle). Failure leaves the object uninitialized. Initialization resets state and allocates; serialize it with processing. ### `aic::Processor::process` ```cpp theme={null} ErrorCode process(float* audio, size_t audio_len); ``` Processes `audio_len` mono float32 samples in `audio` in place. The writable buffer remains caller-owned and must stay valid until the call returns. Use normalized samples, nominally -1.0 to 1.0. Returns `Success`, `NullPointer`, `NotInitialized`, `AudioConfigMismatch` or `ProcessingNotAllowed` (and internal errors). On processing denial, buffering or delayed output may already have changed; error output is not enhanced audio. Keep one instance per stream and serialize its processing calls. ### `aic::Processor::terminate_session` ```cpp theme={null} ErrorCode terminate_session(); ``` Requests asynchronous session termination and returns `Success` (or `NullPointer` for an invalid underlying handle). Processing may continue until the request is handled. It is a no-op for a credential with no telemetry session. The call neither destroys the object nor proves backend acknowledgment. Stop application processing explicitly, then allow normal destruction. On native targets, terminating the final active session may wait for the shared telemetry tasks to finish. Call it outside the audio callback. ### `aic::Processor::create_context` ```cpp theme={null} Result create_context() const; ``` Creates a separately owned control object with shared state. Check the result before extracting it. The context can outlive its source object, but it cannot process audio after that object is destroyed. Errors include `NullPointer`. Context creation allocates. ### `aic::Processor::create_energy_vad_context` ```cpp theme={null} Result create_energy_vad_context() const; ``` Creates an [`aic::EnergyVadContext`](/reference/sdk/api/cpp/vad#aic-EnergyVadContext) driven by this processor's enhanced signal. No separate model or process call is needed; detection advances with `process`. All contexts from one processor share the same VAD. Creating a context keeps enhancement inference active even when the processor is bypassed or its enhancement level is zero, and it stays active for the processor's lifetime after all contexts are destroyed. A context can safely outlive the processor but then stops receiving new data. Returns `ModelTypeUnsupported` if this processor does not support energy VAD. Allocates memory and is not real-time safe; do not use or destroy the processor from another thread during the call. ## `aic::ProcessorContext` Owns one native handle. Its destructor releases that handle; do not destroy or move the object while another thread uses it. Construction/destruction can allocate or block, so keep them outside the audio callback. The default constructor and raw-handle constructor are private: use the documented factory. | Member | Contract | | - | - | | `~ProcessorContext()` | Releases the native handle if non-null. | | `ProcessorContext(ProcessorContext&& other) noexcept` | Transfers the handle and clears the source. Do not call processing/getter methods on the moved-from object. | | `ProcessorContext& operator=(ProcessorContext&& other) noexcept` | Releases the destination's old handle, transfers ownership and clears the source. Self-move is guarded; returns `*this`. | | `ProcessorContext(const ProcessorContext&) = delete` | Copy construction is unavailable. | | `ProcessorContext& operator=(const ProcessorContext&) = delete` | Copy assignment is unavailable. | Context control reads, parameter updates and reset requests use shared state and can run alongside processing. Keep handles alive through all concurrent calls. Credential updates are control-thread operations; destruction is never concurrent-safe. ### `aic::ProcessorContext::reset` ```cpp theme={null} ErrorCode reset() const; ``` Requests stream-buffer/model reset for the next processing call. Audio configuration and parameters remain in place. Any energy VAD on this processor is reset as well. Returns `Success` or `NullPointer`. Coordinate the stream boundary if you require a precise reset position. ### `aic::ProcessorContext::set_parameter` ```cpp theme={null} ErrorCode set_parameter(ProcessorParameter parameter, float value) const; ``` Sets a declared `ProcessorParameter` to `value`. Returns `Success`, `NullPointer` or `ParameterOutOfRange`; NaN is out of range. The parameter table below defines units, defaults and accepted ranges. ### `aic::ProcessorContext::get_parameter` ```cpp theme={null} float get_parameter(ProcessorParameter parameter) const; ``` Returns the stored value of a declared parameter. The wrapper asserts C success, rather than returning a `Result`. A C failure leaves the initialized fallback at zero if assertions are disabled. Do not use invalid enum values or a moved-from context. ### `aic::ProcessorContext::get_audio_delay` ```cpp theme={null} size_t get_audio_delay() const; ``` Returns the audio delay in samples at the initialized host rate. Query after successful initialization and again after changing audio configuration. This is not elapsed CPU time. The wrapper asserts C success and has a zero fallback if assertions are disabled. ### `aic::ProcessorContext::update_bearer_token` ```cpp theme={null} ErrorCode update_bearer_token(const std::string& token) const; ``` Replaces local credentials using `token.c_str()`. Both the original and replacement credentials must use supported JWT form. Returns `Success`, `LicenseFormatInvalid`, other license errors or `TokenUpdateUnsupported` (and `NullPointer` for an invalid handle). Success does not prove backend acceptance. Run on a control thread. See [authentication](/models/get-started/authenticate-apps). ## `aic::ProcessorParameter` Use only these `enum class` members, whose underlying type is `int`. | Member | Value | Range, units and default | | - | - | - | | `ProcessorParameter::Bypass` | 0 | 0 means off; greater than 0 through 1 means on. Default off; getter returns 0 or 1. Preserves delay alignment. | | `ProcessorParameter::EnhancementLevel` | 1 | 0–1 inclusive. Model-specific default, falling back to 1. Model metadata can scale the effective strength. | ## Related [C++ API index](/reference/sdk/api/cpp/index) · [Streams and state](/reference/concepts/streams-and-state) · [Audio format](/reference/concepts/audio-format) ## Example: check each processing call Use a successfully initialized processor and keep its buffer alive for the call. This helper propagates the SDK status to the application. ```cpp theme={null} #include "aic.hpp" aic::ErrorCode enhance_block(aic::Processor& processor, float* audio, size_t count) { return processor.process(audio, count); } ``` # C++ results and errors Source: https://docs.ai-coustics.com/reference/sdk/api/cpp/results-and-errors Check factory results, move owned values and interpret every SDK error. C++ wrapper **0.26.0**, core **0.26.0**, C++11 or newer. Include `aic.hpp` and link the matching wrapper/native libraries. Start with the [C++ integration guide](/reference/sdk/language-bindings/cpp). All names below are in namespace `aic`. Check [Result and error handling](/reference/sdk/api/cpp/results-and-errors) before extracting a factory result. Ordinary C++ allocation or string operations can still throw; SDK status failures use the declared return values. ## `aic::Result` `Result` stores an ordinary value and a status. It does not throw on SDK errors, check access or automatically unwrap. `take()` moves the stored value regardless of the error code. Always call `ok()` or inspect `error` before extraction. | Public field | Type | Meaning | | - | - | - | | `value` | `T` | Stored success value, or the factory's failure placeholder. Never use a failed handle. | | `error` | `ErrorCode` | Operation status. `Success` is zero. | ### `aic::Result::Result-copy` ```cpp theme={null} Result(const T& v, ErrorCode e); ``` Copies `v` and stores `e`. This overload requires `T` to be copyable when instantiated; it cannot copy an SDK-owned move-only handle. It performs no validation. ### `aic::Result::Result-move` ```cpp theme={null} Result(T&& v, ErrorCode e); ``` Moves `v` into the result and stores `e`. Use it for move-only handles. It performs no validation. There is no default constructor. ### `aic::Result::ok` ```cpp theme={null} bool ok() const; ``` Returns `error == ErrorCode::Success` without inspecting the stored object. ### `aic::Result::take` ```cpp theme={null} T take(); ``` Returns `std::move(value)` without checking `error` and without resetting it. Extract a successful owned handle once. After extraction, the original handle value is moved-from; it can be destroyed or assigned, but must not be used to process or query audio state. ## Checked extraction This complete credential-free program checks the model-loading result before extracting the model and printing the linked core version. A missing file prints the error code and exits with status 1. Link it as described in the [C++ guide](/reference/sdk/language-bindings/cpp). ```cpp theme={null} #include "aic.hpp" #include int main() { auto result = aic::Model::create_from_file("path/to/model.aicmodel"); if (!result.ok()) { std::cerr << "Model load failed: " << static_cast(result.error) << '\n'; return 1; } auto model = result.take(); std::cout << model.get_id() << " with core " << aic::get_sdk_version() << '\n'; } ``` ## Getter assertions Model metadata getters and context value/decision/delay getters return scalar values and assert the underlying C call succeeded. They are not checked `Result` APIs. In assertion-disabled builds, a failure returns the wrapper's initialized fallback (zero or false). Use valid objects and enum members; do not treat fallback values as error reporting. `Model::get_id()` separately returns an empty string for a null native handle. ## `aic::ErrorCode` `enum class ErrorCode : int` maps directly to the C status values. The following list is complete for wrapper 0.26.0. | Member | Value | Meaning and recovery | | - | - | - | | `ErrorCode::Success` | 0 | The operation succeeded. A returned result value can be used. | | `ErrorCode::NullPointer` | 1 | A required native pointer is null. Use valid handles and buffers; do not use a moved-from handle. | | `ErrorCode::ParameterOutOfRange` | 2 | A parameter is outside its accepted range or is NaN. Check the parameter bounds before setting it. | | `ErrorCode::NotInitialized` | 3 | The processor, VAD or collector has not been initialized. Call its `initialize` method successfully before supplying audio. | | `ErrorCode::AudioConfigUnsupported` | 4 | The sample rate or block configuration is unsupported. Use a positive block size and settings supported by the model. | | `ErrorCode::AudioConfigMismatch` | 5 | The audio length violates the configured fixed block size or variable maximum. Correct the buffer length. | | `ErrorCode::ProcessingNotAllowed` | 6 | The session disallows processing. Check credentials, network access and session state, and apply your application's audio fallback. | | `ErrorCode::InternalError` | 7 | An internal operation failed. If valid input reproduces the failure, contact support with a minimal reproduction. | | `ErrorCode::LicenseFormatInvalid` | 50 | The credential cannot be parsed. Check the exact key or token and its encoding without logging it. | | `ErrorCode::LicenseVersionUnsupported` | 51 | The SDK does not support the credential version. Check SDK and account compatibility. | | `ErrorCode::LicenseExpired` | 52 | The credential has expired. Obtain a valid credential through the approved account flow. | | `ErrorCode::TokenUpdateUnsupported` | 53 | Token replacement requires both the original and replacement credentials to be JWTs. Start a new session when changing credential types. | | `ErrorCode::ModelInvalid` | 100 | The model data is invalid or corrupted. Obtain a complete compatible model file. | | `ErrorCode::ModelVersionUnsupported` | 101 | The model file format is incompatible with this SDK. Obtain a model in the matching format. | | `ErrorCode::FilePathInvalid` | 102 | The model path is not valid UTF-8. Supply a UTF-8 path string. | | `ErrorCode::FileSystemError` | 103 | The model file cannot be opened or mapped. Check its path, permissions and integrity. | | `ErrorCode::ModelDataUnaligned` | 104 | The model buffer is not aligned to 64 bytes. Use correctly aligned storage and retain it for every dependent object. | | `ErrorCode::ModelTypeUnsupported` | 105 | The model type does not match the operation. Use the corresponding enhancement, VAD or analysis API. | ## Related [C++ API index](/reference/sdk/api/cpp/index) · [Troubleshooting](/production/troubleshooting) · [Authentication](/models/get-started/authenticate-apps) # C++ voice activity detection Source: https://docs.ai-coustics.com/reference/sdk/api/cpp/vad Create a dedicated VAD object and manage its stream state. C++ wrapper **0.26.0**, core **0.26.0**, C++11 or newer. Include `aic.hpp` and link the matching wrapper/native libraries. Start with the [C++ integration guide](/reference/sdk/language-bindings/cpp). All names below are in namespace `aic`. Check [Result and error handling](/reference/sdk/api/cpp/results-and-errors) before extracting a factory result. Ordinary C++ allocation or string operations can still throw; SDK status failures use the declared return values. ## `aic::Vad` Owns one native handle. Its destructor releases that handle; do not destroy or move the object while another thread uses it. Construction/destruction can allocate or block, so keep them outside the audio callback. The default constructor and raw-handle constructor are private: use the documented factory. | Member | Contract | | - | - | | `~Vad()` | Releases the native handle if non-null. | | `Vad(Vad&& other) noexcept` | Transfers the handle and clears the source. Do not call processing/getter methods on the moved-from object. | | `Vad& operator=(Vad&& other) noexcept` | Releases the destination's old handle, transfers ownership and clears the source. Self-move is guarded; returns `*this`. | | `Vad(const Vad&) = delete` | Copy construction is unavailable. | | `Vad& operator=(const Vad&) = delete` | Copy assignment is unavailable. | ### `aic::Vad::create` ```cpp theme={null} static Result create(const Model& model, const std::string& license_key, const OtelConfig* otel_config = nullptr); ``` Creates an owned `Vad` using a dedicated VAD model and the null-terminated representation of `license_key` (SDK key or supported bearer token). The object retains model data; no ownership of the `Model` wrapper is transferred. `otel_config` is optional and is copied during creation. Returns a checked result; errors include `ModelTypeUnsupported`, license errors and `InternalError`. Construction does not initialize audio configuration. Keep it outside the audio callback. ### `aic::Vad::initialize` ```cpp theme={null} ErrorCode initialize(uint32_t sample_rate, size_t block_size, bool variable_block_size); ``` Initializes or reinitializes the object. `sample_rate` is the host rate in Hz (8,000–192,000); `block_size` is a positive mono sample count. With `variable_block_size=false`, input must match exactly; with `true`, it is the maximum per call. All three arguments are required: there is no config-object overload. Returns `Success` or `AudioConfigUnsupported` (or `NullPointer` for an invalid underlying handle). Failure leaves the object uninitialized. Initialization resets state and allocates; serialize it with processing. ### `aic::Vad::process` ```cpp theme={null} ErrorCode process(const float* audio, size_t audio_len); ``` Reads `audio_len` mono float32 samples from `audio` and copies them to an internal buffer. It does not modify the caller's buffer. On success, read the updated decision through the context. Use normalized samples, nominally -1.0 to 1.0. Returns `Success`, `NullPointer`, `NotInitialized`, `AudioConfigMismatch` or `ProcessingNotAllowed` (and internal errors). Do not use a stale VAD decision after a failed call. Keep one instance per stream and serialize its processing calls. ### `aic::Vad::terminate_session` ```cpp theme={null} ErrorCode terminate_session(); ``` Requests asynchronous session termination and returns `Success` (or `NullPointer` for an invalid underlying handle). Processing may continue until the request is handled. It is a no-op for a credential with no telemetry session. The call neither destroys the object nor proves backend acknowledgment. Stop application processing explicitly, then allow normal destruction. On native targets, terminating the final active session may wait for the shared telemetry tasks to finish. Call it outside the audio callback. ### `aic::Vad::create_context` ```cpp theme={null} Result create_context() const; ``` Creates a separately owned control object with shared state. Check the result before extracting it. The context can outlive its source object, but it cannot process audio after that object is destroyed. Errors include `NullPointer` and `InternalError` if a VAD context is unavailable. Context creation allocates. ## `aic::VadContext` Owns one native handle. Its destructor releases that handle; do not destroy or move the object while another thread uses it. Construction/destruction can allocate or block, so keep them outside the audio callback. The default constructor and raw-handle constructor are private: use the documented factory. | Member | Contract | | - | - | | `~VadContext()` | Releases the native handle if non-null. | | `VadContext(VadContext&& other) noexcept` | Transfers the handle and clears the source. Do not call processing/getter methods on the moved-from object. | | `VadContext& operator=(VadContext&& other) noexcept` | Releases the destination's old handle, transfers ownership and clears the source. Self-move is guarded; returns `*this`. | | `VadContext(const VadContext&) = delete` | Copy construction is unavailable. | | `VadContext& operator=(const VadContext&) = delete` | Copy assignment is unavailable. | Context control reads, parameter updates and reset requests use shared state and can run alongside processing. Keep handles alive through all concurrent calls. Credential updates are control-thread operations; destruction is never concurrent-safe. ### `aic::VadContext::reset` ```cpp theme={null} ErrorCode reset() const; ``` Requests processing-state reset for the next audio call and immediately clears the published decision and probability. Audio configuration and parameters remain in place. Returns `Success` or `NullPointer`. Coordinate the stream boundary if you require a precise reset position. ### `aic::VadContext::set_parameter` ```cpp theme={null} ErrorCode set_parameter(VadParameter parameter, float value) const; ``` Sets a declared `VadParameter` to `value`. Returns `Success`, `NullPointer` or `ParameterOutOfRange`; NaN is out of range. The parameter table below defines units, defaults and accepted ranges. ### `aic::VadContext::get_parameter` ```cpp theme={null} float get_parameter(VadParameter parameter) const; ``` Returns the stored value of a declared parameter. The wrapper asserts C success, rather than returning a `Result`. A C failure leaves the initialized fallback at zero if assertions are disabled. Do not use invalid enum values or a moved-from context. Duration parameters are in seconds; frame quantization affects the actual decisions. ### `aic::VadContext::get_prediction_delay` ```cpp theme={null} size_t get_prediction_delay() const; ``` Returns the prediction delay in samples at the initialized host rate. Query after successful initialization and again after changing audio configuration. This is not elapsed CPU time. The wrapper asserts C success and has a zero fallback if assertions are disabled. ### `aic::VadContext::update_bearer_token` ```cpp theme={null} ErrorCode update_bearer_token(const std::string& token) const; ``` Replaces local credentials using `token.c_str()`. Both the original and replacement credentials must use supported JWT form. Returns `Success`, `LicenseFormatInvalid`, other license errors or `TokenUpdateUnsupported` (and `NullPointer` for an invalid handle). Success does not prove backend acceptance. Run on a control thread. See [authentication](/models/get-started/authenticate-apps). ### `aic::VadContext::is_speech_detected` ```cpp theme={null} bool is_speech_detected() const; ``` Returns the latest filtered speech decision. Call `Vad::process` successfully to advance it. It combines probability threshold, minimum speech duration and hold behavior. The wrapper asserts C success and uses `false` as its assertion-disabled error fallback. ### `aic::VadContext::get_raw_vad_probability` ```cpp theme={null} float get_raw_vad_probability() const; ``` Returns the latest speech probability before duration filtering. It does not process audio or replace the final speech decision. The wrapper asserts C success and uses zero as its assertion-disabled error fallback. ## `aic::EnergyVadContext` Owns one native handle to an enhancement processor's energy VAD, which detects speech from the enhanced signal before output mixing and runs no separate model. Detection advances with `Processor::process`; there is no separate process call. Create it with [`aic::Processor::create_energy_vad_context`](/reference/sdk/api/cpp/processing#aic-Processor-create_energy_vad_context); the default and raw-handle constructors are private. All contexts from one processor share state and parameters, and a context may safely outlive its processor, after which its prediction stops updating. Control and query methods are thread-safe and real-time safe. Destruction is not real-time safe and must not overlap calls on the same handle; it releases the handle without destroying the processor or disabling its energy VAD. | Member | Contract | | - | - | | `~EnergyVadContext()` | Releases the native handle if non-null. Deallocates memory; not real-time safe. | | `EnergyVadContext(EnergyVadContext&& other) noexcept` | Transfers the handle and clears the source. Do not call methods on the moved-from object. | | `EnergyVadContext& operator=(EnergyVadContext&& other) noexcept` | Releases the destination's old handle, transfers ownership and clears the source. Self-move is guarded; returns `*this`. | | `EnergyVadContext(const EnergyVadContext&) = delete` | Copy construction is unavailable. | | `EnergyVadContext& operator=(const EnergyVadContext&) = delete` | Copy assignment is unavailable. | ### `aic::EnergyVadContext::reset` ```cpp theme={null} ErrorCode reset() const; ``` Clears the energy VAD state and immediately resets the prediction to `false`. Call it when seeking or when the stream is interrupted. Parameters are retained and the backing processor is not reset; [`ProcessorContext::reset`](/reference/sdk/api/cpp/processing#aic-ProcessorContext-reset) also resets this VAD. Returns `Success` or an error code. Thread-safe and real-time safe. ### `aic::EnergyVadContext::is_speech_detected` ```cpp theme={null} bool is_speech_detected() const; ``` Returns the energy VAD's prediction, `false` before processing or after a reset. Predictions update during `Processor::process` and stop updating if the processor stops processing or is destroyed. The prediction lags its input by `get_prediction_delay()` samples; speech hold and minimum speech duration affect its timing further. ### `aic::EnergyVadContext::get_prediction_delay` ```cpp theme={null} size_t get_prediction_delay() const; ``` Returns the prediction delay in samples for the current audio configuration, covering input reblocking, STFT and enhancement model processing. It equals [`ProcessorContext::get_audio_delay`](/reference/sdk/api/cpp/processing#aic-ProcessorContext-get_audio_delay) for the backing processor; energy detection adds no audio delay. Speech hold and minimum speech duration are not included. ### `aic::EnergyVadContext::set_parameter` ```cpp theme={null} ErrorCode set_parameter(VadParameter parameter, float value) const; ``` Sets a declared `VadParameter` to `value`. `VadParameter::Sensitivity` takes the energy range, 1.0 to 15.0, on this context. Returns `Success`, `NullPointer` or `ParameterOutOfRange`. All parameters can be changed during processing, from any thread. ### `aic::EnergyVadContext::get_parameter` ```cpp theme={null} float get_parameter(VadParameter parameter) const; ``` Returns the stored value of a declared parameter. Thread-safe and real-time safe. ## `aic::VadParameter` Use only these `enum class` members, whose underlying type is `int`. | Member | Value | Range, units and default | | - | - | - | | `VadParameter::SpeechHoldDuration` | 0 | Seconds, zero through the model/window-dependent maximum. Model-specific default; holds speech through short gaps. Decisions are quantized to model frames. | | `VadParameter::Sensitivity` | 1 | Meaning depends on the detector. On a `VadContext`, a probability threshold, 0–1 inclusive, where a higher value requires stronger speech evidence. On an `EnergyVadContext`, the energy threshold of the enhanced signal, computed as `10 ^ (-sensitivity)` over 1–15 inclusive, where higher values detect quieter speech. Model-specific default. | | `VadParameter::MinimumSpeechDuration` | 2 | Seconds, 0–1 inclusive. Model-specific default. Requires sustained speech before the decision becomes true. | ## Related [C++ API index](/reference/sdk/api/cpp/index) · [Streams and state](/reference/concepts/streams-and-state) · [Audio format](/reference/concepts/audio-format) ## Example: read the decision after processing Use a valid initialized VAD and its context. The decision getter relies on that valid context. ```cpp theme={null} #include "aic.hpp" aic::ErrorCode detect_block(aic::Vad& vad, const aic::VadContext& context, const float* audio, size_t count, bool& speech) { auto error = vad.process(audio, count); if (error != aic::ErrorCode::Success) return error; speech = context.is_speech_detected(); return aic::ErrorCode::Success; } ``` # Node.js analysis API Source: https://docs.ai-coustics.com/reference/sdk/api/node/analysis Collect mono audio and analyze the retained window with Tyto. **Version:** `@ai-coustics/aic-sdk` 0.26.0, Core SDK 0.26.0. [API index](/reference/sdk/api/node/index) · [Node.js quickstart](/reference/sdk/language-bindings/nodejs). ## `Analyzer` A mono audio collector and analysis engine combined in one JavaScript object. Use an analysis model such as Tyto. Initialize, buffer original audio and analyze the retained window. Only the model's maximum window is retained; new audio replaces older audio. Short histories are zero-padded. ### `Analyzer.constructor` ```typescript theme={null} constructor(model: Model, licenseKey: string) ``` `model` must be a live analysis model, not an enhancement or VAD model. `licenseKey` is an SDK credential. Construction synchronously creates the collector/analyzer pair and can throw for credentials, model type or disposal errors. There is no per-instance `OtelConfig` constructor argument. Call `initialize` before `buffer`. ### `Analyzer.dispose` ```typescript theme={null} dispose(): void ``` Synchronously releases the collector and analyzer; repeated calls are harmless. Since Node.js SDK 0.26.0, this call can run while `analyzeAsync()` is pending. It waits for the analyzer lock if analysis is running, so it can block the event loop. Queued analysis that obtains the lock afterward rejects. Later operations throw `Analyzer has been disposed`. Await outstanding analysis to avoid a synchronous wait and keep a clear lifecycle. ### `Analyzer.initialize` ```typescript theme={null} initialize(sampleRate: number, blockSize: number, variableBlockSize?: boolean | undefined | null): void ``` `sampleRate` is a whole-number rate in Hz; `blockSize` is a positive whole-number mono sample count. Query `model.getOptimalBlockSize(sampleRate)` for the preferred size. Omitted, `undefined` or `null` `variableBlockSize` means `false`, requiring exactly `blockSize` samples. Variable mode allows shorter blocks, with possible buffering delay, but rejects larger blocks. Unsupported configurations throw an SDK error. Initialization allocates memory. Configures the collector synchronously. For Tyto, use its native 16 kHz input and the block size returned by the model query. A failed reinitialization leaves the collector uninitialized; correct the configuration before buffering again. ### `Analyzer.buffer` ```typescript theme={null} buffer(audio: Float32Array): void ``` Reads a mono `Float32Array` without modifying it and collects samples for later analysis. Returns `void`; it does not run the analysis model. Requires successful initialization and the configured block length. It can continue while `analyzeAsync` runs because collection does not take the analyzer lock. Older audio is discarded as the model window fills. ### `Analyzer.analyze` ```typescript theme={null} analyze(): AnalysisResult ``` Synchronously analyzes the latest buffered window and returns `AnalysisResult`. Blocks the calling thread and can wait for an earlier async analysis. Short or empty histories are zero-padded; the SDK does not provide a readiness check here. Track the amount of real buffered audio yourself. Throws for disallowed processing or native analysis failure. ### `Analyzer.analyzeAsync` ```typescript theme={null} analyzeAsync(): Promise ``` Queues analysis on the libuv pool and resolves to `AnalysisResult`. The worker reads the available buffered snapshot when it executes; submission does not freeze the collector. Collection can continue in parallel. Since Node.js SDK 0.26.0, `buffer()` and `dispose()` can be called while the promise is pending. `dispose()` remains synchronous and may block until analysis releases the analyzer lock. Await before assuming completion or disposing when you want to avoid that wait. Native analysis failures reject the promise. This is expensive analysis, not an audio-callback operation. ### `Analyzer.reset` ```typescript theme={null} reset(): void ``` Synchronously requests clearing of the collector state while retaining audio settings. Until the next `buffer` applies that reset, analysis uses a zero-filled snapshot instead of stale audio. Waits for the analyzer lock and can block during async analysis. ### `Analyzer.updateBearerToken` ```typescript theme={null} updateBearerToken(token: string): void ``` `token` replaces a bearer token on a JWT-authenticated session. Both the original credential and replacement must be JWT-form licenses. A synchronous failure preserves the previous token. Return without error confirms local format acceptance, not backend acceptance; subsequent reporting can reject the token and eventually disable work. Obtain a valid replacement to recover. This operation allocates and takes a lock; keep it outside audio callbacks. See [authentication](/models/get-started/authenticate-apps). This synchronous method also waits for any active analysis holding the analyzer lock. ### `Analyzer.terminateSession` ```typescript theme={null} terminateSession(): void ``` Requests termination of the associated session. Once termination is handled, further analysis is disallowed. This does not release the native object; still call `dispose()`. Completion may involve asynchronous session handling when another session remains active. Do not use it as a flush operation. Synchronous; can block on the analyzer lock and session handling. ## `AnalysisResult` A returned object with seven `number` fields, not a class to construct. Values are normalized scores from 0 to 1. Lower values indicate less problematic audio except for `speakerLoudness`, where loudness itself is measured. These are model estimates, not a guarantee of transcription quality. See [Tyto](/models/audio-insight/tyto) for interpretation. ### `AnalysisResult.riskScore` ```typescript theme={null} riskScore: number ``` Estimate of risk to downstream speech-model performance. Evaluate against observed failures; it is not a word error rate or a probability guarantee for an individual request. ### `AnalysisResult.speakerReverb` ```typescript theme={null} speakerReverb: number ``` Speaker distance/reverberation score. Lower values indicate less problematic reverberation. ### `AnalysisResult.speakerLoudness` ```typescript theme={null} speakerLoudness: number ``` Speaker loudness score. Interpret it separately from the other risk dimensions; lower is not universally better. ### `AnalysisResult.interferingSpeech` ```typescript theme={null} interferingSpeech: number ``` Score for speech from sources other than the main speaker. ### `AnalysisResult.noise` ```typescript theme={null} noise: number ``` Ambient or environmental noise score. ### `AnalysisResult.codecDegradation` ```typescript theme={null} codecDegradation: number ``` Score for lossy speech-codec artifacts, including narrowband or low-bitrate degradation. ### `AnalysisResult.packetLoss` ```typescript theme={null} packetLoss: number ``` Score for dropouts and discontinuities, such as packet loss, frame erasure, jitter or CPU overload. It is not a network packet counter. ## Example With the pinned package installed, set `AIC_SDK_LICENSE` and run `node analyze-window.cjs path/to/tyto.aicmodel`. It collects at least 5 s of silence and prints seven score fields. For call-quality evaluation, use representative audio and follow [real-time analysis](/models/audio-insight/real-time-analysis) for window interpretation. ```javascript analyze-window.cjs theme={null} const { Analyzer, Model } = require('@ai-coustics/aic-sdk'); async function main() { const key = process.env.AIC_SDK_LICENSE; const modelPath = process.argv[2]; if (!key || !modelPath) throw new Error('Set AIC_SDK_LICENSE and pass a Tyto model path'); const model = Model.fromFile(modelPath); let analyzer; try { analyzer = new Analyzer(model, key); const rate = model.getOptimalSampleRate(); const size = model.getOptimalBlockSize(rate); analyzer.initialize(rate, size); const silence = new Float32Array(size); for (let samples = 0; samples < 5 * rate; samples += size) analyzer.buffer(silence); const result = await analyzer.analyzeAsync(); console.log(result); } finally { if (analyzer) analyzer.dispose(); model.dispose(); } } main().catch((error) => { console.error(error.message); process.exitCode = 1; }); ``` ## Related [Node.js API index](/reference/sdk/api/node/index) · [Errors and recovery](/reference/sdk/api/node/errors) · [Stream lifecycle](/reference/concepts/streams-and-state). # Node.js enhancement API Source: https://docs.ai-coustics.com/reference/sdk/api/node/enhancement Process mono audio synchronously or asynchronously and control enhancement state. **Version:** `@ai-coustics/aic-sdk` 0.26.0, Core SDK 0.26.0. [API index](/reference/sdk/api/node/index) · [Node.js quickstart](/reference/sdk/language-bindings/nodejs). ## `Processor` Synchronous mono enhancement on the calling JavaScript thread. Use an enhancement or bypass model and a separate instance for each stream. Initialize before processing. The input buffer is modified in place. ### `Processor.constructor` ```typescript theme={null} constructor(model: Model, licenseKey: string, otelConfig?: OtelConfig | undefined | null) ``` `model` must be a live model handle of the required type. `licenseKey` is the SDK credential string; see [authentication](/models/get-started/authenticate-apps). Construction is synchronous and can throw for an invalid key, a disposed model or a model-type mismatch. Omitted or `null` `otelConfig` uses environment settings; otherwise pass an [OtelConfig](/reference/sdk/api/node/models-and-config#node-otelconfig) object. There is no automatic initialization. ### `Processor.dispose` ```typescript theme={null} dispose(): void ``` Destroys the native processor synchronously. Repeated calls have no effect. Later methods on this object throw `Processor has been disposed`. A context retained separately no longer reaches a live processor. ### `Processor.initialize` ```typescript theme={null} initialize(sampleRate: number, blockSize: number, variableBlockSize?: boolean | undefined | null): void ``` `sampleRate` is a whole-number rate in Hz; `blockSize` is a positive whole-number mono sample count. Query `model.getOptimalBlockSize(sampleRate)` for the preferred size. Omitted, `undefined` or `null` `variableBlockSize` means `false`, requiring exactly `blockSize` samples. Variable mode allows shorter blocks, with possible buffering delay, but rejects larger blocks. Unsupported configurations throw an SDK error. Initialization allocates memory. The streaming SDK accepts supported rates from 8,000 through 192,000 Hz. Call on the setup path before `process`. ### `Processor.process` ```typescript theme={null} process(audio: Float32Array): void ``` `audio` must be a mono `Float32Array` of normalized samples, nominally -1 to 1, matching initialization. Writes enhanced samples directly into the caller's array and returns `void`. Throws before initialization, after disposal, for a block mismatch or when processing is disallowed. If the underlying buffer is shared with another worker, prevent all concurrent access while this call runs. Copy input yourself if you need the original. ### `Processor.getContext` ```typescript theme={null} getContext(): ProcessorContext ``` Returns an independent JavaScript handle to this processor's shared control state. Throws after processor disposal. Releasing the context does not destroy the processor. ### `Processor.getEnergyVadContext` ```typescript theme={null} getEnergyVadContext(): EnergyVadContext ``` Returns an [`EnergyVadContext`](/reference/sdk/api/node/vad#node-energyvadcontext) that detects speech from this processor's enhanced signal before output mixing, without running a separate VAD model. The prediction updates as `process()` consumes audio. All handles from one processor share a single detector. Creating a handle keeps enhancement inference active even when the processor is bypassed or its enhancement level is zero, and it stays active for the processor's lifetime after every handle is released. Allocates memory; keep it out of audio callbacks. Throws after disposal of the processor. ### `Processor.terminateSession` ```typescript theme={null} terminateSession(): void ``` Requests termination of the associated session. Once termination is handled, further processing is disallowed. This does not release the native object; still call `dispose()`. Completion may involve asynchronous session handling when another session remains active. Do not use it as a flush operation. Runs synchronously and may block. ## `ProcessorAsync` Mono enhancement through Node's shared libuv worker pool. Construction and disposal remain synchronous. Await initialization, then await each block before submitting the next block on the same instance. A mutex protects native access but does not guarantee submission order for overlapping calls. Use separate instances for concurrent streams. ### `ProcessorAsync.constructor` ```typescript theme={null} constructor(model: Model, licenseKey: string, otelConfig?: OtelConfig | undefined | null) ``` `model` must be a live model handle of the required type. `licenseKey` is the SDK credential string; see [authentication](/models/get-started/authenticate-apps). Construction is synchronous and can throw for an invalid key, a disposed model or a model-type mismatch. Omitted or `null` `otelConfig` uses environment settings; otherwise pass an [OtelConfig](/reference/sdk/api/node/models-and-config#node-otelconfig) object. There is no automatic initialization. ### `ProcessorAsync.dispose` ```typescript theme={null} dispose(): void ``` Synchronous and idempotent. Waits if a worker holds the instance lock, so it can block the JavaScript thread. It invalidates all handles sharing this instance, including one returned by `withConfig`. Queued operations that acquire the lock after disposal reject. Await pending operations before disposing. ### `ProcessorAsync.withConfig` ```typescript theme={null} withConfig(sampleRate: number, blockSize: number, variableBlockSize?: boolean | undefined | null): Promise ``` `sampleRate` is a whole-number rate in Hz; `blockSize` is a positive whole-number mono sample count. Query `model.getOptimalBlockSize(sampleRate)` for the preferred size. Omitted, `undefined` or `null` `variableBlockSize` means `false`, requiring exactly `blockSize` samples. Variable mode allows shorter blocks, with possible buffering delay, but rejects larger blocks. Unsupported configurations reject the promise with an SDK error. Initialization allocates memory. Runs initialization on a worker and resolves to another handle to the same native instance, not a cloned processor. Disposing either handle invalidates both. Retain the original handle until initialization succeeds so a rejection can still be cleaned up. ### `ProcessorAsync.initialize` ```typescript theme={null} initialize(sampleRate: number, blockSize: number, variableBlockSize?: boolean | undefined | null): Promise ``` `sampleRate` is a whole-number rate in Hz; `blockSize` is a positive whole-number mono sample count. Query `model.getOptimalBlockSize(sampleRate)` for the preferred size. Omitted, `undefined` or `null` `variableBlockSize` means `false`, requiring exactly `blockSize` samples. Variable mode allows shorter blocks, with possible buffering delay, but rejects larger blocks. Unsupported configurations reject the promise with an SDK error. Initialization allocates memory. Runs on a libuv worker and resolves to `void`. Await it before any processing. SDK initialization failures reject the promise. ### `ProcessorAsync.process` ```typescript theme={null} process(audio: Float32Array): Promise> ``` Copies `audio` into worker-owned memory on the JavaScript thread before queuing work. Resolves to a new `Float32Array` of enhanced samples; the caller's array stays unchanged. The result never uses `SharedArrayBuffer`. Input must meet the same mono format and block-length contract as `Processor.process`. Native errors reject the promise. Await each block to preserve stream order; do not queue an unbounded audio backlog. ### `ProcessorAsync.getContext` ```typescript theme={null} getContext(): Promise ``` Resolves to a `ProcessorContext`. The worker waits for the instance lock. Context methods are synchronous after the handle resolves. Rejects if the processor was disposed before the worker acquired it. ### `ProcessorAsync.getEnergyVadContext` ```typescript theme={null} getEnergyVadContext(): Promise ``` Resolves to an [`EnergyVadContext`](/reference/sdk/api/node/vad#node-energyvadcontext) for this processor. Creation runs on a worker thread because it can wait for processing to release the instance lock. The resolved context's own methods are synchronous and may be called while audio is processed. See [`Processor.getEnergyVadContext`](/reference/sdk/api/node/enhancement#node-processor-getenergyvadcontext) for detector behavior. Rejects after disposal of the processor. ### `ProcessorAsync.terminateSession` ```typescript theme={null} terminateSession(): Promise ``` Requests termination of the associated session. Once termination is handled, further processing is disallowed. This does not release the native object; still call `dispose()`. Completion may involve asynchronous session handling when another session remains active. Do not use it as a flush operation. Runs on a libuv worker; await the returned promise before disposal. ## `ProcessorContext` Control handle obtained from `Processor.getContext()` or `await ProcessorAsync.getContext()`. There is no public constructor or `dispose()` method. Its synchronous methods use the shared control state and may be called while processing runs. A retained handle remains valid after the processor is disposed, but no longer controls a live processor. Keep lifecycle changes outside audio callbacks. ### `ProcessorContext.setParameter` ```typescript theme={null} setParameter(parameter: ProcessorParameter, value: number): void ``` `parameter` selects a `ProcessorParameter`; `value` must meet its range. Converts the JavaScript number to a 32-bit float before setting it. Invalid enum/value arguments throw. See the enum below for bypass's boolean readback behavior. ### `ProcessorContext.getParameter` ```typescript theme={null} getParameter(parameter: ProcessorParameter): number ``` Returns the current stored value for `parameter`, widened from a 32-bit float. For example, setting `0.8` can read back as `Math.fround(0.8)`. Invalid parameter values throw. ### `ProcessorContext.getAudioDelay` ```typescript theme={null} getAudioDelay(): number ``` Returns audio delay in samples at the configured input rate, including model and block-adaptation buffering. Before initialization, it reports delay at the model's default audio configuration. Convert to milliseconds with `samples * 1000 / sampleRate`. It is not wall-clock inference time. ### `ProcessorContext.reset` ```typescript theme={null} reset(): void ``` Requests clearing of processing state and delay buffers before subsequent processing. Audio configuration is preserved. Any [`EnergyVadContext`](/reference/sdk/api/node/vad#node-energyvadcontext) on this processor is reset as well. Use at a seek or stream discontinuity, not between adjacent blocks. It neither emits nor flushes delayed output. ### `ProcessorContext.updateBearerToken` ```typescript theme={null} updateBearerToken(token: string): void ``` `token` replaces a bearer token on a JWT-authenticated session. Both the original credential and replacement must be JWT-form licenses. A synchronous failure preserves the previous token. Return without error confirms local format acceptance, not backend acceptance; subsequent reporting can reject the token and eventually disable work. Obtain a valid replacement to recover. This operation allocates and takes a lock; keep it outside audio callbacks. See [authentication](/models/get-started/authenticate-apps). ## `ProcessorParameter` Exported numeric enum used by `ProcessorContext`. Parameters are stored as 32-bit floats even though JavaScript exposes `number`. Read back the value when exact comparison matters. Changes are observed by subsequent processing; they do not rewrite already produced audio. ### `ProcessorParameter.Bypass` ```typescript theme={null} Bypass = 0 ``` Numeric enum value `0`. The parameter accepts values from 0 to 1: `0` enables enhancement and any value greater than `0` enables bypass. Readback is exactly `0` or `1`. Default is `0`. Bypass preserves processing delay; it is not an undelayed raw-audio path. ### `ProcessorParameter.EnhancementLevel` ```typescript theme={null} EnhancementLevel = 1 ``` Numeric enum value `1`. Accepts 0 to 1. Defaults are taken from model metadata, falling back to `1` where no model default is supplied; read the effective value from the context. The effect depends on the model: compare Quail model suppression and Rook Multi Speaker listening quality on representative audio. ## Example With the pinned package installed, set `AIC_SDK_LICENSE` and run `node enhance-block.cjs path/to/enhancement.aicmodel`. This processes one silent block and reports its length and `newBuffer: true`. It demonstrates buffer ownership, not enhancement quality. Use the [WAV quickstart](/reference/sdk/language-bindings/nodejs) for meaningful audio output. ```javascript enhance-block.cjs theme={null} const { Model, ProcessorAsync } = require('@ai-coustics/aic-sdk'); async function main() { const key = process.env.AIC_SDK_LICENSE; const modelPath = process.argv[2]; if (!key || !modelPath) throw new Error('Set AIC_SDK_LICENSE and pass an enhancement model path'); const model = Model.fromFile(modelPath); let processor; try { processor = new ProcessorAsync(model, key); const rate = model.getOptimalSampleRate(); const size = model.getOptimalBlockSize(rate); await processor.initialize(rate, size); const input = new Float32Array(size); const enhanced = await processor.process(input); console.log({ samples: enhanced.length, newBuffer: enhanced.buffer !== input.buffer }); } finally { if (processor) processor.dispose(); model.dispose(); } } main().catch((error) => { console.error(error.message); process.exitCode = 1; }); ``` ## Related [Node.js API index](/reference/sdk/api/node/index) · [Errors and recovery](/reference/sdk/api/node/errors) · [Stream lifecycle](/reference/concepts/streams-and-state). # Node.js errors Source: https://docs.ai-coustics.com/reference/sdk/api/node/errors Identify thrown errors and rejected promises, then recover with the correct state and inputs. **Version:** `@ai-coustics/aic-sdk` 0.26.0, Core SDK 0.26.0. [API index](/reference/sdk/api/node/index) · [Node.js quickstart](/reference/sdk/language-bindings/nodejs). SDK failures become ordinary JavaScript `Error` objects with the SDK message. This package exports no SDK exception subclasses or public error-code enum. Native SDK errors use N-API's generic-failure category; do not import Python/Rust error class names in Node.js. JavaScript argument conversion can also throw before native work is queued. Synchronous methods and constructors throw. Native work queued by asynchronous methods rejects its promise. Put both construction and `await` inside error handling. Dispose only after outstanding work has settled; never turn a failed operation into a success response or assume an input buffer contains enhanced output. ## Error messages and recovery | Message or cause | Recovery | | - | - | | `Parameter value is outside the acceptable range` | Use the documented enum/range and finite values. Read model defaults before tuning. | | `Handle must be initialized` | Successfully initialize the object before processing or buffering. | | `Audio configuration (sample_rate, block_size) is not supported` | Use a supported whole-number rate and a positive block size; start with model-optimal geometry. | | `Audio block configuration differs` | Match the configured block length or explicitly enable variable blocks. | | `Processing is not allowed` | Check credential authorization and usage-reporting failures. Follow [authentication](/models/get-started/authenticate-apps); do not busy-loop retries. | | `License key format is invalid or corrupted` | Check the credential was copied correctly, including unintended trailing characters. | | `License version is not compatible` | Match the SDK release to the supported credential or contact support. | | `License key has expired` | Renew the credential. For a JWT session, obtain an accepted replacement token. | | `Updating the token is only supported` | Both the original and replacement must be JWT-form credentials. Signed-key sessions cannot be converted through token update. | | `The model file is invalid or corrupted` | Provision a valid complete model file. | | `The model file version is not compatible` | Download a compatible artifact or use the matching SDK. | | `The model type is not supported` | Use enhancement/bypass for Processor, dedicated VAD for Vad and analysis for Analyzer. | | `The file path is invalid` | Supply a valid local path. | | `The model file cannot be opened` | Check file existence and permissions. | | `Model download error:` | Inspect the attached network, manifest, checksum or filesystem detail; correct the cause before retrying. | | `Internal error occurred` / `Unknown error code:` | Record versions and a minimal reproduction without credentials, then contact support. | | `The model data is not aligned to 64 bytes` | Node has no public raw-buffer model loader; if seen through normal Node factories, report a binding/native integration issue rather than manually aligning a JS buffer. | | ` has been disposed` | Construct a new object. Disposal cannot be reversed. | Message excerpts describe this release, not stable programmatic error discriminants. Keep secrets out of logs. For deployment recovery and network requirements, see [authentication](/models/get-started/authenticate-apps) and [SDK telemetry](/reference/concepts/sdk-telemetry). ## Reserved export ## `_setSdkId` ```typescript theme={null} function _setSdkId(id: number): void ``` Reserved internal export for ai-coustics embedding wrappers, not an application configuration API. Sets a telemetry wrapper ID only on the first write in the process; later writes are ignored. Applications should leave this untouched. ## Related [Node.js API index](/reference/sdk/api/node/index) · [Errors and recovery](/reference/sdk/api/node/errors) · [Stream lifecycle](/reference/concepts/streams-and-state). # Node.js API reference Source: https://docs.ai-coustics.com/reference/sdk/api/node/index Complete reference for the released Node.js SDK, including methods, parameters, errors and ownership. **Version:** `@ai-coustics/aic-sdk` 0.26.0, Core SDK 0.26.0. The package supports Node.js 18 and later. Start with the [Node.js quickstart](/reference/sdk/language-bindings/nodejs) for installation and a complete WAV integration. The package is CommonJS with TypeScript declarations. Signature blocks below describe class members; they are not standalone programs. Example blocks have a filename and can be saved as `.cjs` files. This release has no public `FileAnalyzer`, `Collector` or `ProcessorConfig` class. Analysis collection is part of `Analyzer`; audio settings are arguments to `initialize`. ## Choose an API | Task | Reference | Ownership and execution | | - | - | - | | Download/load a model and inspect versions | [Models and configuration](/reference/sdk/api/node/models-and-config) | Model weights are shared; downloaded files are separate from live handles. | | Enhance audio on the calling thread | [Processor](/reference/sdk/api/node/enhancement#node-processor) | Mutates the caller's mono `Float32Array` in place. | | Enhance through the worker pool | [ProcessorAsync](/reference/sdk/api/node/enhancement#node-processorasync) | Copies input before queuing and returns a new enhanced array. | | Detect speech with a dedicated VAD model | [Vad and VadAsync](/reference/sdk/api/node/vad) | Input is preserved. The async call returns a copy of the original samples. | | Detect speech from an enhancement processor | [EnergyVadContext](/reference/sdk/api/node/vad#node-energyvadcontext) | Reads the processor's enhanced signal; no separate model or process call. | | Inspect a retained audio window | [Analyzer and AnalysisResult](/reference/sdk/api/node/analysis) | Buffer synchronously; run analysis synchronously or on a worker. | | Recover from a failure | [Errors](/reference/sdk/api/node/errors) | Plain JavaScript errors; native async work rejects promises. | ## Audio and lifecycle Pass mono, normalized 32-bit floating-point samples, nominally -1 to 1, in `Float32Array`. Each initialized stream has a sample rate and block length. Fixed blocks must match exactly; variable mode permits shorter blocks, never larger ones. Preserve stream order and state. Use one processor, VAD or analyzer per independent stream, while sharing a compatible `Model` where useful. Async methods use Node's shared libuv pool, not a private thread per object. They share capacity with other pool work. Set `UV_THREADPOOL_SIZE` before Node starts only when measurements justify it. `AIC_NUM_THREADS` does not configure these bindings. Async constructors, context methods, collection and disposal remain synchronous. Do not infer that every method on an async class is safe for an audio callback. Await pending operations before calling `dispose()` in `finally` to avoid synchronous waits. In Node.js SDK 0.26.0, `Analyzer.dispose()` can run during async analysis but waits for its analyzer lock. Disposal is idempotent but cannot be reversed. `terminateSession()` is a session-lifecycle request, not disposal or a flush. Contexts retain control state independently; after the owner is destroyed, they cannot operate a live stream. The `withConfig()` result shares the original instance rather than making a copy. Model mappings stay alive while any dependent instance retains them. ## `__napiBindingTarget` ```typescript theme={null} const __napiBindingTarget: 'native' | 'wasm32-wasi' | 'wasm32-wasip1' ``` Reports which binding artifact the package loader loaded in this process. `native` identifies a native addon; a WASI value identifies its `platformArchABI`. The type lists every WASI flavor that napi-rs can build. `NAPI_RS_NATIVE_LIBRARY_PATH` can select a WASI artifact that this package does not build itself, so use the value to report the loaded target rather than to infer the package's built-in targets. ## Complete symbol index All application-facing exports, constructors, methods, interface fields and enum values are listed below. `_setSdkId` is a shipped internal export and is explicitly marked reserved. `__napiBindingTarget` reports loader metadata. | Symbol | Domain | | - | - | | [`_setSdkId`](/reference/sdk/api/node/errors#node-_setsdkid) | errors (reserved) | | [`__napiBindingTarget`](/reference/sdk/api/node/index#node-napibindingtarget) | package metadata | | [`AnalysisResult`](/reference/sdk/api/node/analysis#node-analysisresult) | analysis | | [`AnalysisResult.codecDegradation`](/reference/sdk/api/node/analysis#node-analysisresult-codecdegradation) | analysis | | [`AnalysisResult.interferingSpeech`](/reference/sdk/api/node/analysis#node-analysisresult-interferingspeech) | analysis | | [`AnalysisResult.noise`](/reference/sdk/api/node/analysis#node-analysisresult-noise) | analysis | | [`AnalysisResult.packetLoss`](/reference/sdk/api/node/analysis#node-analysisresult-packetloss) | analysis | | [`AnalysisResult.riskScore`](/reference/sdk/api/node/analysis#node-analysisresult-riskscore) | analysis | | [`AnalysisResult.speakerLoudness`](/reference/sdk/api/node/analysis#node-analysisresult-speakerloudness) | analysis | | [`AnalysisResult.speakerReverb`](/reference/sdk/api/node/analysis#node-analysisresult-speakerreverb) | analysis | | [`Analyzer`](/reference/sdk/api/node/analysis#node-analyzer) | analysis | | [`Analyzer.analyze`](/reference/sdk/api/node/analysis#node-analyzer-analyze) | analysis | | [`Analyzer.analyzeAsync`](/reference/sdk/api/node/analysis#node-analyzer-analyzeasync) | analysis | | [`Analyzer.buffer`](/reference/sdk/api/node/analysis#node-analyzer-buffer) | analysis | | [`Analyzer.constructor`](/reference/sdk/api/node/analysis#node-analyzer-constructor) | analysis | | [`Analyzer.dispose`](/reference/sdk/api/node/analysis#node-analyzer-dispose) | analysis | | [`Analyzer.initialize`](/reference/sdk/api/node/analysis#node-analyzer-initialize) | analysis | | [`Analyzer.reset`](/reference/sdk/api/node/analysis#node-analyzer-reset) | analysis | | [`Analyzer.terminateSession`](/reference/sdk/api/node/analysis#node-analyzer-terminatesession) | analysis | | [`Analyzer.updateBearerToken`](/reference/sdk/api/node/analysis#node-analyzer-updatebearertoken) | analysis | | [`EnergyVadContext`](/reference/sdk/api/node/vad#node-energyvadcontext) | VAD | | [`EnergyVadContext.getParameter`](/reference/sdk/api/node/vad#node-energyvadcontext-getparameter) | VAD | | [`EnergyVadContext.getPredictionDelay`](/reference/sdk/api/node/vad#node-energyvadcontext-getpredictiondelay) | VAD | | [`EnergyVadContext.isSpeechDetected`](/reference/sdk/api/node/vad#node-energyvadcontext-isspeechdetected) | VAD | | [`EnergyVadContext.reset`](/reference/sdk/api/node/vad#node-energyvadcontext-reset) | VAD | | [`EnergyVadContext.setParameter`](/reference/sdk/api/node/vad#node-energyvadcontext-setparameter) | VAD | | [`getCompatibleModelVersion`](/reference/sdk/api/node/models-and-config#node-getcompatiblemodelversion) | models and config | | [`getVersion`](/reference/sdk/api/node/models-and-config#node-getversion) | models and config | | [`Model`](/reference/sdk/api/node/models-and-config#node-model) | models and config | | [`Model.dispose`](/reference/sdk/api/node/models-and-config#node-model-dispose) | models and config | | [`Model.download`](/reference/sdk/api/node/models-and-config#node-model-download) | models and config | | [`Model.fromFile`](/reference/sdk/api/node/models-and-config#node-model-fromfile) | models and config | | [`Model.getId`](/reference/sdk/api/node/models-and-config#node-model-getid) | models and config | | [`Model.getOptimalBlockSize`](/reference/sdk/api/node/models-and-config#node-model-getoptimalblocksize) | models and config | | [`Model.getOptimalSampleRate`](/reference/sdk/api/node/models-and-config#node-model-getoptimalsamplerate) | models and config | | [`OtelConfig`](/reference/sdk/api/node/models-and-config#node-otelconfig) | models and config | | [`OtelConfig.enable`](/reference/sdk/api/node/models-and-config#node-otelconfig-enable) | models and config | | [`OtelConfig.exportIntervalMs`](/reference/sdk/api/node/models-and-config#node-otelconfig-exportintervalms) | models and config | | [`OtelConfig.sessionId`](/reference/sdk/api/node/models-and-config#node-otelconfig-sessionid) | models and config | | [`Processor`](/reference/sdk/api/node/enhancement#node-processor) | enhancement | | [`Processor.constructor`](/reference/sdk/api/node/enhancement#node-processor-constructor) | enhancement | | [`Processor.dispose`](/reference/sdk/api/node/enhancement#node-processor-dispose) | enhancement | | [`Processor.getContext`](/reference/sdk/api/node/enhancement#node-processor-getcontext) | enhancement | | [`Processor.getEnergyVadContext`](/reference/sdk/api/node/enhancement#node-processor-getenergyvadcontext) | enhancement | | [`Processor.initialize`](/reference/sdk/api/node/enhancement#node-processor-initialize) | enhancement | | [`Processor.process`](/reference/sdk/api/node/enhancement#node-processor-process) | enhancement | | [`Processor.terminateSession`](/reference/sdk/api/node/enhancement#node-processor-terminatesession) | enhancement | | [`ProcessorAsync`](/reference/sdk/api/node/enhancement#node-processorasync) | enhancement | | [`ProcessorAsync.constructor`](/reference/sdk/api/node/enhancement#node-processorasync-constructor) | enhancement | | [`ProcessorAsync.dispose`](/reference/sdk/api/node/enhancement#node-processorasync-dispose) | enhancement | | [`ProcessorAsync.getContext`](/reference/sdk/api/node/enhancement#node-processorasync-getcontext) | enhancement | | [`ProcessorAsync.getEnergyVadContext`](/reference/sdk/api/node/enhancement#node-processorasync-getenergyvadcontext) | enhancement | | [`ProcessorAsync.initialize`](/reference/sdk/api/node/enhancement#node-processorasync-initialize) | enhancement | | [`ProcessorAsync.process`](/reference/sdk/api/node/enhancement#node-processorasync-process) | enhancement | | [`ProcessorAsync.terminateSession`](/reference/sdk/api/node/enhancement#node-processorasync-terminatesession) | enhancement | | [`ProcessorAsync.withConfig`](/reference/sdk/api/node/enhancement#node-processorasync-withconfig) | enhancement | | [`ProcessorContext`](/reference/sdk/api/node/enhancement#node-processorcontext) | enhancement | | [`ProcessorContext.getAudioDelay`](/reference/sdk/api/node/enhancement#node-processorcontext-getaudiodelay) | enhancement | | [`ProcessorContext.getParameter`](/reference/sdk/api/node/enhancement#node-processorcontext-getparameter) | enhancement | | [`ProcessorContext.reset`](/reference/sdk/api/node/enhancement#node-processorcontext-reset) | enhancement | | [`ProcessorContext.setParameter`](/reference/sdk/api/node/enhancement#node-processorcontext-setparameter) | enhancement | | [`ProcessorContext.updateBearerToken`](/reference/sdk/api/node/enhancement#node-processorcontext-updatebearertoken) | enhancement | | [`ProcessorParameter`](/reference/sdk/api/node/enhancement#node-processorparameter) | enhancement | | [`ProcessorParameter.Bypass`](/reference/sdk/api/node/enhancement#node-processorparameter-bypass) | enhancement | | [`ProcessorParameter.EnhancementLevel`](/reference/sdk/api/node/enhancement#node-processorparameter-enhancementlevel) | enhancement | | [`Vad`](/reference/sdk/api/node/vad#node-vad) | VAD | | [`Vad.constructor`](/reference/sdk/api/node/vad#node-vad-constructor) | VAD | | [`Vad.dispose`](/reference/sdk/api/node/vad#node-vad-dispose) | VAD | | [`Vad.getContext`](/reference/sdk/api/node/vad#node-vad-getcontext) | VAD | | [`Vad.initialize`](/reference/sdk/api/node/vad#node-vad-initialize) | VAD | | [`Vad.process`](/reference/sdk/api/node/vad#node-vad-process) | VAD | | [`Vad.terminateSession`](/reference/sdk/api/node/vad#node-vad-terminatesession) | VAD | | [`VadAsync`](/reference/sdk/api/node/vad#node-vadasync) | VAD | | [`VadAsync.constructor`](/reference/sdk/api/node/vad#node-vadasync-constructor) | VAD | | [`VadAsync.dispose`](/reference/sdk/api/node/vad#node-vadasync-dispose) | VAD | | [`VadAsync.getContext`](/reference/sdk/api/node/vad#node-vadasync-getcontext) | VAD | | [`VadAsync.initialize`](/reference/sdk/api/node/vad#node-vadasync-initialize) | VAD | | [`VadAsync.process`](/reference/sdk/api/node/vad#node-vadasync-process) | VAD | | [`VadAsync.terminateSession`](/reference/sdk/api/node/vad#node-vadasync-terminatesession) | VAD | | [`VadAsync.withConfig`](/reference/sdk/api/node/vad#node-vadasync-withconfig) | VAD | | [`VadContext`](/reference/sdk/api/node/vad#node-vadcontext) | VAD | | [`VadContext.getParameter`](/reference/sdk/api/node/vad#node-vadcontext-getparameter) | VAD | | [`VadContext.getPredictionDelay`](/reference/sdk/api/node/vad#node-vadcontext-getpredictiondelay) | VAD | | [`VadContext.getRawVadProbability`](/reference/sdk/api/node/vad#node-vadcontext-getrawvadprobability) | VAD | | [`VadContext.isSpeechDetected`](/reference/sdk/api/node/vad#node-vadcontext-isspeechdetected) | VAD | | [`VadContext.reset`](/reference/sdk/api/node/vad#node-vadcontext-reset) | VAD | | [`VadContext.setParameter`](/reference/sdk/api/node/vad#node-vadcontext-setparameter) | VAD | | [`VadContext.updateBearerToken`](/reference/sdk/api/node/vad#node-vadcontext-updatebearertoken) | VAD | | [`VadParameter`](/reference/sdk/api/node/vad#node-vadparameter) | VAD | | [`VadParameter.MinimumSpeechDuration`](/reference/sdk/api/node/vad#node-vadparameter-minimumspeechduration) | VAD | | [`VadParameter.Sensitivity`](/reference/sdk/api/node/vad#node-vadparameter-sensitivity) | VAD | | [`VadParameter.SpeechHoldDuration`](/reference/sdk/api/node/vad#node-vadparameter-speechholdduration) | VAD | ## Related [Node.js quickstart](/reference/sdk/language-bindings/nodejs) · [Model catalog](/reference/sdk/models) · [Compatibility matrix](/reference/sdk/compatibility-matrix) · [Authentication](/models/get-started/authenticate-apps). # Node.js models and configuration Source: https://docs.ai-coustics.com/reference/sdk/api/node/models-and-config Load model weights, inspect SDK versions and configure optional OpenTelemetry export. **Version:** `@ai-coustics/aic-sdk` 0.26.0, Core SDK 0.26.0. [API index](/reference/sdk/api/node/index) · [Node.js quickstart](/reference/sdk/language-bindings/nodejs). ## `Model` Read-only model weights. Use `Model.fromFile`; there is no public constructor. Enhancement, VAD and analysis models are different types. A model can supply multiple independent compatible objects. Those objects retain the weights after this handle is disposed. The file stays memory-mapped until the last dependent object is released; do not change or delete it meanwhile. ### `Model.fromFile` ```typescript theme={null} static fromFile(path: string): Model ``` `path` names a local `.aicmodel` file. Loads it synchronously and returns a new handle. Throws for an invalid path, filesystem failure, corrupt model or incompatible format. It does not download the model. Keep the file unchanged while any object retains it. ### `Model.dispose` ```typescript theme={null} dispose(): void ``` Releases this handle's native reference synchronously. Idempotent. Instance methods then throw `Model has been disposed`; existing processors, VADs and analyzers retain their own model reference. Static factories remain callable. ### `Model.download` ```typescript theme={null} static download(modelId: string, downloadDir: string): Promise ``` `modelId` is the exact catalog ID; `downloadDir` is the destination directory, created if needed. Returns a promise for the local path. Work runs on the libuv pool. The downloader resolves a compatible artifact through its manifest/cache and verifies the checksum of an existing file before reuse. It can fetch or refresh metadata and replace an invalid cached file. It can reject for an unknown/incompatible ID, network, checksum or filesystem failure. For a deployment that must load without downloads, provision the file first and use `fromFile`. ### `Model.getId` ```typescript theme={null} getId(): string ``` Returns the loaded model's identifier, which can include build and format suffixes beyond the requested download ID. Use it when recording an evaluation. Throws after disposal. ### `Model.getOptimalSampleRate` ```typescript theme={null} getOptimalSampleRate(): number ``` Returns the model's native rate in Hz as a JavaScript number. Throws after disposal. Native frequency coverage does not expand when host input is resampled from a higher rate. ### `Model.getOptimalBlockSize` ```typescript theme={null} getOptimalBlockSize(sampleRate: number): number ``` `sampleRate` is the intended whole-number input rate in Hz. Returns the corresponding optimal mono block length in samples as a JavaScript number. This query does not validate an entire audio configuration; `initialize` does. Throws after disposal. ## `OtelConfig` A TypeScript object interface, not a JavaScript constructor. Accepted by `Processor`, `ProcessorAsync`, `Vad` and `VadAsync`. Supplying it overrides environment-based OpenTelemetry settings for that instance. `Analyzer` has no `otelConfig` argument in this release. This configuration does not replace SDK authentication or usage reporting. ### `OtelConfig.enable` ```typescript theme={null} enable: boolean ``` Required boolean. Enables or disables OpenTelemetry export for this instance. Disabling it does not waive credential or usage-reporting requirements. ### `OtelConfig.sessionId` ```typescript theme={null} sessionId?: string ``` Optional string. If omitted, the SDK generates a session identifier. Avoid customer data or secrets in this value. ### `OtelConfig.exportIntervalMs` ```typescript theme={null} exportIntervalMs?: number ``` Optional nonnegative whole-number interval in milliseconds. Omission or `0` requests the SDK default of 60,000 ms. The wrapper passes a 32-bit unsigned integer to the SDK. ## `getCompatibleModelVersion` ```typescript theme={null} function getCompatibleModelVersion(): number ``` Returns the model-file format version supported by the loaded SDK. This is not a model display version or npm package version. No credential or model is needed. ## `getVersion` ```typescript theme={null} function getVersion(): string ``` Returns the underlying native SDK version string. It can differ from the npm package version. No credential or model is needed. ## Example Save as `inspect-model.cjs` and run `node inspect-model.cjs path/to/model.aicmodel` after installing the pinned package. This local inspection needs no SDK key. The output identifies the actual model and its native geometry. ```javascript inspect-model.cjs theme={null} const { Model, getVersion, getCompatibleModelVersion } = require('@ai-coustics/aic-sdk'); const modelPath = process.argv[2]; if (!modelPath) throw new Error('Usage: node inspect-model.cjs path/to/model.aicmodel'); const model = Model.fromFile(modelPath); try { const sampleRate = model.getOptimalSampleRate(); console.log({ sdkVersion: getVersion(), modelFormat: getCompatibleModelVersion(), modelId: model.getId(), sampleRate, blockSize: model.getOptimalBlockSize(sampleRate), }); } finally { model.dispose(); } ``` ## Related [Node.js API index](/reference/sdk/api/node/index) · [Errors and recovery](/reference/sdk/api/node/errors) · [Stream lifecycle](/reference/concepts/streams-and-state). # Node.js VAD API Source: https://docs.ai-coustics.com/reference/sdk/api/node/vad Read dedicated speech predictions and configure voice activity detection. **Version:** `@ai-coustics/aic-sdk` 0.26.0, Core SDK 0.26.0. [API index](/reference/sdk/api/node/index) · [Node.js quickstart](/reference/sdk/language-bindings/nodejs). ## `Vad` Synchronous dedicated voice activity detection (VAD). Use a dedicated VAD model and one instance per stream. Initialize before processing. Input audio is read without mutation. Feed original audio before synchronous enhancement changes that buffer. To detect speech from an enhancement model instead, use [`EnergyVadContext`](/reference/sdk/api/node/vad#node-energyvadcontext). ### `Vad.constructor` ```typescript theme={null} constructor(model: Model, licenseKey: string, otelConfig?: OtelConfig | undefined | null) ``` `model` must be a live model handle of the required type. `licenseKey` is the SDK credential string; see [authentication](/models/get-started/authenticate-apps). Construction is synchronous and can throw for an invalid key, a disposed model or a model-type mismatch. Omitted or `null` `otelConfig` uses environment settings; otherwise pass an [OtelConfig](/reference/sdk/api/node/models-and-config#node-otelconfig) object. There is no automatic initialization. ### `Vad.dispose` ```typescript theme={null} dispose(): void ``` Destroys the native VAD synchronously. Idempotent. Later methods on the VAD object throw `Vad has been disposed`. Retained contexts remain readable but no new predictions are produced. ### `Vad.initialize` ```typescript theme={null} initialize(sampleRate: number, blockSize: number, variableBlockSize?: boolean | undefined | null): void ``` `sampleRate` is a whole-number rate in Hz; `blockSize` is a positive whole-number mono sample count. Query `model.getOptimalBlockSize(sampleRate)` for the preferred size. Omitted, `undefined` or `null` `variableBlockSize` means `false`, requiring exactly `blockSize` samples. Variable mode allows shorter blocks, with possible buffering delay, but rejects larger blocks. Unsupported configurations throw an SDK error. Initialization allocates memory. The streaming SDK accepts supported rates from 8,000 through 192,000 Hz. Call before `process`. ### `Vad.process` ```typescript theme={null} process(audio: Float32Array): void ``` Reads mono normalized `Float32Array` samples without modifying the caller's input. The native VAD copies the samples into its processing buffer. Returns `void`; read the updated prediction through `getContext`. Input length must match the initialized block contract. Throws before initialization, for a mismatch, after disposal or when processing is disallowed. Do not concurrently modify a shared input buffer. ### `Vad.getContext` ```typescript theme={null} getContext(): VadContext ``` Returns an independent handle to this VAD's shared prediction and control state. Throws after disposal of the VAD object. ### `Vad.terminateSession` ```typescript theme={null} terminateSession(): void ``` Requests termination of the associated session. Once termination is handled, further processing is disallowed. This does not release the native object; still call `dispose()`. Completion may involve asynchronous session handling when another session remains active. Do not use it as a flush operation. Runs synchronously and may block. ## `VadAsync` Dedicated VAD through Node's shared libuv worker pool. Construction and disposal are synchronous. Await initialization and each processing call in stream order. Concurrent calls on one instance share a lock but have no guaranteed submission order. Use separate instances for independent streams. ### `VadAsync.constructor` ```typescript theme={null} constructor(model: Model, licenseKey: string, otelConfig?: OtelConfig | undefined | null) ``` `model` must be a live model handle of the required type. `licenseKey` is the SDK credential string; see [authentication](/models/get-started/authenticate-apps). Construction is synchronous and can throw for an invalid key, a disposed model or a model-type mismatch. Omitted or `null` `otelConfig` uses environment settings; otherwise pass an [OtelConfig](/reference/sdk/api/node/models-and-config#node-otelconfig) object. There is no automatic initialization. ### `VadAsync.dispose` ```typescript theme={null} dispose(): void ``` Synchronous and idempotent. Can block while a worker holds the native lock. Invalidates both the original object and any `withConfig` handle. Work that acquires the lock after disposal rejects. Await pending operations before disposing. ### `VadAsync.withConfig` ```typescript theme={null} withConfig(sampleRate: number, blockSize: number, variableBlockSize?: boolean | undefined | null): Promise ``` `sampleRate` is a whole-number rate in Hz; `blockSize` is a positive whole-number mono sample count. Query `model.getOptimalBlockSize(sampleRate)` for the preferred size. Omitted, `undefined` or `null` `variableBlockSize` means `false`, requiring exactly `blockSize` samples. Variable mode allows shorter blocks, with possible buffering delay, but rejects larger blocks. Unsupported configurations reject the promise with an SDK error. Initialization allocates memory. Initializes on a worker and resolves to another handle sharing the same native VAD. Disposing either handle invalidates both. Keep the original object available for cleanup if initialization rejects. ### `VadAsync.initialize` ```typescript theme={null} initialize(sampleRate: number, blockSize: number, variableBlockSize?: boolean | undefined | null): Promise ``` `sampleRate` is a whole-number rate in Hz; `blockSize` is a positive whole-number mono sample count. Query `model.getOptimalBlockSize(sampleRate)` for the preferred size. Omitted, `undefined` or `null` `variableBlockSize` means `false`, requiring exactly `blockSize` samples. Variable mode allows shorter blocks, with possible buffering delay, but rejects larger blocks. Unsupported configurations reject the promise with an SDK error. Initialization allocates memory. Runs on a libuv worker. Await the promise before processing; initialization errors reject it. ### `VadAsync.process` ```typescript theme={null} process(audio: Float32Array): Promise> ``` Copies `audio` on the JavaScript thread before queuing work. Resolves to a new `Float32Array` containing the original samples, not enhanced audio or VAD probabilities. The original input is unchanged. Read predictions from `VadContext` after awaiting the call. Format and block constraints match `Vad.process`; native failures reject. ### `VadAsync.getContext` ```typescript theme={null} getContext(): Promise ``` Resolves to a `VadContext` after worker access to the instance lock. The returned context's methods are synchronous. Rejects if the VAD was disposed before the worker acquired it. ### `VadAsync.terminateSession` ```typescript theme={null} terminateSession(): Promise ``` Requests termination of the associated session. Once termination is handled, further processing is disallowed. This does not release the native object; still call `dispose()`. Completion may involve asynchronous session handling when another session remains active. Do not use it as a flush operation. Runs on a libuv worker; await it before disposal. ## `VadContext` Read predictions and control a `Vad` or `VadAsync`. Obtain it through the corresponding `getContext()` method; there is no public constructor or `dispose()`. All methods on this context are synchronous, including a context obtained asynchronously. The handle survives disposal of the VAD, but its prediction stops updating. ### `VadContext.setParameter` ```typescript theme={null} setParameter(parameter: VadParameter, value: number): void ``` Sets `parameter` to `value`, converted to a 32-bit float. Throws for an unknown enum value, an out-of-range value or a non-finite value. Timing controls are seconds; see `VadParameter` below. ### `VadContext.getParameter` ```typescript theme={null} getParameter(parameter: VadParameter): number ``` Returns the current stored 32-bit float value widened to a JavaScript number. The effective detector timing is frame-quantized; do not treat this readback as an observed speech-boundary time. Unknown parameters throw. ### `VadContext.isSpeechDetected` ```typescript theme={null} isSpeechDetected(): boolean ``` Returns the latest boolean decision after sensitivity and speech-timing controls. The result stops changing when no new audio is processed. It lags the corresponding input by `getPredictionDelay()` samples. ### `VadContext.getRawVadProbability` ```typescript theme={null} getRawVadProbability(): number ``` Returns the latest model speech probability from 0 to 1 before sensitivity thresholding, speech hold and minimum duration. The same prediction delay applies. This is not a guarantee that speech is present. ### `VadContext.getPredictionDelay` ```typescript theme={null} getPredictionDelay(): number ``` Returns prediction delay in samples at the configured input rate, including input buffering and model processing. Convert with `delaySamples * 1000 / sampleRate`. It is separate from enhancement audio delay: VAD does not delay or modify the caller's samples. ### `VadContext.reset` ```typescript theme={null} reset(): void ``` Clears the published decision and probability immediately and requests processing-state reset for subsequent audio. Preserves initialization. Reset before unrelated audio or after a discontinuity to prevent stale speech decisions. ### `VadContext.updateBearerToken` ```typescript theme={null} updateBearerToken(token: string): void ``` `token` replaces a bearer token on a JWT-authenticated session. Both the original credential and replacement must be JWT-form licenses. A synchronous failure preserves the previous token. Return without error confirms local format acceptance, not backend acceptance; subsequent reporting can reject the token and eventually disable work. Obtain a valid replacement to recover. This operation allocates and takes a lock; keep it outside audio callbacks. See [authentication](/models/get-started/authenticate-apps). ## `EnergyVadContext` Read energy-based speech predictions from an enhancement `Processor`. Obtain it through [`Processor.getEnergyVadContext()`](/reference/sdk/api/node/enhancement#node-processor-getenergyvadcontext) or `await ProcessorAsync.getEnergyVadContext()`; there is no public constructor or `dispose()`. Detection uses the enhanced signal before output mixing and runs no separate VAD model, so an enhancement model yields speech decisions without a dedicated VAD model. All handles from one processor share a single detector, and every method is synchronous and may be called while audio is processed. The handle survives disposal of the processor, but its prediction stops updating. Releasing it neither destroys the processor nor disables detection. `Sensitivity` uses the energy range, 1 to 15, not the 0 to 1 probability threshold of a dedicated VAD model. See [`VadParameter.Sensitivity`](/reference/sdk/api/node/vad#node-vadparameter-sensitivity). ### `EnergyVadContext.isSpeechDetected` ```typescript theme={null} isSpeechDetected(): boolean ``` Returns the current decision. It is `false` before processing and after `reset()`, and lags its input by `getPredictionDelay()` samples. It stops updating when the backing processor stops processing. ### `EnergyVadContext.setParameter` ```typescript theme={null} setParameter(parameter: VadParameter, value: number): void ``` Sets `parameter` to `value`, converted to a 32-bit float. Throws for an unknown enum value, an out-of-range value or a non-finite value. `Sensitivity` accepts 1 to 15 on this context. ### `EnergyVadContext.getParameter` ```typescript theme={null} getParameter(parameter: VadParameter): number ``` Returns the current stored 32-bit float value widened to a JavaScript number. Unknown parameters throw. ### `EnergyVadContext.getPredictionDelay` ```typescript theme={null} getPredictionDelay(): number ``` Returns the prediction delay in samples at the configured sample rate, covering input buffering, STFT and model processing. It equals the processor's `getAudioDelay()`; energy detection adds no audio delay. A non-optimal or variable block size adds buffering latency, which is included. Convert to milliseconds with `delaySamples * 1000 / sampleRate`. ### `EnergyVadContext.reset` ```typescript theme={null} reset(): void ``` Clears the energy VAD state, including the published decision. Use at a seek or stream discontinuity. Parameters are retained and the processor is not reset. [`ProcessorContext.reset()`](/reference/sdk/api/node/enhancement#node-processorcontext-reset) also resets the energy VAD. ## `VadParameter` Exported numeric enum used by `VadContext` and `EnergyVadContext`. All defaults come from the loaded model; read them with `getParameter`. Timing values are seconds. The detector operates on model frames, so effective timing is quantized to frame boundaries. The stored parameter is a 32-bit float, not a measurement of the resulting decision delay. ### `VadParameter.SpeechHoldDuration` ```typescript theme={null} SpeechHoldDuration = 0 ``` Numeric enum value `0`. Duration in seconds, from 0 through 300 times the model window length. Controls how recent speech sustains a positive decision when the current probability is at or below the threshold: speech is reported when at least half of the frames in the lookback window (twice the hold duration) contain speech. When the current probability is above the threshold, the consecutive-frame rule set by `MinimumSpeechDuration` applies instead. Effective timing is rounded to model frames. Default is model-specific. ### `VadParameter.Sensitivity` ```typescript theme={null} Sensitivity = 1 ``` Numeric enum value `1`. Its meaning depends on the detector. On a `VadContext`, it is a probability threshold from 0 to 1: a model probability above this value counts as speech, so higher values require stronger evidence. On an [`EnergyVadContext`](/reference/sdk/api/node/vad#node-energyvadcontext), it sets the energy threshold of the enhanced signal to `10 ** -sensitivity` over the range 1 to 15, so higher values detect quieter speech. Default is model-specific. ### `VadParameter.MinimumSpeechDuration` ```typescript theme={null} MinimumSpeechDuration = 2 ``` Numeric enum value `2`. Duration in seconds from 0 to 1. Controls the speech duration required before a positive decision. Effective timing is rounded to model frames. Default is model-specific. ## Example With the pinned package installed, set `AIC_SDK_LICENSE` and run `node detect-block.cjs path/to/vad.aicmodel`. The object printed contains a decision, probability, prediction delay and model sensitivity. One silent block does not measure detection quality. Feed representative speech and pauses in sequence to evaluate decisions. ```javascript detect-block.cjs theme={null} const { Model, Vad, VadParameter } = require('@ai-coustics/aic-sdk'); const key = process.env.AIC_SDK_LICENSE; const modelPath = process.argv[2]; if (!key || !modelPath) throw new Error('Set AIC_SDK_LICENSE and pass a dedicated VAD model path'); const model = Model.fromFile(modelPath); let vad; try { vad = new Vad(model, key); const rate = model.getOptimalSampleRate(); const size = model.getOptimalBlockSize(rate); vad.initialize(rate, size); const context = vad.getContext(); const input = new Float32Array(size); vad.process(input); console.log({ speech: context.isSpeechDetected(), probability: context.getRawVadProbability(), delaySamples: context.getPredictionDelay(), sensitivity: context.getParameter(VadParameter.Sensitivity), }); } finally { if (vad) vad.dispose(); model.dispose(); } ``` ## Related [Node.js API index](/reference/sdk/api/node/index) · [Errors and recovery](/reference/sdk/api/node/errors) · [Stream lifecycle](/reference/concepts/streams-and-state). # Python audio analysis Source: https://docs.ai-coustics.com/reference/sdk/api/python/analysis Python reference for `analyzer_pair`, `Collector`, `Analyzer`, `FileAnalyzer` and `AnalysisResult` in aic-sdk. **Package:** `aic-sdk==3.4.0`. **Core SDK:** `0.26.0`. The fragments below use these imports. Supply `license_key` from your approved secret source and use the loaded model and initialized objects described in each section. For complete examples, follow [batch call analysis](/models/audio-insight/batch-call-analysis) with `FileAnalyzer` or [real-time analysis](/models/audio-insight/real-time-analysis) with `analyzer_pair`. ```python theme={null} import numpy as np import numpy.typing as npt import aic_sdk as aic from aic_sdk import Model, ProcessorConfig, Collector, Analyzer, FileAnalyzer, AnalysisResult ``` `audio` denotes a one-dimensional NumPy `float32` array. Async fragments run inside an async function. ## `analyzer_pair()` function ```python theme={null} def analyzer_pair(model: Model, license_key: str) -> tuple[Collector, Analyzer] ``` For a complete collector/worker example, follow [real-time analysis with Tyto](/models/audio-insight/real-time-analysis). Creates a [`Collector`](/reference/sdk/api/python/analysis#collector)/[`Analyzer`](/reference/sdk/api/python/analysis#analyzer) pair for non-real-time analysis. Buffer audio in the capture path and run analysis on a separate thread. The analyzer safely reads the collector across threads. Native buffering releases the GIL, but interpreter calls and strided-array copies do not guarantee hard real-time execution. The collector retains a span of audio determined by the analysis model. As more samples get collected, old audio is discarded. **Parameters** **model** `Model` *required* The loaded model instance. See [`Model`](/reference/sdk/api/python/models-and-config#model). **license\_key** `str` *required* SDK key or JWT for the ai-coustics SDK (generate your key at [developers.ai-coustics.com](https://developers.ai-coustics.com/)). **Returns** * `tuple[Collector, Analyzer]`: A tuple of ([`Collector`](/reference/sdk/api/python/analysis#collector), [`Analyzer`](/reference/sdk/api/python/analysis#analyzer)). **Raises** * [`LicenseFormatInvalidError`](/reference/sdk/api/python/errors#licenseformatinvaliderror): If the license key string contains null bytes. * [SDK exceptions](/reference/sdk/api/python/errors): Invalid credentials, an unsupported model type or native creation failures. **Example** ```python theme={null} collector, analyzer = aic.analyzer_pair(model, license_key) config = aic.ProcessorConfig.optimal(model) collector.initialize(config) ``` ## `Collector` class Buffers audio for later analysis. The collector is designed to be placed in the audio thread, buffering audio chunks for the [`Analyzer`](/reference/sdk/api/python/analysis#analyzer) to analyze later. Created via [`analyzer_pair()`](/reference/sdk/api/python/analysis#analyzer_pair). ### `Collector.initialize()` ```python theme={null} def initialize(self, config: ProcessorConfig) -> None ``` Configures the collector for specific audio settings. This function must be called before buffering any audio. Using the sample rate and block size returned by [`Model.get_optimal_sample_rate()`](/reference/sdk/api/python/models-and-config#model-get_optimal_sample_rate) and [`Model.get_optimal_block_size()`](/reference/sdk/api/python/models-and-config#model-get_optimal_block_size) avoids internal resampling and rebuffering. **Parameters** **config** `ProcessorConfig` *required* Audio buffering configuration. See [`ProcessorConfig`](/reference/sdk/api/python/models-and-config#processorconfig). **Raises** * [`AudioConfigUnsupportedError`](/reference/sdk/api/python/errors#audioconfigunsupportederror): If the audio configuration is unsupported. > [!WARNING] > > Do not call from audio processing threads as this allocates memory. **Example** ```python theme={null} config = aic.ProcessorConfig.optimal(model) collector.initialize(config) ``` ### `Collector.buffer()` ```python theme={null} def buffer(self, buffer: npt.NDArray[np.float32]) -> None ``` Buffers a one-dimensional NumPy `float32` array of mono samples without changing it. Contiguous arrays are read directly and strided arrays are copied. Do not mutate input concurrently. Native work releases the GIL. Supply the configured fixed length or a length up to `block_size` when variable blocks are enabled. Wrong dtype or dimensionality raises `TypeError`. **Parameters** **buffer** `npt.NDArray[np.float32]` *required* 1D NumPy array of mono float32 samples to be buffered. **Raises** * [`NotInitializedError`](/reference/sdk/api/python/errors#notinitializederror): If the collector has not been initialized. * [`AudioConfigMismatchError`](/reference/sdk/api/python/errors#audioconfigmismatcherror): If the buffer shape doesn't match the configured audio settings. **Example** ```python theme={null} audio = np.zeros(config.block_size, dtype=np.float32) collector.buffer(audio) ``` ## `Analyzer` class Runs an analysis model over the audio buffered by a [`Collector`](/reference/sdk/api/python/analysis#collector). Run analysis outside the audio thread. The analyzer safely reads audio from a collector on another thread. Created via [`analyzer_pair()`](/reference/sdk/api/python/analysis#analyzer_pair). ### `Analyzer.reset()` ```python theme={null} def reset(self) -> None ``` Requests a reset of analyzer and collector state and buffers. The collector applies it on the next collection pass. Until then, analysis reads a zero-filled snapshot instead of the previously published audio. Call this when the audio stream is interrupted or when seeking to prevent mispredictions from previous audio content. This operates on both the analyzer and its collector. The collector stays initialized to the configured settings. > [!NOTE] > > **Concurrency.** Reset requests clear shared analyzer and collector state. Serialize reset with your application's stream boundaries; Python calls are not a hard real-time guarantee. **Example** ```python theme={null} analyzer.reset() ``` ### `Analyzer.analyze_buffered()` ```python theme={null} def analyze_buffered(self) -> AnalysisResult ``` Analyzes the buffered signal, releasing the GIL during native work. Calls on the same analyzer must be serialized. `ProcessingNotAllowedError` means no `AnalysisResult` is returned; other native failures use the [SDK exception mapping](/reference/sdk/api/python/errors). Analyzes a fixed-length window determined by the model. If the collector has buffered less audio, the input tail is padded with silence. **Returns** * [`AnalysisResult`](/reference/sdk/api/python/analysis#analysisresult): An AnalysisResult. > [!NOTE] > > This function is not real-time safe. Avoid calling it from audio threads. **Example** ```python theme={null} result = analyzer.analyze_buffered() print(result.risk_score) ``` ### `Analyzer.terminate_session()` ```python theme={null} def terminate_session(self) -> None ``` Terminates the analyzer's telemetry session. Stop submitting audio and treat this session as closed once you request termination. Processing becomes disallowed when the native lifecycle task handles the signal. The call can return before that handling completes when other sessions remain alive; it is not proof of remote usage acknowledgment. The session is also stopped when the object is destroyed. > [!WARNING] > > This method may block and is not real-time safe. ### `Analyzer.update_bearer_token()` ```python theme={null} def update_bearer_token(self, token: str) -> None ``` Replaces the bearer token on the analyzer. Use this when your license key is a JWT and needs to be refreshed before it expires. The replacement is used for subsequent authentication. A successful update does not prove backend acceptance or uninterrupted processing; continue handling processing errors. Both the original key and the new token must be JWTs; otherwise a [`TokenUnsupportedError`](/reference/sdk/api/python/errors#tokenunsupportederror) is raised and the existing token stays in use. **Parameters** **token** `str` *required* The new JWT to install. **Raises** * [`TokenUnsupportedError`](/reference/sdk/api/python/errors#tokenunsupportederror): If either the original or new token is not a JWT. * [`LicenseFormatInvalidError`](/reference/sdk/api/python/errors#licenseformatinvaliderror): If the token string contains null bytes. **Example** ```python theme={null} analyzer.update_bearer_token(renewed_jwt) ``` ## `FileAnalyzer` class Analyzes complete mono audio buffers. FileAnalyzer is a convenience wrapper around a [`Collector`](/reference/sdk/api/python/analysis#collector) and [`Analyzer`](/reference/sdk/api/python/analysis#analyzer) pair for non-real-time analysis of audio that is already loaded in memory. Each call to [`analyze()`](/reference/sdk/api/python/analysis#fileanalyzer-analyze) configures the collector for mono input with the model's optimal block size. It analyzes independent five-second windows, advancing the start of each window by `step_samples`. For a complete file-analysis example, follow [batch call analysis with Tyto](/models/audio-insight/batch-call-analysis). For streaming analysis, use [`analyzer_pair()`](/reference/sdk/api/python/analysis#analyzer_pair) directly. **Example** ```python theme={null} analyzer = aic.FileAnalyzer(model, license_key) results = analyzer.analyze(audio, 16000) print(results[0].risk_score) ``` ### `FileAnalyzer()` constructor ```python theme={null} FileAnalyzer(model: Model, license_key: str) -> FileAnalyzer ``` Creates a new file analyzer for a Tyto analysis model. The wrapper retains a strong reference to `model`. There is no file-path argument: decode the file into mono `float32` samples before calling `analyze()`. Native resources are released when the object is released. This class has no public token-update or session-termination method; use the streaming `Analyzer` when those controls are needed. The collector is not initialized until [`analyze()`](/reference/sdk/api/python/analysis#fileanalyzer-analyze) is called. This lets the same FileAnalyzer instance analyze mono buffers with different sample rates or step sizes. **Parameters** **model** `Model` *required* The loaded model instance. See [`Model`](/reference/sdk/api/python/models-and-config#model). **license\_key** `str` *required* SDK key or JWT for the ai-coustics SDK (generate your key at [developers.ai-coustics.com](https://developers.ai-coustics.com/)). **Raises** * [`LicenseFormatInvalidError`](/reference/sdk/api/python/errors#licenseformatinvaliderror): If the license key string contains null bytes. * [SDK exceptions](/reference/sdk/api/python/errors): Invalid credentials, an unsupported model type or native creation failures. **Example** ```python theme={null} analyzer = aic.FileAnalyzer(model, license_key) ``` ### `FileAnalyzer.analyze()` ```python theme={null} def analyze( self, audio: npt.NDArray[np.float32], sample_rate: int, step_samples: int | None = None, ) -> list[AnalysisResult] ``` Analyzes a complete mono audio buffer. The input must be a one-dimensional NumPy `float32` array of mono samples at the actual `sample_rate`. There is no channel mixing. Native collection handles supported non-native input rates. The wrapper reads contiguous input directly and copies strided input; native analysis releases the GIL. Do not mutate the input concurrently. Wrong dtype or dimensionality raises `TypeError`. The analyzer evaluates five-second windows. FileAnalyzer buffers a window starting at sample 0, runs the analyzer once, resets, then repeats with a window starting `step_samples` later. If audio is empty, shorter than or equal to five seconds, it is padded with silence and a single result is returned. For longer signals, only complete five-second windows are analyzed after the first window. **Parameters** **audio** `npt.NDArray[np.float32]` *required* 1D NumPy array of mono float32 samples to analyze. **sample\_rate** `int` *required* Sample rate of audio in Hz. **step\_samples** `int | None` (default: None) Number of samples to advance between analysis results. Defaults to `5 * sample_rate` samples with no overlap. Must be greater than zero. Smaller values overlap windows; larger values leave gaps. **Returns** * `list[AnalysisResult]`: A list of [`AnalysisResult`](/reference/sdk/api/python/analysis#analysisresult) values, one per analysis window. **Raises** * [`AudioConfigUnsupportedError`](/reference/sdk/api/python/errors#audioconfigunsupportederror): If the sample rate or step size is unsupported. **Example** ```python theme={null} results = analyzer.analyze(audio, 16000) print(results[0].risk_score) ``` ## `AnalysisResult` class The result of analyzing an audio signal with an [`Analyzer`](/reference/sdk/api/python/analysis#analyzer). Returned results expose read-only properties; there is no public `AnalysisResult()` constructor. Scores are model outputs in the range 0.0–1.0, not calibrated probabilities or guarantees about a specific downstream system. For all fields except `speaker_loudness`, lower values indicate less problematic audio. #### `AnalysisResult.risk_score` **risk\_score** `float` Headline audio score. Predicts likelihood of failure of downstream models including speech-to-text, voice activity detection or turn-taking or speech-to-speech models. Lower indicates less problematic audio. **Range:** 0.0–1.0 #### `AnalysisResult.speaker_reverb` **speaker\_reverb** `float` Measure of speaker distance and reverberance. Lower indicates less problematic audio. **Range:** 0.0–1.0 #### `AnalysisResult.speaker_loudness` **speaker\_loudness** `float` Measure of speaker loudness. **Range:** 0.0–1.0 #### `AnalysisResult.interfering_speech` **interfering\_speech** `float` Measure of interference from additional speakers present in audio. Lower indicates less problematic audio. **Range:** 0.0–1.0 #### `AnalysisResult.noise` **noise** `float` Measure of ambient or environmental noise. Lower indicates less problematic audio. **Range:** 0.0–1.0 #### `AnalysisResult.codec_degradation` **codec\_degradation** `float` Measure of artifacts introduced by lossy speech codecs, e.g. from a low bitrate or a narrowband codec. Lower indicates less problematic audio. **Range:** 0.0–1.0 Added in Python package 3.1.0. #### `AnalysisResult.packet_loss` **packet\_loss** `float` Measure of audio dropouts or discontinuities in the stream, e.g. from packet loss, frame erasure, jitter or CPU overload. Lower indicates less problematic audio. **Range:** 0.0–1.0 See the [Python API index](/reference/sdk/api/python/index), [batch call analysis](/models/audio-insight/batch-call-analysis), [real-time analysis](/models/audio-insight/real-time-analysis) and [troubleshooting](/production/troubleshooting). ### `AnalysisResult.__repr__()` ```python theme={null} def __repr__(self) -> str ``` Returns a diagnostic string containing the object's current fields. It is not a serialization format. # Python enhancement Source: https://docs.ai-coustics.com/reference/sdk/api/python/enhancement Python reference for Processor, ProcessorAsync, ProcessorContext and ProcessorParameter in aic-sdk. **Package:** `aic-sdk==3.4.0`. **Core SDK:** `0.26.0`. The fragments below use these imports. Supply `license_key` from your approved secret source and use the loaded model and initialized objects described in each section. For a complete file-processing example, follow the [Python guide](/reference/sdk/language-bindings/python). ```python theme={null} import typing import numpy as np import numpy.typing as npt from aic_sdk import Model, Processor, ProcessorAsync, ProcessorConfig, ProcessorContext, ProcessorParameter, OtelConfig ``` `audio` denotes a one-dimensional NumPy `float32` array. Async fragments run inside an async function. ## `Processor` class Stateful mono audio enhancement. Use one processor per independent audio stream. Initialization and processing on the same synchronous instance must not overlap. A context can control parameters from another thread. Native resources are released when Python releases the object; explicit session termination is permanent for that instance. **Example** ```python theme={null} model = Model.from_file("/path/to/model.aicmodel") processor = Processor(model, license_key) config = ProcessorConfig.optimal(model) processor.initialize(config) audio = np.zeros(config.block_size, dtype=np.float32) enhanced = processor.process(audio) ``` ### `Processor()` constructor ```python theme={null} Processor( model: Model, license_key: str, config: ProcessorConfig | None = None, otel_config: OtelConfig | None = None, ) -> Processor ``` Creates a new audio enhancement processor instance. Use separate processors for concurrent streams or different enhancement models. If a config is provided, the processor will be initialized immediately. Otherwise, you must call [`initialize()`](/reference/sdk/api/python/enhancement#processor-initialize) before processing audio. **Parameters** **model** `Model` *required* The loaded enhancement or bypass model instance. See [`Model`](/reference/sdk/api/python/models-and-config#model). **license\_key** `str` *required* SDK key or JWT for the ai-coustics SDK (generate your key at [developers.ai-coustics.com](https://developers.ai-coustics.com/)). **config** `ProcessorConfig | None` (default: None) Optional audio processing configuration. If provided, the processor will be initialized immediately with this configuration. See [`ProcessorConfig`](/reference/sdk/api/python/models-and-config#processorconfig). **otel\_config** `OtelConfig | None` (default: None) Per-instance OpenTelemetry settings. See [`OtelConfig`](/reference/sdk/api/python/models-and-config#otelconfig). **Raises** * [SDK exceptions](/reference/sdk/api/python/errors): Invalid credentials, unsupported model types or native creation failures. * [`AudioConfigUnsupportedError`](/reference/sdk/api/python/errors#audioconfigunsupportederror): If the supplied config is unsupported. **Example** ```python theme={null} # Create processor without initialization processor = Processor(model, license_key) processor.initialize(config) # Or create and initialize in one step config = ProcessorConfig.optimal(model) processor = Processor(model, license_key, config) ``` See also [One model, many streams](/reference/sdk/models#one-model-many-streams). ### `Processor.initialize()` ```python theme={null} def initialize(self, config: ProcessorConfig) -> None ``` Configures the processor for specific audio settings. This function must be called before processing any audio. For the lowest delay use the sample rate and block size returned by [`Model.get_optimal_sample_rate()`](/reference/sdk/api/python/models-and-config#model-get_optimal_sample_rate) and [`Model.get_optimal_block_size()`](/reference/sdk/api/python/models-and-config#model-get_optimal_block_size). **Parameters** **config** `ProcessorConfig` *required* Audio processing configuration. See [`ProcessorConfig`](/reference/sdk/api/python/models-and-config#processorconfig). **Raises** * [`AudioConfigUnsupportedError`](/reference/sdk/api/python/errors#audioconfigunsupportederror): If the audio configuration is unsupported. > [!WARNING] > > Do not call from audio processing threads as this allocates memory. **Example** ```python theme={null} config = ProcessorConfig.optimal(model) processor.initialize(config) ``` ### `Processor.process()` ```python theme={null} def process(self, audio: npt.NDArray[np.float32]) -> npt.NDArray[np.float32] ``` Accepts a one-dimensional NumPy `float32` array and returns a new one-dimensional `float32` array with the same number of samples. The wrapper copies the input before native processing, so the input remains unchanged, including for strided views. It releases the Python GIL during native work. Pass exactly `config.block_size` samples, or 1 through `config.block_size` with `variable_block_size=True`. Values represent normalized audio, conventionally -1.0 to 1.0; the wrapper does not normalize integers or mix channels. Wrong dimensionality or dtype raises `TypeError` before processing. On an SDK error, Python raises an exception and returns no processed array. Implement an explicit fallback if your application must keep delivering audio. **Raises** * [`NotInitializedError`](/reference/sdk/api/python/errors#notinitializederror): If the processor has not been initialized. * [`AudioConfigMismatchError`](/reference/sdk/api/python/errors#audioconfigmismatcherror): If the block size does not match the configuration. * [`ProcessingNotAllowedError`](/reference/sdk/api/python/errors#processingnotallowederror): If processing is not authorized. See also [Block size](/reference/concepts/audio-format#block-size) and [Real-time safety](/reference/concepts/streams-and-state#real-time-safety). ### `Processor.get_context()` ```python theme={null} def get_context(self) -> ProcessorContext ``` Creates a [`ProcessorContext`](/reference/sdk/api/python/enhancement#processorcontext) instance. This can be used to control all parameters and other settings of the processor. **Returns** * [`ProcessorContext`](/reference/sdk/api/python/enhancement#processorcontext): A new ProcessorContext instance. **Example** ```python theme={null} processor_context = processor.get_context() ``` ### `Processor.get_energy_vad_context()` ```python theme={null} def get_energy_vad_context(self) -> EnergyVadContext ``` Creates an [`EnergyVadContext`](/reference/sdk/api/python/vad#energyvadcontext) for energy-based speech detection on this processor. The detector uses the enhanced signal before output mixing and updates when [`process()`](/reference/sdk/api/python/enhancement#processor-process) consumes audio. It shares the processor's enhancement model and runs no separate VAD model. All contexts from this processor share one detector. Creating a context keeps enhancement inference active even when the processor is bypassed or its enhancement level is zero, and inference stays active for the processor's lifetime even after every context is released. **Returns** * [`EnergyVadContext`](/reference/sdk/api/python/vad#energyvadcontext): A new energy VAD context. > [!WARNING] > > This method allocates memory and is not real-time safe. Do not call it from audio processing threads. **Example** ```python theme={null} vad_context = processor.get_energy_vad_context() ``` ### `Processor.terminate_session()` ```python theme={null} def terminate_session(self) -> None ``` Terminates the processor's telemetry session. Stop submitting audio and treat this session as closed once you request termination. Processing becomes disallowed when the native lifecycle task handles the signal. The call can return before that handling completes when other sessions remain alive; it is not proof of remote usage acknowledgment. The session is also stopped when the object is destroyed. > [!WARNING] > > This method may block and is not real-time safe. ## `ProcessorAsync` class Async wrapper for [`Processor`](/reference/sdk/api/python/enhancement#processor) that offloads work to background threads. Awaitable initialization, processing and termination use a shared background processing pool. Set `AIC_NUM_THREADS` before the first pool use to override its default of available CPU parallelism. `AIC_NUM_RUNTIME_THREADS` separately controls the async runtime and defaults to one. The constructor is synchronous, including initialization when `config` is supplied. `get_context()` is also synchronous and can wait for in-flight work. To avoid synchronous initialization, omit `config` and await `initialize_async(config)`. Calls on one instance serialize internally; await each block in stream order and bound work across streams. Do not infer an unbounded queue or cancellation guarantee from the async API. **Example** ```python theme={null} model = Model.from_file("/path/to/model.aicmodel") processor = ProcessorAsync(model, license_key) config = ProcessorConfig.optimal(model) await processor.initialize_async(config) audio = np.zeros(config.block_size, dtype=np.float32) enhanced = await processor.process_async(audio) ``` ### `ProcessorAsync()` constructor ```python theme={null} ProcessorAsync( model: Model, license_key: str, config: ProcessorConfig | None = None, otel_config: OtelConfig | None = None, ) -> ProcessorAsync ``` Creates a new async audio enhancement processor instance. Use separate processors for concurrent streams or different enhancement models. If a config is provided, the processor will be initialized immediately. Otherwise, you must call [`initialize_async()`](/reference/sdk/api/python/enhancement#processorasync-initialize_async) before processing audio. **Parameters** **model** `Model` *required* The loaded enhancement or bypass model instance. See [`Model`](/reference/sdk/api/python/models-and-config#model). **license\_key** `str` *required* SDK key or JWT for the ai-coustics SDK (generate your key at [developers.ai-coustics.com](https://developers.ai-coustics.com/)). **config** `ProcessorConfig | None` (default: None) Optional audio processing configuration. If provided, the processor will be initialized immediately with this configuration. See [`ProcessorConfig`](/reference/sdk/api/python/models-and-config#processorconfig). **otel\_config** `OtelConfig | None` (default: None) Per-instance OpenTelemetry settings. See [`OtelConfig`](/reference/sdk/api/python/models-and-config#otelconfig). **Raises** * [SDK exceptions](/reference/sdk/api/python/errors): Invalid credentials, unsupported model types or native creation failures. * [`AudioConfigUnsupportedError`](/reference/sdk/api/python/errors#audioconfigunsupportederror): If the supplied config is unsupported. **Example** ```python theme={null} # Create processor without initialization processor = ProcessorAsync(model, license_key) await processor.initialize_async(config) # Or create and initialize in one step config = ProcessorConfig.optimal(model) processor = ProcessorAsync(model, license_key, config) ``` ### `ProcessorAsync.initialize_async()` async ```python theme={null} def initialize_async(self, config: ProcessorConfig) -> typing.Awaitable[None] ``` Configures the processor asynchronously for specific audio settings. This function must be called before processing any audio. For the lowest delay use the sample rate and block size returned by [`Model.get_optimal_sample_rate()`](/reference/sdk/api/python/models-and-config#model-get_optimal_sample_rate) and [`Model.get_optimal_block_size()`](/reference/sdk/api/python/models-and-config#model-get_optimal_block_size). **Parameters** **config** `ProcessorConfig` *required* Audio processing configuration. See [`ProcessorConfig`](/reference/sdk/api/python/models-and-config#processorconfig). **Raises** * [`AudioConfigUnsupportedError`](/reference/sdk/api/python/errors#audioconfigunsupportederror): If the audio configuration is unsupported. **Example** ```python theme={null} config = ProcessorConfig.optimal(model) await processor.initialize_async(config) ``` ### `ProcessorAsync.process_async()` async ```python theme={null} def process_async(self, audio: npt.NDArray[np.float32]) -> typing.Awaitable[npt.NDArray[np.float32]] ``` Copies a one-dimensional NumPy `float32` input on the calling thread, then returns an awaitable resolving to a new `float32` array. Native processing runs in the background; input remains unchanged. The length, dtype and error rules of `Processor.process()` apply. **Raises** * [`NotInitializedError`](/reference/sdk/api/python/errors#notinitializederror): If the processor has not been initialized. * [`AudioConfigMismatchError`](/reference/sdk/api/python/errors#audioconfigmismatcherror): If the block size does not match the configuration. * [`ProcessingNotAllowedError`](/reference/sdk/api/python/errors#processingnotallowederror): If processing is not authorized. ### `ProcessorAsync.get_context()` ```python theme={null} def get_context(self) -> ProcessorContext ``` Returns a [`ProcessorContext`](/reference/sdk/api/python/enhancement#processorcontext) for real-time parameter control. **Returns** * [`ProcessorContext`](/reference/sdk/api/python/enhancement#processorcontext): A new ProcessorContext instance. **Example** ```python theme={null} processor_context = processor.get_context() ``` ### `ProcessorAsync.get_energy_vad_context()` ```python theme={null} def get_energy_vad_context(self) -> EnergyVadContext ``` Creates an [`EnergyVadContext`](/reference/sdk/api/python/vad#energyvadcontext) for energy-based speech detection on this processor. This call is synchronous and can wait for in-flight work. See [`Processor.get_energy_vad_context()`](/reference/sdk/api/python/enhancement#processor-get_energy_vad_context) for detector behavior. **Returns** * [`EnergyVadContext`](/reference/sdk/api/python/vad#energyvadcontext): A new energy VAD context. **Example** ```python theme={null} vad_context = processor.get_energy_vad_context() ``` ### `ProcessorAsync.terminate_session_async()` async ```python theme={null} def terminate_session_async(self) -> typing.Awaitable[None] ``` Terminates the processor's telemetry session asynchronously. Await the returned awaitable and stop submitting audio. Treat the session as closed immediately; native processing becomes disallowed when the lifecycle task handles the signal. Other live sessions can allow termination handling to continue after the awaitable resolves. Await completion does not prove remote usage acknowledgment. ## `ProcessorContext` class Shared control handle for processor state and parameters. There is no public `ProcessorContext()` constructor. Contexts from the same processor share control state. Retaining a context does not create a new processing stream or resume a terminated session. Created via [`Processor.get_context()`](/reference/sdk/api/python/enhancement#processor-get_context). ### `ProcessorContext.reset()` ```python theme={null} def reset(self) -> None ``` Requests a reset of enhancement state and buffers. The processing path applies the reset on its next processing call. Call this when the audio stream is interrupted or when seeking to prevent artifacts from previous audio content. The processor stays initialized to the configured settings. Any [`EnergyVadContext`](/reference/sdk/api/python/vad#energyvadcontext) on this processor is reset as well. > [!NOTE] > > **Concurrency.** The context can request a reset from another thread. Python calls still involve the interpreter; this is not a hard real-time guarantee for a Python callback. **Example** ```python theme={null} processor_context.reset() ``` ### `ProcessorContext.set_parameter()` ```python theme={null} def set_parameter(self, parameter: ProcessorParameter, value: float) -> None ``` Modifies a processor parameter. Parameters can be changed through a context while audio is processed elsewhere. `VoiceGain` is a deprecated no-op: setting it emits `DeprecationWarning` and returns `None`; reading it emits the warning and returns `1.0`. **Parameters** **parameter** `ProcessorParameter` *required* Parameter to modify. See [`ProcessorParameter`](/reference/sdk/api/python/enhancement#processorparameter). **value** `float` *required* New parameter value. See parameter documentation for ranges. **Raises** * [`ParameterOutOfRangeError`](/reference/sdk/api/python/errors#parameteroutofrangeerror): If the parameter value is out of range. **Example** ```python theme={null} processor_context.set_parameter(ProcessorParameter.EnhancementLevel, 0.8) ``` ### `ProcessorContext.get_parameter()` ```python theme={null} def get_parameter(self, parameter: ProcessorParameter) -> float ``` Retrieves the current value of a parameter. This function can be called from any thread. **Parameters** **parameter** `ProcessorParameter` *required* Parameter to query. See [`ProcessorParameter`](/reference/sdk/api/python/enhancement#processorparameter). **Returns** * `float`: The current parameter value. **Example** ```python theme={null} level = processor_context.get_parameter(ProcessorParameter.EnhancementLevel) print(f"Current enhancement level: {level}") ``` ### `ProcessorContext.parameter()` deprecated > [!WARNING] > > Deprecated. Use [`get_parameter()`](/reference/sdk/api/python/enhancement#processorcontext-get_parameter) instead. ```python theme={null} def parameter(self, parameter: ProcessorParameter) -> float ``` ### `ProcessorContext.get_audio_delay()` ```python theme={null} def get_audio_delay(self) -> int ``` Returns the delay applied to the audio in samples for the current audio configuration. This reports SDK signal delay, including algorithmic delay and internal buffering. It does not measure CPU execution, scheduling, transport or application queue time. The processed audio leaves [`Processor.process()`](/reference/sdk/api/python/enhancement#processor-process) this many samples behind its input. It does not include VAD delay; use [`VadContext.get_prediction_delay()`](/reference/sdk/api/python/vad#vadcontext-get_prediction_delay) for a separate VAD. **Delay behavior.** * Before initialization: Returns the base processing delay using the model's optimal block size at its native sample rate * After initialization: Returns the actual delay for your specific configuration, including any additional buffering introduced by a non-optimal block size **Returns** * `int`: The delay in samples. > [!NOTE] > > After initialization, delay is expressed in samples at the configured sample rate; before initialization, use the model native rate. To convert to time units: `delay_ms = (delay_samples * 1000) / sample_rate` > [!NOTE] > > Using a block size different from the optimal value returned by [`get_optimal_block_size()`](/reference/sdk/api/python/models-and-config#model-get_optimal_block_size) will increase the delay beyond the model's base latency. **Example** ```python theme={null} delay = processor_context.get_audio_delay() print(f"Audio delay: {delay} samples") ``` ### `ProcessorContext.update_bearer_token()` ```python theme={null} def update_bearer_token(self, token: str) -> None ``` Replaces the bearer token on the running processor. Use this when your license key is a JWT and needs to be refreshed before it expires. The replacement is used for subsequent authentication. A successful update does not prove backend acceptance or uninterrupted processing; continue handling processing errors. Both the original key and the new token must be JWTs; otherwise a [`TokenUnsupportedError`](/reference/sdk/api/python/errors#tokenunsupportederror) error is raised and the existing token stays in use. **Parameters** **token** `str` *required* The new JWT to install. **Raises** * [`TokenUnsupportedError`](/reference/sdk/api/python/errors#tokenunsupportederror): If either the original or new token is not a JWT. * [`LicenseFormatInvalidError`](/reference/sdk/api/python/errors#licenseformatinvaliderror): If the token string contains null bytes. **Example** ```python theme={null} processor_context.update_bearer_token(renewed_jwt) ``` ## `ProcessorParameter` enum Parameter constants for audio enhancement. Use the named constants directly. The stub presents this type as an enum; the runtime exposes PyO3 enum-like objects, so do not depend on standard-library `enum.Enum` iteration or `.value` behavior. ### `ProcessorParameter` members #### `ProcessorParameter.Bypass` Controls whether audio processing is bypassed while preserving algorithmic delay. When enabled, the input audio passes through unmodified, but the output is still delayed by the same amount as during normal processing. The delay remains when switching between bypass and enhancement. **Range:** 0.0–1.0 * 0.0: Enhancement active (normal processing) * Any value greater than 0.0 up to 1.0: Bypass enabled (latency-compensated passthrough); reading the value returns 1.0 **Default:** 0.0 #### `ProcessorParameter.EnhancementLevel` Tune enhancement strength for your speech-to-text (STT) engine or listening task. The exact behavior depends on the active model: * **Quail models:** Controls how aggressively the model suppresses noise. When used with Quail Voice Focus, it also suppresses background and competing speech. * **Rook models:** Controls the mixback and therefore the intensity of the enhancement. **Range:** 0.0–1.0. The initial enhancement level can be model-specific; read it with `get_parameter()` when needed. #### `ProcessorParameter.VoiceGain` deprecated > [!WARNING] > > This parameter has no effect and will be removed in a future version. Retained for compatibility. Setting any value emits `DeprecationWarning` and has no effect; reading returns `1.0` with the same warning. See the [Python API index](/reference/sdk/api/python/index), [Python guide](/reference/sdk/language-bindings/python) and [troubleshooting](/production/troubleshooting). # Python errors Source: https://docs.ai-coustics.com/reference/sdk/api/python/errors Exception constructors, attributes, causes and recovery for aic-sdk. **Package:** `aic-sdk==3.4.0`. **Core SDK:** `0.26.0`. Every SDK exception below subclasses `Exception` directly. There is no shared SDK base exception. Catch the specific errors you can recover from. Native failures from model loading, constructors, initialization, processing, parameter control, token updates and analysis are mapped to these classes. Every class accepts `message: str` and exposes a read-only `message: str` property. `ModelDownloadError` and `UnknownError` require one additional constructor argument, shown below. The inherited `args`, `str()` and traceback behavior comes from Python's `Exception`. Python argument conversion can instead raise `TypeError` for an incorrect NumPy dtype or dimension, or `OverflowError` for integers outside the native unsigned range. A noncontiguous one-dimensional `float32` view is accepted and normalized by the wrapper. Wrong block length is a separate SDK error. Async methods can raise conversion errors when called and SDK errors when awaited. Background download task failure can raise `RuntimeError`. > [!WARNING] > > A Python processing exception returns no output array. The wrapper discards its local output on an SDK error, even if the underlying C processor writes fallback samples. Choose and implement your application fallback explicitly. The sections below describe causes, not an exhaustive list of every native call that can raise each exception. See [authentication](/models/get-started/authenticate-apps), [audio format](/reference/concepts/audio-format) and [troubleshooting](/production/troubleshooting). ## License and authorization ### `LicenseFormatInvalidError` ```python theme={null} LicenseFormatInvalidError(message: str) ``` **Cause:** The SDK key or JWT is malformed, empty or contains a NUL character. **Recovery:** Check that you copied the complete credential without extra characters. Read it from your approved secret source; do not print it. **`message: str` (read-only):** Human-readable diagnostic text. ### `LicenseExpiredError` ```python theme={null} LicenseExpiredError(message: str) ``` **Cause:** The credential has expired. **Recovery:** Renew it. For a session originally created with a JWT, update the bearer token before expiry. Recreate the session when token replacement is unsupported. **`message: str` (read-only):** Human-readable diagnostic text. ### `LicenseVersionUnsupportedError` ```python theme={null} LicenseVersionUnsupportedError(message: str) ``` **Cause:** The credential format version is unsupported by this SDK. **Recovery:** Use a compatible released SDK and credential, or contact support. **`message: str` (read-only):** Human-readable diagnostic text. ### `TokenUnsupportedError` ```python theme={null} TokenUnsupportedError(message: str) ``` **Cause:** Token replacement is only supported when the original credential and replacement are both JWTs. **Recovery:** Use a JWT from initial session creation if rotation is required. The rejected replacement is not installed; recreate the session when changing credential type. **`message: str` (read-only):** Human-readable diagnostic text. ### `ProcessingNotAllowedError` ```python theme={null} ProcessingNotAllowedError(message: str) ``` **Cause:** Authorization or usage reporting failed, or the session was terminated. This can occur after successful initialization. **Recovery:** Check the credential and required network access. Keep handling this error in the processing loop. A terminated session requires a new processor, detector or analyzer; a reset does not reopen it. **`message: str` (read-only):** Human-readable diagnostic text. ## Model files ### `ModelInvalidError` ```python theme={null} ModelInvalidError(message: str) ``` **Cause:** The model file is malformed or incomplete. **Recovery:** Download the model again and verify the local file. **`message: str` (read-only):** Human-readable diagnostic text. ### `ModelVersionUnsupportedError` ```python theme={null} ModelVersionUnsupportedError(message: str) ``` **Cause:** The model file format is incompatible with the installed core SDK. **Recovery:** Use `Model.download()` with the installed SDK to select compatible data. Compare `get_compatible_model_version()` when diagnosing a manually supplied file. **`message: str` (read-only):** Human-readable diagnostic text. ### `ModelTypeUnsupportedError` ```python theme={null} ModelTypeUnsupportedError(message: str) ``` **Cause:** The model type does not match the operation. **Recovery:** Use an enhancement model for `Processor`, a dedicated VAD model for `Vad` and a Tyto analysis model for `analyzer_pair` or `FileAnalyzer`. **`message: str` (read-only):** Human-readable diagnostic text. ### `ModelDataUnalignedError` ```python theme={null} ModelDataUnalignedError(message: str) ``` **Cause:** Native model data does not satisfy the required 64-byte alignment. **Recovery:** Python exposes file loading rather than raw buffer loading. Use `Model.from_file()`; report this error with package and platform details if it occurs through that path. **`message: str` (read-only):** Human-readable diagnostic text. ### `ModelDownloadError` ```python theme={null} ModelDownloadError(message: str, details: str) ``` **Cause:** Manifest retrieval, model selection, download, verification or writing the destination failed. **Recovery:** Inspect details, check the model ID, network access and destination permissions, then retry the download. **`message: str` (read-only):** Human-readable diagnostic text. **`details: str` (read-only):** Underlying download failure details. ### `FileSystemError` ```python theme={null} FileSystemError(message: str) ``` **Cause:** The model file cannot be opened or read. **Recovery:** Check that the path exists, is a model file and is readable. **`message: str` (read-only):** Human-readable diagnostic text. ### `FilePathInvalidError` ```python theme={null} FilePathInvalidError(message: str) ``` **Cause:** The native file path is invalid. **Recovery:** Use a valid path without embedded NUL characters. In aic-sdk 3.4.0 a NUL path can escape normal SDK exception conversion; validate it before calling `Model.from_file()`. **`message: str` (read-only):** Human-readable diagnostic text. ## Audio configuration and state ### `AudioConfigUnsupportedError` ```python theme={null} AudioConfigUnsupportedError(message: str) ``` **Cause:** The native sample rate or block configuration is unsupported. `FileAnalyzer` also rejects `sample_rate=0` and `step_samples=0`. **Recovery:** Start with `ProcessorConfig.optimal(model)`, then initialize. Native input rates are 8,000–192,000 Hz; use a positive block size and a configuration supported by the model. **`message: str` (read-only):** Human-readable diagnostic text. ### `AudioConfigMismatchError` ```python theme={null} AudioConfigMismatchError(message: str) ``` **Cause:** The number of samples differs from the initialized fixed size or exceeds the maximum variable size. **Recovery:** Use exactly `config.block_size` mono samples, or a block of up to that size with `variable_block_size=True`. A wrong dtype or dimension raises Python `TypeError` instead. **`message: str` (read-only):** Human-readable diagnostic text. ### `NotInitializedError` ```python theme={null} NotInitializedError(message: str) ``` **Cause:** Processing or buffering was attempted before initialization. **Recovery:** Pass config to the processor or detector constructor, or call `initialize`/`initialize_async`. Initialize the `Collector` before `buffer()`. **`message: str` (read-only):** Human-readable diagnostic text. ### `ParameterOutOfRangeError` ```python theme={null} ParameterOutOfRangeError(message: str) ``` **Cause:** A parameter value lies outside its supported range. **Recovery:** Use the bounds on `ProcessorParameter` or `VadParameter`. Read the current value with `get_parameter()`; do not infer model-specific defaults. **`message: str` (read-only):** Human-readable diagnostic text. ### `ParameterFixedError` ```python theme={null} ParameterFixedError(message: str) ``` **Cause:** Compatibility exception retained in the Python public surface. The 3.4.0 error mapper does not emit it. **Recovery:** Keep it only where existing application code requires the type; current parameter validation uses `ParameterOutOfRangeError`. **`message: str` (read-only):** Human-readable diagnostic text. ## Internal ### `InternalError` ```python theme={null} InternalError(message: str) ``` **Cause:** A native internal operation failed. A NUL-containing `OtelConfig.session_id` also maps to this error during processor or detector construction. **Recovery:** First check the supplied session ID. For other failures, retain package/core versions and a minimal reproduction and contact support; omit credentials. **`message: str` (read-only):** Human-readable diagnostic text. ### `UnknownError` ```python theme={null} UnknownError(message: str, error_code: int) ``` **Cause:** The native SDK returned an error code not recognized by this wrapper. **Recovery:** Record `error_code` and package/core versions, then report a minimal reproduction without credentials. **`message: str` (read-only):** Human-readable diagnostic text. **`error_code: int` (read-only):** Signed 32-bit native error code. ## Handling an error This example exercises a local file error without a model download or SDK credential: ```python theme={null} from pathlib import Path from tempfile import TemporaryDirectory import aic_sdk as aic with TemporaryDirectory() as directory: try: aic.Model.from_file(Path(directory) / "missing.aicmodel") except aic.FileSystemError as error: print(type(error).__name__) # FileSystemError ``` See the [Python API index](/reference/sdk/api/python/index) and [Python guide](/reference/sdk/language-bindings/python). # Python API reference Source: https://docs.ai-coustics.com/reference/sdk/api/python/index Complete public API surface for aic-sdk: models, enhancement, VAD, analysis and errors. **Package:** `aic-sdk==3.4.0`. **Core SDK:** `0.26.0`. Import the package as `aic_sdk`. The [Python guide](/reference/sdk/language-bindings/python) contains installation and the runnable audio example. Where released type stubs differ from runtime behavior, the entries note the correction. ## Domains | Domain | Use it to | | - | - | | [Models and configuration](/reference/sdk/api/python/models-and-config) | Load models, choose audio configuration and configure OpenTelemetry | | [Enhancement](/reference/sdk/api/python/enhancement) | Process audio synchronously or asynchronously and control stream state | | [Voice activity detection](/reference/sdk/api/python/vad) | Run dedicated VAD models, or detect speech from an enhancement processor, and read speech decisions | | [Audio analysis](/reference/sdk/api/python/analysis) | Buffer live audio or analyze complete buffers with Tyto | | [Errors](/reference/sdk/api/python/errors) | Identify failures and implement recovery | ## Shared conventions Use `import aic_sdk as aic` and `import numpy as np` in application code. Reference signatures abbreviate `numpy.typing` as `npt` and standard-library `typing` as `typing`. Reference fragments assume the model, credential and initialized object from the linked guide. They are not separate end-to-end tutorials. Audio is one-dimensional mono NumPy `float32`, at the configured sample rate. The enhancement wrapper copies its input and returns a new array; VAD and collection leave input unchanged. Each processing object owns stream state. Await blocks in order on async instances and use separate instances for independent streams. Do not share a mutable input with concurrent native work. Configuration objects are copied at initialization or construction; later field edits do not reconfigure existing native objects. Python owns the native handles and releases them with the corresponding objects. A memory-mapped model file must not be modified or deleted while the model or any dependent processing object remains alive. After termination, create a new processing object to start another session. All documented classes and functions are available in this released package; there are no Python feature flags for this surface. `set_sdk_id` is a runtime integration hook intentionally excluded from the supported public API. Runtime shutdown and automatically inherited Python object machinery are implementation details; the explicitly implemented diagnostic representations are listed below. Native-only raw-buffer model loading is not exposed in Python. ## Symbol index Each symbol links directly to its constructor, member, field or function. Property setters share the getter's entry and are labeled read/write in the domain page. Symbols are sorted alphabetically. | Symbol | Kind | | - | - | | [`AnalysisResult`](/reference/sdk/api/python/analysis#analysisresult) | class | | [`AnalysisResult.__repr__`](/reference/sdk/api/python/analysis#analysisresult-__repr__) | method | | [`AnalysisResult.codec_degradation`](/reference/sdk/api/python/analysis#analysisresult-codec_degradation) | property | | [`AnalysisResult.interfering_speech`](/reference/sdk/api/python/analysis#analysisresult-interfering_speech) | property | | [`AnalysisResult.noise`](/reference/sdk/api/python/analysis#analysisresult-noise) | property | | [`AnalysisResult.packet_loss`](/reference/sdk/api/python/analysis#analysisresult-packet_loss) | property | | [`AnalysisResult.risk_score`](/reference/sdk/api/python/analysis#analysisresult-risk_score) | property | | [`AnalysisResult.speaker_loudness`](/reference/sdk/api/python/analysis#analysisresult-speaker_loudness) | property | | [`AnalysisResult.speaker_reverb`](/reference/sdk/api/python/analysis#analysisresult-speaker_reverb) | property | | [`Analyzer`](/reference/sdk/api/python/analysis#analyzer) | class | | [`Analyzer.analyze_buffered`](/reference/sdk/api/python/analysis#analyzer-analyze_buffered) | method | | [`Analyzer.reset`](/reference/sdk/api/python/analysis#analyzer-reset) | method | | [`Analyzer.terminate_session`](/reference/sdk/api/python/analysis#analyzer-terminate_session) | method | | [`Analyzer.update_bearer_token`](/reference/sdk/api/python/analysis#analyzer-update_bearer_token) | method | | [`analyzer_pair`](/reference/sdk/api/python/analysis#analyzer_pair) | function | | [`AudioConfigMismatchError`](/reference/sdk/api/python/errors#audioconfigmismatcherror) | class | | [`AudioConfigMismatchError()`](/reference/sdk/api/python/errors#audioconfigmismatcherror-constructor) | constructor | | [`AudioConfigMismatchError.message`](/reference/sdk/api/python/errors#audioconfigmismatcherror-message) | property | | [`AudioConfigUnsupportedError`](/reference/sdk/api/python/errors#audioconfigunsupportederror) | class | | [`AudioConfigUnsupportedError()`](/reference/sdk/api/python/errors#audioconfigunsupportederror-constructor) | constructor | | [`AudioConfigUnsupportedError.message`](/reference/sdk/api/python/errors#audioconfigunsupportederror-message) | property | | [`Collector`](/reference/sdk/api/python/analysis#collector) | class | | [`Collector.buffer`](/reference/sdk/api/python/analysis#collector-buffer) | method | | [`Collector.initialize`](/reference/sdk/api/python/analysis#collector-initialize) | method | | [`EnergyVadContext`](/reference/sdk/api/python/vad#energyvadcontext) | class | | [`EnergyVadContext.get_parameter`](/reference/sdk/api/python/vad#energyvadcontext-get_parameter) | method | | [`EnergyVadContext.get_prediction_delay`](/reference/sdk/api/python/vad#energyvadcontext-get_prediction_delay) | method | | [`EnergyVadContext.is_speech_detected`](/reference/sdk/api/python/vad#energyvadcontext-is_speech_detected) | method | | [`EnergyVadContext.reset`](/reference/sdk/api/python/vad#energyvadcontext-reset) | method | | [`EnergyVadContext.set_parameter`](/reference/sdk/api/python/vad#energyvadcontext-set_parameter) | method | | [`FileAnalyzer`](/reference/sdk/api/python/analysis#fileanalyzer) | class | | [`FileAnalyzer()`](/reference/sdk/api/python/analysis#fileanalyzer-constructor) | constructor | | [`FileAnalyzer.analyze`](/reference/sdk/api/python/analysis#fileanalyzer-analyze) | method | | [`FilePathInvalidError`](/reference/sdk/api/python/errors#filepathinvaliderror) | class | | [`FilePathInvalidError()`](/reference/sdk/api/python/errors#filepathinvaliderror-constructor) | constructor | | [`FilePathInvalidError.message`](/reference/sdk/api/python/errors#filepathinvaliderror-message) | property | | [`FileSystemError`](/reference/sdk/api/python/errors#filesystemerror) | class | | [`FileSystemError()`](/reference/sdk/api/python/errors#filesystemerror-constructor) | constructor | | [`FileSystemError.message`](/reference/sdk/api/python/errors#filesystemerror-message) | property | | [`get_compatible_model_version`](/reference/sdk/api/python/models-and-config#get_compatible_model_version) | function | | [`get_sdk_version`](/reference/sdk/api/python/models-and-config#get_sdk_version) | function | | [`InternalError`](/reference/sdk/api/python/errors#internalerror) | class | | [`InternalError()`](/reference/sdk/api/python/errors#internalerror-constructor) | constructor | | [`InternalError.message`](/reference/sdk/api/python/errors#internalerror-message) | property | | [`LicenseExpiredError`](/reference/sdk/api/python/errors#licenseexpirederror) | class | | [`LicenseExpiredError()`](/reference/sdk/api/python/errors#licenseexpirederror-constructor) | constructor | | [`LicenseExpiredError.message`](/reference/sdk/api/python/errors#licenseexpirederror-message) | property | | [`LicenseFormatInvalidError`](/reference/sdk/api/python/errors#licenseformatinvaliderror) | class | | [`LicenseFormatInvalidError()`](/reference/sdk/api/python/errors#licenseformatinvaliderror-constructor) | constructor | | [`LicenseFormatInvalidError.message`](/reference/sdk/api/python/errors#licenseformatinvaliderror-message) | property | | [`LicenseVersionUnsupportedError`](/reference/sdk/api/python/errors#licenseversionunsupportederror) | class | | [`LicenseVersionUnsupportedError()`](/reference/sdk/api/python/errors#licenseversionunsupportederror-constructor) | constructor | | [`LicenseVersionUnsupportedError.message`](/reference/sdk/api/python/errors#licenseversionunsupportederror-message) | property | | [`Model`](/reference/sdk/api/python/models-and-config#model) | class | | [`Model.download`](/reference/sdk/api/python/models-and-config#model-download) | method | | [`Model.download_async`](/reference/sdk/api/python/models-and-config#model-download_async) | method | | [`Model.from_file`](/reference/sdk/api/python/models-and-config#model-from_file) | method | | [`Model.get_id`](/reference/sdk/api/python/models-and-config#model-get_id) | method | | [`Model.get_optimal_block_size`](/reference/sdk/api/python/models-and-config#model-get_optimal_block_size) | method | | [`Model.get_optimal_sample_rate`](/reference/sdk/api/python/models-and-config#model-get_optimal_sample_rate) | method | | [`ModelDataUnalignedError`](/reference/sdk/api/python/errors#modeldataunalignederror) | class | | [`ModelDataUnalignedError()`](/reference/sdk/api/python/errors#modeldataunalignederror-constructor) | constructor | | [`ModelDataUnalignedError.message`](/reference/sdk/api/python/errors#modeldataunalignederror-message) | property | | [`ModelDownloadError`](/reference/sdk/api/python/errors#modeldownloaderror) | class | | [`ModelDownloadError()`](/reference/sdk/api/python/errors#modeldownloaderror-constructor) | constructor | | [`ModelDownloadError.details`](/reference/sdk/api/python/errors#modeldownloaderror-details) | property | | [`ModelDownloadError.message`](/reference/sdk/api/python/errors#modeldownloaderror-message) | property | | [`ModelInvalidError`](/reference/sdk/api/python/errors#modelinvaliderror) | class | | [`ModelInvalidError()`](/reference/sdk/api/python/errors#modelinvaliderror-constructor) | constructor | | [`ModelInvalidError.message`](/reference/sdk/api/python/errors#modelinvaliderror-message) | property | | [`ModelTypeUnsupportedError`](/reference/sdk/api/python/errors#modeltypeunsupportederror) | class | | [`ModelTypeUnsupportedError()`](/reference/sdk/api/python/errors#modeltypeunsupportederror-constructor) | constructor | | [`ModelTypeUnsupportedError.message`](/reference/sdk/api/python/errors#modeltypeunsupportederror-message) | property | | [`ModelVersionUnsupportedError`](/reference/sdk/api/python/errors#modelversionunsupportederror) | class | | [`ModelVersionUnsupportedError()`](/reference/sdk/api/python/errors#modelversionunsupportederror-constructor) | constructor | | [`ModelVersionUnsupportedError.message`](/reference/sdk/api/python/errors#modelversionunsupportederror-message) | property | | [`NotInitializedError`](/reference/sdk/api/python/errors#notinitializederror) | class | | [`NotInitializedError()`](/reference/sdk/api/python/errors#notinitializederror-constructor) | constructor | | [`NotInitializedError.message`](/reference/sdk/api/python/errors#notinitializederror-message) | property | | [`OtelConfig`](/reference/sdk/api/python/models-and-config#otelconfig) | class | | [`OtelConfig()`](/reference/sdk/api/python/models-and-config#otelconfig-constructor) | constructor | | [`OtelConfig.__repr__`](/reference/sdk/api/python/models-and-config#otelconfig-__repr__) | method | | [`OtelConfig.enable`](/reference/sdk/api/python/models-and-config#otelconfig-enable) | property | | [`OtelConfig.export_interval_ms`](/reference/sdk/api/python/models-and-config#otelconfig-export_interval_ms) | property | | [`OtelConfig.session_id`](/reference/sdk/api/python/models-and-config#otelconfig-session_id) | property | | [`ParameterFixedError`](/reference/sdk/api/python/errors#parameterfixederror) | class | | [`ParameterFixedError()`](/reference/sdk/api/python/errors#parameterfixederror-constructor) | constructor | | [`ParameterFixedError.message`](/reference/sdk/api/python/errors#parameterfixederror-message) | property | | [`ParameterOutOfRangeError`](/reference/sdk/api/python/errors#parameteroutofrangeerror) | class | | [`ParameterOutOfRangeError()`](/reference/sdk/api/python/errors#parameteroutofrangeerror-constructor) | constructor | | [`ParameterOutOfRangeError.message`](/reference/sdk/api/python/errors#parameteroutofrangeerror-message) | property | | [`ProcessingNotAllowedError`](/reference/sdk/api/python/errors#processingnotallowederror) | class | | [`ProcessingNotAllowedError()`](/reference/sdk/api/python/errors#processingnotallowederror-constructor) | constructor | | [`ProcessingNotAllowedError.message`](/reference/sdk/api/python/errors#processingnotallowederror-message) | property | | [`Processor`](/reference/sdk/api/python/enhancement#processor) | class | | [`Processor()`](/reference/sdk/api/python/enhancement#processor-constructor) | constructor | | [`Processor.get_context`](/reference/sdk/api/python/enhancement#processor-get_context) | method | | [`Processor.get_energy_vad_context`](/reference/sdk/api/python/enhancement#processor-get_energy_vad_context) | method | | [`Processor.initialize`](/reference/sdk/api/python/enhancement#processor-initialize) | method | | [`Processor.process`](/reference/sdk/api/python/enhancement#processor-process) | method | | [`Processor.terminate_session`](/reference/sdk/api/python/enhancement#processor-terminate_session) | method | | [`ProcessorAsync`](/reference/sdk/api/python/enhancement#processorasync) | class | | [`ProcessorAsync()`](/reference/sdk/api/python/enhancement#processorasync-constructor) | constructor | | [`ProcessorAsync.get_context`](/reference/sdk/api/python/enhancement#processorasync-get_context) | method | | [`ProcessorAsync.get_energy_vad_context`](/reference/sdk/api/python/enhancement#processorasync-get_energy_vad_context) | method | | [`ProcessorAsync.initialize_async`](/reference/sdk/api/python/enhancement#processorasync-initialize_async) | method | | [`ProcessorAsync.process_async`](/reference/sdk/api/python/enhancement#processorasync-process_async) | method | | [`ProcessorAsync.terminate_session_async`](/reference/sdk/api/python/enhancement#processorasync-terminate_session_async) | method | | [`ProcessorConfig`](/reference/sdk/api/python/models-and-config#processorconfig) | class | | [`ProcessorConfig()`](/reference/sdk/api/python/models-and-config#processorconfig-constructor) | constructor | | [`ProcessorConfig.__repr__`](/reference/sdk/api/python/models-and-config#processorconfig-__repr__) | method | | [`ProcessorConfig.block_size`](/reference/sdk/api/python/models-and-config#processorconfig-block_size) | property | | [`ProcessorConfig.optimal`](/reference/sdk/api/python/models-and-config#processorconfig-optimal) | method | | [`ProcessorConfig.sample_rate`](/reference/sdk/api/python/models-and-config#processorconfig-sample_rate) | property | | [`ProcessorConfig.variable_block_size`](/reference/sdk/api/python/models-and-config#processorconfig-variable_block_size) | property | | [`ProcessorContext`](/reference/sdk/api/python/enhancement#processorcontext) | class | | [`ProcessorContext.get_audio_delay`](/reference/sdk/api/python/enhancement#processorcontext-get_audio_delay) | method | | [`ProcessorContext.get_parameter`](/reference/sdk/api/python/enhancement#processorcontext-get_parameter) | method | | [`ProcessorContext.parameter`](/reference/sdk/api/python/enhancement#processorcontext-parameter) | method | | [`ProcessorContext.reset`](/reference/sdk/api/python/enhancement#processorcontext-reset) | method | | [`ProcessorContext.set_parameter`](/reference/sdk/api/python/enhancement#processorcontext-set_parameter) | method | | [`ProcessorContext.update_bearer_token`](/reference/sdk/api/python/enhancement#processorcontext-update_bearer_token) | method | | [`ProcessorParameter`](/reference/sdk/api/python/enhancement#processorparameter) | class | | [`ProcessorParameter.Bypass`](/reference/sdk/api/python/enhancement#processorparameter-bypass) | enum member | | [`ProcessorParameter.EnhancementLevel`](/reference/sdk/api/python/enhancement#processorparameter-enhancementlevel) | enum member | | [`ProcessorParameter.VoiceGain`](/reference/sdk/api/python/enhancement#processorparameter-voicegain) | enum member | | [`TokenUnsupportedError`](/reference/sdk/api/python/errors#tokenunsupportederror) | class | | [`TokenUnsupportedError()`](/reference/sdk/api/python/errors#tokenunsupportederror-constructor) | constructor | | [`TokenUnsupportedError.message`](/reference/sdk/api/python/errors#tokenunsupportederror-message) | property | | [`UnknownError`](/reference/sdk/api/python/errors#unknownerror) | class | | [`UnknownError()`](/reference/sdk/api/python/errors#unknownerror-constructor) | constructor | | [`UnknownError.error_code`](/reference/sdk/api/python/errors#unknownerror-error_code) | property | | [`UnknownError.message`](/reference/sdk/api/python/errors#unknownerror-message) | property | | [`Vad`](/reference/sdk/api/python/vad#vad) | class | | [`Vad()`](/reference/sdk/api/python/vad#vad-constructor) | constructor | | [`Vad.get_context`](/reference/sdk/api/python/vad#vad-get_context) | method | | [`Vad.initialize`](/reference/sdk/api/python/vad#vad-initialize) | method | | [`Vad.process`](/reference/sdk/api/python/vad#vad-process) | method | | [`Vad.terminate_session`](/reference/sdk/api/python/vad#vad-terminate_session) | method | | [`VadAsync`](/reference/sdk/api/python/vad#vadasync) | class | | [`VadAsync()`](/reference/sdk/api/python/vad#vadasync-constructor) | constructor | | [`VadAsync.get_context`](/reference/sdk/api/python/vad#vadasync-get_context) | method | | [`VadAsync.initialize_async`](/reference/sdk/api/python/vad#vadasync-initialize_async) | method | | [`VadAsync.process_async`](/reference/sdk/api/python/vad#vadasync-process_async) | method | | [`VadAsync.terminate_session_async`](/reference/sdk/api/python/vad#vadasync-terminate_session_async) | method | | [`VadContext`](/reference/sdk/api/python/vad#vadcontext) | class | | [`VadContext.get_parameter`](/reference/sdk/api/python/vad#vadcontext-get_parameter) | method | | [`VadContext.get_prediction_delay`](/reference/sdk/api/python/vad#vadcontext-get_prediction_delay) | method | | [`VadContext.is_speech_detected`](/reference/sdk/api/python/vad#vadcontext-is_speech_detected) | method | | [`VadContext.parameter`](/reference/sdk/api/python/vad#vadcontext-parameter) | method | | [`VadContext.raw_vad_probability`](/reference/sdk/api/python/vad#vadcontext-raw_vad_probability) | method | | [`VadContext.reset`](/reference/sdk/api/python/vad#vadcontext-reset) | method | | [`VadContext.set_parameter`](/reference/sdk/api/python/vad#vadcontext-set_parameter) | method | | [`VadContext.update_bearer_token`](/reference/sdk/api/python/vad#vadcontext-update_bearer_token) | method | | [`VadParameter`](/reference/sdk/api/python/vad#vadparameter) | class | | [`VadParameter.MinimumSpeechDuration`](/reference/sdk/api/python/vad#vadparameter-minimumspeechduration) | enum member | | [`VadParameter.Sensitivity`](/reference/sdk/api/python/vad#vadparameter-sensitivity) | enum member | | [`VadParameter.SpeechHoldDuration`](/reference/sdk/api/python/vad#vadparameter-speechholdduration) | enum member | # Python models and configuration Source: https://docs.ai-coustics.com/reference/sdk/api/python/models-and-config Python reference for `Model`, `ProcessorConfig`, `OtelConfig`, `get_sdk_version` and `get_compatible_model_version` in aic-sdk. **Package:** `aic-sdk==3.4.0`. **Core SDK:** `0.26.0`. The fragments below use these imports. Supply `license_key` from your approved secret source and use the loaded model and initialized objects described in each section. For a complete file-processing example, follow the [Python guide](/reference/sdk/language-bindings/python). ```python theme={null} import os import pathlib import tempfile from pathlib import Path import typing import aic_sdk as aic from aic_sdk import Model, Processor, ProcessorConfig, OtelConfig ``` `audio` denotes a one-dimensional NumPy `float32` array. Async fragments run inside an async function. ## `Model` class Loaded model weights and model metadata. Create a model with `Model.from_file()`; there is no public `Model()` constructor. A loaded model can be shared by multiple processors. Native handles release their resources when Python releases the objects. **Example** ```python theme={null} model = Model.from_file("/path/to/model.aicmodel") processor = Processor(model, license_key) config = ProcessorConfig.optimal(model) processor.initialize(config) ``` ### `Model.from_file()` static ```python theme={null} @staticmethod def from_file(path: str | os.PathLike | pathlib.Path) -> Model ``` Creates a new model instance backed by memory-mapped file data. Do not modify or delete that file while the model or any dependent processor, detector or analyzer remains alive. Native references retain model data after the Python model handle is released; automatic handle management does not make changing the backing file safe. Multiple models can be loaded for enhancement, voice activity detection or analysis. **Parameters** **path** `str | os.PathLike | pathlib.Path` *required* Path to the model file (.aicmodel). You can download models manually from [artifacts.ai-coustics.io](https://artifacts.ai-coustics.io) or use [`Model.download()`](/reference/sdk/api/python/models-and-config#model-download) to fetch them programmatically. Accepts both string paths and pathlib.Path objects. **Returns** * [`Model`](/reference/sdk/api/python/models-and-config#model): A new Model instance. **Raises** * [`FileSystemError`](/reference/sdk/api/python/errors#filesystemerror): The file cannot be opened. * [`ModelInvalidError`](/reference/sdk/api/python/errors#modelinvaliderror) or [`ModelVersionUnsupportedError`](/reference/sdk/api/python/errors#modelversionunsupportederror): Invalid or incompatible model data. Pass a valid filesystem path without embedded NUL characters. aic-sdk 3.4.0 does not consistently map a NUL-containing path to an SDK exception. **Example** ```python theme={null} model = Model.from_file("/path/to/model.aicmodel") model = Model.from_file(Path.cwd() / "model.aicmodel") ``` **See also** * [artifacts.ai-coustics.io](https://artifacts.ai-coustics.io) for available model IDs and downloads. ### `Model.download()` static ```python theme={null} @staticmethod def download(model_id: str, download_dir: str | os.PathLike | pathlib.Path) -> str ``` Downloads a model file from the ai-coustics artifact CDN. Resolves a compatible model through its manifest and downloads it to the specified directory. An existing file is reused if its checksum matches; otherwise it is replaced. Fresh manifests are reused from memory or the download directory according to the server's cache lifetime. Stale manifests are revalidated. Resolution is retried when the model is absent or a failed download may reflect a changed mapping. Available models can be browsed at [artifacts.ai-coustics.io](https://artifacts.ai-coustics.io/). **Parameters** **model\_id** `str` *required* The model identifier (e.g., `"quail-ms-l-16khz"`). **download\_dir** `str | os.PathLike | pathlib.Path` *required* Directory where the model file will be stored. **Returns** * `str`: The model file path. It remains relative when `download_dir` is relative. **Raises** * [`ModelDownloadError`](/reference/sdk/api/python/errors#modeldownloaderror): Manifest access, model selection, checksum, download or filesystem failure. Inspect `details` for the underlying cause. > [!NOTE] > > This is a blocking operation that may perform network I/O. **Example** ```python theme={null} # Find model IDs at path = Model.download("rook-ms-l-16khz", "/tmp/models") # Or using pathlib.Path path = Model.download("rook-ms-l-16khz", Path(tempfile.gettempdir()) / "models") model = Model.from_file(path) ``` ### `Model.download_async()` static ```python theme={null} @staticmethod def download_async(model_id: str, download_dir: str | os.PathLike | pathlib.Path) -> typing.Awaitable[str] ``` Downloads a model file asynchronously from the ai-coustics artifact CDN. The network I/O runs on a background blocking task and does not block the caller's event loop. Resolves a compatible model through its manifest and downloads it to the specified directory. An existing file is reused if its checksum matches; otherwise it is replaced. Fresh manifests are reused from memory or the download directory according to the server's cache lifetime. Stale manifests are revalidated. Resolution is retried when the model is absent or a failed download may reflect a changed mapping. Available models can be browsed at [artifacts.ai-coustics.io](https://artifacts.ai-coustics.io/). **Parameters** **model\_id** `str` *required* The model identifier (e.g., `"quail-ms-l-16khz"`). **download\_dir** `str | os.PathLike | pathlib.Path` *required* Directory where the model file will be stored. **Returns** * `typing.Awaitable[str]`: Await it to obtain the model file path, relative when `download_dir` is relative. The released `.pyi` says `typing.Any`; the wrapper returns an awaitable resolving to `str`. Background task failure can also raise `RuntimeError`. **Raises** * [`ModelDownloadError`](/reference/sdk/api/python/errors#modeldownloaderror): Manifest access, model selection, checksum, download or filesystem failure. Inspect `details` for the underlying cause. **Example** ```python theme={null} # Find model IDs at path = await Model.download_async("rook-ms-l-16khz", "/tmp/models") # Or using pathlib.Path path = await Model.download_async("rook-ms-l-16khz", Path(tempfile.gettempdir()) / "models") model = Model.from_file(path) ``` ### `Model.get_id()` ```python theme={null} def get_id(self) -> str ``` Returns the model identifier string. **Returns** * `str`: The model ID string. ### `Model.get_optimal_sample_rate()` ```python theme={null} def get_optimal_sample_rate(self) -> int ``` Retrieves the native sample rate of the model. This is the model's native rate in Hz. It does not validate or configure your input. Use `ProcessorConfig` to describe the actual input rate and query `get_optimal_block_size(sample_rate)` for that rate. See [audio format](/reference/concepts/audio-format) for supported rates and resampling. **Returns** * `int`: The model's native sample rate in Hz. **Example** ```python theme={null} optimal_rate = model.get_optimal_sample_rate() print(f"Optimal sample rate: {optimal_rate} Hz") ``` See also [Latency](/reference/concepts/latency) and [Non-native sample rates](/reference/sdk/models#non-native-sample-rates). ### `Model.get_optimal_block_size()` ```python theme={null} def get_optimal_block_size(self, sample_rate: int) -> int ``` Retrieves the optimal block size for the model at a given sample rate. Using the optimal block size minimizes latency by avoiding internal buffering. A non-optimal block size adds buffering latency on top of the model's base delay. The optimal block size varies with sample rate because each model operates on a fixed time window. For example, a 10 ms window is 480 samples at 48 kHz and 160 samples at 16 kHz. **Parameters** **sample\_rate** `int` *required* Sample rate in Hz for which to calculate the optimal block size. **Returns** * `int`: The optimal block size for the given sample rate. **Example** ```python theme={null} sample_rate = model.get_optimal_sample_rate() block_size = model.get_optimal_block_size(sample_rate) print(f"Optimal block size: {block_size}") ``` ## `ProcessorConfig` class Audio configuration passed to [`Processor.initialize()`](/reference/sdk/api/python/enhancement#processor-initialize), [`Vad.initialize()`](/reference/sdk/api/python/vad#vad-initialize) and [`Collector.initialize()`](/reference/sdk/api/python/analysis#collector-initialize). Use [`ProcessorConfig.optimal()`](/reference/sdk/api/python/models-and-config#processorconfig-optimal) as a starting point, then adjust fields to match your audio stream. ### `ProcessorConfig()` constructor ```python theme={null} ProcessorConfig( sample_rate: int, block_size: int, variable_block_size: bool = False, ) -> ProcessorConfig ``` Create a configuration value. Construction stores the fields; native initialization validates whether the combination is supported. Editing this object after initialization does not reconfigure a running processor, detector or collector. Reinitialize the owning object to apply changes. **Parameters** **sample\_rate** `int` *required* Input sample rate in Hz. Native initialization supports 8,000–192,000 Hz, subject to the model and configuration. This field is converted to an unsigned 32-bit integer. **block\_size** `int` *required* Number of mono samples per call, greater than zero. This field is converted to a platform-sized unsigned integer. **variable\_block\_size** `bool` (default: False) Allow calls of up to `block_size` samples. With `False`, every call must contain exactly `block_size` samples. ### `ProcessorConfig.optimal()` static ```python theme={null} @staticmethod def optimal( model: Model, sample_rate: int | None = None, block_size: int | None = None, variable_block_size: bool = False, ) -> ProcessorConfig ``` Returns a `ProcessorConfig` with the model's optimal settings and any supplied overrides. **Parameters** **model** `Model` *required* The `Model` instance to get optimal config for. See [`Model`](/reference/sdk/api/python/models-and-config#model). **sample\_rate** `int | None` (default: None) Custom sample rate in Hz. If `None`, uses the model's optimal sample rate (default: `None`). **block\_size** `int | None` (default: None) Custom number of samples per processing call. If `None`, uses the optimal block size for the sample rate (default: `None`). A non-optimal block size increases latency. **variable\_block\_size** `bool` (default: False) Allow calls of up to `block_size` samples. With `False`, every call must contain exactly `block_size` samples. **Returns** * [`ProcessorConfig`](/reference/sdk/api/python/models-and-config#processorconfig): ProcessorConfig with optimal settings for the given model. **Example** ```python theme={null} # Use all optimal defaults config = ProcessorConfig.optimal(model) # Use a custom sample rate (optimal block size calculated automatically) config = ProcessorConfig.optimal(model, sample_rate=44100) # Use a custom sample rate and block size (increases latency) config = ProcessorConfig.optimal(model, sample_rate=48000, block_size=512) ``` ### `ProcessorConfig` properties #### `ProcessorConfig.sample_rate` **sample\_rate** `int` Input sample rate in Hz. Native initialization supports 8,000–192,000 Hz, subject to the model and configuration. This field is converted to an unsigned 32-bit integer. #### `ProcessorConfig.block_size` **block\_size** `int` Number of mono samples per call, greater than zero. This field is converted to a platform-sized unsigned integer. A non-optimal block size increases latency. #### `ProcessorConfig.variable_block_size` **variable\_block\_size** `bool` Allows calls of up to `block_size` samples, with added buffering latency. It does not change the sample rate or allow oversized blocks. ## `OtelConfig` class OpenTelemetry (OTel) configuration for a [`Processor`](/reference/sdk/api/python/enhancement#processor) or [`Vad`](/reference/sdk/api/python/vad#vad). Pass to `Processor`, [`ProcessorAsync`](/reference/sdk/api/python/enhancement#processorasync), `Vad` or [`VadAsync`](/reference/sdk/api/python/vad#vadasync) to control telemetry per instance. When no `OtelConfig` is provided, telemetry is configured according to the runtime environment (e.g. the `AIC_SDK_OTEL_ENABLE` environment variable). **Example** ```python theme={null} processor = Processor(model, license_key, otel_config=OtelConfig(enable=True, session_id="my-session")) ``` ### `OtelConfig()` constructor ```python theme={null} OtelConfig( enable: bool, session_id: str | None = None, export_interval_ms: int = 0, ) -> OtelConfig ``` Creates an OpenTelemetry configuration value. `enable` is required; `export_interval_ms` is an unsigned 32-bit integer. Settings are copied into the native object at construction. Later edits to this value do not change an existing session. A `session_id` containing a NUL character raises `InternalError` when passed to a processor or detector constructor. OpenTelemetry controls optional observability, independently of SDK authorization and usage reporting. See [telemetry](/reference/concepts/sdk-telemetry). **Parameters** **enable** `bool` *required* Whether to enable OpenTelemetry export. **session\_id** `str | None` (default: None) Optional session ID. If `None`, a random ID is generated. **export\_interval\_ms** `int` (default: 0) Metric export interval in ms. 0 uses the SDK default of 60,000 ms. ### `OtelConfig` properties #### `OtelConfig.enable` **enable** `bool` Whether to enable OpenTelemetry export. Overrides the `AIC_SDK_OTEL_ENABLE` environment variable. #### `OtelConfig.session_id` **session\_id** `str | None` Optional session ID for telemetry. If `None`, a random session ID is generated. #### `OtelConfig.export_interval_ms` **export\_interval\_ms** `int` OpenTelemetry metric export interval in milliseconds. Set to 0 to use the SDK default of 60,000 ms. ## `get_sdk_version()` function ```python theme={null} def get_sdk_version() -> str ``` Returns the version of the ai-coustics core SDK library used by this package. **Returns** * `str`: The library version as a string. > [!NOTE] > > This is not necessarily the same as this package's version. **Example** ```python theme={null} version = aic.get_sdk_version() print(f"ai-coustics SDK version: {version}") ``` ## `get_compatible_model_version()` function ```python theme={null} def get_compatible_model_version() -> int ``` Returns the model file format version compatible with this core SDK build. This is a format number, not a model ID or model release version. **Returns** * `int`: The compatible model version number. See the [Python API index](/reference/sdk/api/python/index), [Python guide](/reference/sdk/language-bindings/python) and [troubleshooting](/production/troubleshooting). ### `OtelConfig.__repr__()` ```python theme={null} def __repr__(self) -> str ``` Returns a diagnostic string containing the object's current fields. It is not a serialization format. ### `ProcessorConfig.__repr__()` ```python theme={null} def __repr__(self) -> str ``` Returns a diagnostic string containing the object's current fields. It is not a serialization format. # Python voice activity detection Source: https://docs.ai-coustics.com/reference/sdk/api/python/vad Python reference for Vad, VadAsync, VadContext, EnergyVadContext and VadParameter in aic-sdk. **Package:** `aic-sdk==3.4.0`. **Core SDK:** `0.26.0`. The fragments below use these imports. Supply `license_key` from your approved secret source and use the loaded model and initialized objects described in each section. For a complete file-processing example and tuning guidance, follow the [ai-coustics VAD guide](/models/voice-activity-detection/vad#how-it-works). ```python theme={null} import typing import numpy as np import numpy.typing as npt from aic_sdk import EnergyVadContext, Model, Processor, ProcessorAsync, ProcessorConfig, Vad, VadAsync, VadContext, VadParameter, OtelConfig ``` `audio` denotes a one-dimensional NumPy `float32` array. Async fragments run inside an async function. ## `Vad` class Stateful voice activity detector (VAD) backed by a dedicated VAD model. Use one instance per independent stream and serialize initialization and processing on each instance. Native resources are released when Python releases the object. To detect speech with an enhancement model instead of a dedicated VAD model, use [`EnergyVadContext`](/reference/sdk/api/python/vad#energyvadcontext). Feed mono audio to [`process()`](/reference/sdk/api/python/vad#vad-process) and read predictions through [`get_context()`](/reference/sdk/api/python/vad#vad-get_context). The audio is not modified; processing only updates the detector's prediction. When enhancement and VAD run together, feed the VAD the original input audio, not the enhanced output of [`Processor.process()`](/reference/sdk/api/python/enhancement#processor-process). Run both on the same block instead of chaining them: ```python theme={null} vad.process(audio) # reads the block, does not modify it enhanced = processor.process(audio) # enhances the same original block ``` **Example** ```python theme={null} model = Model.from_file("/path/to/vad_model.aicmodel") config = ProcessorConfig.optimal(model) vad = Vad(model, license_key, config) vad_context = vad.get_context() audio = np.zeros(config.block_size, dtype=np.float32) vad.process(audio) print(vad_context.is_speech_detected()) ``` ### `Vad()` constructor ```python theme={null} Vad( model: Model, license_key: str, config: ProcessorConfig | None = None, otel_config: OtelConfig | None = None, ) -> Vad ``` Creates a voice activity detector. The model must be a dedicated VAD model, such as `vad-ms-2.1-xxs-16khz`. Enhancement models raise [`ModelTypeUnsupportedError`](/reference/sdk/api/python/errors#modeltypeunsupportederror); for an enhancement model, use [`Processor.get_energy_vad_context()`](/reference/sdk/api/python/enhancement#processor-get_energy_vad_context). If config is provided, the VAD is initialized immediately. Otherwise, call [`initialize()`](/reference/sdk/api/python/vad#vad-initialize) before processing audio. **Parameters** **model** `Model` *required* A loaded dedicated VAD model. See [`Model`](/reference/sdk/api/python/models-and-config#model). **license\_key** `str` *required* SDK key or JWT for the ai-coustics SDK. **config** `ProcessorConfig | None` (default: None) Optional audio configuration. See [`ProcessorConfig`](/reference/sdk/api/python/models-and-config#processorconfig). **otel\_config** `OtelConfig | None` (default: None) Optional per-instance OpenTelemetry configuration. See [`OtelConfig`](/reference/sdk/api/python/models-and-config#otelconfig). ### `Vad.initialize()` ```python theme={null} def initialize(self, config: ProcessorConfig) -> None ``` Configures the VAD for a sample rate and block size. Unsupported configurations raise `AudioConfigUnsupportedError`. For the most frequent prediction updates, use [`ProcessorConfig.optimal(model)`](/reference/sdk/api/python/models-and-config#processorconfig-optimal). **Parameters** **config** `ProcessorConfig` *required* Audio configuration. See [`ProcessorConfig`](/reference/sdk/api/python/models-and-config#processorconfig). > [!WARNING] > > This method allocates memory and is not real-time safe. ### `Vad.process()` ```python theme={null} def process(self, audio: npt.NDArray[np.float32]) -> None ``` Accepts a one-dimensional NumPy `float32` array of normalized mono samples. Its length must equal `config.block_size`, or be 1 through `config.block_size` when variable blocks are enabled. Native work releases the GIL. A contiguous array is read directly; a strided view is copied. Do not mutate a shared input while the call runs. Wrong dtype or dimensionality raises `TypeError`. Returns `None`: VAD processing does not modify the audio. Read the updated prediction through [`get_context()`](/reference/sdk/api/python/vad#vad-get_context). When enhancement and VAD run together, pass the original input audio here, not the enhanced output of [`Processor.process()`](/reference/sdk/api/python/enhancement#processor-process). **Raises** * [`NotInitializedError`](/reference/sdk/api/python/errors#notinitializederror): If the VAD has not been initialized. * [`AudioConfigMismatchError`](/reference/sdk/api/python/errors#audioconfigmismatcherror): If the block size does not match the configuration. * [`ProcessingNotAllowedError`](/reference/sdk/api/python/errors#processingnotallowederror): If processing is not authorized. ### `Vad.get_context()` ```python theme={null} def get_context(self) -> VadContext ``` Returns a [`VadContext`](/reference/sdk/api/python/vad#vadcontext) for reading predictions and controlling the VAD. ### `Vad.terminate_session()` ```python theme={null} def terminate_session(self) -> None ``` Terminates the VAD's telemetry session. Stop submitting audio and treat this session as closed once you request termination. Processing becomes disallowed when the native lifecycle task handles the signal. The call can return before that handling completes when other sessions remain alive; it is not proof of remote usage acknowledgment. The session is also stopped when the object is destroyed. > [!WARNING] > > This method may block and is not real-time safe. ## `VadAsync` class Async voice activity detector backed by a dedicated VAD model. Awaitable processing runs on the shared SDK processing pool. The constructor and `get_context()` are synchronous; both can block. Omit `config` at construction and await `initialize_async(config)` to initialize asynchronously. Await blocks in stream order and bound pending work. See [async enhancement](/reference/sdk/api/python/enhancement#processorasync) for pool settings and concurrency. When enhancement and VAD run together, feed the VAD the original input audio, not the enhanced output of [`ProcessorAsync.process_async()`](/reference/sdk/api/python/enhancement#processorasync-process_async). ### `VadAsync()` constructor ```python theme={null} VadAsync( model: Model, license_key: str, config: ProcessorConfig | None = None, otel_config: OtelConfig | None = None, ) -> VadAsync ``` Creates an async voice activity detector. The model must be a dedicated VAD model, such as `vad-ms-2.1-xxs-16khz`. Enhancement models raise [`ModelTypeUnsupportedError`](/reference/sdk/api/python/errors#modeltypeunsupportederror); for an enhancement model, use [`ProcessorAsync.get_energy_vad_context()`](/reference/sdk/api/python/enhancement#processorasync-get_energy_vad_context). **Parameters** **model** `Model` *required* A loaded dedicated VAD model. See [`Model`](/reference/sdk/api/python/models-and-config#model). **license\_key** `str` *required* SDK key or JWT for the ai-coustics SDK. **config** `ProcessorConfig | None` (default: None) Optional audio configuration. See [`ProcessorConfig`](/reference/sdk/api/python/models-and-config#processorconfig). **otel\_config** `OtelConfig | None` (default: None) Optional per-instance OpenTelemetry configuration. See [`OtelConfig`](/reference/sdk/api/python/models-and-config#otelconfig). ### `VadAsync.initialize_async()` async ```python theme={null} def initialize_async(self, config: ProcessorConfig) -> typing.Awaitable[None] ``` Returns an awaitable resolving to `None` after initialization. Unsupported configurations raise `AudioConfigUnsupportedError` when awaited. The configuration is copied into the operation. ### `VadAsync.process_async()` async ```python theme={null} def process_async(self, audio: npt.NDArray[np.float32]) -> typing.Awaitable[None] ``` Copies the one-dimensional NumPy `float32` input before dispatch, then updates the VAD prediction in the background. Await it to obtain `None`. Input remains unchanged; the length, dtype and SDK error rules of `Vad.process()` apply. After awaiting, read the updated prediction through [`get_context()`](/reference/sdk/api/python/vad#vadasync-get_context). When enhancement and VAD run together, pass the original input audio here, not the enhanced output of [`ProcessorAsync.process_async()`](/reference/sdk/api/python/enhancement#processorasync-process_async). ### `VadAsync.get_context()` ```python theme={null} def get_context(self) -> VadContext ``` Returns a [`VadContext`](/reference/sdk/api/python/vad#vadcontext) for reading predictions and controlling the VAD. ### `VadAsync.terminate_session_async()` async ```python theme={null} def terminate_session_async(self) -> typing.Awaitable[None] ``` Terminates the VAD's telemetry session asynchronously. Await the returned awaitable and stop submitting audio. Treat the session as closed immediately; native processing becomes disallowed when the lifecycle task handles the signal. Other live sessions can allow termination handling to continue after the awaitable resolves. Await completion does not prove remote usage acknowledgment. ## `VadContext` class Shared control handle for a [`Vad`](/reference/sdk/api/python/vad#vad). There is no public `VadContext()` constructor. Contexts created by the same Vad reference the same detector. They can be used from any thread while audio is being processed elsewhere. ### `VadContext.is_speech_detected()` ```python theme={null} def is_speech_detected(self) -> bool ``` Returns the post-processed VAD prediction. The prediction lags its input by [`get_prediction_delay()`](/reference/sdk/api/python/vad#vadcontext-get_prediction_delay) samples. If the backing Vad stops being processed, the prediction does not update. ### `VadContext.raw_vad_probability()` ```python theme={null} def raw_vad_probability(self) -> float ``` Returns the VAD model's raw speech probability without SDK post-processing. The prediction lags its input by [`get_prediction_delay()`](/reference/sdk/api/python/vad#vadcontext-get_prediction_delay) samples. ### `VadContext.set_parameter()` ```python theme={null} def set_parameter(self, parameter: VadParameter, value: float) -> None ``` Modifies a VAD parameter. Out-of-range values, including NaN, raise `ParameterOutOfRangeError`. Query `get_parameter()` for the value used by the current model. **Parameters** **parameter** `VadParameter` *required* Parameter to modify. See [`VadParameter`](/reference/sdk/api/python/vad#vadparameter). **value** `float` *required* New parameter value. ### `VadContext.get_parameter()` ```python theme={null} def get_parameter(self, parameter: VadParameter) -> float ``` Retrieves the current value of a VAD parameter. ### `VadContext.parameter()` deprecated > [!WARNING] > > Deprecated. Use [`get_parameter()`](/reference/sdk/api/python/vad#vadcontext-get_parameter) instead. ```python theme={null} def parameter(self, parameter: VadParameter) -> float ``` ### `VadContext.get_prediction_delay()` ```python theme={null} def get_prediction_delay(self) -> int ``` Returns the total VAD prediction delay in samples. This includes input reblocking, model processing and buffering overhead for the current configuration. Use it to align speech decisions with the input timeline. This delay is not applied to the audio: [`Vad.process()`](/reference/sdk/api/python/vad#vad-process) leaves its input untouched. The value only describes how far behind its input the published prediction is, and it is independent of [`ProcessorContext.get_audio_delay()`](/reference/sdk/api/python/enhancement#processorcontext-get_audio_delay). ### `VadContext.reset()` ```python theme={null} def reset(self) -> None ``` Clears the VAD's internal state and published predictions. The VAD remains initialized. Reset clears the published predictions immediately and requests internal processing state reset for the next block. Immediately after `reset()`, [`is_speech_detected()`](/reference/sdk/api/python/vad#vadcontext-is_speech_detected) is False and [`raw_vad_probability()`](/reference/sdk/api/python/vad#vadcontext-raw_vad_probability) is 0.0. ### `VadContext.update_bearer_token()` ```python theme={null} def update_bearer_token(self, token: str) -> None ``` Replaces the bearer token on the running VAD. Both the original key and new token must be JWTs. Otherwise `TokenUnsupportedError` is raised. Embedded NUL characters raise `LicenseFormatInvalidError`. A successful update is not proof of backend acceptance; continue handling processing errors. ## `EnergyVadContext` class Control handle for an enhancement processor's energy-based voice activity detector. Detection uses the enhanced signal before output mixing and runs no separate VAD model, so an enhancement model provides speech decisions without loading a dedicated VAD model. There is no public `EnergyVadContext()` constructor. Create one with [`Processor.get_energy_vad_context()`](/reference/sdk/api/python/enhancement#processor-get_energy_vad_context) or [`ProcessorAsync.get_energy_vad_context()`](/reference/sdk/api/python/enhancement#processorasync-get_energy_vad_context). Contexts from the same processor share one detector and can be used from any thread. Creating a context keeps enhancement inference active even when the processor is bypassed or its enhancement level is zero. Inference stays active for the processor's lifetime, even after every context is released. A context remains usable after the processor is destroyed but receives no further audio, and releasing a context neither destroys the processor nor disables detection. Sensitivity uses the energy range, 1.0 to 15.0, rather than the 0.0 to 1.0 probability threshold of a dedicated VAD model. See [`VadParameter.Sensitivity`](/reference/sdk/api/python/vad#vadparameter-sensitivity). **Example** ```python theme={null} model = Model.from_file("/path/to/enhancement_model.aicmodel") config = ProcessorConfig.optimal(model) processor = Processor(model, license_key, config) vad_context = processor.get_energy_vad_context() vad_context.set_parameter(VadParameter.Sensitivity, 6.0) audio = np.zeros(config.block_size, dtype=np.float32) enhanced = processor.process(audio) print(vad_context.is_speech_detected()) ``` ### `EnergyVadContext.is_speech_detected()` ```python theme={null} def is_speech_detected(self) -> bool ``` Returns the current speech prediction. This is `False` before processing and after [`reset()`](/reference/sdk/api/python/vad#energyvadcontext-reset). It updates as the processor processes audio and lags its input by [`get_prediction_delay()`](/reference/sdk/api/python/vad#energyvadcontext-get_prediction_delay) samples. ### `EnergyVadContext.set_parameter()` ```python theme={null} def set_parameter(self, parameter: VadParameter, value: float) -> None ``` Modifies an energy VAD parameter. Parameters can be changed from any thread during processing. **Parameters** **parameter** `VadParameter` *required* Parameter to modify. See [`VadParameter`](/reference/sdk/api/python/vad#vadparameter). **value** `float` *required* New parameter value. `Sensitivity` ranges from 1.0 to 15.0 on this context. **Raises** * [`ParameterOutOfRangeError`](/reference/sdk/api/python/errors#parameteroutofrangeerror): If the parameter value is out of range. **Example** ```python theme={null} vad_context.set_parameter(VadParameter.Sensitivity, 6.0) vad_context.set_parameter(VadParameter.SpeechHoldDuration, 0.08) ``` ### `EnergyVadContext.get_parameter()` ```python theme={null} def get_parameter(self, parameter: VadParameter) -> float ``` Returns an energy VAD parameter's current value. **Parameters** **parameter** `VadParameter` *required* Parameter to query. See [`VadParameter`](/reference/sdk/api/python/vad#vadparameter). **Returns** * `float`: The current parameter value. **Example** ```python theme={null} sensitivity = vad_context.get_parameter(VadParameter.Sensitivity) ``` ### `EnergyVadContext.get_prediction_delay()` ```python theme={null} def get_prediction_delay(self) -> int ``` Returns the prediction delay in samples for the current audio configuration. The delay covers input reblocking, STFT and model processing, and matches the processor's [`ProcessorContext.get_audio_delay()`](/reference/sdk/api/python/enhancement#processorcontext-get_audio_delay). Energy detection adds no audio delay. `SpeechHoldDuration` and `MinimumSpeechDuration` also affect decision timing but are not included. Before initialization the value uses the model's optimal block size and native sample rate. After initialization it includes input buffering for the configured block size and is expressed in samples at the configured sample rate. A non-optimal or variable block size adds buffering delay, which is included. **Returns** * `int`: The delay in samples. **Example** ```python theme={null} print(f"Prediction delay: {vad_context.get_prediction_delay()} samples") ``` ### `EnergyVadContext.reset()` ```python theme={null} def reset(self) -> None ``` Clears the energy VAD's state and prediction. Use this after an interruption or seek to discard predictions from earlier audio. Parameters are retained and the processor is not reset. [`ProcessorContext.reset()`](/reference/sdk/api/python/enhancement#processorcontext-reset) also resets the energy VAD. > [!NOTE] > > **Concurrency.** The underlying SDK reset is real-time safe. Python calls still involve the interpreter; this is not a hard real-time guarantee for a Python callback. **Example** ```python theme={null} vad_context.reset() ``` ## `VadParameter` enum Parameter constants for voice activity detection. Use named constants directly; the runtime exposes PyO3 enum-like objects rather than promising standard-library `enum.Enum` iteration or `.value` behavior. ### `VadParameter` members #### `VadParameter.SpeechHoldDuration` Controls how long the VAD continues to detect speech after the audio signal no longer contains speech. This affects the stability of speech detected -> not detected transitions. When the current probability is at or below the threshold, speech remains detected while at least half of the retained history was above threshold. The history spans approximately `speech_hold_duration * 2` seconds. When the current probability is above threshold, the consecutive-frame test uses `MinimumSpeechDuration`. For example, a `speech_hold_duration` of 0.5 s sustains detection for 0.5 s after speech stops. Additional speech blocks during that period can extend detection until the 50% history threshold is no longer met. > [!NOTE] > > Timing is rounded to the nearest model window: for a 10 ms window, to the nearest multiple of 10 ms. `get_parameter()` returns the stored requested value, not the effective transition timing. **Range:** 0.0 to 300x model window length (seconds) **Default:** model-specific #### `VadParameter.Sensitivity` Threshold used to decide whether speech is detected. Its meaning and range depend on the detector. [`Vad`](/reference/sdk/api/python/vad#vad) and [`VadAsync`](/reference/sdk/api/python/vad#vadasync) run a dedicated VAD model, which outputs a speech probability for each processed audio block. A value above this threshold triggers a speech-detected decision. [`EnergyVadContext`](/reference/sdk/api/python/vad#energyvadcontext) compares the energy left in the enhanced signal against `10 ** -sensitivity`, so higher values detect quieter speech. **Range:** 0.0–1.0 for dedicated VAD models; 1.0–15.0 for the energy VAD **Default:** model-specific #### `VadParameter.MinimumSpeechDuration` Controls how long speech needs to be present in the audio signal before the VAD considers it speech. This affects the stability of speech not detected -> detected transitions. > [!NOTE] > > Timing is rounded to the nearest model window: for a 10 ms window, to the nearest multiple of 10 ms. `get_parameter()` returns the stored requested value, not the effective transition timing. **Range:** 0.0–1.0 (seconds) **Default:** model-specific See the [Python API index](/reference/sdk/api/python/index), [Python guide](/reference/sdk/language-bindings/python) and [troubleshooting](/production/troubleshooting). # Rust audio analysis Source: https://docs.ai-coustics.com/reference/sdk/api/rust/analysis Collector, Analyzer, FileAnalyzer and AnalysisResult in aic-sdk. **Crate:** `aic-sdk = "=0.25.2"`. **Core SDK:** `0.25.2`. These APIs do not require the `async` feature. Import types from `aic_sdk`; signatures below are declarations. ## `analyzer_pair` ```rust theme={null} pub fn analyzer_pair<'a>( model: &Model<'a>, license_key: &str, ) -> Result<(Collector, Analyzer<'a>), AicError> ``` Creates a collector and analyzer for a Tyto analysis model and an SDK key or JWT. The collector buffers a model-defined span of audio; new audio replaces older samples. Run expensive analysis separately from collection. Invalid credentials, incompatible model types and native creation failures return `AicError`. The pair shares native audio state. Retained model storage keeps weights available after dropping the model handle; borrowed model bytes must still outlive the analyzer. There are no public `Collector::new` or `Analyzer::new` constructors. This function accepts no `OtelConfig`. Its native creation path disables optional OpenTelemetry export; SDK authorization and session reporting requirements remain separate. ## `Collector` ```rust theme={null} pub struct Collector { /* private fields */ } ``` A buffering handle created by `analyzer_pair`. Implements `Drop`, `Send` and `Sync`; it is not `Clone`. Collection uses mutable access and can run on a separate thread from the paired analyzer. Dropping it releases its native handle. ### `Collector::initialize` ```rust theme={null} pub fn initialize(&mut self, config: &ProcessorConfig) -> Result<(), AicError> ``` Configures the actual input rate and sample count. Use `ProcessorConfig::optimal(model)` as a starting point. The configuration is copied; unsupported combinations return `AudioConfigUnsupported`. This allocates and must run outside the audio callback. ### `Collector::buffer` ```rust theme={null} pub fn buffer(&mut self, audio: &[f32]) -> Result<(), AicError> ``` Reads normalized mono samples without modifying the slice. Requires initialization and the configured length, or a length up to `block_size` with variable blocks enabled. Returns `NotInitialized` or `AudioConfigMismatch` when applicable. The call buffers audio; it does not return a score or perform the expensive analysis forward pass. ## `Analyzer` ```rust theme={null} pub struct Analyzer<'a> { /* private fields */ } ``` Analyzes audio buffered by the paired collector. Implements `Drop`, `Send` and `Sync`; it is not `Clone`. Mutable access serializes analysis and termination. The lifetime keeps borrowed model bytes alive; native handles retain model storage. Dropping the analyzer releases its handle and requests session shutdown. ### `Analyzer::reset` ```rust theme={null} pub fn reset(&self) ``` Requests reset of the shared collector state. The next collection pass clears buffered/delayed state while preserving configuration. Until then, analysis uses a zero-filled snapshot instead of the previously published audio. Use this at an application stream boundary; reset does not restore authorization or reopen a terminated session. ### `Analyzer::analyze_buffered` ```rust theme={null} pub fn analyze_buffered(&mut self) -> Result ``` Runs the model over the latest buffered span and returns a score snapshot. Incomplete initial input is padded with silence. This is blocking computation and must run outside the audio callback. Authorization failures return `ProcessingNotAllowed` with no result. Repeated calls without fresh audio are not fresh independent observations. ### `Analyzer::terminate_session` ```rust theme={null} pub fn terminate_session(&mut self) ``` Requests session termination. Stop analysis and treat the session as closed. Native work becomes disallowed when the lifecycle task handles the signal; with other sessions alive this can happen after the method returns. It may block for final-session shutdown. Return is not a universal remote usage acknowledgment. Create a new pair for another session. ### `Analyzer::update_bearer_token` ```rust theme={null} pub fn update_bearer_token(&self, token: &str) -> Result<(), AicError> ``` Updates a JWT in a session originally created with a JWT. Returns `TokenUpdateUnsupported` for unsupported credential types and `LicenseFormatInvalid` for embedded NUL characters. Local replacement does not prove backend acceptance; keep checking analysis errors. ## `FileAnalyzer` ```rust theme={null} pub struct FileAnalyzer<'model, 'a> { /* private fields */ } ``` Convenience analysis for a mono buffer already decoded into memory. It does not open or decode an audio file. It owns a collector/analyzer pair and **borrows the `Model` itself for `'model`**; keep that model handle alive, as well as any bytes borrowed for `'a`. This is stricter than using `analyzer_pair` directly. Its owned fields release native resources on drop. There is no public token-update, reset or session-termination method on this type. Use `Analyzer` directly when those lifecycle controls are required. Calls require mutable access and must be serialized. ### `FileAnalyzer::new` ```rust theme={null} pub fn new(model: &'model Model<'a>, license_key: &str) -> Result ``` Creates the internal pair for a Tyto model. The collector is initialized by each `analyze` call, allowing different input rates on subsequent calls. Credential and model errors match `analyzer_pair`. ### `FileAnalyzer::analyze` ```rust theme={null} pub fn analyze( &mut self, audio: &[f32], sample_rate: u32, step_samples: Option, ) -> Result, AicError> ``` Reads normalized mono samples at their actual `sample_rate`, leaving the slice unchanged. The native collector handles supported non-native rates; this method does not mix channels. It initializes the collector at the model's preferred block size and analyzes independent five-second windows. `step_samples` is the advance between window starts. `None` uses `5 * sample_rate`; smaller positive values overlap windows and larger values leave gaps. Rate zero or step zero returns `AudioConfigUnsupported`, as does an unsupported native configuration. Other initialization, buffering or analysis errors propagate as `AicError` without a partial result vector. Empty input and buffers up to five seconds produce one silence-padded result. Longer buffers produce only complete windows on the step grid starting at zero; partial trailing windows are omitted. Each window resets the analysis/collection state. The operation allocates and performs blocking computation; run it outside the audio callback. ## `AnalysisResult` ```rust theme={null} pub struct AnalysisResult { pub risk_score: f32, pub speaker_reverb: f32, pub speaker_loudness: f32, pub interfering_speech: f32, pub noise: f32, pub codec_degradation: f32, pub packet_loss: f32, } ``` An owned score snapshot. Its public fields are writable Rust values; changing them does not change the analyzer. Implements `Debug`, `Clone` and `PartialEq`, plus conversion from the native result struct. Values returned by the model lie between 0.0 and 1.0. They are not calibrated failure probabilities for your downstream system. | Field | Interpretation | | - | - | | `risk_score: f32` | Overall audio risk for downstream speech processing; lower is less problematic | | `speaker_reverb: f32` | Speaker distance/reverberance; lower is less problematic | | `speaker_loudness: f32` | Relative loudness dimension; lower is not universally better | | `interfering_speech: f32` | Interference from other speakers; lower is less problematic | | `noise: f32` | Ambient/environmental noise; lower is less problematic | | `codec_degradation: f32` | Lossy codec artifacts; lower is less problematic | | `packet_loss: f32` | Dropouts/discontinuities; lower is less problematic | ## Borrowing example This reference function accepts a loaded Tyto model, decoded mono audio and a credential from its caller. Use the [Rust guide](/reference/sdk/language-bindings/rust) for project setup. ```rust theme={null} use aic_sdk::{AicError, AnalysisResult, FileAnalyzer, Model}; fn analyze_audio( model: &Model<'_>, sdk_key: &str, audio: &[f32], sample_rate: u32, ) -> Result, AicError> { let mut analyzer = FileAnalyzer::new(model, sdk_key)?; analyzer.analyze(audio, sample_rate, None) } ``` See [Tyto analysis](/models/audio-insight/real-time-analysis), [errors and features](/reference/sdk/api/rust/errors-and-features) and the [symbol index](/reference/sdk/api/rust/index). # Rust enhancement Source: https://docs.ai-coustics.com/reference/sdk/api/rust/enhancement Processor, ProcessorAsync, contexts, stream ownership and parameters in aic-sdk. **Crate:** `aic-sdk = "=0.25.2"`. **Core SDK:** `0.25.2`. Signatures are declarations; import the named types from `aic_sdk`. See the [Rust guide](/reference/sdk/language-bindings/rust) for a complete runnable program. ## `Processor` ```rust theme={null} pub struct Processor<'a> { /* private fields */ } ``` Stateful mono enhancement. Use one instance per independent stream. Mutable borrowing serializes initialization, processing and termination; a separate `ProcessorContext` can control state from another thread. Implements `Drop`, `Send` and `Sync`; it is not `Clone`. Native model storage is retained internally, while `'a` keeps any borrowed model bytes alive. Dropping the model handle does not invalidate the processor, but its borrowed backing bytes must outlive it. ### `Processor::new` ```rust theme={null} pub fn new(model: &Model<'a>, license_key: &str) -> Result ``` Creates an uninitialized processor for an enhancement or bypass model. The credential is an SDK key or JWT. Invalid credentials and incompatible model types return the corresponding `AicError`. Call `initialize` or `with_config` before processing. ### `Processor::with_otel_config` ```rust theme={null} pub fn with_otel_config( model: &Model<'a>, license_key: &str, otel_config: &OtelConfig, ) -> Result ``` Creates an uninitialized processor with explicit [OpenTelemetry settings](/reference/sdk/api/rust/models-and-config#rust-aic_sdk-OtelConfig). Settings and credential data are copied into the native session. A NUL-containing SDK key returns `LicenseFormatInvalid`; a NUL-containing telemetry session ID returns `Internal`. ### `Processor::with_config` ```rust theme={null} pub fn with_config(self, config: &ProcessorConfig) -> Result ``` Consumes the processor, calls initialization and returns it on success. On failure, the consumed processor is dropped. Use this to chain construction and initialization. ### `Processor::initialize` ```rust theme={null} pub fn initialize(&mut self, config: &ProcessorConfig) -> Result<(), AicError> ``` Configures the input sample rate and block size, copies the settings and initializes processing state. Invalid configurations return `AudioConfigUnsupported`. This allocates and must run outside the audio callback. If reinitialization fails, do not continue with assumed previous settings; successfully initialize again before processing. ### `Processor::process` ```rust theme={null} pub fn process(&mut self, audio: &mut [f32]) -> Result<(), AicError> ``` Enhances normalized mono samples in place. Fixed mode requires exactly `block_size` samples; variable mode accepts slices up to that size. Returns `NotInitialized`, `AudioConfigMismatch` or `ProcessingNotAllowed` when applicable. The returned `Result` must be checked even when construction succeeded. The native processor may write delay-preserving fallback samples when processing is disallowed; other errors are not a universal unchanged-buffer guarantee. Handle errors according to your application's continuity policy. ### `Processor::context` ```rust theme={null} pub fn context(&self) -> ProcessorContext ``` Creates a shared control handle. Multiple contexts refer to the same control state, not separate audio streams. Context creation asserts native success rather than returning a `Result`; an internal failure can panic. ### `Processor::terminate_session` ```rust theme={null} pub fn terminate_session(&mut self) ``` Requests termination of the telemetry and authorization session. Stop submitting work before termination. Return is not an acknowledgment that a remote service has received all usage. The object cannot start a new session; create a new processor to resume. This operation may block and is unsuitable for the audio callback. Native work becomes disallowed when the lifecycle task handles the signal; with other sessions alive that can occur after return. ### `Processor::energy_vad_context` ```rust theme={null} pub fn energy_vad_context(&mut self) -> EnergyVadContext ``` Creates an [`EnergyVadContext`](/reference/sdk/api/rust/vad#rust-aic_sdk-EnergyVadContext) driven by this processor's enhanced signal, before output mixing. It shares the processor's enhancement model and runs no separate model, and it advances with `process` rather than a separate call. All contexts from one processor reference the same energy VAD. Creating a context keeps inference active even when the processor is bypassed or fully dry, for the processor's lifetime and after every context is dropped. A context can outlive the processor but then publishes no new predictions. This allocates and is not real-time safe. ## `ProcessorContext` ```rust theme={null} pub struct ProcessorContext { /* private fields */ } ``` Create with `Processor::context` or await `ProcessorAsync::context`. There is no public constructor. Implements `Drop`, `Send` and `Sync`. Contexts share native control state and can be used while another thread processes audio. Dropping a context releases that handle; it does not destroy its processor. Keeping a context does not produce audio after its processor is gone. ### `ProcessorContext::set_parameter` ```rust theme={null} pub fn set_parameter(&self, parameter: ProcessorParameter, value: f32) -> Result<(), AicError> ``` Sets a parameter using the bounds below. Values outside the accepted range, including NaN, return `ParameterOutOfRange`. ### `ProcessorContext::parameter` ```rust theme={null} pub fn parameter(&self, parameter: ProcessorParameter) -> f32 ``` Reads the current parameter value. Read the active model's enhancement level rather than assuming a universal model default. ### `ProcessorContext::audio_delay` ```rust theme={null} pub fn audio_delay(&self) -> usize ``` Returns algorithmic and internal buffering delay in samples at the configured input rate, or native rate before initialization. It excludes CPU execution time, scheduling, transport and application queues. Convert using `1000.0 * delay as f64 / sample_rate as f64`. The native query is asserted and can panic on internal failure. ### `ProcessorContext::reset` ```rust theme={null} pub fn reset(&self) ``` Requests a reset. The processing path clears its state and buffers on its next processing call, retaining audio configuration. Any energy VAD on this processor is reset as well. Reset does not reopen a terminated session. ### `ProcessorContext::update_bearer_token` ```rust theme={null} pub fn update_bearer_token(&self, token: &str) -> Result<(), AicError> ``` Replaces a JWT in a session originally created with a JWT. Otherwise returns `TokenUpdateUnsupported`; an embedded NUL returns `LicenseFormatInvalid`. A rejected replacement is not installed. Successful local replacement does not prove backend acceptance; continue handling processing errors. ## `ProcessorParameter` ```rust theme={null} pub enum ProcessorParameter { Bypass, EnhancementLevel } ``` Parameter selector. Both variants accept values from 0.0 through 1.0. Implements `Debug`, `Clone`, `Copy`, `PartialEq`, `Eq` and `Hash`, plus conversion to the matching native parameter type. There is no Rust `VoiceGain` variant in this release. ### `ProcessorParameter::Bypass` ```rust theme={null} ProcessorParameter::Bypass ``` Zero enables enhancement; any positive accepted value enables delay-preserving bypass. Readback is 0.0 or 1.0. The initial bypass value is 0.0. ### `ProcessorParameter::EnhancementLevel` ```rust theme={null} ProcessorParameter::EnhancementLevel ``` Controls enhancement strength. Quail models adjust suppression, including competing speech for Quail Voice Focus. Rook models adjust mixback for human listening. Initial strength can be model-specific; read `parameter` for the active value. ## `ProcessorAsync` ```rust theme={null} pub struct ProcessorAsync { /* private fields */ } ``` **Requires feature:** `async`. Owns a synchronized processor backed by a shared worker pool. Constructors are synchronous. Methods marked `async` serialize access to this instance through a mutex and run expensive processing work on the pool. Await blocks in stream order and bound pending work; separate instances serve independent streams. `AIC_NUM_THREADS`, read when the global pool is first created, selects a positive thread count; the default is available CPU parallelism. This type requires `Model<'static>`, from file loading or static embedded data. It implements `Send` and `Sync` through its fields, but not `Clone`; use `Arc` to share it. No cancellation or unbounded queue guarantee is implied. ### `ProcessorAsync::new` ```rust theme={null} pub fn new(model: &Model<'static>, license_key: &str) -> Result ``` Synchronously creates an uninitialized enhancement processor. Construction errors match `Processor::new`. ### `ProcessorAsync::with_otel_config` ```rust theme={null} pub fn with_otel_config( model: &Model<'static>, license_key: &str, otel_config: &OtelConfig, ) -> Result ``` Synchronously creates an uninitialized processor with explicit telemetry settings; errors match the synchronous constructor. ### `ProcessorAsync::with_config` ```rust theme={null} pub async fn with_config(self, config: &ProcessorConfig) -> Result ``` Consumes the async processor, awaits initialization and returns it. A failed initialization drops the consumed instance. ### `ProcessorAsync::initialize` ```rust theme={null} pub async fn initialize(&self, config: &ProcessorConfig) -> Result<(), AicError> ``` Copies the configuration, waits for exclusive access and initializes on the processing pool. Unsupported configurations return `AudioConfigUnsupported`. ### `ProcessorAsync::process` ```rust theme={null} pub async fn process(&self, audio: Vec) -> Result, AicError> ``` Takes ownership of the audio vector, processes it in place on the background pool and returns the vector on success. Input size and sample rules match `Processor::process`. On error the vector is dropped and is not returned, including when the native processor wrote fallback data. ### `ProcessorAsync::terminate_session` ```rust theme={null} pub async fn terminate_session(&self) ``` Waits for exclusive access and requests termination on the background pool. Stop submitting audio first; create a new object for another session. Await the method, but do not treat completion as proof that native signal handling or remote usage acknowledgment has finished when other sessions remain alive. ### `ProcessorAsync::context` ```rust theme={null} pub async fn context(&self) -> ProcessorContext ``` Waits for the mutex and returns a control handle. This method is async in Rust, unlike the Python wrapper's `get_context`. Internal native context creation failure can panic. ### `ProcessorAsync::energy_vad_context` ```rust theme={null} pub async fn energy_vad_context(&self) -> EnergyVadContext ``` Waits for the mutex and returns an [`EnergyVadContext`](/reference/sdk/api/rust/vad#rust-aic_sdk-EnergyVadContext) for this processor. See [`Processor::energy_vad_context`](/reference/sdk/api/rust/enhancement#rust-aic_sdk-Processor-energy_vad_context) for detector behavior. Internal native context creation failure can panic. See the [model and configuration reference](/reference/sdk/api/rust/models-and-config), [errors and features](/reference/sdk/api/rust/errors-and-features) and [symbol index](/reference/sdk/api/rust/index). ## Process one block This function receives an initialized processor and a normalized mono block from the caller. Errors propagate to the application: ```rust theme={null} use aic_sdk::{AicError, Processor}; fn enhance_block(processor: &mut Processor<'_>, audio: &mut [f32]) -> Result<(), AicError> { processor.process(audio) } ``` With the `async` feature, ownership of the vector passes to the operation: ```rust theme={null} use aic_sdk::{AicError, ProcessorAsync}; async fn enhance_owned(processor: &ProcessorAsync, audio: Vec) -> Result, AicError> { processor.process(audio).await } ``` # Rust errors and features Source: https://docs.ai-coustics.com/reference/sdk/api/rust/errors-and-features Cargo features, runtime loading, complete error variants and trait contracts for aic-sdk. **Crate:** `aic-sdk = "=0.25.2"`. **Core SDK:** `0.25.2`. The minimum Rust version is 1.88, using edition 2024. ## Cargo features No features are enabled by default. Static native linking is the default strategy, but a native library must still be supplied. Cargo features are additive across dependencies. | Feature | Available API and build behavior | | - | - | | `async` | Exposes `ProcessorAsync` and `VadAsync`, using a shared Rayon worker pool and per-instance async mutex | | `download-model` | Adds `Model::download`; otherwise this associated function is absent | | `download-lib` | Permits the build script to download the matching native library when `AIC_LIB_PATH` is absent and build-time linking is selected | | `dynamic-linking` | Uses a shared library with build-time linking; deploy the runtime library as well as the executable | | `runtime-linking` | Resolves the shared library at runtime; exposes `load_library`, `is_library_loaded` and `DynamicLoadingError`, and skips the native build-time link/download step | If both linking features are enabled, runtime linking wins and the build emits a warning. Prefer selecting one explicitly. `AIC_LIB_PATH` identifies the SDK library directory for static/dynamic build-time linking; it is not the runtime `load_library` file path. With no download feature, build-time linking requires a local library. See the [released linking guide](https://docs.rs/aic-sdk/0.25.2/aic_sdk/docs/linking/index.html) for platform deployment details. For runtime loading and async processing, a minimal dependency declaration is: ```toml theme={null} [dependencies] aic-sdk = { version = "=0.25.2", features = ["runtime-linking", "async"] } ``` ## `load_library` **Requires feature:** `runtime-linking`. ```rust theme={null} pub unsafe fn load_library>( path: P, ) -> Result<(), DynamicLoadingError> ``` Explicitly loads a native shared library before the first SDK operation. **Safety:** the file must be trusted and ABI-compatible with the bundled 0.25.2 header. Loading an incompatible library can cause undefined behavior. Checking a filename or a version string after loading does not establish ABI compatibility. The loaded library remains for the process lifetime. It cannot be safely replaced. A subsequent valid load returns `AlreadyLoaded`; the implementation attempts opening and resolving the supplied library before storing it, so an invalid subsequent path can return an open/symbol error first. If you omit this call, the first SDK operation loads the platform default filename through the OS loader search path (`libaic.so`, `libaic.dylib` or `aic.dll`). Automatic loading failure panics. Explicit loading lets you handle `DynamicLoadingError` before SDK use. ## `is_library_loaded` **Requires feature:** `runtime-linking`. ```rust theme={null} pub fn is_library_loaded() -> bool ``` Reports whether this process has installed the SDK dynamic library. It does not trigger loading or prove SDK authorization. ## `DynamicLoadingError` **Requires feature:** `runtime-linking`. Reexported from `aic_sdk_sys`. ```rust theme={null} pub enum DynamicLoadingError { AlreadyLoaded, OpenLibrary { path: std::path::PathBuf, source: libloading::Error, }, LoadSymbol { symbol: &'static str, source: libloading::Error, }, } ``` | Variant | Meaning and recovery | | - | - | | `AlreadyLoaded` | A library was already installed; use the existing library or restart with the intended build | | `OpenLibrary { path, source }` | The loader could not open the file; check the exact path, architecture and dependent libraries | | `LoadSymbol { symbol, source }` | A required symbol is missing; supply the matching complete native SDK | All named variant fields are public pattern-match payloads with the types shown above. `path` identifies the attempted file and `symbol` the missing native function. Both `source` fields preserve the platform loader error. The enum implements `Debug`, `Display` and `std::error::Error`; `Error::source()` returns the underlying loader error for the two payload variants and `None` for `AlreadyLoaded`. It is not `Clone` or `Eq`. ## `AicError` ```rust theme={null} pub enum AicError { ParameterOutOfRange, NotInitialized, AudioConfigUnsupported, AudioConfigMismatch, ProcessingNotAllowed, Internal, LicenseFormatInvalid, LicenseVersionUnsupported, LicenseExpired, TokenUpdateUnsupported, ModelInvalid, ModelVersionUnsupported, ModelTypeUnsupported, FilePathInvalid, FileSystemError, ModelDataUnaligned, ModelDownload(String), Unknown(aic_sdk_sys::AicErrorCode::Type), } ``` Returned by fallible wrapper operations. Implements `Debug`, `Clone`, `PartialEq`, `Eq`, `Display` and `std::error::Error`. Display provides diagnostic text; match variants rather than parsing those strings. `ModelDownload` carries text rather than a nested error source. | Variant | Cause and recovery | | - | - | | `ParameterOutOfRange` | Parameter outside its bounds; use the documented ranges and read the current value | | `NotInitialized` | Processing/buffering before successful initialization; initialize the object first | | `AudioConfigUnsupported` | Invalid rate/block combination, or zero FileAnalyzer rate/step; start with the model's optimal configuration | | `AudioConfigMismatch` | Slice length violates the initialized block contract; split or buffer samples appropriately | | `ProcessingNotAllowed` | Authorization/reporting failed or a termination signal was handled; check credentials/network and apply your explicit audio fallback | | `Internal` | Native internal failure, including a NUL-containing telemetry session ID; correct input or report a minimal reproduction | | `LicenseFormatInvalid` | Malformed credential or embedded NUL; verify the exact SDK key/JWT without logging it | | `LicenseVersionUnsupported` | Unsupported credential format; use a compatible SDK and credential | | `LicenseExpired` | Credential expired; renew it and rotate JWTs before expiry when supported | | `TokenUpdateUnsupported` | Original or replacement credential is not a JWT; start with JWT credentials when rotation is required | | `ModelInvalid` | Corrupted/invalid model data; obtain a verified model file | | `ModelVersionUnsupported` | Model file format differs from the core SDK; download compatible data | | `ModelTypeUnsupported` | Wrong model family for processor, VAD or analyzer; select a matching model | | `FilePathInvalid` | Path is not valid UTF-8 or contains an embedded NUL; validate it and handle this error before loading | | `FileSystemError` | Model file cannot be read; check existence, type and permissions | | `ModelDataUnaligned` | Buffer address is not 64-byte aligned; use `include_model!` or a correctly aligned allocation | | `ModelDownload(String)` | Manifest/model/file operation failed; inspect the payload and check model ID, connectivity and destination permissions | | `Unknown(AicErrorCode::Type)` | Unrecognized native code; record the code and versions for investigation | The tuple payloads are available through pattern matching. `ModelDownload` exists even with `download-model` disabled, although the public downloader is then absent. There is no `ParameterFixed` variant in this release. ## Panics and Result boundaries `Result` covers ordinary native errors but is not a promise that no call can panic. Model/query/context functions assert native success. Worker initialization or unexpected worker channel loss can panic in async code. Runtime automatic loading can panic before the called SDK operation returns. Explicit loader handling and validated inputs keep these conditions distinct from routine processing errors. ## Trait and conversion surface | Types | Explicit or derived traits | | - | - | | `Model<'a>`, `Processor<'a>`, `ProcessorContext`, `Vad<'a>`, `VadContext`, `Collector`, `Analyzer<'a>` | `Drop`, `Send`, `Sync`; native handles are released on drop | | `ProcessorAsync`, `VadAsync` | `Send` and `Sync` through owned synchronized fields; use `Arc` rather than assuming `Clone` | | `FileAnalyzer<'model, 'a>` | `Send`/`Sync` through its borrowed model and owned fields; field destruction releases the pair | | `ProcessorConfig`, `OtelConfig` | `Debug`, `Clone`, `PartialEq`, `Eq`, `Hash`; no `Default` or `Copy` | | `ProcessorParameter`, `VadParameter` | `Debug`, `Clone`, `Copy`, `PartialEq`, `Eq`, `Hash` | | `AnalysisResult` | `Debug`, `Clone`, `PartialEq`; no `Eq` because it contains floating-point scores | | `AicError` | `Debug`, `Clone`, `PartialEq`, `Eq`, `Display`, `Error` | | `DynamicLoadingError` | `Debug`, `Display`, `Error`, behind `runtime-linking` | Explicit conversions are: ```rust theme={null} impl From for aic_sdk_sys::AicProcessorParameter::Type impl From for aic_sdk_sys::AicVadParameter::Type impl From for AnalysisResult impl From for AicError ``` Parameter conversions map the named variant to its C enum value. Result conversion copies all seven fields. Error conversion maps known failure codes and wraps other values in `Unknown`; the null-pointer error code panics as a wrapper invariant failure. Do not convert a native success code into an error: this conversion does not perform the success check used by fallible SDK methods. Naming the `aic_sdk_sys` types in application code requires that crate as a direct dependency; they are not root type reexports of `aic_sdk`. Rustdoc also lists standard blanket traits and other compiler-derived implementations. ## Reserved integration hook: `set_sdk_id` ```rust theme={null} pub unsafe fn set_sdk_id(id: u32) ``` This public export is reserved for ai-coustics wrapper integrations, not application setup. Callers must use an ID assigned by ai-coustics. Application constructors already identify the Rust wrapper; do not override it. See the [symbol index](/reference/sdk/api/rust/index), [authentication](/models/get-started/authenticate-apps) and [troubleshooting](/production/troubleshooting). # Rust API reference Source: https://docs.ai-coustics.com/reference/sdk/api/rust/index Complete application API for aic-sdk, with ownership, feature gates, errors and runtime linking. **Crate:** `aic-sdk = "=0.25.2"`. **Core SDK:** `0.25.2`. **Rust:** 1.88 or newer. Start with the [Rust guide](/reference/sdk/language-bindings/rust) for installation and a runnable audio example. This reference covers root reexports, fields, variants, constructors, methods, macros and feature-dependent loading APIs. Raw FFI exports belong to the separate `aic-sdk-sys` crate, not `aic_sdk`. ## Domains | Domain | Contents | | - | - | | [Models and configuration](/reference/sdk/api/rust/models-and-config) | File/borrowed models, aligned embedding, audio/telemetry configuration and version queries | | [Enhancement](/reference/sdk/api/rust/enhancement) | In-place and async processing, contexts and parameter control | | [Voice activity detection](/reference/sdk/api/rust/vad) | Dedicated VAD, energy VAD on an enhancement processor, predictions, timing and async vector ownership | | [Audio analysis](/reference/sdk/api/rust/analysis) | Shared collection, analysis snapshots and FileAnalyzer lifetimes | | [Errors and features](/reference/sdk/api/rust/errors-and-features) | Complete error variants, runtime loader, feature gates and traits | ## Ownership and feature conventions Native handles own resources released through Rust destruction. A model loaded from a file has static data lifetime, but its memory-mapped file must remain unchanged and present while dependent objects exist. A model created from borrowed bytes retains their lifetime in processors, VADs and analyzers. `FileAnalyzer` additionally borrows the model handle itself. Async constructors require `Model<'static>`. Synchronous enhancement modifies `&mut [f32]`; VAD and collection read `&[f32]`. Async operations own `Vec` and return it only on success. Process a stream in order, with one stateful instance per independent stream. `Send` and `Sync` do not remove the methods' borrowing and ordering requirements. No Cargo features are enabled by default. This index includes conditionally available symbols, whose domain entries show the required feature next to the signature. There is no Rust `ProcessorParameter::VoiceGain`, `FileAnalyzer::update_bearer_token` or asynchronous model-download method in 0.25.2. ## Symbol index | Symbol | Kind | | - | - | | [`AicError`](/reference/sdk/api/rust/errors-and-features#rust-aic_sdk-AicError) | type | | [`AicError::AudioConfigMismatch`](/reference/sdk/api/rust/errors-and-features#rust-aic_sdk-AicError-AudioConfigMismatch) | field or variant | | [`AicError::AudioConfigUnsupported`](/reference/sdk/api/rust/errors-and-features#rust-aic_sdk-AicError-AudioConfigUnsupported) | field or variant | | [`AicError::FilePathInvalid`](/reference/sdk/api/rust/errors-and-features#rust-aic_sdk-AicError-FilePathInvalid) | field or variant | | [`AicError::FileSystemError`](/reference/sdk/api/rust/errors-and-features#rust-aic_sdk-AicError-FileSystemError) | field or variant | | [`AicError::Internal`](/reference/sdk/api/rust/errors-and-features#rust-aic_sdk-AicError-Internal) | field or variant | | [`AicError::LicenseExpired`](/reference/sdk/api/rust/errors-and-features#rust-aic_sdk-AicError-LicenseExpired) | field or variant | | [`AicError::LicenseFormatInvalid`](/reference/sdk/api/rust/errors-and-features#rust-aic_sdk-AicError-LicenseFormatInvalid) | field or variant | | [`AicError::LicenseVersionUnsupported`](/reference/sdk/api/rust/errors-and-features#rust-aic_sdk-AicError-LicenseVersionUnsupported) | field or variant | | [`AicError::ModelDataUnaligned`](/reference/sdk/api/rust/errors-and-features#rust-aic_sdk-AicError-ModelDataUnaligned) | field or variant | | [`AicError::ModelDownload`](/reference/sdk/api/rust/errors-and-features#rust-aic_sdk-AicError-ModelDownload) | field or variant | | [`AicError::ModelInvalid`](/reference/sdk/api/rust/errors-and-features#rust-aic_sdk-AicError-ModelInvalid) | field or variant | | [`AicError::ModelTypeUnsupported`](/reference/sdk/api/rust/errors-and-features#rust-aic_sdk-AicError-ModelTypeUnsupported) | field or variant | | [`AicError::ModelVersionUnsupported`](/reference/sdk/api/rust/errors-and-features#rust-aic_sdk-AicError-ModelVersionUnsupported) | field or variant | | [`AicError::NotInitialized`](/reference/sdk/api/rust/errors-and-features#rust-aic_sdk-AicError-NotInitialized) | field or variant | | [`AicError::ParameterOutOfRange`](/reference/sdk/api/rust/errors-and-features#rust-aic_sdk-AicError-ParameterOutOfRange) | field or variant | | [`AicError::ProcessingNotAllowed`](/reference/sdk/api/rust/errors-and-features#rust-aic_sdk-AicError-ProcessingNotAllowed) | field or variant | | [`AicError::TokenUpdateUnsupported`](/reference/sdk/api/rust/errors-and-features#rust-aic_sdk-AicError-TokenUpdateUnsupported) | field or variant | | [`AicError::Unknown`](/reference/sdk/api/rust/errors-and-features#rust-aic_sdk-AicError-Unknown) | field or variant | | [`AnalysisResult`](/reference/sdk/api/rust/analysis#rust-aic_sdk-AnalysisResult) | type | | [`AnalysisResult::codec_degradation`](/reference/sdk/api/rust/analysis#rust-aic_sdk-AnalysisResult-codec_degradation) | field or variant | | [`AnalysisResult::interfering_speech`](/reference/sdk/api/rust/analysis#rust-aic_sdk-AnalysisResult-interfering_speech) | field or variant | | [`AnalysisResult::noise`](/reference/sdk/api/rust/analysis#rust-aic_sdk-AnalysisResult-noise) | field or variant | | [`AnalysisResult::packet_loss`](/reference/sdk/api/rust/analysis#rust-aic_sdk-AnalysisResult-packet_loss) | field or variant | | [`AnalysisResult::risk_score`](/reference/sdk/api/rust/analysis#rust-aic_sdk-AnalysisResult-risk_score) | field or variant | | [`AnalysisResult::speaker_loudness`](/reference/sdk/api/rust/analysis#rust-aic_sdk-AnalysisResult-speaker_loudness) | field or variant | | [`AnalysisResult::speaker_reverb`](/reference/sdk/api/rust/analysis#rust-aic_sdk-AnalysisResult-speaker_reverb) | field or variant | | [`Analyzer`](/reference/sdk/api/rust/analysis#rust-aic_sdk-Analyzer) | type | | [`Analyzer::analyze_buffered`](/reference/sdk/api/rust/analysis#rust-aic_sdk-Analyzer-analyze_buffered) | method | | [`Analyzer::reset`](/reference/sdk/api/rust/analysis#rust-aic_sdk-Analyzer-reset) | method | | [`Analyzer::terminate_session`](/reference/sdk/api/rust/analysis#rust-aic_sdk-Analyzer-terminate_session) | method | | [`Analyzer::update_bearer_token`](/reference/sdk/api/rust/analysis#rust-aic_sdk-Analyzer-update_bearer_token) | method | | [`analyzer_pair`](/reference/sdk/api/rust/analysis#rust-aic_sdk-analyzer_pair) | function | | [`Collector`](/reference/sdk/api/rust/analysis#rust-aic_sdk-Collector) | type | | [`Collector::buffer`](/reference/sdk/api/rust/analysis#rust-aic_sdk-Collector-buffer) | method | | [`Collector::initialize`](/reference/sdk/api/rust/analysis#rust-aic_sdk-Collector-initialize) | method | | [`DynamicLoadingError`](/reference/sdk/api/rust/errors-and-features#rust-aic_sdk-DynamicLoadingError) | type | | [`DynamicLoadingError::AlreadyLoaded`](/reference/sdk/api/rust/errors-and-features#rust-aic_sdk-DynamicLoadingError-AlreadyLoaded) | field or variant | | [`DynamicLoadingError::LoadSymbol`](/reference/sdk/api/rust/errors-and-features#rust-aic_sdk-DynamicLoadingError-LoadSymbol) | field or variant | | [`DynamicLoadingError::LoadSymbol::source`](/reference/sdk/api/rust/errors-and-features#rust-aic_sdk-DynamicLoadingError-LoadSymbol-source) | field or variant | | [`DynamicLoadingError::LoadSymbol::symbol`](/reference/sdk/api/rust/errors-and-features#rust-aic_sdk-DynamicLoadingError-LoadSymbol-symbol) | field or variant | | [`DynamicLoadingError::OpenLibrary`](/reference/sdk/api/rust/errors-and-features#rust-aic_sdk-DynamicLoadingError-OpenLibrary) | field or variant | | [`DynamicLoadingError::OpenLibrary::path`](/reference/sdk/api/rust/errors-and-features#rust-aic_sdk-DynamicLoadingError-OpenLibrary-path) | field or variant | | [`DynamicLoadingError::OpenLibrary::source`](/reference/sdk/api/rust/errors-and-features#rust-aic_sdk-DynamicLoadingError-OpenLibrary-source) | field or variant | | [`EnergyVadContext`](/reference/sdk/api/rust/vad#rust-aic_sdk-EnergyVadContext) | type | | [`EnergyVadContext::is_speech_detected`](/reference/sdk/api/rust/vad#rust-aic_sdk-EnergyVadContext-is_speech_detected) | method | | [`EnergyVadContext::parameter`](/reference/sdk/api/rust/vad#rust-aic_sdk-EnergyVadContext-parameter) | method | | [`EnergyVadContext::prediction_delay`](/reference/sdk/api/rust/vad#rust-aic_sdk-EnergyVadContext-prediction_delay) | method | | [`EnergyVadContext::reset`](/reference/sdk/api/rust/vad#rust-aic_sdk-EnergyVadContext-reset) | method | | [`EnergyVadContext::set_parameter`](/reference/sdk/api/rust/vad#rust-aic_sdk-EnergyVadContext-set_parameter) | method | | [`FileAnalyzer`](/reference/sdk/api/rust/analysis#rust-aic_sdk-FileAnalyzer) | type | | [`FileAnalyzer::analyze`](/reference/sdk/api/rust/analysis#rust-aic_sdk-FileAnalyzer-analyze) | method | | [`FileAnalyzer::new`](/reference/sdk/api/rust/analysis#rust-aic_sdk-FileAnalyzer-new) | method | | [`get_compatible_model_version`](/reference/sdk/api/rust/models-and-config#rust-aic_sdk-get_compatible_model_version) | function | | [`get_sdk_version`](/reference/sdk/api/rust/models-and-config#rust-aic_sdk-get_sdk_version) | function | | [`include_model`](/reference/sdk/api/rust/models-and-config#rust-aic_sdk-include_model) | macro | | [`is_library_loaded`](/reference/sdk/api/rust/errors-and-features#rust-aic_sdk-is_library_loaded) | function | | [`load_library`](/reference/sdk/api/rust/errors-and-features#rust-aic_sdk-load_library) | function | | [`Model`](/reference/sdk/api/rust/models-and-config#rust-aic_sdk-Model) | type | | [`Model::download`](/reference/sdk/api/rust/models-and-config#rust-aic_sdk-Model-download) | method | | [`Model::from_buffer`](/reference/sdk/api/rust/models-and-config#rust-aic_sdk-Model-from_buffer) | method | | [`Model::from_file`](/reference/sdk/api/rust/models-and-config#rust-aic_sdk-Model-from_file) | method | | [`Model::id`](/reference/sdk/api/rust/models-and-config#rust-aic_sdk-Model-id) | method | | [`Model::optimal_block_size`](/reference/sdk/api/rust/models-and-config#rust-aic_sdk-Model-optimal_block_size) | method | | [`Model::optimal_sample_rate`](/reference/sdk/api/rust/models-and-config#rust-aic_sdk-Model-optimal_sample_rate) | method | | [`OtelConfig`](/reference/sdk/api/rust/models-and-config#rust-aic_sdk-OtelConfig) | type | | [`OtelConfig::disabled`](/reference/sdk/api/rust/models-and-config#rust-aic_sdk-OtelConfig-disabled) | method | | [`OtelConfig::enable`](/reference/sdk/api/rust/models-and-config#rust-aic_sdk-OtelConfig-enable) | field or variant | | [`OtelConfig::enabled`](/reference/sdk/api/rust/models-and-config#rust-aic_sdk-OtelConfig-enabled) | method | | [`OtelConfig::export_interval_ms`](/reference/sdk/api/rust/models-and-config#rust-aic_sdk-OtelConfig-export_interval_ms) | field or variant | | [`OtelConfig::session_id`](/reference/sdk/api/rust/models-and-config#rust-aic_sdk-OtelConfig-session_id) | field or variant | | [`OtelConfig::with_session_id`](/reference/sdk/api/rust/models-and-config#rust-aic_sdk-OtelConfig-with_session_id) | method | | [`Processor`](/reference/sdk/api/rust/enhancement#rust-aic_sdk-Processor) | type | | [`Processor::context`](/reference/sdk/api/rust/enhancement#rust-aic_sdk-Processor-context) | method | | [`Processor::energy_vad_context`](/reference/sdk/api/rust/enhancement#rust-aic_sdk-Processor-energy_vad_context) | method | | [`Processor::initialize`](/reference/sdk/api/rust/enhancement#rust-aic_sdk-Processor-initialize) | method | | [`Processor::new`](/reference/sdk/api/rust/enhancement#rust-aic_sdk-Processor-new) | method | | [`Processor::process`](/reference/sdk/api/rust/enhancement#rust-aic_sdk-Processor-process) | method | | [`Processor::terminate_session`](/reference/sdk/api/rust/enhancement#rust-aic_sdk-Processor-terminate_session) | method | | [`Processor::with_config`](/reference/sdk/api/rust/enhancement#rust-aic_sdk-Processor-with_config) | method | | [`Processor::with_otel_config`](/reference/sdk/api/rust/enhancement#rust-aic_sdk-Processor-with_otel_config) | method | | [`ProcessorAsync`](/reference/sdk/api/rust/enhancement#rust-aic_sdk-ProcessorAsync) | type | | [`ProcessorAsync::context`](/reference/sdk/api/rust/enhancement#rust-aic_sdk-ProcessorAsync-context) | method | | [`ProcessorAsync::energy_vad_context`](/reference/sdk/api/rust/enhancement#rust-aic_sdk-ProcessorAsync-energy_vad_context) | method | | [`ProcessorAsync::initialize`](/reference/sdk/api/rust/enhancement#rust-aic_sdk-ProcessorAsync-initialize) | method | | [`ProcessorAsync::new`](/reference/sdk/api/rust/enhancement#rust-aic_sdk-ProcessorAsync-new) | method | | [`ProcessorAsync::process`](/reference/sdk/api/rust/enhancement#rust-aic_sdk-ProcessorAsync-process) | method | | [`ProcessorAsync::terminate_session`](/reference/sdk/api/rust/enhancement#rust-aic_sdk-ProcessorAsync-terminate_session) | method | | [`ProcessorAsync::with_config`](/reference/sdk/api/rust/enhancement#rust-aic_sdk-ProcessorAsync-with_config) | method | | [`ProcessorAsync::with_otel_config`](/reference/sdk/api/rust/enhancement#rust-aic_sdk-ProcessorAsync-with_otel_config) | method | | [`ProcessorConfig`](/reference/sdk/api/rust/models-and-config#rust-aic_sdk-ProcessorConfig) | type | | [`ProcessorConfig::block_size`](/reference/sdk/api/rust/models-and-config#rust-aic_sdk-ProcessorConfig-block_size) | field or variant | | [`ProcessorConfig::optimal`](/reference/sdk/api/rust/models-and-config#rust-aic_sdk-ProcessorConfig-optimal) | method | | [`ProcessorConfig::sample_rate`](/reference/sdk/api/rust/models-and-config#rust-aic_sdk-ProcessorConfig-sample_rate) | field or variant | | [`ProcessorConfig::variable_block_size`](/reference/sdk/api/rust/models-and-config#rust-aic_sdk-ProcessorConfig-variable_block_size) | field or variant | | [`ProcessorConfig::with_variable_block_size`](/reference/sdk/api/rust/models-and-config#rust-aic_sdk-ProcessorConfig-with_variable_block_size) | method | | [`ProcessorContext`](/reference/sdk/api/rust/enhancement#rust-aic_sdk-ProcessorContext) | type | | [`ProcessorContext::audio_delay`](/reference/sdk/api/rust/enhancement#rust-aic_sdk-ProcessorContext-audio_delay) | method | | [`ProcessorContext::parameter`](/reference/sdk/api/rust/enhancement#rust-aic_sdk-ProcessorContext-parameter) | method | | [`ProcessorContext::reset`](/reference/sdk/api/rust/enhancement#rust-aic_sdk-ProcessorContext-reset) | method | | [`ProcessorContext::set_parameter`](/reference/sdk/api/rust/enhancement#rust-aic_sdk-ProcessorContext-set_parameter) | method | | [`ProcessorContext::update_bearer_token`](/reference/sdk/api/rust/enhancement#rust-aic_sdk-ProcessorContext-update_bearer_token) | method | | [`ProcessorParameter`](/reference/sdk/api/rust/enhancement#rust-aic_sdk-ProcessorParameter) | type | | [`ProcessorParameter::Bypass`](/reference/sdk/api/rust/enhancement#rust-aic_sdk-ProcessorParameter-Bypass) | field or variant | | [`ProcessorParameter::EnhancementLevel`](/reference/sdk/api/rust/enhancement#rust-aic_sdk-ProcessorParameter-EnhancementLevel) | field or variant | | [`set_sdk_id`](/reference/sdk/api/rust/errors-and-features#rust-aic_sdk-set_sdk_id) | function | | [`Vad`](/reference/sdk/api/rust/vad#rust-aic_sdk-Vad) | type | | [`Vad::context`](/reference/sdk/api/rust/vad#rust-aic_sdk-Vad-context) | method | | [`Vad::initialize`](/reference/sdk/api/rust/vad#rust-aic_sdk-Vad-initialize) | method | | [`Vad::new`](/reference/sdk/api/rust/vad#rust-aic_sdk-Vad-new) | method | | [`Vad::process`](/reference/sdk/api/rust/vad#rust-aic_sdk-Vad-process) | method | | [`Vad::terminate_session`](/reference/sdk/api/rust/vad#rust-aic_sdk-Vad-terminate_session) | method | | [`Vad::with_config`](/reference/sdk/api/rust/vad#rust-aic_sdk-Vad-with_config) | method | | [`Vad::with_otel_config`](/reference/sdk/api/rust/vad#rust-aic_sdk-Vad-with_otel_config) | method | | [`VadAsync`](/reference/sdk/api/rust/vad#rust-aic_sdk-VadAsync) | type | | [`VadAsync::context`](/reference/sdk/api/rust/vad#rust-aic_sdk-VadAsync-context) | method | | [`VadAsync::initialize`](/reference/sdk/api/rust/vad#rust-aic_sdk-VadAsync-initialize) | method | | [`VadAsync::new`](/reference/sdk/api/rust/vad#rust-aic_sdk-VadAsync-new) | method | | [`VadAsync::process`](/reference/sdk/api/rust/vad#rust-aic_sdk-VadAsync-process) | method | | [`VadAsync::terminate_session`](/reference/sdk/api/rust/vad#rust-aic_sdk-VadAsync-terminate_session) | method | | [`VadAsync::with_config`](/reference/sdk/api/rust/vad#rust-aic_sdk-VadAsync-with_config) | method | | [`VadAsync::with_otel_config`](/reference/sdk/api/rust/vad#rust-aic_sdk-VadAsync-with_otel_config) | method | | [`VadContext`](/reference/sdk/api/rust/vad#rust-aic_sdk-VadContext) | type | | [`VadContext::is_speech_detected`](/reference/sdk/api/rust/vad#rust-aic_sdk-VadContext-is_speech_detected) | method | | [`VadContext::parameter`](/reference/sdk/api/rust/vad#rust-aic_sdk-VadContext-parameter) | method | | [`VadContext::prediction_delay`](/reference/sdk/api/rust/vad#rust-aic_sdk-VadContext-prediction_delay) | method | | [`VadContext::raw_vad_probability`](/reference/sdk/api/rust/vad#rust-aic_sdk-VadContext-raw_vad_probability) | method | | [`VadContext::reset`](/reference/sdk/api/rust/vad#rust-aic_sdk-VadContext-reset) | method | | [`VadContext::set_parameter`](/reference/sdk/api/rust/vad#rust-aic_sdk-VadContext-set_parameter) | method | | [`VadContext::update_bearer_token`](/reference/sdk/api/rust/vad#rust-aic_sdk-VadContext-update_bearer_token) | method | | [`VadParameter`](/reference/sdk/api/rust/vad#rust-aic_sdk-VadParameter) | type | | [`VadParameter::MinimumSpeechDuration`](/reference/sdk/api/rust/vad#rust-aic_sdk-VadParameter-MinimumSpeechDuration) | field or variant | | [`VadParameter::Sensitivity`](/reference/sdk/api/rust/vad#rust-aic_sdk-VadParameter-Sensitivity) | field or variant | | [`VadParameter::SpeechHoldDuration`](/reference/sdk/api/rust/vad#rust-aic_sdk-VadParameter-SpeechHoldDuration) | field or variant | ## Traits and conversions [Ownership and trait contracts](/reference/sdk/api/rust/errors-and-features#rust-aic_sdk-traits) include destruction, thread transfer, copying and equality. Explicit conversions are [processor parameters](/reference/sdk/api/rust/errors-and-features#rust-aic_sdk-ProcessorParameter-From), [VAD parameters](/reference/sdk/api/rust/errors-and-features#rust-aic_sdk-VadParameter-From), [analysis results](/reference/sdk/api/rust/errors-and-features#rust-aic_sdk-AnalysisResult-From) and [native error codes](/reference/sdk/api/rust/errors-and-features#rust-aic_sdk-AicError-From). ## Documentation modules The public `docs` module provides these documentation pages: | Module | Released documentation | | - | - | | `docs` | [Documentation root](https://docs.rs/aic-sdk/0.25.2/aic_sdk/docs/index.html) | | `docs::guide` | [Integration guide](https://docs.rs/aic-sdk/0.25.2/aic_sdk/docs/guide/index.html) | | `docs::linking` | [Linking guide](https://docs.rs/aic-sdk/0.25.2/aic_sdk/docs/linking/index.html) | | `docs::examples` | [Examples index](https://docs.rs/aic-sdk/0.25.2/aic_sdk/docs/examples/index.html) | | `docs::examples::enhancement` | [Released example](https://docs.rs/aic-sdk/0.25.2/aic_sdk/docs/examples/enhancement/index.html) | | `docs::examples::vad` | [Released example](https://docs.rs/aic-sdk/0.25.2/aic_sdk/docs/examples/vad/index.html) | | `docs::examples::analyze_file` | [Released example](https://docs.rs/aic-sdk/0.25.2/aic_sdk/docs/examples/analyze_file/index.html) | | `docs::examples::benchmark` | [Released example](https://docs.rs/aic-sdk/0.25.2/aic_sdk/docs/examples/benchmark/index.html) | | `docs::examples::parallel_async` (requires `async`) | [Released example](https://docs.rs/aic-sdk/0.25.2/aic_sdk/docs/examples/parallel_async/index.html) | | `docs::examples::build_time_download` | [Released example](https://docs.rs/aic-sdk/0.25.2/aic_sdk/docs/examples/build_time_download/index.html) | The [reserved integration hook](/reference/sdk/api/rust/errors-and-features#rust-aic_sdk-set_sdk_id) is for ai-coustics wrappers; applications should not call it. # Rust models and configuration Source: https://docs.ai-coustics.com/reference/sdk/api/rust/models-and-config Model loading, borrowed data, configuration fields and SDK metadata in aic-sdk. **Crate:** `aic-sdk = "=0.25.2"`. **Core SDK:** `0.25.2`. For installation and a complete audio program, use the [Rust guide](/reference/sdk/language-bindings/rust). Signatures below are declarations. Use the root exports, for example `use aic_sdk::{AicError, Model, OtelConfig, ProcessorConfig};`. `Path` and `PathBuf` refer to `std::path` types. ## `Model` ```rust theme={null} pub struct Model<'a> { /* private fields */ } ``` A native model handle. Choose a model matching the operation: enhancement for `Processor`, dedicated voice activity detection (VAD) for `Vad` and Tyto analysis for the analyzers. One model can supply several independent processing instances. File loading creates a `Model<'static>`. Buffer loading creates a `Model<'a>` borrowing its input bytes. The backing bytes must remain valid and immutable for all dependent processors, VADs and analyzers, even if you drop the original model handle. Native reference counting keeps model storage alive; it does not extend the Rust lifetime of borrowed bytes. A file-backed model's file must not be modified or deleted while the model or dependent objects exist. `Model` implements `Drop`, `Send` and `Sync`. Dropping the handle releases its native reference. It does not implement `Clone`; share a reference or use `Arc>` when appropriate. ### `Model::from_file` ```rust theme={null} pub fn from_file>(path: P) -> Result, AicError> ``` Loads a model from `path`. This is blocking setup work. File and model failures return `FileSystemError`, `ModelInvalid` or `ModelVersionUnsupported`, as applicable. ### `Model::from_buffer` ```rust theme={null} pub fn from_buffer(buffer: &'a [u8]) -> Result ``` Borrows model bytes without copying the backing buffer. The address must be aligned to 64 bytes; an ordinary `Vec` does not guarantee that alignment. Misalignment returns `ModelDataUnaligned`; invalid contents return model errors. The borrow is carried by the returned model and dependent native objects. ### `include_model!` ```rust theme={null} include_model!(path_expression) ``` Embeds a model file using `include_bytes!` inside a 64-byte-aligned static allocation and evaluates to a reference to its bytes. The path follows `include_bytes!` resolution relative to the Rust source file. The file must exist at compile time; this macro does not download it. Its static storage can be used by async processing types. This declaration is a compile-time embedding pattern; replace the path with an existing compatible model file: ```rust theme={null} use aic_sdk::{include_model, AicError, Model}; static MODEL_BYTES: &[u8] = include_model!("path/to/model.aicmodel"); fn load_embedded() -> Result, AicError> { Model::from_buffer(MODEL_BYTES) } ``` ### `Model::id` ```rust theme={null} pub fn id(&self) -> &str ``` Returns the model ID borrowed from the native handle. Returns `"unknown"` if the native string is null or cannot be decoded as UTF-8. The borrowed string cannot outlive this model handle. ### `Model::optimal_sample_rate` ```rust theme={null} pub fn optimal_sample_rate(&self) -> u32 ``` Returns the model's native sample rate in Hz. This query does not configure or validate an input stream. ### `Model::optimal_block_size` ```rust theme={null} pub fn optimal_block_size(&self, sample_rate: u32) -> usize ``` Returns the preferred sample count per processing call at `sample_rate`. Use the stream's actual rate. Initialization validates support for the rate and block combination. Metadata queries return values directly and assert native success; they do not return `Result` for internal native failures. ### `Model::download` **Requires feature:** `download-model`. Absent when that feature is disabled. ```rust theme={null} pub fn download>( model_id: &str, download_dir: P, ) -> Result ``` Resolves the model ID against a manifest using the core SDK's compatible model file version, downloads compatible data and returns its path. The result remains relative when `download_dir` is relative. Creates missing destination directories. The downloader can reuse a fresh manifest in memory or in the download directory according to server cache lifetime. It revalidates stale entries, retries manifest resolution when needed and reuses a model file only when its SHA-256 matches. Replacement data is checked before installation. Failures return `AicError::ModelDownload(String)` with the underlying detail. This method blocks and has no async Rust counterpart in this release; provision models before processing. ## `ProcessorConfig` ```rust theme={null} pub struct ProcessorConfig { pub sample_rate: u32, pub block_size: usize, pub variable_block_size: bool, } ``` Construct with a struct literal or `optimal`. Configuration is copied into the processor, detector or collector at initialization; changing the value later does not reconfigure it. There is no `Default` implementation. | Field | Contract | | - | - | | `sample_rate: u32` | Actual input rate in Hz; native initialization accepts 8,000–192,000 Hz subject to the model/configuration | | `block_size: usize` | Positive mono sample count per fixed call, or maximum call length with variable blocks | | `variable_block_size: bool` | `false`: exactly `block_size` samples. `true`: calls up to `block_size`, with additional buffering delay | ### `ProcessorConfig::optimal` ```rust theme={null} pub fn optimal(model: &Model) -> Self ``` Uses the model native rate, its preferred block size at that rate and `variable_block_size: false`. Override fields before initialization when the input has a different rate. ### `ProcessorConfig::with_variable_block_size` ```rust theme={null} pub fn with_variable_block_size(self, variable_block_size: bool) -> Self ``` Consumes the configuration, sets the flag and returns the updated configuration. Does not initialize an object. ## `OtelConfig` ```rust theme={null} pub struct OtelConfig { pub enable: bool, pub session_id: Option, pub export_interval_ms: u32, } ``` Optional per-instance OpenTelemetry settings for processor and VAD constructors. Without an explicit configuration, native environment defaults apply. These settings control observability separately from mandatory authorization and usage reporting. See [telemetry](/reference/concepts/sdk-telemetry). | Field | Contract | | - | - | | `enable: bool` | Overrides the runtime environment's enable setting | | `session_id: Option` | `None` requests an automatically generated ID; an embedded NUL causes `AicError::Internal` when constructing a processor or detector | | `export_interval_ms: u32` | Positive values override the interval in milliseconds; zero uses the SDK default of 60,000 ms | There is no `Default` implementation. Configuration is copied at construction; subsequent changes do not affect existing sessions. ### `OtelConfig::disabled` ```rust theme={null} pub fn disabled() -> Self ``` Returns `{ enable: false, session_id: None, export_interval_ms: 0 }`. ### `OtelConfig::enabled` ```rust theme={null} pub fn enabled() -> Self ``` Returns `{ enable: true, session_id: None, export_interval_ms: 0 }`. ### `OtelConfig::with_session_id` ```rust theme={null} pub fn with_session_id(session_id: impl Into) -> Self ``` Returns enabled telemetry with the converted session ID and interval zero. ## `get_sdk_version` ```rust theme={null} pub fn get_sdk_version() -> &'static str ``` Returns the loaded native SDK version, which is separate from the Cargo package version. Returns `"unknown"` for an undecodable native string. Under `runtime-linking`, this is an SDK call that can trigger automatic library loading. ## `get_compatible_model_version` ```rust theme={null} pub fn get_compatible_model_version() -> u32 ``` Returns the compatible model file format version. This is not the model ID or model release version. ## Configuration example This example needs no model or SDK key: ```rust theme={null} use aic_sdk::{OtelConfig, ProcessorConfig}; fn main() { let config = ProcessorConfig { sample_rate: 16_000, block_size: 160, variable_block_size: false, }.with_variable_block_size(true); assert!(config.variable_block_size); let telemetry = OtelConfig::disabled(); assert!(!telemetry.enable); } ``` See the [symbol index](/reference/sdk/api/rust/index) and [features, errors and traits](/reference/sdk/api/rust/errors-and-features). # Rust voice activity detection Source: https://docs.ai-coustics.com/reference/sdk/api/rust/vad Vad, VadAsync, EnergyVadContext, prediction control and parameters in aic-sdk. **Crate:** `aic-sdk = "=0.25.2"`. **Core SDK:** `0.25.2`. Signatures are declarations; import the named types from `aic_sdk`. See the [Rust guide](/reference/sdk/language-bindings/rust) for a complete runnable program. ## `Vad` ```rust theme={null} pub struct Vad<'a> { /* private fields */ } ``` Stateful dedicated VAD. Feed original mono audio, independently of enhancement; processing leaves input unchanged. Use one instance per stream and read predictions from its context. Implements `Drop`, `Send` and `Sync`; borrowed model bytes must outlive the detector. Mutable access serializes processing and initialization. ### `Vad::new` ```rust theme={null} pub fn new(model: &Model<'a>, license_key: &str) -> Result ``` Creates an uninitialized detector. The model must be a dedicated VAD model; an enhancement model returns `ModelTypeUnsupported`. Credentials are an SDK key or JWT. ### `Vad::with_otel_config` ```rust theme={null} pub fn with_otel_config( model: &Model<'a>, license_key: &str, otel_config: &OtelConfig, ) -> Result ``` Creates an uninitialized detector with explicit copied telemetry settings. Invalid credentials return license errors; a NUL-containing session ID returns `Internal`. ### `Vad::with_config` ```rust theme={null} pub fn with_config(self, config: &ProcessorConfig) -> Result ``` Consumes the detector, initializes it and returns it on success. A failure drops the consumed detector. ### `Vad::initialize` ```rust theme={null} pub fn initialize(&mut self, config: &ProcessorConfig) -> Result<(), AicError> ``` Copies and validates the audio configuration. Unsupported settings return `AudioConfigUnsupported`. This allocates; run it outside the audio callback. Reinitialize successfully after any failed reconfiguration. ### `Vad::process` ```rust theme={null} pub fn process(&mut self, audio: &[f32]) -> Result<(), AicError> ``` Reads normalized mono samples and updates detector state; returns no audio. Use exactly the configured block length, or a slice up to that length when variable blocks are enabled. Errors include `NotInitialized`, `AudioConfigMismatch` and `ProcessingNotAllowed`. Read predictions after successful processing. ### `Vad::context` ```rust theme={null} pub fn context(&self) -> VadContext ``` Creates a shared prediction/control handle. Multiple handles refer to the same detector. Native failure is asserted and can panic. ### `Vad::terminate_session` ```rust theme={null} pub fn terminate_session(&mut self) ``` Requests permanent session termination for this detector. Stop processing first and use a new object for another session. This may block and is unsuitable for the audio callback. Native work becomes disallowed when the lifecycle task handles the signal; with other sessions alive that can occur after return. ## `VadContext` ```rust theme={null} pub struct VadContext { /* private fields */ } ``` Created by `Vad::context` or awaited `VadAsync::context`. Implements `Drop`, `Send` and `Sync`; no public constructor. It permits cross-thread prediction reads and parameter control while the detector processes elsewhere. Predictions stop updating when audio is no longer processed. ### `VadContext::is_speech_detected` ```rust theme={null} pub fn is_speech_detected(&self) -> bool ``` Returns the latest post-processed decision. It lags the input by `prediction_delay()` samples; do not treat a stale decision as a new inference. ### `VadContext::raw_vad_probability` ```rust theme={null} pub fn raw_vad_probability(&self) -> f32 ``` Returns the latest model probability without SDK hold/threshold post-processing. It has the same input alignment delay. ### `VadContext::set_parameter` ```rust theme={null} pub fn set_parameter(&self, parameter: VadParameter, value: f32) -> Result<(), AicError> ``` Stores a parameter for the detector. Out-of-range or NaN values return `ParameterOutOfRange`. Effective transitions are quantized to model frames. ### `VadContext::parameter` ```rust theme={null} pub fn parameter(&self, parameter: VadParameter) -> f32 ``` Returns the stored parameter value. Duration readback is the requested value; it is not a promise of exact transition timing. Defaults are model-specific. ### `VadContext::prediction_delay` ```rust theme={null} pub fn prediction_delay(&self) -> usize ``` Returns prediction lag in samples at the configured input rate, including reblocking and model buffering. This delay is not applied to the input audio and is independent of enhancement audio delay. Value-returning native queries assert success and can panic on internal failures. ### `VadContext::reset` ```rust theme={null} pub fn reset(&self) ``` Immediately clears the published decision to false and raw probability to 0.0, and requests processing-state reset on the next block. Audio configuration remains initialized. A terminated session is not reopened. ### `VadContext::update_bearer_token` ```rust theme={null} pub fn update_bearer_token(&self, token: &str) -> Result<(), AicError> ``` Updates a JWT only when the original and new credentials are JWTs; otherwise returns `TokenUpdateUnsupported`. Embedded NUL returns `LicenseFormatInvalid`. Local success does not prove backend acceptance; keep handling processing errors. ## `EnergyVadContext` ```rust theme={null} pub struct EnergyVadContext { /* private fields */ } ``` Created by `Processor::energy_vad_context` or awaited `ProcessorAsync::energy_vad_context`. Implements `Drop`; no public constructor. It detects speech from the processor's enhanced signal before output mixing, without running a separate model, and advances with `Processor::process` rather than its own call. All handles from one processor reference the same energy VAD, and every method maps to a native call usable from any thread, so a context can be moved to another thread while audio is processed elsewhere. Creating one keeps inference active even when the processor is bypassed or fully dry. Dropping the backing processor stops new predictions; dropping the context destroys neither the processor nor its detection. ### `EnergyVadContext::is_speech_detected` ```rust theme={null} pub fn is_speech_detected(&self) -> bool ``` Returns the energy VAD's prediction. It lags its input by `prediction_delay` samples; align speech decisions to the input timeline using that value. The prediction stops updating if the backing processor stops being processed. ### `EnergyVadContext::set_parameter` ```rust theme={null} pub fn set_parameter(&self, parameter: VadParameter, value: f32) -> Result<(), AicError> ``` Stores a parameter for the energy VAD. `VadParameter::Sensitivity` takes the energy range, 1.0 through 15.0. Out-of-range values return `ParameterOutOfRange`. All parameters can be changed during processing, from any thread. ### `EnergyVadContext::parameter` ```rust theme={null} pub fn parameter(&self, parameter: VadParameter) -> f32 ``` Returns the stored parameter value. ### `EnergyVadContext::prediction_delay` ```rust theme={null} pub fn prediction_delay(&self) -> usize ``` Returns prediction lag in samples, covering input reblocking, STFT and enhancement model processing. It equals `ProcessorContext::audio_delay` for the backing processor; energy detection adds no audio delay. Speech hold and minimum speech duration affect decision timing and are not included. ### `EnergyVadContext::reset` ```rust theme={null} pub fn reset(&self) ``` Clears the energy VAD state and the published prediction. Parameters are retained and the backing processor is not reset; `ProcessorContext::reset` also resets this VAD. ## `VadParameter` ```rust theme={null} pub enum VadParameter { SpeechHoldDuration, Sensitivity, MinimumSpeechDuration } ``` Named parameter selectors, used by both `VadContext` and `EnergyVadContext`. Implements `Debug`, `Clone`, `Copy`, `PartialEq`, `Eq` and `Hash`, plus native parameter conversion. Read defaults from the active context. ### `VadParameter::SpeechHoldDuration` ```rust theme={null} VadParameter::SpeechHoldDuration ``` Duration in seconds controlling the speech-to-silence transition. Range: 0.0 through 300 times the model frame duration. The effective duration is rounded to model frames. When the current probability is at or below threshold, speech remains detected while at least half the approximately `2 * duration` history was above threshold. ### `VadParameter::Sensitivity` ```rust theme={null} VadParameter::Sensitivity ``` Its meaning depends on the detector. On a `VadContext`, a probability threshold, 0.0 through 1.0: a probability strictly greater than this value contributes a positive frame, so a lower threshold is more permissive. On an [`EnergyVadContext`](/reference/sdk/api/rust/vad#rust-aic_sdk-EnergyVadContext), the energy threshold of the enhanced signal, computed as `10 ^ (-sensitivity)` over 1.0 through 15.0, so higher values detect quieter speech. ### `VadParameter::MinimumSpeechDuration` ```rust theme={null} VadParameter::MinimumSpeechDuration ``` Duration in seconds required for consecutive above-threshold frames to turn speech detection on. Range: 0.0 through 1.0. Effective timing is rounded to model frames; the stored value can differ from the effective duration. ## `VadAsync` ```rust theme={null} pub struct VadAsync { /* private fields */ } ``` **Requires feature:** `async`. Uses the same shared worker pool and per-instance mutex as [async enhancement](/reference/sdk/api/rust/enhancement#rust-aic_sdk-ProcessorAsync). Constructors are synchronous, model data must be static, and async operations should be awaited in stream order. The type is `Send` and `Sync`; share through `Arc` when needed. ### `VadAsync::new` ```rust theme={null} pub fn new(model: &Model<'static>, license_key: &str) -> Result ``` Creates an uninitialized dedicated detector. Model and credential errors match `Vad::new`. ### `VadAsync::with_otel_config` ```rust theme={null} pub fn with_otel_config( model: &Model<'static>, license_key: &str, otel_config: &OtelConfig, ) -> Result ``` Creates an uninitialized detector with copied telemetry settings. ### `VadAsync::with_config` ```rust theme={null} pub async fn with_config(self, config: &ProcessorConfig) -> Result ``` Consumes the detector and awaits initialization. Failure drops the consumed object. ### `VadAsync::initialize` ```rust theme={null} pub async fn initialize(&self, config: &ProcessorConfig) -> Result<(), AicError> ``` Copies settings and initializes on the shared worker pool. Errors match `Vad::initialize`. ### `VadAsync::process` ```rust theme={null} pub async fn process(&self, audio: Vec) -> Result, AicError> ``` Consumes the vector, reads it on the processing pool and returns it unchanged on success. Updates the prediction. On failure the vector is dropped. This Rust return value differs from Python VAD's `None` result; input length and errors match `Vad::process`. ### `VadAsync::terminate_session` ```rust theme={null} pub async fn terminate_session(&self) ``` Waits for exclusive access and requests termination. Stop submitting audio first; use a new object for another session. Await the method, but do not treat completion as proof that native signal handling or remote usage acknowledgment has finished when other sessions remain alive. ### `VadAsync::context` ```rust theme={null} pub async fn context(&self) -> VadContext ``` Waits for exclusive access and returns a context. Internal native context creation failure can panic. See [configuration](/reference/sdk/api/rust/models-and-config), [errors](/reference/sdk/api/rust/errors-and-features) and the [symbol index](/reference/sdk/api/rust/index). ## Read a prediction The caller supplies an initialized dedicated detector and a normalized mono block. Prediction is read only after successful processing: ```rust theme={null} use aic_sdk::{AicError, Vad}; fn detect_block(vad: &mut Vad<'_>, audio: &[f32]) -> Result { let context = vad.context(); vad.process(audio)?; Ok(context.is_speech_detected()) } ``` # WebAssembly analysis API Source: https://docs.ai-coustics.com/reference/sdk/api/wasm/analysis Collect audio, analyze a window and release analysis results. **Version:** `@ai-coustics/aic-sdk-wasm` 0.26.0, Core SDK 0.26.0. [API index](/reference/sdk/api/wasm/index) · [WebAssembly quickstart](/reference/sdk/language-bindings/wasm). ## `Analyzer` ```typescript theme={null} export class Analyzer ``` Collects mono audio and runs an analysis model such as Tyto over the latest retained window. The window uses the maximum length supported by the model; this binding has no window-length argument. New audio replaces older audio. Short histories include zero-filled input, so track how much real audio you have collected. ### `Analyzer.free` ```typescript theme={null} free(): void; ``` Releases the owned WebAssembly allocation. Call once in `finally` and do not use the handle afterward. Garbage collection does not guarantee timely cleanup; `free()` does not acknowledge session termination. ### `Analyzer.Symbol.dispose` ```typescript theme={null} [Symbol.dispose](): void; ``` Aliases `free()` when the runtime supports `Symbol.dispose`; do not call both on the same handle. Otherwise, call `free()` in `finally`. ### `Analyzer.analyze` ```typescript theme={null} analyze(): AnalysisResult; ``` Synchronously analyzes the current retained window and returns a newly allocated `AnalysisResult`. It blocks the calling JavaScript thread. Short or empty histories are zero-padded; a successful result does not establish that enough real audio was collected. This method reads a snapshot and does not consume or clear the buffered history. Throws for disallowed processing or native analysis failure. Free each returned result after copying its values. ### `Analyzer.buffer` ```typescript theme={null} buffer(audio: Float32Array): void; ``` Synchronously collects a block of normalized mono `Float32Array` samples without modifying the caller's array. The binding copies samples into WebAssembly memory. This call does not run analysis inference. Requires successful initialization and the configured block length; invalid input throws. The collector retains only the newest model window. ### `Analyzer.initialize` ```typescript theme={null} initialize(sample_rate: number, block_size: number, variable_block_size: boolean): void; ``` All three arguments are required. `sample_rate` is a whole-number rate in Hz from 8,000 through 192,000; `block_size` is a positive whole-number count of mono samples, not bytes. Prefer the model's optimal sample rate and block size. Unsupported block configurations throw. Pass `false` for fixed blocks of exactly `block_size` samples or `true` to permit shorter blocks up to that maximum. Variable blocks can add buffering delay. Initialization allocates memory and resets signal state. A failed initialization leaves processing uninitialized; correct the configuration before submitting audio again. ### `Analyzer.constructor` ```typescript theme={null} constructor(model: Model, license_key: string); ``` Creates an analysis collector and engine using a live analysis `model` and the credential in `license_key`. Use a backend-issued short-lived JWT in browsers. An enhancement or VAD model cannot be analyzed through this interface. Construction can throw for model type, runtime creation or credential errors. No OpenTelemetry configuration or analysis-window argument is exposed. ### `Analyzer.reset` ```typescript theme={null} reset(): void; ``` Requests clearing of collector signal history on the next `buffer` call while preserving the initialized audio format. Until that call applies the reset, `analyze()` uses a zero-filled snapshot instead of the previously buffered audio. ### `Analyzer.terminateSession` ```typescript theme={null} terminateSession(): void; ``` Requests termination of the telemetry session. Stop submitting audio before calling this method. Processing becomes disallowed once the telemetry task handles the signal; the `void` return is not an acknowledgment of server delivery or immediate completion. This method neither flushes delayed audio nor frees the object. Call `free()` separately when finished. ### `Analyzer.updateBearerToken` ```typescript theme={null} updateBearerToken(token: string): void; ``` Replaces the bearer token for subsequent session requests without creating a new processing instance. Both the original credential and the replacement must be JWT-form credentials. A malformed or unsupported replacement throws and leaves the previous credential in place. Local format acceptance does not prove that the backend accepts the new token. Obtain fresh short-lived tokens through your backend; keep the SDK key on the server. This call returns `void`, not a network-completion promise. ## `AnalysisResult` ```typescript theme={null} export class AnalysisResult ``` An owned WebAssembly result returned by `Analyzer.analyze`, with seven read-only numeric properties. Its constructor is private. Read the values into ordinary JavaScript data before freeing the result. It is not a plain JavaScript record and spreading it does not copy these prototype getters. ### `AnalysisResult.free` ```typescript theme={null} free(): void; ``` Releases the owned WebAssembly allocation. Call once in `finally` and do not use the handle afterward. Garbage collection does not guarantee timely cleanup; `free()` does not acknowledge session termination. ### `AnalysisResult.Symbol.dispose` ```typescript theme={null} [Symbol.dispose](): void; ``` Aliases `free()` when the runtime supports `Symbol.dispose`; do not call both on the same handle. Otherwise, call `free()` in `finally`. ### `AnalysisResult.codecDegradation` ```typescript theme={null} readonly codecDegradation: number; ``` Codec-degradation estimate from the analysis model. ### `AnalysisResult.interferingSpeech` ```typescript theme={null} readonly interferingSpeech: number; ``` Interfering-speech estimate, taking the larger of the model's background-speaker and background-media outputs. ### `AnalysisResult.noise` ```typescript theme={null} readonly noise: number; ``` Background-noise estimate from the analysis model. ### `AnalysisResult.packetLoss` ```typescript theme={null} readonly packetLoss: number; ``` Packet-loss estimate from the analysis model. ### `AnalysisResult.riskScore` ```typescript theme={null} readonly riskScore: number; ``` Composite risk score derived from the model outputs and the loaded model's postprocessing coefficients. It is not a measured word error rate. ### `AnalysisResult.speakerLoudness` ```typescript theme={null} readonly speakerLoudness: number; ``` Main-speaker loudness estimate from the analysis model. Do not interpret it as a calibrated sound-pressure measurement. ### `AnalysisResult.speakerReverb` ```typescript theme={null} readonly speakerReverb: number; ``` Main-speaker reverberation estimate from the analysis model. ## Copy and release a result This helper assumes initialization has completed, `model` is a live analysis model and `token` is a backend-issued JWT. Supply mono audio at the model's optimal sample rate with a length divisible by its optimal block size. It buffers the supplied audio and returns ordinary JavaScript numbers, freeing the WebAssembly result afterward. Supply enough real audio for the model's window; shorter input is padded with zeros. Buffering a long recording synchronously blocks the event loop, so run that work in an appropriate worker. ```javascript theme={null} import { Analyzer } from "@ai-coustics/aic-sdk-wasm"; /** * @param {import("@ai-coustics/aic-sdk-wasm").Model} model * @param {string} token * @param {Float32Array} audio */ export function analyzeWindow(model, token, audio) { const sampleRate = model.getOptimalSampleRate(); const blockSize = model.getOptimalBlockSize(sampleRate); if (audio.length % blockSize !== 0) throw new Error("Expected complete blocks"); const analyzer = new Analyzer(model, token); try { analyzer.initialize(sampleRate, blockSize, false); for (let offset = 0; offset < audio.length; offset += blockSize) { analyzer.buffer(audio.subarray(offset, offset + blockSize)); } const result = analyzer.analyze(); try { return { riskScore: result.riskScore, speakerReverb: result.speakerReverb, speakerLoudness: result.speakerLoudness, interferingSpeech: result.interferingSpeech, noise: result.noise, codecDegradation: result.codecDegradation, packetLoss: result.packetLoss, }; } finally { result.free(); } } finally { try { analyzer.terminateSession(); } finally { analyzer.free(); } } } ``` # WebAssembly enhancement API Source: https://docs.ai-coustics.com/reference/sdk/api/wasm/enhancement Process audio blocks and control enhancement state. **Version:** `@ai-coustics/aic-sdk-wasm` 0.26.0, Core SDK 0.26.0. [API index](/reference/sdk/api/wasm/index) · [WebAssembly quickstart](/reference/sdk/language-bindings/wasm). ## `Processor` ```typescript theme={null} export class Processor ``` A synchronous mono enhancement stream. Each instance has its own signal state and retains the model weights. Use one instance per stream and process blocks in order. ### `Processor.free` ```typescript theme={null} free(): void; ``` Releases the owned WebAssembly allocation. Call once in `finally` and do not use the handle afterward. Garbage collection does not guarantee timely cleanup; `free()` does not acknowledge session termination. ### `Processor.Symbol.dispose` ```typescript theme={null} [Symbol.dispose](): void; ``` Aliases `free()` when the runtime supports `Symbol.dispose`; do not call both on the same handle. Otherwise, call `free()` in `finally`. ### `Processor.getContext` ```typescript theme={null} getContext(): ProcessorContext; ``` Returns a newly owned handle to this processor's shared control state. Repeated calls produce separate handles to the same state. Free each returned context when finished. > [!WARNING] > > Renamed in 0.25.0. This method was `getProcessorContext()` through 0.23.0. ### `Processor.getEnergyVadContext` ```typescript theme={null} getEnergyVadContext(): EnergyVadContext; ``` Returns a newly owned [`EnergyVadContext`](/reference/sdk/api/wasm/vad#wasm-energyvadcontext) that detects speech from this processor's enhanced signal before output mixing, without running a separate model. Detection advances with `process`; there is no separate process call. Every handle from one processor refers to the same energy VAD, and each must be freed separately. Creating a handle keeps enhancement inference active even when the processor is bypassed or its enhancement level is zero, and it stays active for the processor's lifetime after all handles are freed. Freeing the processor stops new predictions but leaves the handle usable. ### `Processor.initialize` ```typescript theme={null} initialize(sample_rate: number, block_size: number, variable_block_size: boolean): void; ``` All three arguments are required. `sample_rate` is a whole-number rate in Hz from 8,000 through 192,000; `block_size` is a positive whole-number count of mono samples, not bytes. Prefer the model's optimal sample rate and block size. Unsupported block configurations throw. Pass `false` for fixed blocks of exactly `block_size` samples or `true` to permit shorter blocks up to that maximum. Variable blocks can add buffering delay. Initialization allocates memory and resets signal state. A failed initialization leaves processing uninitialized; correct the configuration before submitting audio again. ### `Processor.constructor` ```typescript theme={null} constructor(model: Model, license_key: string); ``` Creates an enhancement stream using a live `model` and the credential in `license_key`. For browser applications, pass a short-lived JWT supplied by your backend. Enhancement and bypass model types are accepted; dedicated VAD and analysis models are rejected. The constructor can throw for model creation, model type or credential errors. It does not initialize the audio format. No OpenTelemetry configuration argument is exposed. ### `Processor.process` ```typescript theme={null} process(audio: Float32Array): void; ``` Processes one block of normalized mono floating-point samples and writes the enhanced samples back into the same `Float32Array`. Returns `void`. The generated binding copies input into WebAssembly memory and copies processed values back; this is not zero-copy processing. Requires successful initialization and the configured block length. Throws for mismatched audio, disallowed processing or runtime failures. Do not rely on the input remaining unchanged if processing throws. ### `Processor.terminateSession` ```typescript theme={null} terminateSession(): void; ``` Requests termination of the telemetry session. Stop submitting audio before calling this method. Processing becomes disallowed once the telemetry task handles the signal; the `void` return is not an acknowledgment of server delivery or immediate completion. This method neither flushes delayed audio nor frees the object. Call `free()` separately when finished. ## `ProcessorContext` ```typescript theme={null} export class ProcessorContext ``` A shared control handle returned by `Processor.getContext`. Its constructor is private. Each returned context is separately owned and must be freed. Freeing a context does not free the processor. A context can retain control state after the processor is freed, but it does not keep an active processing stream alive. ### `ProcessorContext.free` ```typescript theme={null} free(): void; ``` Releases the owned WebAssembly allocation. Call once in `finally` and do not use the handle afterward. Garbage collection does not guarantee timely cleanup; `free()` does not acknowledge session termination. ### `ProcessorContext.Symbol.dispose` ```typescript theme={null} [Symbol.dispose](): void; ``` Aliases `free()` when the runtime supports `Symbol.dispose`; do not call both on the same handle. Otherwise, call `free()` in `finally`. ### `ProcessorContext.getAudioDelay` ```typescript theme={null} getAudioDelay(): number; ``` Returns end-to-end processing delay in samples at the initialized host sample rate, including block adaptation and model delay. Query after initialization or reinitialization. Divide by the host sample rate to convert to seconds. ### `ProcessorContext.getParameter` ```typescript theme={null} getParameter(parameter: ProcessorParameter): number; ``` Returns the stored value for a `ProcessorParameter`. Bypass reads as `0` or `1`; enhancement level is a normalized floating-point value. ### `ProcessorContext.reset` ```typescript theme={null} reset(): void; ``` Requests clearing of signal history on the next processing pass, retaining the initialized audio configuration and parameter values. Any energy VAD on this processor is reset as well. Use when beginning a new unrelated stream. It does not allocate a new processor or terminate its session. ### `ProcessorContext.setParameter` ```typescript theme={null} setParameter(parameter: ProcessorParameter, value: number): void; ``` Sets the selected parameter. Both parameters accept finite values from `0` through `1`; out-of-range values and NaN throw `RangeError`. Changes affect subsequent processing. See `ProcessorParameter` below for defaults and interpretation. ### `ProcessorContext.updateBearerToken` ```typescript theme={null} updateBearerToken(token: string): void; ``` Replaces the bearer token for subsequent session requests without creating a new processing instance. Both the original credential and the replacement must be JWT-form credentials. A malformed or unsupported replacement throws and leaves the previous credential in place. Local format acceptance does not prove that the backend accepts the new token. Obtain fresh short-lived tokens through your backend; keep the SDK key on the server. This call returns `void`, not a network-completion promise. ## `ProcessorParameter` ```typescript theme={null} export enum ProcessorParameter ``` Parameters accepted by `ProcessorContext.getParameter` and `setParameter`. ### `ProcessorParameter.Bypass` ```typescript theme={null} Bypass = 0, ``` `0` disables bypass; any accepted value greater than `0` enables bypass and reads back as `1`. Default: `0`. Bypass preserves the configured processing delay. ### `ProcessorParameter.EnhancementLevel` ```typescript theme={null} EnhancementLevel = 1, ``` Normalized enhancement amount from `0` through `1`. `0` is dry output and `1` uses the model's maximum enhancement. The initial value is the model's default, falling back to `1` when absent. ## Process one block This helper assumes module initialization has completed, `model` is a live enhancement model, `token` is a backend-issued JWT and `audio` contains exactly one optimal block of mono samples. It copies the caller's block before enhancement, then returns the enhanced block and delay. For a stream, retain the processor across blocks instead of creating it for each call. ```javascript theme={null} import { Processor } from "@ai-coustics/aic-sdk-wasm"; /** * @param {import("@ai-coustics/aic-sdk-wasm").Model} model * @param {string} token * @param {Float32Array} audio */ export function enhanceBlock(model, token, audio) { const sampleRate = model.getOptimalSampleRate(); const blockSize = model.getOptimalBlockSize(sampleRate); if (audio.length !== blockSize) throw new Error("Expected one optimal block"); const processor = new Processor(model, token); try { processor.initialize(sampleRate, blockSize, false); const context = processor.getContext(); try { const output = audio.slice(); processor.process(output); return { output, delaySamples: context.getAudioDelay() }; } finally { context.free(); } } finally { try { processor.terminateSession(); } finally { processor.free(); } } } ``` # WebAssembly errors Source: https://docs.ai-coustics.com/reference/sdk/api/wasm/errors Handle initialization, model, parameter and processing failures. **Version:** `@ai-coustics/aic-sdk-wasm` 0.26.0, Core SDK 0.26.0. [API index](/reference/sdk/api/wasm/index) · [WebAssembly quickstart](/reference/sdk/language-bindings/wasm). The binding throws JavaScript `Error` or `RangeError` objects. It does not export SDK exception classes, an error-code enum or a structured `code` property. TypeScript signatures do not list thrown exceptions. Catch errors around construction, initialization, model loading, token renewal and processing, and release already-created handles in `finally`. | Failure | JavaScript error | Recovery | | - | - | - | | Processor or VAD parameter outside its accepted range | `RangeError` | Correct the parameter before processing again. | | Analysis-window range error propagated by the core | `RangeError` | Check model compatibility; this binding exposes no window-length setting. | | Processor or collector not initialized | `Error` | Successfully initialize before passing audio. | | Unsupported audio configuration | `Error` | Use a supported sample rate and valid block size. | | Audio block does not match initialized configuration | `Error` | Supply the required number of mono samples. | | Processing disallowed | `Error` | Resolve session authorization and network requirements; do not retry in a tight processing loop. | | Invalid, unsupported or expired credential | `Error` | Obtain a valid credential through your backend. | | Unsupported token update | `Error` | Ensure the original and replacement credentials are both JWT-form credentials. | | Model type unsupported by the selected class | `Error` | Match enhancement, VAD and analysis models to their respective classes. | | Model parsing, allocation or runtime creation failure | `Error` | Check model bytes and runtime compatibility. | | Internal processing failure | `Error` | Stop using the stream and retain the error message for diagnosis. | The delegated core also defines voiceprint errors for other interfaces. This package exposes no enrollment or voiceprint methods. Binding misuse, invalid JavaScript types, initialization failures and access after `free()` can produce JavaScript or WebAssembly errors outside the SDK mapping; do not depend on their exact text or class. A failed `updateBearerToken` preserves the previous token. A successful call checks local format, not backend acceptance. A failed initialization requires successful reinitialization before submitting more audio. A failed enhancement call does not guarantee the input array is unchanged. ```javascript theme={null} try { context.setParameter(ProcessorParameter.EnhancementLevel, requestedLevel); } catch (error) { if (error instanceof RangeError) { console.error("Enhancement level must be between 0 and 1."); } else { throw error; } } ``` This fragment assumes a live `ProcessorContext` named `context`, a numeric `requestedLevel` and `ProcessorParameter` imported from the package. See [enhancement](/reference/sdk/api/wasm/enhancement) for the full control API and [lifecycle](/reference/sdk/api/wasm/initialization#ownership-and-cleanup) for cleanup. # WebAssembly API reference Source: https://docs.ai-coustics.com/reference/sdk/api/wasm/index Complete application API for the released WebAssembly package. **Version:** `@ai-coustics/aic-sdk-wasm` 0.26.0, Core SDK 0.26.0. [API index](/reference/sdk/api/wasm/index) · [WebAssembly quickstart](/reference/sdk/language-bindings/wasm). This reference covers [@ai-coustics/aic-sdk-wasm 0.26.0](https://www.npmjs.com/package/@ai-coustics/aic-sdk-wasm/v/0.26.0). Use the [WebAssembly quickstart](/reference/sdk/language-bindings/wasm) for the complete browser setup and backend token exchange. Read [initialization and lifecycle](/reference/sdk/api/wasm/initialization) before constructing SDK objects. | Domain | Use it to | | - | - | | [Initialization and lifecycle](/reference/sdk/api/wasm/initialization) | Load the module and release owned handles. | | [Models](/reference/sdk/api/wasm/models-and-config) | Load model bytes and query metadata. | | [Enhancement](/reference/sdk/api/wasm/enhancement) | Enhance blocks and configure a stream. | | [VAD](/reference/sdk/api/wasm/vad) | Run dedicated voice activity detection. | | [Analysis](/reference/sdk/api/wasm/analysis) | Collect audio and read analysis results. | | [Errors](/reference/sdk/api/wasm/errors) | Diagnose errors and recover. | The JavaScript API has no asynchronous processor, model downloader, file analyzer, enrollment API or OpenTelemetry configuration object. Application downloads use `fetch`; SDK processing itself is synchronous. Preserve each stream's block order and keep objects within the JavaScript context that owns their initialized module. ## Symbol index | Symbol | Reference | | - | - | | `__aic_sdk_wasm_init` | [Details](/reference/sdk/api/wasm/initialization#wasm-__aic_sdk_wasm_init) | | `__wbg_init` | [Details](/reference/sdk/api/wasm/initialization#wasm-__wbg_init) | | `AnalysisResult` | [Details](/reference/sdk/api/wasm/analysis#wasm-analysisresult) | | `AnalysisResult.codecDegradation` | [Details](/reference/sdk/api/wasm/analysis#wasm-analysisresult-codecdegradation) | | `AnalysisResult.free` | [Details](/reference/sdk/api/wasm/analysis#wasm-analysisresult-free) | | `AnalysisResult.interferingSpeech` | [Details](/reference/sdk/api/wasm/analysis#wasm-analysisresult-interferingspeech) | | `AnalysisResult.noise` | [Details](/reference/sdk/api/wasm/analysis#wasm-analysisresult-noise) | | `AnalysisResult.packetLoss` | [Details](/reference/sdk/api/wasm/analysis#wasm-analysisresult-packetloss) | | `AnalysisResult.riskScore` | [Details](/reference/sdk/api/wasm/analysis#wasm-analysisresult-riskscore) | | `AnalysisResult.speakerLoudness` | [Details](/reference/sdk/api/wasm/analysis#wasm-analysisresult-speakerloudness) | | `AnalysisResult.speakerReverb` | [Details](/reference/sdk/api/wasm/analysis#wasm-analysisresult-speakerreverb) | | `AnalysisResult.Symbol.dispose` | [Details](/reference/sdk/api/wasm/analysis#wasm-analysisresult-symbol-dispose) | | `Analyzer` | [Details](/reference/sdk/api/wasm/analysis#wasm-analyzer) | | `Analyzer.analyze` | [Details](/reference/sdk/api/wasm/analysis#wasm-analyzer-analyze) | | `Analyzer.buffer` | [Details](/reference/sdk/api/wasm/analysis#wasm-analyzer-buffer) | | `Analyzer.constructor` | [Details](/reference/sdk/api/wasm/analysis#wasm-analyzer-constructor) | | `Analyzer.free` | [Details](/reference/sdk/api/wasm/analysis#wasm-analyzer-free) | | `Analyzer.initialize` | [Details](/reference/sdk/api/wasm/analysis#wasm-analyzer-initialize) | | `Analyzer.reset` | [Details](/reference/sdk/api/wasm/analysis#wasm-analyzer-reset) | | `Analyzer.Symbol.dispose` | [Details](/reference/sdk/api/wasm/analysis#wasm-analyzer-symbol-dispose) | | `Analyzer.terminateSession` | [Details](/reference/sdk/api/wasm/analysis#wasm-analyzer-terminatesession) | | `Analyzer.updateBearerToken` | [Details](/reference/sdk/api/wasm/analysis#wasm-analyzer-updatebearertoken) | | `getCompatibleModelVersion` | [Details](/reference/sdk/api/wasm/models-and-config#wasm-getcompatiblemodelversion) | | `getVersion` | [Details](/reference/sdk/api/wasm/models-and-config#wasm-getversion) | | `InitInput` | [Details](/reference/sdk/api/wasm/initialization#wasm-initinput) | | `EnergyVadContext` | [Details](/reference/sdk/api/wasm/vad#wasm-energyvadcontext) | | `EnergyVadContext.free` | [Details](/reference/sdk/api/wasm/vad#wasm-energyvadcontext-free) | | `EnergyVadContext.getParameter` | [Details](/reference/sdk/api/wasm/vad#wasm-energyvadcontext-getparameter) | | `EnergyVadContext.getPredictionDelay` | [Details](/reference/sdk/api/wasm/vad#wasm-energyvadcontext-getpredictiondelay) | | `EnergyVadContext.isSpeechDetected` | [Details](/reference/sdk/api/wasm/vad#wasm-energyvadcontext-isspeechdetected) | | `EnergyVadContext.reset` | [Details](/reference/sdk/api/wasm/vad#wasm-energyvadcontext-reset) | | `EnergyVadContext.setParameter` | [Details](/reference/sdk/api/wasm/vad#wasm-energyvadcontext-setparameter) | | `EnergyVadContext.Symbol.dispose` | [Details](/reference/sdk/api/wasm/vad#wasm-energyvadcontext-symbol-dispose) | | `InitOutput` | [Details](/reference/sdk/api/wasm/initialization#wasm-initoutput) | | `initSync` | [Details](/reference/sdk/api/wasm/initialization#wasm-initsync) | | `Model` | [Details](/reference/sdk/api/wasm/models-and-config#wasm-model) | | `Model.free` | [Details](/reference/sdk/api/wasm/models-and-config#wasm-model-free) | | `Model.fromBytes` | [Details](/reference/sdk/api/wasm/models-and-config#wasm-model-frombytes) | | `Model.getId` | [Details](/reference/sdk/api/wasm/models-and-config#wasm-model-getid) | | `Model.getOptimalBlockSize` | [Details](/reference/sdk/api/wasm/models-and-config#wasm-model-getoptimalblocksize) | | `Model.getOptimalSampleRate` | [Details](/reference/sdk/api/wasm/models-and-config#wasm-model-getoptimalsamplerate) | | `Model.Symbol.dispose` | [Details](/reference/sdk/api/wasm/models-and-config#wasm-model-symbol-dispose) | | `Processor` | [Details](/reference/sdk/api/wasm/enhancement#wasm-processor) | | `Processor.constructor` | [Details](/reference/sdk/api/wasm/enhancement#wasm-processor-constructor) | | `Processor.free` | [Details](/reference/sdk/api/wasm/enhancement#wasm-processor-free) | | `Processor.getContext` | [Details](/reference/sdk/api/wasm/enhancement#wasm-processor-getcontext) | | `Processor.getEnergyVadContext` | [Details](/reference/sdk/api/wasm/enhancement#wasm-processor-getenergyvadcontext) | | `Processor.initialize` | [Details](/reference/sdk/api/wasm/enhancement#wasm-processor-initialize) | | `Processor.process` | [Details](/reference/sdk/api/wasm/enhancement#wasm-processor-process) | | `Processor.Symbol.dispose` | [Details](/reference/sdk/api/wasm/enhancement#wasm-processor-symbol-dispose) | | `Processor.terminateSession` | [Details](/reference/sdk/api/wasm/enhancement#wasm-processor-terminatesession) | | `ProcessorContext` | [Details](/reference/sdk/api/wasm/enhancement#wasm-processorcontext) | | `ProcessorContext.free` | [Details](/reference/sdk/api/wasm/enhancement#wasm-processorcontext-free) | | `ProcessorContext.getAudioDelay` | [Details](/reference/sdk/api/wasm/enhancement#wasm-processorcontext-getaudiodelay) | | `ProcessorContext.getParameter` | [Details](/reference/sdk/api/wasm/enhancement#wasm-processorcontext-getparameter) | | `ProcessorContext.reset` | [Details](/reference/sdk/api/wasm/enhancement#wasm-processorcontext-reset) | | `ProcessorContext.setParameter` | [Details](/reference/sdk/api/wasm/enhancement#wasm-processorcontext-setparameter) | | `ProcessorContext.Symbol.dispose` | [Details](/reference/sdk/api/wasm/enhancement#wasm-processorcontext-symbol-dispose) | | `ProcessorContext.updateBearerToken` | [Details](/reference/sdk/api/wasm/enhancement#wasm-processorcontext-updatebearertoken) | | `ProcessorParameter` | [Details](/reference/sdk/api/wasm/enhancement#wasm-processorparameter) | | `ProcessorParameter.Bypass` | [Details](/reference/sdk/api/wasm/enhancement#wasm-processorparameter-bypass) | | `ProcessorParameter.EnhancementLevel` | [Details](/reference/sdk/api/wasm/enhancement#wasm-processorparameter-enhancementlevel) | | `SyncInitInput` | [Details](/reference/sdk/api/wasm/initialization#wasm-syncinitinput) | | `Vad` | [Details](/reference/sdk/api/wasm/vad#wasm-vad) | | `Vad.constructor` | [Details](/reference/sdk/api/wasm/vad#wasm-vad-constructor) | | `Vad.free` | [Details](/reference/sdk/api/wasm/vad#wasm-vad-free) | | `Vad.getContext` | [Details](/reference/sdk/api/wasm/vad#wasm-vad-getcontext) | | `Vad.initialize` | [Details](/reference/sdk/api/wasm/vad#wasm-vad-initialize) | | `Vad.process` | [Details](/reference/sdk/api/wasm/vad#wasm-vad-process) | | `Vad.Symbol.dispose` | [Details](/reference/sdk/api/wasm/vad#wasm-vad-symbol-dispose) | | `Vad.terminateSession` | [Details](/reference/sdk/api/wasm/vad#wasm-vad-terminatesession) | | `VadContext` | [Details](/reference/sdk/api/wasm/vad#wasm-vadcontext) | | `VadContext.free` | [Details](/reference/sdk/api/wasm/vad#wasm-vadcontext-free) | | `VadContext.getParameter` | [Details](/reference/sdk/api/wasm/vad#wasm-vadcontext-getparameter) | | `VadContext.getPredictionDelay` | [Details](/reference/sdk/api/wasm/vad#wasm-vadcontext-getpredictiondelay) | | `VadContext.getRawVadProbability` | [Details](/reference/sdk/api/wasm/vad#wasm-vadcontext-getrawvadprobability) | | `VadContext.isSpeechDetected` | [Details](/reference/sdk/api/wasm/vad#wasm-vadcontext-isspeechdetected) | | `VadContext.reset` | [Details](/reference/sdk/api/wasm/vad#wasm-vadcontext-reset) | | `VadContext.setParameter` | [Details](/reference/sdk/api/wasm/vad#wasm-vadcontext-setparameter) | | `VadContext.Symbol.dispose` | [Details](/reference/sdk/api/wasm/vad#wasm-vadcontext-symbol-dispose) | | `VadContext.updateBearerToken` | [Details](/reference/sdk/api/wasm/vad#wasm-vadcontext-updatebearertoken) | | `VadParameter` | [Details](/reference/sdk/api/wasm/vad#wasm-vadparameter) | | `VadParameter.MinimumSpeechDuration` | [Details](/reference/sdk/api/wasm/vad#wasm-vadparameter-minimumspeechduration) | | `VadParameter.Sensitivity` | [Details](/reference/sdk/api/wasm/vad#wasm-vadparameter-sensitivity) | | `VadParameter.SpeechHoldDuration` | [Details](/reference/sdk/api/wasm/vad#wasm-vadparameter-speechholdduration) | # WebAssembly initialization and lifecycle Source: https://docs.ai-coustics.com/reference/sdk/api/wasm/initialization Initialize the module, choose an input source and manage owned handles. **Version:** `@ai-coustics/aic-sdk-wasm` 0.26.0, Core SDK 0.26.0. [API index](/reference/sdk/api/wasm/index) · [WebAssembly quickstart](/reference/sdk/language-bindings/wasm). Initialize the module once before loading models or constructing SDK objects. Processing, VAD and analysis calls are synchronous; the asynchronous initializer loads the module but does not turn processing into background work. A long loop can block the browser event loop and delay session requests. For background processing, initialize and own SDK objects inside a worker, then pass ordinary audio buffers through your application. Do not transfer SDK handles between workers or WebAssembly instances. ## `__wbg_init` ```typescript theme={null} export default function __wbg_init (module_or_path?: { module_or_path: InitInput | Promise } | InitInput | Promise): Promise; ``` The default export, conventionally imported as `init`, asynchronously instantiates the module. With no argument, it resolves `aic_sdk_wasm_bg.wasm` relative to the JavaScript module URL and fetches it. Serve both package files through your bundler or web server. Prefer the object form, for example `await init({ module_or_path: wasmUrl })`. The older bare input form remains accepted but logs a deprecation warning. A directly supplied `Request`, URL or string is fetched. A `Response`, byte buffer or compiled module can be supplied directly or through a promise. Although the declaration permits `Promise`, this release checks whether to fetch before awaiting the input. Resolve promises of URLs, strings or requests yourself before passing their value to the initializer; a promise of a URL is not fetched automatically. HTTP, fetch and WebAssembly compilation/instantiation failures reject the promise. Correct `application/wasm` MIME enables streaming instantiation; the loader can fall back to buffering for an unsuitable MIME type. After successful initialization, later calls return the already initialized instance. Complete one initialization before using the SDK; do not rely on simultaneous first calls sharing an in-flight promise. ## `initSync` ```typescript theme={null} export function initSync(module: { module: SyncInitInput } | SyncInitInput): InitOutput; ``` Synchronously instantiates already available bytes or a compiled `WebAssembly.Module`. Prefer `initSync({ module: bytes })`; the bare form is deprecated. It performs no download and throws if compilation or instantiation fails. It returns the already initialized instance if initialization has completed. Use the asynchronous initializer when bytes still need to be fetched. ## `InitInput` ```typescript theme={null} export type InitInput = RequestInfo | URL | Response | BufferSource | WebAssembly.Module; ``` Accepted input forms for the asynchronous initializer. A string URL is included through `RequestInfo`. ## `SyncInitInput` ```typescript theme={null} export type SyncInitInput = BufferSource | WebAssembly.Module; ``` Accepted input forms for `initSync`. Fetch or read the bytes before calling it. ## `InitOutput` ```typescript theme={null} export interface InitOutput ``` The initializer returns the generated raw WebAssembly export object. Application code normally ignores it and uses the exported JavaScript classes. Its `memory` field is a `WebAssembly.Memory`; its remaining fields contain raw pointer-level calls, allocation helpers, tables and binding internals. These generated ABI members are excluded from the application API documented here. Do not call their raw constructors or destructors, mix pointers with JavaScript handles or rely on their names across builds. The installed package's `.d.ts` contains the complete ABI declaration. ## `__aic_sdk_wasm_init` ```typescript theme={null} export function __aic_sdk_wasm_init(): void; ``` Generated startup hook invoked by module initialization. It sets up panic reporting and SDK wrapper identification. It is exported for binding startup, not for application initialization; use the default export or `initSync` instead. ## Ownership and cleanup `Model`, `Processor`, `ProcessorContext`, `Vad`, `VadContext`, `Analyzer` and `AnalysisResult` all own WebAssembly allocations. Every returned handle needs its own `free()` call, including repeated context queries and each analysis result. Methods and properties require a live handle. Do not call `free()` twice, use a freed handle or pass a handle from a different module instance. When the runtime supports `Symbol.dispose`, the package aliases it to `free()` on all seven classes. Otherwise, use explicit `finally` cleanup. Finalization support does not guarantee when memory will be reclaimed. Terminate a processing or analysis session when finished and free the corresponding handle separately. The termination method returns `void`; it does not wait for the request to reach the server. Keep persistent SDK keys on your backend and pass short-lived JWTs to browser constructors. See [authentication](/models/get-started/authenticate-apps) for the token flow. # WebAssembly model API Source: https://docs.ai-coustics.com/reference/sdk/api/wasm/models-and-config Load model bytes and inspect model metadata. **Version:** `@ai-coustics/aic-sdk-wasm` 0.26.0, Core SDK 0.26.0. [API index](/reference/sdk/api/wasm/index) · [WebAssembly quickstart](/reference/sdk/language-bindings/wasm). ## `Model` ```typescript theme={null} export class Model ``` A loaded model and its metadata. Create it with `Model.fromBytes`; its constructor is private. Model storage is retained by each processor, VAD or analyzer created from it. Those instances remain valid if the original `Model` handle is freed. ### `Model.free` ```typescript theme={null} free(): void; ``` Releases the owned WebAssembly allocation. Call once in `finally` and do not use the handle afterward. Garbage collection does not guarantee timely cleanup; `free()` does not acknowledge session termination. Dependent processors, VAD instances and analyzers retain shared model storage until they are freed. ### `Model.Symbol.dispose` ```typescript theme={null} [Symbol.dispose](): void; ``` Aliases `free()` when the runtime supports `Symbol.dispose`; do not call both on the same handle. Otherwise, call `free()` in `finally`. ### `Model.fromBytes` ```typescript theme={null} static fromBytes(bytes: Uint8Array): Model; ``` Loads an `.aicmodel` from `bytes` and returns a new model. The wrapper copies bytes into owned aligned storage; the caller may release or change the original `Uint8Array` after this call. Loading can throw for invalid, incompatible or unsupported data, or allocation failure. There is no `Model.download` or `Model.fromFile` in this package. Fetch the bytes asynchronously in your application, then call this synchronous factory. ### `Model.getId` ```typescript theme={null} getId(): string; ``` Returns the model ID embedded in the loaded file as a JavaScript string. This is a metadata query and does not require a credential. ### `Model.getOptimalBlockSize` ```typescript theme={null} getOptimalBlockSize(sample_rate: number): number; ``` Returns the preferred mono block size, in samples, for the requested whole-number host sample rate in Hz. Query the rate you will actually initialize. The query computes a size; it is not a substitute for initialization validation. ### `Model.getOptimalSampleRate` ```typescript theme={null} getOptimalSampleRate(): number; ``` Returns the model's native sample rate in Hz. Use this as the starting point for initialization; other supported host rates require adaptation. ## `getVersion` ```typescript theme={null} export function getVersion(): string; ``` Returns this WebAssembly wrapper's package version, `0.26.0` for this release. It is not a query of a separately installed native library. ## `getCompatibleModelVersion` ```typescript theme={null} export function getCompatibleModelVersion(): number; ``` Returns the model format version supported by the compiled runtime. This is a format compatibility number, not a model ID or package release version. Model loading still validates the supplied file. ## Fetch and inspect a model After initialization, fetch a model URL supplied by your application. This helper checks the HTTP response and frees the loaded model after reading its metadata. It requires no SDK credential. ```javascript theme={null} import init, { Model, getVersion } from "@ai-coustics/aic-sdk-wasm"; export async function inspectModel(modelUrl) { await init(); const response = await fetch(modelUrl); if (!response.ok) { throw new Error(`Model download failed: ${response.status}`); } const bytes = new Uint8Array(await response.arrayBuffer()); const model = Model.fromBytes(bytes); try { const sampleRate = model.getOptimalSampleRate(); return { sdkVersion: getVersion(), modelId: model.getId(), sampleRate, blockSize: model.getOptimalBlockSize(sampleRate), }; } finally { model.free(); } } ``` # WebAssembly VAD API Source: https://docs.ai-coustics.com/reference/sdk/api/wasm/vad Process dedicated VAD models and read speech predictions. **Version:** `@ai-coustics/aic-sdk-wasm` 0.26.0, Core SDK 0.26.0. [API index](/reference/sdk/api/wasm/index) · [WebAssembly quickstart](/reference/sdk/language-bindings/wasm). ## `Vad` ```typescript theme={null} export class Vad ``` A synchronous dedicated voice activity detection stream. Supply a VAD Multi Speaker or VAD Voice Focus model. Each instance keeps separate signal state and retains the model weights. ### `Vad.free` ```typescript theme={null} free(): void; ``` Releases the owned WebAssembly allocation. Call once in `finally` and do not use the handle afterward. Garbage collection does not guarantee timely cleanup; `free()` does not acknowledge session termination. ### `Vad.Symbol.dispose` ```typescript theme={null} [Symbol.dispose](): void; ``` Aliases `free()` when the runtime supports `Symbol.dispose`; do not call both on the same handle. Otherwise, call `free()` in `finally`. ### `Vad.getContext` ```typescript theme={null} getContext(): VadContext; ``` Returns a newly owned handle to shared prediction and control state. The handle does not contain a separate VAD model. Repeated calls require separate `free()` calls for the returned contexts. > [!WARNING] > > Renamed in 0.25.0. This method was `getVadContext()` through 0.23.0. ### `Vad.initialize` ```typescript theme={null} initialize(sample_rate: number, block_size: number, variable_block_size: boolean): void; ``` All three arguments are required. `sample_rate` is a whole-number rate in Hz from 8,000 through 192,000; `block_size` is a positive whole-number count of mono samples, not bytes. Prefer the model's optimal sample rate and block size. Unsupported block configurations throw. Pass `false` for fixed blocks of exactly `block_size` samples or `true` to permit shorter blocks up to that maximum. Variable blocks can add buffering delay. Initialization allocates memory and resets signal state. A failed initialization leaves processing uninitialized; correct the configuration before submitting audio again. ### `Vad.constructor` ```typescript theme={null} constructor(model: Model, license_key: string); ``` Creates a dedicated VAD stream using a live VAD `model` and the credential in `license_key`. Use a short-lived JWT from your backend in browser code. Enhancement and analysis models are rejected. Construction can throw for model type, model creation or credential errors. Initialize the audio format before processing. No OpenTelemetry configuration argument is exposed. ### `Vad.process` ```typescript theme={null} process(audio: Float32Array): void; ``` Processes one block of normalized mono `Float32Array` samples without changing the caller's array. Samples are copied into WebAssembly memory and into the VAD's processing buffer. Returns `void`; read the prediction through the context afterward. Requires successful initialization and the configured block length. Throws for uninitialized or mismatched audio, disallowed processing or runtime failures. ### `Vad.terminateSession` ```typescript theme={null} terminateSession(): void; ``` Requests termination of the telemetry session. Stop submitting audio before calling this method. Processing becomes disallowed once the telemetry task handles the signal; the `void` return is not an acknowledgment of server delivery or immediate completion. This method neither flushes delayed audio nor frees the object. Call `free()` separately when finished. ## `VadContext` ```typescript theme={null} export class VadContext ``` A shared prediction and control handle returned by `Vad.getContext`. Its constructor is private. Each returned handle must be freed separately. Freeing it does not free its VAD. A surviving context retains state after the VAD is freed, but cannot produce new predictions. ### `VadContext.free` ```typescript theme={null} free(): void; ``` Releases the owned WebAssembly allocation. Call once in `finally` and do not use the handle afterward. Garbage collection does not guarantee timely cleanup; `free()` does not acknowledge session termination. ### `VadContext.Symbol.dispose` ```typescript theme={null} [Symbol.dispose](): void; ``` Aliases `free()` when the runtime supports `Symbol.dispose`; do not call both on the same handle. Otherwise, call `free()` in `finally`. ### `VadContext.getParameter` ```typescript theme={null} getParameter(parameter: VadParameter): number; ``` Returns the stored floating-point value for the selected `VadParameter`. Duration values are in seconds. Effective timing follows model frame boundaries; do not interpret the getter as a measurement of the resulting delay. ### `VadContext.getPredictionDelay` ```typescript theme={null} getPredictionDelay(): number; ``` Returns end-to-end prediction delay in samples at the initialized host sample rate, including input block adaptation. Query after initialization. Divide by sample rate for seconds. ### `VadContext.getRawVadProbability` ```typescript theme={null} getRawVadProbability(): number; ``` Returns the latest raw speech probability as a number from `0` through `1`, before the hold and minimum-duration decision logic. A fresh or reset context reads `0` until new predictions are available. ### `VadContext.isSpeechDetected` ```typescript theme={null} isSpeechDetected(): boolean; ``` Returns the latest speech decision after sensitivity and duration logic. A fresh or reset context reads `false` until processing provides a new decision. ### `VadContext.reset` ```typescript theme={null} reset(): void; ``` Immediately clears the published speech decision and raw probability, and requests clearing of the underlying signal history on the next processing pass. Preserves the initialized format and configured parameters. ### `VadContext.setParameter` ```typescript theme={null} setParameter(parameter: VadParameter, value: number): void; ``` Sets the parameter for subsequent processing. Invalid ranges, infinities and NaN throw `RangeError`. Defaults come from the loaded model, so query them rather than assuming a universal preset. See `VadParameter` below for units and ranges. ### `VadContext.updateBearerToken` ```typescript theme={null} updateBearerToken(token: string): void; ``` Replaces the bearer token for subsequent session requests without creating a new processing instance. Both the original credential and the replacement must be JWT-form credentials. A malformed or unsupported replacement throws and leaves the previous credential in place. Local format acceptance does not prove that the backend accepts the new token. Obtain fresh short-lived tokens through your backend; keep the SDK key on the server. This call returns `void`, not a network-completion promise. ## `EnergyVadContext` ```typescript theme={null} export class EnergyVadContext ``` An energy VAD handle returned by [`Processor.getEnergyVadContext`](/reference/sdk/api/wasm/enhancement#wasm-processor-getenergyvadcontext). Its constructor is private. Detection uses the enhanced signal before output mixing and runs no separate model, so an enhancement model yields speech decisions without loading a dedicated VAD model. Detection advances with `Processor.process`. Every handle from one processor refers to the same energy VAD, and each must be freed separately. Freeing a handle does not free the processor or disable detection. A surviving handle stays usable after the processor is freed, but produces no new predictions. `Sensitivity` uses the energy range, `1` through `15`, not the `0` through `1` probability threshold of a dedicated VAD model. See [`VadParameter.Sensitivity`](/reference/sdk/api/wasm/vad#wasm-vadparameter-sensitivity). ### `EnergyVadContext.free` ```typescript theme={null} free(): void; ``` Releases this handle. Call it exactly once when finished; it does not free the backing processor. ### `EnergyVadContext.Symbol.dispose` ```typescript theme={null} [Symbol.dispose](): void; ``` Aliases `free()` when the runtime supports `Symbol.dispose`; do not call both on the same handle. Otherwise, call `free()` in `finally`. ### `EnergyVadContext.isSpeechDetected` ```typescript theme={null} isSpeechDetected(): boolean; ``` Returns the energy VAD's prediction. It is `false` before audio is processed and after a reset, and lags its input by `getPredictionDelay()` samples. Speech hold and minimum speech duration affect its timing further. The prediction stops updating if the backing processor stops being processed. ### `EnergyVadContext.setParameter` ```typescript theme={null} setParameter(parameter: VadParameter, value: number): void; ``` Modifies an energy VAD parameter. `Sensitivity` uses the energy range, `1` through `15`. A value outside the valid range throws a `RangeError`. All parameters can be changed during processing. ### `EnergyVadContext.getParameter` ```typescript theme={null} getParameter(parameter: VadParameter): number; ``` Returns the current value of an energy VAD parameter. ### `EnergyVadContext.getPredictionDelay` ```typescript theme={null} getPredictionDelay(): number; ``` Returns the prediction delay in samples, covering input reblocking, STFT and enhancement model processing. It equals [`ProcessorContext.getAudioDelay`](/reference/sdk/api/wasm/enhancement#wasm-processorcontext-getaudiodelay) for the backing processor; energy detection does not delay the audio. Speech hold and minimum speech duration affect decision timing and are not included. Before initialization the value uses the processor's optimal block size at its native sample rate. After initialization it is expressed in samples at the rate given to `Processor.initialize` and includes input-buffering latency for the configured block size, which a non-optimal or variable block size increases. ### `EnergyVadContext.reset` ```typescript theme={null} reset(): void; ``` Clears the energy VAD state, including the published speech decision. Use it when the stream is interrupted or when seeking. Configured parameters are retained and the backing processor is not reset; [`ProcessorContext.reset`](/reference/sdk/api/wasm/enhancement#wasm-processorcontext-reset) also resets the energy VAD. ## `VadParameter` ```typescript theme={null} export enum VadParameter ``` Parameters accepted by the `getParameter` and `setParameter` methods of `VadContext` and `EnergyVadContext`. Defaults are supplied by the model. ### `VadParameter.SpeechHoldDuration` ```typescript theme={null} SpeechHoldDuration = 0, ``` Controls recent-speech hold behavior in seconds. Range: `0` through the model's maximum supported hold duration. When the current probability is at or below the threshold, the decision uses the positive-frame count in the recent lookback window. Above the threshold, the consecutive-frame rule from `MinimumSpeechDuration` applies. Effective timing follows frame boundaries. ### `VadParameter.Sensitivity` ```typescript theme={null} Sensitivity = 1, ``` Its meaning depends on the detector. On a `VadContext`, a speech-decision probability threshold from `0` through `1`, where lower values classify more frames as speech. On an [`EnergyVadContext`](/reference/sdk/api/wasm/vad#wasm-energyvadcontext), the energy threshold of the enhanced signal, computed as `10 ** -sensitivity` over `1` through `15`, where higher values detect quieter speech. ### `VadParameter.MinimumSpeechDuration` ```typescript theme={null} MinimumSpeechDuration = 2, ``` Required speech duration in seconds, from `0` through `1`, before speech is detected. Effective timing follows frame boundaries. ## Read a block prediction This helper assumes the module is initialized, `model` is a live dedicated VAD model, `token` is a backend-issued JWT and `audio` contains one optimal mono block. A single initial block can precede a usable prediction because of model delay and duration settings. Keep a VAD instance alive across the full stream in an integration. ```javascript theme={null} import { Vad } from "@ai-coustics/aic-sdk-wasm"; /** * @param {import("@ai-coustics/aic-sdk-wasm").Model} model * @param {string} token * @param {Float32Array} audio */ export function detectBlock(model, token, audio) { const sampleRate = model.getOptimalSampleRate(); const blockSize = model.getOptimalBlockSize(sampleRate); if (audio.length !== blockSize) throw new Error("Expected one optimal block"); const vad = new Vad(model, token); try { vad.initialize(sampleRate, blockSize, false); const context = vad.getContext(); try { vad.process(audio); return { speech: context.isSpeechDetected(), probability: context.getRawVadProbability(), delaySamples: context.getPredictionDelay(), }; } finally { context.free(); } } finally { try { vad.terminateSession(); } finally { vad.free(); } } } ``` # Compatibility matrix Source: https://docs.ai-coustics.com/reference/sdk/compatibility-matrix Compatibility matrix for core SDK, language bindings and model file versions. Match the binding, core SDK and model file format before upgrading. Binding versions are independent of the core SDK version. For example, Python 3.4.0 embeds core SDK 0.26.0. A model's product version is also separate from its file format version. ## Versions used by the quickstarts | Route | Pinned package | Core SDK | Model file format | | - | - | - | - | | Python | `aic-sdk==3.4.0` | 0.26.0 | 8 | | Node.js | `@ai-coustics/aic-sdk@0.26.0` | 0.26.0 | 8 | | C | SDK archive 0.26.0 | 0.26.0 | 8 | | C++ | Wrapper 0.26.0 | 0.26.0 | 8 | | Rust | `aic-sdk = 0.25.2` | 0.25.2 | 7 | | WebAssembly | `@ai-coustics/aic-sdk-wasm@0.26.0` | 0.26.0 | 8 | | ai-coustics LiveKit extras plugin | Python/Node 0.26.0 | 0.26.0 | 8 | | Pipecat | `pipecat-ai==1.15.0`, `aic-sdk==3.3.2` | 0.25.2 | 7 | Use each [language guide](/reference/sdk/language-bindings) for runtime and platform prerequisites. Test audio processing on your deployment target and lock transitive dependencies. The ai-coustics LiveKit extras plugin and LiveKit's official plugin are different packages with different capabilities and authentication. See [plugin scope](/reference/livekit/plugin-scope). The Pipecat quickstart uses the highest compatible Python SDK release published by Pipecat 1.15.0: 3.3.2, which embeds core SDK 0.25.2. Keep the LiveKit and Pipecat dependency sets separate. The LiveKit extras plugin pins the SDK binding exactly, and its version matches the core SDK version. ## Release history The tables below preserve historical release mappings. They do not extend an old dependency pin to every later framework release. Before core SDK 0.13.0, models were embedded in the SDK and had no separate file format version. > [tab] LiveKit > > This table applies to ai-coustics' `ai-coustics-livekit-extras` and `@ai-coustics/livekit-extras` packages. > > | LiveKit Extras Plugin Version | Core SDK Version | Model File Version | > | :-: | :-: | :-: | > | 0.26.0 | 0.26.0 | 8 | > | 0.25.2 | 0.25.2 | 7 | > | 0.25.1 | 0.25.1 | 7 | > | 0.25.0 | 0.25.0 | 7 | > > This table applies to ai-coustics' deprecated `ai-coustics-livekit-plugin` and `@ai-coustics/livekit-plugin` packages. > > | LiveKit Plugin Version | Core SDK Version | Model File Version | > | :-: | :-: | :-: | > | 0.2.0 | 0.24.0 with the quickstart pins | 7 | > | 0.1.0 | 0.23.0 | 7 | > > This table applies to LiveKit's `livekit-plugins-ai-coustics` and `@livekit/plugins-ai-coustics` packages. > > | LiveKit Plugin Version | Core SDK Version | > | :-: | :-: | > | 0.3.0 | 0.17.1 | > | 0.2.15 | 0.17.1 | > | 0.2.14 | 0.17.1 | > | 0.2.12 | 0.17.1 | > | 0.2.6 - 0.2.11 | 0.15.1 | > | 0.2.1 - 0.2.5 | 0.15.0 | > | 0.1.9 - 0.2.0 | 0.14.0 | > | 0.1.7 | 0.13.1 | > | 0.1.5 - 0.1.6 | 0.13.0 | > | 0.1.2 - 0.1.4 | 0.10.1 | > [tab] Pipecat > > | Pipecat Version | Python Bindings Version | Core SDK Version | Model File Version | > | :-: | :-: | :-: | :-: | > | 1.15.0 | 3.3.2 | 0.25.2 | 7 | > | 1.11.0 | 3.1.0 | 0.23.0 | 7 | > | 1.4.0 | 2.3.0 | 0.19.0 | 4 | > | 1.1.0 - 1.3.0 | 2.2.0 | 0.17.0 | 3 | > | 0.0.105 - 1.0.0 | 2.1.1 | 0.15.1 | 2 | > | 0.0.101 - 0.0.104 | 2.0.1 | 0.14.0 | 1 | > | 0.0.97 - 0.0.100 | 1.2.0 | 0.10.0 | N/A | > | 0.0.95 - 0.0.96 | 1.1.0 | 0.9.0 | N/A | > | 0.0.83 - 0.0.94 | 1.0.1 - 1.0.3 | 0.6.2 - 0.8.0 | N/A | > [tab] Python > > Python bindings are versioned independently from the core SDK. > > | Bindings Version | Core SDK Version | Model File Version | > | :-: | :-: | :-: | > | 3.4.0 | 0.26.0 | 8 | > | 3.3.2 | 0.25.2 | 7 | > | 3.3.1 | 0.25.1 | 7 | > | 3.3.0 | 0.25.0 | 7 | > | 3.2.0 | 0.24.0 | 7 | > | 3.1.1 | 0.23.1 | 7 | > | 3.1.0 | 0.23.0 | 7 | > | 3.0.0 | 0.22.0 | 6 | > | 2.5.0 | 0.21.0 | 5 | > | 2.4.0 | 0.20.0 | 5 | > | 2.3.0 | 0.19.0 | 4 | > | 2.2.1 | 0.17.1 | 3 | > | 2.2.0 | 0.17.0 | 3 | > | 2.1.2 | 0.16.0 | 2 | > | 2.1.1 | 0.15.1 | 2 | > | 2.1.0 | 0.15.0 | 2 | > | 2.0.1 | 0.14.0 | 1 | > | 2.0.0 | 0.13.1 | 1 | > | 1.3.0 | 0.12.0 | N/A | > | 1.2.0 | 0.10.0 | N/A | > | 1.1.0 | 0.9.0 | N/A | > | 1.0.3 | 0.8.0 | N/A | > | 1.0.2 | 0.6.3 | N/A | > | 1.0.1 | 0.6.2 | N/A | > | 0.6.1 | 0.6.1 | N/A | > | 0.6.0 | 0.6.0 | N/A | > [tab] Node.js > > | Bindings Version | Core SDK Version | Model File Version | > | :-: | :-: | :-: | > | 0.26.0 | 0.26.0 | 8 | > | 0.25.2 | 0.25.2 | 7 | > | 0.25.1 | 0.25.1 | 7 | > | 0.25.0 | 0.25.0 | 7 | > | 0.24.0 | 0.24.0 | 7 | > | 0.23.1 | 0.23.1 | 7 | > | 0.23.0 | 0.23.0 | 7 | > | 0.22.0 | 0.22.0 | 6 | > | 0.21.0 | 0.21.0 | 5 | > | 0.20.0 | 0.20.0 | 5 | > | 0.19.0 | 0.19.0 | 4 | > | 0.17.1 | 0.17.1 | 3 | > | 0.17.0 | 0.17.0 | 3 | > | 0.15.1 | 0.15.1 | 2 | > | 0.15.0 | 0.15.0 | 2 | > | 0.14.0 | 0.14.0 | 1 | > | 0.13.0 | 0.13.1 | 1 | > | 0.12.0 | 0.12.0 | N/A | > | 0.10.0 | 0.10.0 | N/A | > | 0.6.3 | 0.6.3 | N/A | > [tab] Rust > > | Bindings Version | Core SDK Version | Model File Version | > | :-: | :-: | :-: | > | 0.25.2 | 0.25.2 | 7 | > | 0.25.1 | 0.25.1 | 7 | > | 0.25.0 | 0.25.0 | 7 | > | 0.24.0 | 0.24.0 | 7 | > | 0.23.1 | 0.23.1 | 7 | > | 0.23.0 | 0.23.0 | 7 | > | 0.22.0 | 0.22.0 | 6 | > | 0.21.4 | 0.21.4 | 5 | > | 0.21.3 | 0.21.3 | 5 | > | 0.21.2 | 0.21.2 | 5 | > | 0.21.1 | 0.21.1 | 5 | > | 0.21.0 | 0.21.0 | 5 | > | 0.20.0 | 0.20.0 | 5 | > | 0.19.3 | 0.19.3 | 4 | > | 0.19.2 | 0.19.2 | 4 | > | 0.19.1 | 0.19.1 | 4 | > | 0.19.0 | 0.19.0 | 4 | > | 0.18.0 | 0.18.0 | 3 | > | 0.17.1 | 0.17.1 | 3 | > | 0.17.0 | 0.17.0 | 3 | > | 0.16.0 | 0.16.0 | 2 | > | 0.15.1 | 0.15.1 | 2 | > | 0.15.0 | 0.15.0 | 2 | > | 0.14.0 | 0.14.0 | 1 | > | 0.13.1 | 0.13.1 | 1 | > | 0.13.0 | 0.13.0 | 1 | > | 0.12.0 | 0.12.0 | N/A | > | 0.11.0 | 0.11.0 | N/A | > | 0.10.1 | 0.10.1 | N/A | > | 0.10.0 | 0.10.0 | N/A | > | 0.9.1 | 0.9.1 | N/A | > | 0.9.0 | 0.9.0 | N/A | > | 0.8.2 | 0.8.0 | N/A | > | 0.8.1 | 0.8.0 | N/A | > | 0.8.0 | 0.8.0 | N/A | > | 0.6.3 | 0.6.3 | N/A | > [tab] C++ > > | Bindings Version | Core SDK Version | Model File Version | > | :-: | :-: | :-: | > | 0.26.0 | 0.26.0 | 8 | > | 0.25.2 | 0.25.2 | 7 | > | 0.25.1 | 0.25.1 | 7 | > | 0.25.0 | 0.25.0 | 7 | > | 0.24.0 | 0.24.0 | 7 | > | 0.23.0 | 0.23.0 | 7 | > | 0.22.0 | 0.22.0 | 6 | > | 0.21.0 | 0.21.0 | 5 | > | 0.20.0 | 0.20.0 | 5 | > | 0.19.0 | 0.19.0 | 4 | > | 0.17.1 | 0.17.1 | 3 | > | 0.17.0 | 0.17.0 | 3 | > | 0.15.0 | 0.15.0 | 2 | > | 0.14.0 | 0.14.0 | 1 | > | 0.12.0 | 0.12.0 | N/A | > | 0.11.0 | 0.11.0 | N/A | > | 0.10.0 | 0.10.0 | N/A | > | 0.9.1 | 0.9.1 | N/A | > | 0.9.0 | 0.9.0 | N/A | > | 0.8.0 | 0.8.0 | N/A | > | 0.7.0 | 0.7.0 | N/A | > | 0.6.3 | 0.6.3 | N/A | > [tab] WebAssembly > > | Bindings Version | Core SDK Version | Model File Version | > | :-: | :-: | :-: | > | 0.26.0 | 0.26.0 | 8 | > | 0.25.1 | 0.25.1 | 7 | > | 0.25.0 | 0.25.0 | 7 | > | 0.23.0 | 0.23.0 | 7 | > | 0.22.0 | 0.22.0 | 6 | > | 0.21.0 | 0.21.0 | 5 | > | 0.20.0 | 0.20.0 | 5 | > | 0.19.0 | 0.19.0 | 4 | > | 0.17.5 | 0.17.1 | 3 | > | 0.17.4 | 0.17.0 | 3 | > | 0.15.0 | 0.15.0 | 2 | > | 0.14.1 | 0.14.0 | 1 | ## Upgrade without mixing artifacts Keep the old application lockfile, SDK binary and model files together until the candidate passes your audio and operational checks. If the new core requires a different model file format, download compatible models into a separate cache location. See [SDK and model versions](/reference/sdk/upgrading) for how these versions fit together. Repeat your checks when the package, model hash, runtime, operating system, CPU architecture or dependency lockfile changes. # Examples Source: https://docs.ai-coustics.com/reference/sdk/examples Browse example code for the ai-coustics SDK across all supported languages. Find examples of model loading, audio enhancement, VAD, analysis and benchmarking for your SDK binding. > [!NOTE] > > Native SDK examples and the ai-coustics LiveKit extras plugin require an `AIC_SDK_LICENSE` environment variable. The [browser quickstart](/reference/sdk/language-bindings/wasm) keeps the SDK key on a backend and gives the browser a short-lived token. Get your license key from the [ai-coustics developer platform](https://developers.ai-coustics.com). LiveKit Cloud authentication applies only to the LiveKit-owned plugins. Start with the [SDK quickstart](/models/get-started/sdk-quickstart) for a small file-processing example. The links below use released versions; install the matching binding and the example's dependencies. ## LiveKit > [card] [LiveKit quickstart](/models/get-started/livekit-quickstart) > > Add ai-coustics speech enhancement, VAD and audio-quality analysis to a LiveKit Python or Node.js voice agent. ## Python > [card] [Basic usage](https://github.com/ai-coustics/aic-sdk-py/blob/3.4.0/examples/enhancement.py) > > Download a model from the CDN, load it, configure a processor and enhance audio in a synchronous workflow. > [card] [Async usage](https://github.com/ai-coustics/aic-sdk-py/blob/3.4.0/examples/enhancement_async.py) > > Asynchronous version of the basic example using `async`/`await` for model downloading and audio processing. > [card] [File enhancement](https://github.com/ai-coustics/aic-sdk-py/blob/3.4.0/examples/enhance_files.py) > > Enhance WAV files from disk, downmixing multi-channel input to mono, with progress reporting. > [card] [Voice activity detection](https://github.com/ai-coustics/aic-sdk-py/blob/3.4.0/examples/vad.py) > > Run a dedicated VAD model, tune sensitivity and hold duration and read speech decisions from the VAD context. > [card] [Audio analysis](https://github.com/ai-coustics/aic-sdk-py/blob/3.4.0/examples/analyze_file.py) > > Score an audio file with the Tyto analysis model across five-second windows. > [card] [Benchmark](https://github.com/ai-coustics/aic-sdk-py/blob/3.4.0/examples/benchmark.py) > > Benchmark real-time processing throughput by spawning parallel processing sessions. ## Pipecat The [Pipecat quickstart](/models/get-started/pipecat-quickstart#adapt-this-example) explains how to continue from loopback to the conversational example below, including provider credentials, VAD ownership and recording behavior. Use the matching Pipecat 1.15.0 dependencies. > [card] [Speech enhancement (AICFilter)](https://github.com/pipecat-ai/pipecat/blob/v1.15.0/examples/voice/voice-aicoustics.py) > > Voice agent that enhances incoming audio with the AICFilter. > [card] [Voice activity detection](https://github.com/pipecat-ai/pipecat/blob/v1.15.0/examples/voice/voice-aicoustics-vad-only.py) > > VAD event check without STT, LLM or TTS services. This example also applies enhancement before VAD. > [card] [Audio quality analysis (AICTytoObserver)](https://github.com/pipecat-ai/pipecat/blob/v1.15.0/examples/voice/voice-aicoustics-tyto.py) > > Score incoming audio before enhancement and report per-window results and a call summary. ## Node.js > [card] [Basic usage](https://github.com/ai-coustics/aic-sdk-node/blob/0.26.0/examples/enhancement.js) > > Download a model, create a processor and enhance audio samples with the Node.js SDK. > [card] [Async enhancement](https://github.com/ai-coustics/aic-sdk-node/blob/0.26.0/examples/enhancement-async.js) > > Enhance audio with `ProcessorAsync` and process concurrent streams without blocking the event loop. > [card] [File processing](https://github.com/ai-coustics/aic-sdk-node/blob/0.26.0/examples/file-processing.js) > > Read a WAV file, enhance it with configurable model and enhancement level and write the result to disk. > [card] [Voice activity detection](https://github.com/ai-coustics/aic-sdk-node/blob/0.26.0/examples/vad.js) > > Run a dedicated VAD model and read speech decisions from the VAD context. > [card] [Async voice activity detection](https://github.com/ai-coustics/aic-sdk-node/blob/0.26.0/examples/vad-async.js) > > Run `VadAsync` on a worker thread, including detection combined with enhancement. > [card] [Audio analysis](https://github.com/ai-coustics/aic-sdk-node/blob/0.26.0/examples/analysis.js) > > Buffer audio with `Analyzer` and score it with Tyto using blocking or async analysis. ## Rust > [card] [Basic usage](https://docs.rs/aic-sdk/0.25.2/aic_sdk/docs/examples/enhancement/index.html) > > Download a model at runtime, configure a processor with enhancement parameters and process audio. > [card] [Voice activity detection](https://docs.rs/aic-sdk/0.25.2/aic_sdk/docs/examples/vad/index.html) > > Run a dedicated VAD model and read speech decisions from the VAD context. > [card] [Audio analysis](https://docs.rs/aic-sdk/0.25.2/aic_sdk/docs/examples/analyze_file/index.html) > > Score an audio file with the Tyto analysis model. > [card] [Parallel async](https://docs.rs/aic-sdk/0.25.2/aic_sdk/docs/examples/parallel_async/index.html) > > Process multiple streams concurrently with the async API. > [card] [Benchmark](https://docs.rs/aic-sdk/0.25.2/aic_sdk/docs/examples/benchmark/index.html) > > Multi-threaded benchmark that measures real-time processing throughput across parallel sessions. > [card] [Build-time model download](https://docs.rs/aic-sdk/0.25.2/aic_sdk/docs/examples/build_time_download/index.html) > > Download a model at build time and embed it directly into your binary using the `include_model!` macro. ## C > [card] [Enhancement](https://github.com/ai-coustics/aic-sdk-c/blob/0.26.0/examples/enhancement.c) > > Load a model from file, create a processor and enhance mono audio using the C API. > [card] [Voice activity detection](https://github.com/ai-coustics/aic-sdk-c/blob/0.26.0/examples/vad.c) > > Create an `AicVad` from a dedicated VAD model and read speech decisions, with full error checking. > [card] [Audio analysis](https://github.com/ai-coustics/aic-sdk-c/blob/0.26.0/examples/analyzer.c) > > Buffer audio through a collector and score it with the Tyto analysis model. ## C++ > [card] [Basic usage](https://github.com/ai-coustics/aic-sdk-cpp/blob/0.26.0/example/enhancement.cpp) > > Load a model, configure a processor and enhance mono audio using the C++ API. > [card] [Voice activity detection](https://github.com/ai-coustics/aic-sdk-cpp/blob/0.26.0/example/vad.cpp) > > Run a dedicated VAD model and read speech decisions from the VAD context. > [card] [Audio analysis](https://github.com/ai-coustics/aic-sdk-cpp/blob/0.26.0/example/analyzer.cpp) > > Buffer audio through a collector and score it with the Tyto analysis model. ## WebAssembly > [card] [Browser quickstart](/reference/sdk/language-bindings/wasm) > > Load a model and enhance audio in the browser with the WASM SDK. # Language bindings Source: https://docs.ai-coustics.com/reference/sdk/language-bindings Choose a released binding and follow a complete integration example. The **ai-coustics SDK** has six language bindings. Start with the guide for your application; it includes setup, a complete example, the expected result and recovery steps. | Binding | Start here | API reference | Execution model | | - | - | - | - | | **Python** | [Python guide](/reference/sdk/language-bindings/python) | [Full reference](/reference/sdk/api/python/index) | NumPy audio arrays; synchronous and asynchronous processing | | **Node.js** | [Node.js guide](/reference/sdk/language-bindings/nodejs) | [Full reference](/reference/sdk/api/node/index) | Typed arrays; synchronous and worker-based asynchronous APIs | | **C** | [C guide](/reference/sdk/language-bindings/c) | [Full reference](/reference/sdk/api/c/index) | Explicit handles, buffers and error codes | | **C++** | [C++ guide](/reference/sdk/language-bindings/cpp) | [Full reference](/reference/sdk/api/cpp/index) | C++ wrapper with owned objects and checked results | | **Rust** | [Rust guide](/reference/sdk/language-bindings/rust) | [Full reference](/reference/sdk/api/rust/index) | Owned models/processors, results and optional async features | | **WebAssembly** | [Browser guide](/reference/sdk/language-bindings/wasm) | [Full reference](/reference/sdk/api/wasm/index) | Synchronous browser processing with explicit WASM resource cleanup | Check the [compatibility matrix](/reference/sdk/compatibility-matrix) for core SDK and model file format versions. Use the reference for your installed release: method names, authentication and configuration options differ between bindings. For every route, review [audio format](/reference/concepts/audio-format), [stream state](/reference/concepts/streams-and-state) and [authentication](/models/get-started/authenticate-apps). Use the [examples index](/reference/sdk/examples) for VAD, analysis and multi-stream work, and the [upgrade guide](/reference/sdk/upgrading) when changing an existing integration. # C Source: https://docs.ai-coustics.com/reference/sdk/language-bindings/c Build a C WAV-processing program with explicit SDK error checks and native cleanup. **ai-coustics** exposes its native SDK through opaque C handles and checked return codes. This page uses SDK 0.26.0. Use the [C API reference](/reference/sdk/api/c/index) for functions, ownership rules and error codes. ## Installation Use a C11 compiler, CMake 3.24 or later and a supported macOS, Linux or Windows platform. This tutorial selects the GNU libc Linux archive; see the [compatibility matrix](/reference/sdk/compatibility-matrix). Release 0.25.0 adds musl archives for `x86_64` and `aarch64`. They ship `lib/libaic.a` only, with no musl `libaic.so`, so link the archive statically with a musl-native toolchain such as GCC on Alpine rather than following the shared-library CMake project below. On Windows, run build commands in a Visual Studio developer terminal with the C++ build tools installed. Create an empty project directory: ```bash theme={null} mkdir aic-c-quickstart cd aic-c-quickstart ``` Download and extract the native SDK 0.26.0 archive. These POSIX commands select Apple Silicon, Intel Mac, Linux ARM64 or Linux x86-64 from the host architecture: ```bash macOS / Linux theme={null} case "$(uname -s)-$(uname -m)" in Darwin-arm64) AIC_TARGET=aarch64-apple-darwin ;; Darwin-x86_64) AIC_TARGET=x86_64-apple-darwin ;; Linux-aarch64) AIC_TARGET=aarch64-unknown-linux-gnu ;; Linux-x86_64) AIC_TARGET=x86_64-unknown-linux-gnu ;; *) echo "Select a supported SDK archive from the releases page"; exit 1 ;; esac curl -fL -o sdk.tar.gz "https://github.com/ai-coustics/aic-sdk-c/releases/download/0.26.0/aic-sdk-${AIC_TARGET}-0.26.0.tar.gz" mkdir sdk tar -xzf sdk.tar.gz -C sdk ``` ```powershell Windows PowerShell theme={null} # For an ARM64 build, replace x86_64 with aarch64. $AicTarget = "x86_64-pc-windows-msvc" Invoke-WebRequest "https://github.com/ai-coustics/aic-sdk-c/releases/download/0.26.0/aic-sdk-$AicTarget-0.26.0.zip" -OutFile sdk.zip Expand-Archive sdk.zip -DestinationPath sdk ``` The project must now contain `sdk/include/aic.h` and `sdk/lib/`. Choose the archive for your compiler's target architecture when cross-compiling. [Release 0.26.0](https://github.com/ai-coustics/aic-sdk-c/releases/tag/0.26.0) includes all distributions. ## Quickstart ### Prepare the key, model and input Generate an SDK key on the [developer platform](https://developers.ai-coustics.com). Set it in the terminal where you will run the program. Keep it out of source control and shared logs. ```bash macOS / Linux theme={null} export AIC_SDK_LICENSE="YOUR_SDK_KEY" curl -fL -o model.aicmodel "https://artifacts.ai-coustics.io/models/quail-vf-2-3-l-16khz/v8/quail_vf_2_3_l_16khz_5qsg9lf0_v13.aicmodel" ``` ```powershell Windows PowerShell theme={null} $env:AIC_SDK_LICENSE = "YOUR_SDK_KEY" Invoke-WebRequest "https://artifacts.ai-coustics.io/models/quail-vf-2-3-l-16khz/v8/quail_vf_2_3_l_16khz_5qsg9lf0_v13.aicmodel" -OutFile model.aicmodel ``` Replace `YOUR_SDK_KEY` with your key. This pins a format-8 build of `quail-vf-2.3-l-16khz`. Quail Voice Focus isolates the primary speaker for speech-to-text (STT) input. Downloading the model in advance does not remove SDK key authorization requirements; see [authentication](/models/get-started/authenticate-apps). Download the [noisy speech fixture](/assets/audio/noisy-speech.wav) and save it as `input.wav` in this project directory. It contains 56,080 mono PCM16 samples at 16 kHz (3.505 seconds). The [fixture guide](/guides/test-audio) includes attribution, checksums and the aligned clean reference. For your own recording, export **mono, 16 kHz, signed 16-bit PCM WAV**, at most 60 seconds long. Renaming a file does not convert it. ### Add WAV file handling The example uses [dr\_wav 0.14.4](https://github.com/mackron/dr_libs/tree/wav-0.14.4) for file I/O. Download its pinned single header into the project directory: ```bash macOS / Linux theme={null} curl -fL -o dr_wav.h "https://raw.githubusercontent.com/mackron/dr_libs/wav-0.14.4/dr_wav.h" ``` ```powershell Windows PowerShell theme={null} Invoke-WebRequest "https://raw.githubusercontent.com/mackron/dr_libs/wav-0.14.4/dr_wav.h" -OutFile dr_wav.h ``` Save this helper as `audio_file.h` alongside `dr_wav.h`. It checks input format and length, reads float samples and writes a 32-bit float WAV. ```c audio_file.h theme={null} #ifndef AUDIO_FILE_H #define AUDIO_FILE_H #define DR_WAV_IMPLEMENTATION #include "dr_wav.h" #include #include #include /* A short-file helper for this tutorial, independent of the SDK. */ static float* read_input(size_t* count) { drwav wav; if (!drwav_init_file(&wav, "input.wav", NULL)) { fprintf(stderr, "Cannot open input.wav as a WAV file.\n"); return NULL; } if (wav.channels != 1 || wav.sampleRate != 16000 || wav.translatedFormatTag != DR_WAVE_FORMAT_PCM || wav.bitsPerSample != 16 || wav.totalPCMFrameCount == 0 || wav.totalPCMFrameCount > 960000) { fprintf(stderr, "Use a nonempty mono, 16 kHz, PCM16 input.wav, at most 60 seconds.\n"); drwav_uninit(&wav); return NULL; } *count = (size_t)wav.totalPCMFrameCount; float* audio = (float*)malloc(*count * sizeof(float)); if (!audio || drwav_read_pcm_frames_f32(&wav, *count, audio) != *count) { fprintf(stderr, "Cannot read all input samples.\n"); free(audio); audio = NULL; } drwav_uninit(&wav); return audio; } static int write_output(const float* audio, size_t count) { drwav wav; drwav_data_format format = {drwav_container_riff, DR_WAVE_FORMAT_IEEE_FLOAT, 1, 16000, 32}; for (size_t i = 0; i < count; ++i) { if (!isfinite(audio[i])) { fprintf(stderr, "Non-finite output sample; no output written.\n"); return 0; } } if (!drwav_init_file_write(&wav, "enhanced.wav", &format, NULL)) { fprintf(stderr, "Cannot create enhanced.wav.\n"); return 0; } drwav_uint64 written = drwav_write_pcm_frames(&wav, count, audio); drwav_result closed = drwav_uninit(&wav); if (written != count || closed != DRWAV_SUCCESS) { fprintf(stderr, "Cannot finish enhanced.wav; discard the incomplete file.\n"); return 0; } return 1; } #endif ``` ### Save the program Save as `quickstart.c`: ```c quickstart.c theme={null} #include "aic.h" #include "audio_file.h" #include #define CHECK(call) do { \ enum AicErrorCode error = (call); \ if (error != AIC_ERROR_CODE_SUCCESS) { \ fprintf(stderr, "%s failed (SDK error %d).\n", #call, (int)error); \ goto cleanup; \ } \ } while (0) int main(void) { const char* key = getenv("AIC_SDK_LICENSE"); if (!key || !*key || strcmp(key, "YOUR_SDK_KEY") == 0) { fprintf(stderr, "Set AIC_SDK_LICENSE to your SDK key, then retry.\n"); return 1; } int status = 1; size_t count = 0, block_size = 0, delay = 0, padded_count = 0; float* input = read_input(&count); float* output = NULL; struct AicModel* model = NULL; struct AicProcessor* processor = NULL; struct AicProcessorContext* context = NULL; if (!input) goto cleanup; CHECK(aic_model_create_from_file(&model, "model.aicmodel")); CHECK(aic_model_get_optimal_block_size(model, 16000, &block_size)); CHECK(aic_processor_create(&processor, model, key, NULL)); CHECK(aic_processor_initialize(processor, 16000, block_size, false)); CHECK(aic_processor_context_create(&context, processor)); CHECK(aic_processor_context_get_audio_delay(context, &delay)); if (block_size == 0 || count > SIZE_MAX - delay || count + delay > SIZE_MAX - (block_size - 1)) { fprintf(stderr, "Audio buffer size overflow.\n"); goto cleanup; } padded_count = ((count + delay + block_size - 1) / block_size) * block_size; if (padded_count > SIZE_MAX / sizeof(float)) { fprintf(stderr, "Audio buffer size overflow.\n"); goto cleanup; } output = (float*)calloc(padded_count, sizeof(float)); if (!output) { fprintf(stderr, "Cannot allocate the processing buffer.\n"); goto cleanup; } memcpy(output, input, count * sizeof(float)); for (size_t start = 0; start < padded_count; start += block_size) { CHECK(aic_processor_process(processor, output + start, block_size)); } /* Flush with silence, then omit the initial delay to align the files. */ if (!write_output(output + delay, count)) goto cleanup; printf("SDK %s, model %s\n", aic_get_sdk_version(), aic_model_get_id(model)); printf("Processed %zu samples at 16000 Hz; wrote enhanced.wav\n", count); status = 0; cleanup: aic_processor_context_destroy(context); aic_processor_destroy(processor); aic_model_destroy(model); free(output); free(input); return status; } ``` ### Build and run Save this complete project as `CMakeLists.txt`: ```cmake CMakeLists.txt theme={null} cmake_minimum_required(VERSION 3.24) project(aic_c_quickstart LANGUAGES C) set(CMAKE_C_STANDARD 11) set(CMAKE_C_STANDARD_REQUIRED ON) add_library(aic SHARED IMPORTED) set(AIC_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/sdk") if(WIN32) set_target_properties(aic PROPERTIES IMPORTED_LOCATION "${AIC_ROOT}/lib/aic.dll" IMPORTED_IMPLIB "${AIC_ROOT}/lib/aic.dll.lib") elseif(APPLE) set_target_properties(aic PROPERTIES IMPORTED_LOCATION "${AIC_ROOT}/lib/libaic.dylib") else() set_target_properties(aic PROPERTIES IMPORTED_LOCATION "${AIC_ROOT}/lib/libaic.so") endif() set_target_properties(aic PROPERTIES INTERFACE_INCLUDE_DIRECTORIES "${AIC_ROOT}/include") add_executable(quickstart quickstart.c) target_link_libraries(quickstart PRIVATE aic) if(UNIX AND NOT APPLE) target_link_libraries(quickstart PRIVATE m) endif() if(WIN32) add_custom_command(TARGET quickstart POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy_if_different "$" "$") endif() ``` Configure and build from `aic-c-quickstart`: ```bash theme={null} cmake -S . -B build -DCMAKE_BUILD_TYPE=Release cmake --build build --config Release ``` Run from the project directory so the program can find `input.wav` and `model.aicmodel`: ```bash macOS / Linux theme={null} ./build/quickstart ``` ```powershell Windows PowerShell theme={null} .\build\Release\quickstart.exe ``` ### Check the result A successful run exits with code zero, prints the native SDK version and resolved model ID, then reports `Processed N samples at 16000 Hz; wrote enhanced.wav`, where `N` is your input's sample count (`56080` for the supplied fixture). Open `enhanced.wav` in your audio editor: it should be mono, 16 kHz and the same duration as `input.wav`. The output is a **32-bit float WAV**; the input is PCM16. The program pads the final block, flushes the delayed tail and removes the initial [processing delay](/reference/concepts/latency), preserving the original sample count. File writes are checked; discard any incomplete file if writing fails. Listen to both files and compare them with the same STT settings to evaluate quality. ### Recover from an error | Problem | Cause and retry | | - | - | | **Compiler, SDK header or library missing** | Install the compiler and check the selected archive or CMake download. Use the same target architecture for compiler and SDK. Rerun configure and build. | | **Missing SDK key or SDK error 50** | Set `AIC_SDK_LICENSE` in this terminal to the complete SDK key, then run the program again. Error 50 is an invalid license format. | | **SDK error 6 or 52** | Error 6 means processing is not allowed; error 52 means the license expired. Check account entitlement, key validity and [required connectivity](/models/get-started/authenticate-apps), then restart with a new processor. | | **Input file rejected** | Save a nonempty mono, 16 kHz, PCM16 WAV of at most 60 seconds as `input.wav`, then retry. | | **Model loading fails** | Keep `model.aicmodel` in the current directory. Re-download the exact compatible file above; error 100 means an invalid model, 101 an unsupported model version and 103 a filesystem error. | | **SDK error 5** | The block size differs from initialization. Keep every call at the configured size and pad the final block as shown. | | **Output write fails** | Check free space and write permission. Discard the incomplete `enhanced.wav`, fix the cause and retry. | The CMake build uses the shared SDK library. Keep `sdk/lib` in place for this tutorial. On Windows, it copies `aic.dll` beside the executable; keep that DLL with your application. See the [C binding guide](/reference/sdk/language-bindings/c#integration-behavior) for deployment and static linking. ### Adapt this example Keep one processor per stream and process blocks in order. Reset its context on a discontinuity or before unrelated audio. Downmix stereo or use a processor per channel. See [audio format](/reference/concepts/audio-format) and [streams and state](/reference/concepts/streams-and-state). The helper reads a short recording into memory. For long files and live audio, use bounded buffers and keep file I/O, model loading and session teardown outside the audio callback. For human-listening enhancement, evaluate [Rook Multi Speaker](/models/perceptual-speech-enhancement/rook-multi-speaker). ## Integration behavior | Concern | C SDK 0.26.0 behavior | | - | - | | **Audio buffer** | `aic_processor_process` accepts a writable contiguous buffer of mono `float` samples and modifies it in place. Use normalized float32 samples, nominally -1.0 to 1.0. | | **Errors** | Check each `AicErrorCode` before using an output handle or value. `AIC_ERROR_CODE_SUCCESS` is zero. Creation failure leaves no usable object. | | **Initialization** | Call `aic_processor_initialize` before processing. Choose the block size for the actual input rate with `aic_model_get_optimal_block_size`. The variable-block option defaults to the value your application passes; the tutorial passes `false`. | | **State** | Use one processor per stream. Context reset clears enhancement state and buffers while retaining audio configuration. Do not reset between consecutive blocks. | | **Context** | Create it with `aic_processor_context_create`. It provides parameter control, reset and delay queries. It has its own handle and must be destroyed separately. | | **Concurrency** | Do not process or destroy the same processor concurrently. Context control functions have their own thread-safety contracts in the header. Use separate processors for separate simultaneous streams. | | **Cleanup** | Destroy the context, processor and model handles when finished. The destroy functions accept `NULL`, so one cleanup path can handle partial construction. Destruction also closes the processor's session. | | **Model lifetime** | A model loaded from a file is memory-mapped. Do not alter or delete that file while any dependent object remains alive. Model data has internal reference counting; processors keep their reference when the model handle is destroyed. | Model creation, initialization and teardown allocate resources or may block. Run them outside the real-time audio callback. Keep input/output buffer storage alive throughout each synchronous processing call. ## Link and deploy The tutorial uses a shared library to keep the build configuration small. Ship the matching `libaic.so`, `libaic.dylib` or `aic.dll` with your application and configure the platform's loader path. A successful local build does not ensure a relocated application can find its library. Static archives are also available in the same [release](https://github.com/ai-coustics/aic-sdk-c/releases/tag/0.26.0). Static linking requires the platform system libraries listed in `lib/native-static-libs.txt`; on Windows, select the archive matching the MSVC runtime flavor. Follow the release's build guidance rather than mixing headers and binaries from different SDK versions. For voice activity detection (VAD) or Tyto analysis, use the dedicated VAD or analyzer APIs and their corresponding model types. An enhancement model can also report speech through [`aic_energy_vad_context_create`](/reference/sdk/api/c/vad#aic_energy_vad_context_create). See the [released examples](https://github.com/ai-coustics/aic-sdk-c/tree/0.26.0/examples). Historical examples under `docs/0.24.0` describe that release; check [compatibility](/reference/sdk/compatibility-matrix) when upgrading. # C++ Source: https://docs.ai-coustics.com/reference/sdk/language-bindings/cpp Build a C++ WAV-processing program with checked results and scoped native lifetimes. **ai-coustics** provides a C++11 wrapper around the native C SDK. This page pins the wrapper to 0.26.0 and native library to 0.26.0. Use the [C++ API reference](/reference/sdk/api/cpp/index) for types, methods, ownership and errors. ## Installation Use a C++11 compiler, Git and CMake 3.24 or later on a [supported platform](/reference/sdk/compatibility-matrix). On Windows, use a Visual Studio developer terminal with the C++ build tools installed. Create an empty project directory: ```bash theme={null} mkdir aic-cpp-quickstart cd aic-cpp-quickstart ``` The CMake project below pins the C++ wrapper to 0.26.0. On the first configure, it downloads the matching native C SDK and checks its checksum. The example links the native SDK statically; network access is needed during configuration. ## Quickstart ### Prepare the key, model and input Generate an SDK key on the [developer platform](https://developers.ai-coustics.com). Set it in the terminal where you will run the program. Keep it out of source control and shared logs. ```bash macOS / Linux theme={null} export AIC_SDK_LICENSE="YOUR_SDK_KEY" curl -fL -o model.aicmodel "https://artifacts.ai-coustics.io/models/quail-vf-2-3-l-16khz/v8/quail_vf_2_3_l_16khz_5qsg9lf0_v13.aicmodel" ``` ```powershell Windows PowerShell theme={null} $env:AIC_SDK_LICENSE = "YOUR_SDK_KEY" Invoke-WebRequest "https://artifacts.ai-coustics.io/models/quail-vf-2-3-l-16khz/v8/quail_vf_2_3_l_16khz_5qsg9lf0_v13.aicmodel" -OutFile model.aicmodel ``` Replace `YOUR_SDK_KEY` with your key. This pins a format-8 build of `quail-vf-2.3-l-16khz`. Quail Voice Focus isolates the primary speaker for speech-to-text (STT) input. Downloading the model in advance does not remove SDK key authorization requirements; see [authentication](/models/get-started/authenticate-apps). Download the [noisy speech fixture](/assets/audio/noisy-speech.wav) and save it as `input.wav` in this project directory. It contains 56,080 mono PCM16 samples at 16 kHz (3.505 seconds). The [fixture guide](/guides/test-audio) includes attribution, checksums and the aligned clean reference. For your own recording, export **mono, 16 kHz, signed 16-bit PCM WAV**, at most 60 seconds long. Renaming a file does not convert it. ### Add WAV file handling The example uses [dr\_wav 0.14.4](https://github.com/mackron/dr_libs/tree/wav-0.14.4) for file I/O. Download its pinned single header into the project directory: ```bash macOS / Linux theme={null} curl -fL -o dr_wav.h "https://raw.githubusercontent.com/mackron/dr_libs/wav-0.14.4/dr_wav.h" ``` ```powershell Windows PowerShell theme={null} Invoke-WebRequest "https://raw.githubusercontent.com/mackron/dr_libs/wav-0.14.4/dr_wav.h" -OutFile dr_wav.h ``` Save this helper as `audio_file.h` alongside `dr_wav.h`. It checks input format and length, reads float samples and writes a 32-bit float WAV. ```c audio_file.h theme={null} #ifndef AUDIO_FILE_H #define AUDIO_FILE_H #define DR_WAV_IMPLEMENTATION #include "dr_wav.h" #include #include #include /* A short-file helper for this tutorial, independent of the SDK. */ static float* read_input(size_t* count) { drwav wav; if (!drwav_init_file(&wav, "input.wav", NULL)) { fprintf(stderr, "Cannot open input.wav as a WAV file.\n"); return NULL; } if (wav.channels != 1 || wav.sampleRate != 16000 || wav.translatedFormatTag != DR_WAVE_FORMAT_PCM || wav.bitsPerSample != 16 || wav.totalPCMFrameCount == 0 || wav.totalPCMFrameCount > 960000) { fprintf(stderr, "Use a nonempty mono, 16 kHz, PCM16 input.wav, at most 60 seconds.\n"); drwav_uninit(&wav); return NULL; } *count = (size_t)wav.totalPCMFrameCount; float* audio = (float*)malloc(*count * sizeof(float)); if (!audio || drwav_read_pcm_frames_f32(&wav, *count, audio) != *count) { fprintf(stderr, "Cannot read all input samples.\n"); free(audio); audio = NULL; } drwav_uninit(&wav); return audio; } static int write_output(const float* audio, size_t count) { drwav wav; drwav_data_format format = {drwav_container_riff, DR_WAVE_FORMAT_IEEE_FLOAT, 1, 16000, 32}; for (size_t i = 0; i < count; ++i) { if (!isfinite(audio[i])) { fprintf(stderr, "Non-finite output sample; no output written.\n"); return 0; } } if (!drwav_init_file_write(&wav, "enhanced.wav", &format, NULL)) { fprintf(stderr, "Cannot create enhanced.wav.\n"); return 0; } drwav_uint64 written = drwav_write_pcm_frames(&wav, count, audio); drwav_result closed = drwav_uninit(&wav); if (written != count || closed != DRWAV_SUCCESS) { fprintf(stderr, "Cannot finish enhanced.wav; discard the incomplete file.\n"); return 0; } return 1; } #endif ``` ### Save the program Save as `quickstart.cpp`: ```cpp quickstart.cpp theme={null} #include "aic.hpp" #include "audio_file.h" #include #include #include #include #include #include #include #include static void check(aic::ErrorCode error, const char* operation) { if (error != aic::ErrorCode::Success) { throw std::runtime_error(std::string(operation) + " failed (SDK error " + std::to_string(static_cast(error)) + ")."); } } int main() { try { const char* key = std::getenv("AIC_SDK_LICENSE"); if (!key || !*key || std::strcmp(key, "YOUR_SDK_KEY") == 0) throw std::runtime_error("Set AIC_SDK_LICENSE to your SDK key, then retry."); size_t count = 0; std::unique_ptr input(read_input(&count), &std::free); if (!input) return 1; auto model_result = aic::Model::create_from_file("model.aicmodel"); check(model_result.error, "Model loading"); auto model = model_result.take(); auto processor_result = aic::Processor::create(model, key); check(processor_result.error, "Processor creation"); auto processor = processor_result.take(); const size_t block_size = model.get_optimal_block_size(16000); check(processor.initialize(16000, block_size, false), "Initialization"); auto context_result = processor.create_context(); check(context_result.error, "Context creation"); auto context = context_result.take(); const size_t delay = context.get_audio_delay(); const size_t limit = std::numeric_limits::max(); if (block_size == 0 || count > limit - delay || count + delay > limit - (block_size - 1)) throw std::runtime_error("Audio buffer size overflow."); const size_t padded_count = ((count + delay + block_size - 1) / block_size) * block_size; std::vector output(padded_count, 0.0f); std::copy(input.get(), input.get() + count, output.begin()); for (size_t start = 0; start < padded_count; start += block_size) check(processor.process(output.data() + start, block_size), "Processing"); // Flush with silence, then omit the initial delay to align the files. if (!write_output(output.data() + delay, count)) return 1; std::cout << "SDK " << aic::get_sdk_version() << ", model " << model.get_id() << '\n'; std::cout << "Processed " << count << " samples at 16000 Hz; wrote enhanced.wav\n"; // Destructors release the context, processor and model on success or error. return 0; } catch (const std::exception& error) { std::cerr << error.what() << '\n'; return 1; } } ``` ### Build and run Save this complete project as `CMakeLists.txt`: ```cmake CMakeLists.txt theme={null} cmake_minimum_required(VERSION 3.24) project(aic_cpp_quickstart LANGUAGES C CXX) include(FetchContent) set(AIC_SDK_ALLOW_DOWNLOAD ON CACHE BOOL "Download the matching C SDK") FetchContent_Declare(aic_sdk GIT_REPOSITORY https://github.com/ai-coustics/aic-sdk-cpp.git GIT_TAG 0.26.0 GIT_SHALLOW TRUE) FetchContent_MakeAvailable(aic_sdk) add_executable(quickstart quickstart.cpp) target_compile_features(quickstart PRIVATE cxx_std_11) target_link_libraries(quickstart PRIVATE aic-sdk) ``` Configure and build from `aic-cpp-quickstart`: ```bash theme={null} cmake -S . -B build -DCMAKE_BUILD_TYPE=Release cmake --build build --config Release ``` Run from the project directory so the program can find `input.wav` and `model.aicmodel`: ```bash macOS / Linux theme={null} ./build/quickstart ``` ```powershell Windows PowerShell theme={null} .\build\Release\quickstart.exe ``` ### Check the result A successful run exits with code zero, prints the native SDK version and resolved model ID, then reports `Processed N samples at 16000 Hz; wrote enhanced.wav`, where `N` is your input's sample count (`56080` for the supplied fixture). Open `enhanced.wav` in your audio editor: it should be mono, 16 kHz and the same duration as `input.wav`. The output is a **32-bit float WAV**; the input is PCM16. The program pads the final block, flushes the delayed tail and removes the initial [processing delay](/reference/concepts/latency), preserving the original sample count. File writes are checked; discard any incomplete file if writing fails. Listen to both files and compare them with the same STT settings to evaluate quality. ### Recover from an error | Problem | Cause and retry | | - | - | | **Compiler, SDK header or library missing** | Install the compiler and check the selected archive or CMake download. Use the same target architecture for compiler and SDK. Rerun configure and build. | | **Missing SDK key or SDK error 50** | Set `AIC_SDK_LICENSE` in this terminal to the complete SDK key, then run the program again. Error 50 is an invalid license format. | | **SDK error 6 or 52** | Error 6 means processing is not allowed; error 52 means the license expired. Check account entitlement, key validity and [required connectivity](/models/get-started/authenticate-apps), then restart with a new processor. | | **Input file rejected** | Save a nonempty mono, 16 kHz, PCM16 WAV of at most 60 seconds as `input.wav`, then retry. | | **Model loading fails** | Keep `model.aicmodel` in the current directory. Re-download the exact compatible file above; error 100 means an invalid model, 101 an unsupported model version and 103 a filesystem error. | | **SDK error 5** | The block size differs from initialization. Keep every call at the configured size and pad the final block as shown. | | **Output write fails** | Check free space and write permission. Discard the incomplete `enhanced.wav`, fix the cause and retry. | The helper `check` turns a failed `ErrorCode` into an exception for this application. The SDK wrapper itself returns error codes and `Result` values: calling `.take()` without checking `.error` or `.ok()` does not throw. ### Adapt this example Keep one processor per stream and process blocks in order. Reset its context on a discontinuity or before unrelated audio. Downmix stereo or use a processor per channel. See [audio format](/reference/concepts/audio-format) and [streams and state](/reference/concepts/streams-and-state). The helper reads a short recording into memory. For long files and live audio, use bounded buffers and keep file I/O, model loading and session teardown outside the audio callback. For human-listening enhancement, evaluate [Rook Multi Speaker](/models/perceptual-speech-enhancement/rook-multi-speaker). ## Integration behavior | Concern | C++ wrapper 0.26.0 behavior | | - | - | | **Error handling** | Constructors exposed as factory methods return `Result`. Check `.ok()` or `.error` before `.take()`. Initialization and processing return `ErrorCode`; they do not throw on an SDK failure. | | **Audio buffer** | `processor.process(audio, count)` modifies the writable mono float32 buffer in place. Keep the buffer valid throughout the call. | | **State** | Retain one processor per stream. Use `context.reset()` on a discontinuity or before unrelated audio; check its return code. Reset retains the audio configuration. | | **Context** | `processor.create_context()` returns a checked `Result`. The context exposes parameter control and delay in samples at the initialized rate. | | **Ownership** | Models, processors and contexts own their handles and release them in destructors. Use moves for ownership transfer; the handles are not copyable. | | **Model lifetime** | Processors retain an internal reference to the model data. The memory-mapped model file must remain unchanged while any dependent object exists. | | **Concurrency** | Sequence processing calls on one instance. Use independent processors for simultaneous streams and consult the header for each context method's thread-safety contract. | | **Session termination** | Destruction ends the session automatically. `terminate_session()` requests termination earlier; check its return code. The processor cannot continue processing after termination is handled. | The tutorial converts failed SDK results into exceptions. Use explicit error branches if your application disables exceptions. ## Build and deploy The CMake target `aic-sdk` carries its native dependency and required system libraries. `AIC_SDK_ALLOW_DOWNLOAD=ON` enables the configure-time download. To use a preinstalled distribution, supply `AIC_SDK_ROOT` with `include/` and `lib/` directories; see the [released CMake configuration](https://github.com/ai-coustics/aic-sdk-cpp/blob/0.26.0/CMakeLists.txt). Static linking is the default. `AIC_SDK_USE_STATIC=OFF` selects a shared library and makes its runtime deployment your responsibility. On Windows, match the target architecture and MSVC runtime flavor. Keep model download, object construction and teardown outside the audio callback. The [released examples](https://github.com/ai-coustics/aic-sdk-cpp/tree/0.26.0/example) cover enhancement, voice activity detection (VAD) and analysis as separate objects with different model types. See [streams and state](/reference/concepts/streams-and-state) before combining them. An enhancement processor can also report speech through [`create_energy_vad_context()`](/reference/sdk/api/cpp/processing#aic-Processor-create_energy_vad_context), without a second model. # Node.js Source: https://docs.ai-coustics.com/reference/sdk/language-bindings/nodejs Process a WAV with Node.js, then integrate synchronous or async native audio processing. **ai-coustics** Node.js bindings provide native processing with TypeScript declarations. The tutorial below uses `@ai-coustics/aic-sdk` 0.26.0. Use the [Node.js API reference](/reference/sdk/api/node/index) for classes, functions, properties and errors. See the [released examples](https://github.com/ai-coustics/aic-sdk-node/tree/0.26.0/examples). ## Installation Use Node.js 22 for this example. The package declares Node.js 18 or later; see the [compatibility matrix](/reference/sdk/compatibility-matrix) for native platform support. Create an isolated project and install the pinned SDK and WAV reader: ```bash theme={null} mkdir aic-node-quickstart cd aic-node-quickstart npm init -y npm install --save-exact @ai-coustics/aic-sdk@0.26.0 wavefile@11.0.0 ``` ## Quickstart ### Prepare the key and input Generate an SDK key on the [developer platform](https://developers.ai-coustics.com). Set it in the terminal where you will run the example, replacing `YOUR_SDK_KEY` with your key. Keep it out of source control and shared terminal logs. ```bash macOS / Linux theme={null} export AIC_SDK_LICENSE="YOUR_SDK_KEY" ``` ```powershell Windows PowerShell theme={null} $env:AIC_SDK_LICENSE = "YOUR_SDK_KEY" ``` Download the [noisy speech fixture](/assets/audio/noisy-speech.wav) and save it as `input.wav` in `aic-node-quickstart`. It contains 56,080 mono PCM16 samples at 16 kHz (3.505 seconds). The [fixture guide](/guides/test-audio) includes attribution, checksums and the aligned clean reference. For your own recording, export a short sentence with background noise as **mono, 16 kHz, signed 16-bit PCM WAV**. Renaming a file does not convert it. The example downloads `quail-vf-2.3-l-16khz` into `./models`. Quail Voice Focus isolates the primary speaker for speech-to-text (STT) input. The first run needs network access for the model download and SDK key authorization. See [authentication](/models/get-started/authenticate-apps) for deployment options. ### Save and run Save this complete program as `quickstart.cjs`. The `.cjs` extension makes its CommonJS module format explicit, including in projects that use `"type": "module"`. ```javascript quickstart.cjs theme={null} const fs = require("node:fs"); const { WaveFile } = require("wavefile"); const { Model, ProcessorAsync, getVersion } = require("@ai-coustics/aic-sdk"); async function main() { const licenseKey = process.env.AIC_SDK_LICENSE; if (!licenseKey || licenseKey === "YOUR_SDK_KEY") { throw new Error("Set AIC_SDK_LICENSE to your SDK key, then retry."); } const input = new WaveFile(fs.readFileSync("input.wav")); if (input.fmt.numChannels !== 1 || input.fmt.sampleRate !== 16000 || input.bitDepth !== "16") { throw new Error("Export input.wav as mono, 16 kHz, 16-bit PCM WAV, then retry."); } if (input.data.samples.length !== input.data.chunkSize) { throw new Error("input.wav is truncated. Export the complete recording, then retry."); } input.toBitDepth("32f"); const audio = input.getSamples(false, Float32Array); if (audio.length === 0) { throw new Error("input.wav is empty. Record speech, then retry."); } const modelPath = await Model.download("quail-vf-2.3-l-16khz", "./models"); const model = Model.fromFile(modelPath); let processor; try { const blockSize = model.getOptimalBlockSize(16000); processor = new ProcessorAsync(model, licenseKey); await processor.initialize(16000, blockSize, false); const context = await processor.getContext(); const delay = context.getAudioDelay(); // Pad the last block and flush the delayed tail with silence. const paddedSize = Math.ceil((audio.length + delay) / blockSize) * blockSize; const padded = new Float32Array(paddedSize); padded.set(audio); const output = new Float32Array(paddedSize); for (let start = 0; start < paddedSize; start += blockSize) { // Await each block to preserve stream order. Async processing returns a new array. const enhanced = await processor.process(padded.subarray(start, start + blockSize)); output.set(enhanced, start); } const enhanced = output.subarray(delay, delay + audio.length); if (!enhanced.every(Number.isFinite)) { throw new Error("Processing returned non-finite samples; no output was written."); } const pcm = Int16Array.from(enhanced, (sample) => Math.trunc(Math.max(-1, Math.min(32767 / 32768, sample)) * 32768) ); const result = new WaveFile(); result.fromScratch(1, 16000, "16", pcm); fs.writeFileSync("enhanced.wav", result.toBuffer()); console.log(`SDK ${getVersion()}, model ${model.getId()}`); console.log(`Processed ${audio.length} samples at 16000 Hz; wrote enhanced.wav`); } finally { // All processing promises above have settled before native resources are released. if (processor) processor.dispose(); model.dispose(); } } main().catch((error) => { console.error(`Error: ${error.message}`); process.exitCode = 1; }); ``` Run it from `aic-node-quickstart`: ```bash theme={null} node quickstart.cjs ``` ### Check the result The program prints the native SDK version, resolved model ID and processed sample count. It writes `enhanced.wav` beside `input.wav` at 16 kHz with the same sample count, compensating for [processing delay](/reference/concepts/latency). With the supplied fixture, the processed sample count is `56080`. Verify the file headers: ```bash theme={null} node -e "const fs=require('node:fs'); const {WaveFile}=require('wavefile'); const a=new WaveFile(fs.readFileSync('input.wav')); const b=new WaveFile(fs.readFileSync('enhanced.wav')); for (const k of ['numChannels','sampleRate','bitsPerSample']) if(a.fmt[k]!==b.fmt[k]) throw Error(k+' differs'); if(a.getSamples().length!==b.getSamples().length) throw Error('sample count differs'); console.log('PASS: matching channels, bit depth, sample rate and frame count');" ``` Listen to both recordings and compare them with the same STT settings to evaluate quality. ### Recover from an error | Problem | Cause and retry | | - | - | | **Native module cannot load** | Check `node --version` and your OS/architecture against the [compatibility matrix](/reference/sdk/compatibility-matrix). Install in the target environment with optional dependencies enabled, then rerun `node quickstart.cjs`. | | **Missing or invalid SDK key** | Set `AIC_SDK_LICENSE` in this terminal to the complete SDK key from the developer platform, then retry. | | **Processing is not allowed** | Check key validity, account entitlement and required connectivity in [authentication](/models/get-started/authenticate-apps). Correct the cause and restart the program with a new processor. | | **Missing or invalid `input.wav`** | Save a nonempty mono, 16 kHz, signed 16-bit PCM WAV in the current directory, then rerun the program. | | **Model download or load fails** | Check connectivity, write access to `./models` and the exact model ID. For manual model files, check the [model format version](/reference/sdk/compatibility-matrix). Retry the download after fixing the cause. | | **Audio configuration mismatch** | Keep every call at `blockSize` samples. The example pads the final block; do not pass a short final slice with fixed block sizes. | ### Adapt this example Use one processor per independent stream and await each operation before submitting the next block. Use separate processors for simultaneous streams; `Promise.all` over blocks from one stream can reorder processing. Downmix stereo input or give each channel its own processor. See [audio format](/reference/concepts/audio-format), [streams and state](/reference/concepts/streams-and-state) and the [Node.js binding guide](/reference/sdk/language-bindings/nodejs#integration-behavior). This example reads the full file into memory and uses synchronous file I/O. For live audio or long files, process bounded blocks and keep file I/O and model downloads outside the audio path. For human listening, evaluate [Rook Multi Speaker](/models/perceptual-speech-enhancement/rook-multi-speaker). ## Integration behavior | Concern | Node.js 0.26.0 behavior | | - | - | | **Synchronous processing** | `Processor.process(audio)` accepts a mono `Float32Array`, modifies it in place and returns `void`. Use normalized samples, nominally -1.0 to 1.0. It runs on the calling thread. | | **Async processing** | `await ProcessorAsync.process(audio)` returns a new `Float32Array`; it copies the input before queuing work and leaves that input unchanged. Await `initialize` and `getContext` as well. | | **Ordering** | Await each operation before the next block on the same processor. Concurrent calls are not guaranteed to execute in submission order. Use one instance per stream. | | **Initialization** | Construct the processor, then call `initialize(sampleRate, blockSize, false)`. Obtain the optimal block size for the actual input rate with `model.getOptimalBlockSize(sampleRate)`. | | **Block size** | Every call contains exactly `blockSize` samples by default. Setting the third initialization argument to `true` allows shorter blocks with additional buffering delay. Larger blocks are rejected. | | **State and parameters** | The context exposes `reset`, `setParameter`, `getParameter` and `getAudioDelay`. Reset on a discontinuity or before unrelated audio; reset preserves audio settings. | | **Worker configuration** | Async work uses Node's shared libuv thread pool. Set `UV_THREADPOOL_SIZE` before Node starts if your measurements justify it. `AIC_NUM_THREADS` does not configure these bindings. | | **Cleanup** | Use `dispose()` in `finally` to release native resources. Await outstanding operations first. Async processor disposal is synchronous and may block while a worker holds the instance lock. | | **Model lifetime** | Multiple independent processors can share a model. `Model.fromFile` memory-maps its file; do not modify or delete that file while any dependent object is alive. | The package includes TypeScript declarations and is distributed as CommonJS. The `.cjs` tutorial runs independently of your project's `type` setting. Keep the generated lockfile and install dependencies on the deployment platform so npm selects the matching native package. `terminateSession()` requests session termination but does not replace `dispose()` for deterministic native cleanup. Once termination is handled, processing is no longer allowed. Disposal is idempotent; other methods fail after disposal. Context handles are independent objects, but a retained context no longer controls a live processor after that processor is disposed. For voice activity detection (VAD), use `Vad` or `VadAsync` with a dedicated VAD model. Feed original input to VAD before synchronous enhancement modifies it. See the [VAD example](https://github.com/ai-coustics/aic-sdk-node/blob/0.26.0/examples/vad.js). To read speech decisions from the enhancement processor itself, without a second model, use [`getEnergyVadContext()`](/reference/sdk/api/node/enhancement#node-processor-getenergyvadcontext). For Tyto analysis, use `Analyzer`, which buffers input separately from enhancement. ## Handle SDK errors Synchronous operations throw JavaScript errors; asynchronous operations reject promises. Catch failures around model loading, initialization and processing. The error message distinguishes causes such as invalid credentials, unsupported models and an audio configuration mismatch. Never treat a rejected processing promise as enhanced output. Correct the cause before retrying: use the exact model ID with `Model.download`, keep input blocks consistent with initialization and check [authentication](/models/get-started/authenticate-apps) when processing is not allowed. SDK construction and `dispose()` are synchronous even when you use `ProcessorAsync`; keep lifecycle work outside the audio callback. # Python Source: https://docs.ai-coustics.com/reference/sdk/language-bindings/python Process a WAV with Python, then adapt the SDK to synchronous or async audio streams. **ai-coustics** Python bindings accept NumPy audio arrays. The tutorial below uses `aic-sdk` 3.4.0, which wraps native SDK 0.26.0. Use the [Python API reference](/reference/sdk/api/python/index) for classes, functions, properties and errors. See the [released examples](https://github.com/ai-coustics/aic-sdk-py/tree/3.4.0/examples). ## Installation Use Python 3.11 for this example on a [supported platform](/reference/sdk/compatibility-matrix). The SDK package declares Python 3.10 or later. This example pins `aic-sdk` 3.4.0 and NumPy 2.2.6. Create a project directory and a virtual environment: ```bash macOS / Linux theme={null} mkdir aic-python-quickstart cd aic-python-quickstart python3 -m venv .venv source .venv/bin/activate python -m pip install "aic-sdk==3.4.0" "numpy==2.2.6" ``` ```powershell Windows PowerShell theme={null} mkdir aic-python-quickstart cd aic-python-quickstart py -m venv .venv .venv\Scripts\Activate.ps1 python -m pip install "aic-sdk==3.4.0" "numpy==2.2.6" ``` ## Quickstart ### Prepare the key and input Generate an SDK key on the [developer platform](https://developers.ai-coustics.com). Set it in the terminal where you will run the example, replacing `YOUR_SDK_KEY` with your key. Keep it out of source control and shared terminal logs. ```bash macOS / Linux theme={null} export AIC_SDK_LICENSE="YOUR_SDK_KEY" ``` ```powershell Windows PowerShell theme={null} $env:AIC_SDK_LICENSE = "YOUR_SDK_KEY" ``` Download the [noisy speech fixture](/assets/audio/noisy-speech.wav) and save it as `input.wav` in `aic-python-quickstart`. It contains 56,080 mono PCM16 samples at 16 kHz (3.505 seconds). The [fixture guide](/guides/test-audio) includes attribution, checksums and the aligned clean reference. For your own recording, export a short sentence with background noise as **mono, 16 kHz, signed 16-bit PCM WAV**. Renaming a file does not convert it. The example downloads `quail-vf-2.3-l-16khz` into `./models`. Quail Voice Focus isolates the primary speaker for speech-to-text (STT) input. The first run needs network access for the model download and SDK key authorization. See [authentication](/models/get-started/authenticate-apps) for deployment options. ### Save and run Save this complete program as `quickstart.py` in the same directory: ```python quickstart.py theme={null} import os from pathlib import Path import sys import wave import aic_sdk as aic import numpy as np def main(): license_key = os.environ.get("AIC_SDK_LICENSE") if not license_key or license_key == "YOUR_SDK_KEY": raise ValueError("Set AIC_SDK_LICENSE to your SDK key, then retry.") with wave.open("input.wav", "rb") as source: if (source.getnchannels(), source.getframerate(), source.getsampwidth()) != (1, 16000, 2): raise ValueError("Export input.wav as mono, 16 kHz, 16-bit PCM WAV, then retry.") frames = source.getnframes() raw = source.readframes(frames) if len(raw) != frames * 2: raise ValueError("input.wav is truncated. Export the complete recording, then retry.") audio = np.frombuffer(raw, dtype=" Result<(), Box> { let key = std::env::var("AIC_SDK_LICENSE") .map_err(|_| "Set AIC_SDK_LICENSE to your SDK key, then retry.")?; if key.is_empty() || key == "YOUR_SDK_KEY" { return Err("Set AIC_SDK_LICENSE to your SDK key, then retry.".into()); } let mut reader = WavReader::open("input.wav")?; let spec = reader.spec(); if spec.channels != 1 || spec.sample_rate != 16000 || spec.bits_per_sample != 16 || spec.sample_format != SampleFormat::Int || reader.duration() == 0 || reader.duration() > 960000 { return Err("Use a nonempty mono, 16 kHz, PCM16 input.wav, at most 60 seconds.".into()); } let input: Vec = reader.samples::() .map(|sample| sample.map(|value| value as f32 / 32768.0)) .collect::>()?; let model = Model::from_file("model.aicmodel")?; let config = ProcessorConfig { sample_rate: 16000, block_size: model.optimal_block_size(16000), variable_block_size: false, }; let mut processor = Processor::new(&model, &key)?.with_config(&config)?; let delay = processor.context().audio_delay(); let padded_count = input.len().checked_add(delay) .and_then(|n| n.checked_add(config.block_size - 1)) .ok_or("Audio buffer size overflow")? / config.block_size * config.block_size; let mut output = vec![0.0_f32; padded_count]; output[..input.len()].copy_from_slice(&input); for block in output.chunks_exact_mut(config.block_size) { processor.process(block)?; } // Flush with silence, then omit the initial delay to align the files. let enhanced = &output[delay..delay + input.len()]; if enhanced.iter().any(|sample| !sample.is_finite()) { return Err("Non-finite output sample; no output written.".into()); } let mut writer = WavWriter::create("enhanced.wav", WavSpec { channels: 1, sample_rate: 16000, bits_per_sample: 32, sample_format: SampleFormat::Float, })?; for &sample in enhanced { writer.write_sample(sample)?; } writer.finalize()?; println!("SDK {}, model {}", aic_sdk::get_sdk_version(), model.id()); println!("Processed {} samples at 16000 Hz; wrote enhanced.wav", input.len()); // Drop releases the processor and ends its session, including on an error return. Ok(()) } fn main() { if let Err(error) = run() { eprintln!("{error}"); std::process::exit(1); } } ``` Build and run from `aic-rust-quickstart`: ```bash theme={null} cargo run --release ``` The program propagates SDK and file errors with `?`. Rust drops the processor and model on a normal return or an error return from `run`, releasing native resources. ### Check the result A successful run exits with code zero, prints the native SDK version and resolved model ID, then reports `Processed N samples at 16000 Hz; wrote enhanced.wav`, where `N` is your input's sample count (`56080` for the supplied fixture). Open `enhanced.wav` in your audio editor: it should be mono, 16 kHz and the same duration as `input.wav`. The output is a **32-bit float WAV**; the input is PCM16. The program pads the final block, flushes the delayed tail and removes the initial [processing delay](/reference/concepts/latency), preserving the original sample count. File writes are checked; discard any incomplete file if writing fails. Listen to both files and compare them with the same STT settings to evaluate quality. ### Recover from an error | Problem | Cause and retry | | - | - | | **Build cannot find libclang or a linker** | Install the platform compiler tools and libclang. Set `LIBCLANG_PATH` to your libclang library directory if discovery fails, then rerun `cargo build --release`. | | **Native library download fails** | Check network access and target platform. For a preinstalled SDK, use `AIC_LIB_PATH` as described in the [linking guide](https://docs.rs/aic-sdk/0.25.2/aic_sdk/docs/linking/index.html). | | **Missing or invalid SDK key** | Set `AIC_SDK_LICENSE` in this terminal to the complete SDK key, then rerun `cargo run --release`. | | **Processing is not allowed or the key expired** | Check key validity, entitlement and [required connectivity](/models/get-started/authenticate-apps). Correct the cause and restart the program. | | **Input file rejected** | Save a nonempty mono, 16 kHz, PCM16 WAV of at most 60 seconds as `input.wav`, then retry. | | **Model loading fails** | Run from the project directory containing `model.aicmodel`. Re-download the exact file above for SDK 0.25.2. | | **Audio configuration mismatch** | Keep each `process` call at `config.block_size` samples. The example pads the final block before processing. | | **Output write fails** | Check free space and write permission. Discard the incomplete output, correct the cause and retry. | ### Adapt this example Keep one processor per stream and process blocks in order. Reset its context on a discontinuity or before unrelated audio. Downmix stereo or use a processor per channel. See [audio format](/reference/concepts/audio-format) and [streams and state](/reference/concepts/streams-and-state). The helper reads a short recording into memory. For long files and live audio, use bounded buffers and keep file I/O, model loading and session teardown outside the audio callback. For human-listening enhancement, evaluate [Rook Multi Speaker](/models/perceptual-speech-enhancement/rook-multi-speaker). ## Integration behavior | Concern | Rust crate 0.25.2 behavior | | - | - | | **Input and output** | `Processor::process(&mut [f32])` enhances a mono sample slice in place. Samples are normalized float32 values, nominally -1.0 to 1.0. | | **Initialization** | Build a `ProcessorConfig`, then call `initialize` or use `with_config`. Both return a `Result`; use `?` or handle the error before processing. | | **Block size** | Fixed-size processing requires exactly `config.block_size` samples per call. `variable_block_size: true` permits shorter calls, with additional buffering delay. Larger blocks are rejected. | | **State and control** | Keep one processor per stream. `processor.context()` returns a control handle with parameter access, `audio_delay()` and `reset()`. Reset clears stream state while retaining configuration. | | **Ownership** | Rust drops processor and model handles when their owners leave scope, including error returns. A file-backed model must remain unchanged on disk while its dependent objects are alive. | | **Session termination** | Stop submitting audio before calling `terminate_session()`. It requests termination and returns a `Result`; processing may be disabled after the call returns. `Drop` releases the native object automatically. | | **Model loading** | `Model::from_file` loads a runtime file. `include_model!` embeds aligned model data at compile time for `Model::from_buffer`. The embedded file must exist at build time. | | **Async option** | The `async` feature enables async processing types. Await each operation on a stream before submitting the next block. Use separate instances for independent streams. | ## Select crate features | Feature | Purpose | | - | - | | **`download-lib`** | Fetch the matching prebuilt native library during the build. Without it, provide a local library with `AIC_LIB_PATH`. | | **`download-model`** | Enable `Model::download` for runtime model provisioning. The tutorial uses an explicit model file and does not need this feature. | | **`async`** | Enable async wrappers and their processing worker pool. | | **`dynamic-linking`** | Link against the native shared library at build time. Deploy that library with your application. | | **`runtime-linking`** | Load a native shared library at runtime. Configure its location as described in the released linking guide. | Static linking is the default. Select one linking strategy deliberately; Cargo features are additive. See the [linking guide](https://docs.rs/aic-sdk/0.25.2/aic_sdk/docs/linking/index.html), [integration guide](https://docs.rs/aic-sdk/0.25.2/aic_sdk/docs/guide/index.html) and [examples](https://docs.rs/aic-sdk/0.25.2/aic_sdk/docs/examples/index.html) for detailed configuration, async behavior and model embedding. For voice activity detection (VAD) or Tyto analysis, use the dedicated types and matching models. An enhancement processor can also report speech through [`energy_vad_context()`](/reference/sdk/api/rust/enhancement#rust-aic_sdk-Processor-energy_vad_context), without a second model. Keep initialization, model loading and teardown outside the real-time audio callback, and follow [streams and state](/reference/concepts/streams-and-state) for interruptions and concurrency. # WebAssembly Source: https://docs.ai-coustics.com/reference/sdk/language-bindings/wasm Process browser audio with the released WASM package and keep SDK keys on your backend. The **WebAssembly binding** runs models in the browser. This guide uses [npm package 0.26.0](https://www.npmjs.com/package/@ai-coustics/aic-sdk-wasm/v/0.26.0). Use the [WebAssembly API reference](/reference/sdk/api/wasm/index) for initialization, classes and resource cleanup. The package includes the released `aic_sdk_wasm.d.ts` type declarations. Use the [compatibility matrix](/reference/sdk/compatibility-matrix) when selecting models and upgrading. | API | Contract in 0.26.0 | | - | - | | `init()` | Asynchronously loads the WASM module before SDK calls | | `Model.fromBytes(bytes)` | Loads a compatible model from a `Uint8Array` | | `Processor.process(frame)` | Synchronous, in-place mono enhancement | | `getContext()` | Returns controls for delay, reset, parameters and JWT refresh | | `terminateSession()` and `free()` | End session activity and release owned WASM resources | The package also exports dedicated `Vad` and `Analyzer` APIs. Feed VAD the original input; do not infer that another binding's async or telemetry configuration API exists in WASM. An enhancement processor can also report speech through [`getEnergyVadContext()`](/reference/sdk/api/wasm/enhancement#wasm-processor-getenergyvadcontext), without a second model. See [authentication](/models/get-started/authenticate-apps) and [streams and state](/reference/concepts/streams-and-state). ## Installation Use `@ai-coustics/aic-sdk-wasm` **0.26.0**, Node.js 22 or later for the local token server and a browser with WebAssembly SIMD support. This example processes a local recording into a mono WAV; it does not use an AudioWorklet or microphone pipeline. Download the [noisy speech fixture](/guides/test-audio), or use a short recording you have permission to process, exported as mono PCM16 WAV at 16 kHz. The example accepts up to 60 seconds. Create an SDK key in the [developer platform](https://developers.ai-coustics.com) and put it in the server's `AIC_SDK_LICENSE` environment variable. Do not put the key into HTML, browser storage or client configuration. ```bash theme={null} mkdir aic-wasm-example cd aic-wasm-example npm init -y npm install --save-exact @ai-coustics/aic-sdk-wasm@0.26.0 curl --fail --location \ 'https://artifacts.ai-coustics.io/models/quail-vf-2-3-s-16khz/v8/quail_vf_2_3_s_16khz_398hl32w_v12.aicmodel' \ --output model.aicmodel ``` Set the server credential in this terminal without putting it in shell history: ```bash theme={null} read -r -s AIC_SDK_LICENSE export AIC_SDK_LICENSE ``` Paste your SDK key at the hidden prompt and press Enter. The key remains on the server; the browser receives a short-lived JSON Web Token (JWT). ## Quickstart ### Create the local token server Save the following as `server.mjs`. This server binds to loopback and serves only the listed files. The token endpoint checks the request origin and returns no cached credentials. It decodes the SDK key on the server using the [documented token flow](/models/get-started/authenticate-apps). > [!WARNING] > > This is a local development server. Before production, replace it with an HTTPS backend that authenticates users, authorizes SDK access and enforces rate and usage limits. Never expose this demo server on a public interface. ```javascript server.mjs theme={null} import http from 'node:http'; import { readFile } from 'node:fs/promises'; const origin = 'http://127.0.0.1:4173'; const sdkKey = process.env.AIC_SDK_LICENSE; if (!sdkKey) throw new Error('Set AIC_SDK_LICENSE in the server environment.'); const files = new Map([ ['/', ['index.html', 'text/html']], ['/sdk.js', ['node_modules/@ai-coustics/aic-sdk-wasm/aic_sdk_wasm.js', 'text/javascript']], ['/aic_sdk_wasm_bg.wasm', ['node_modules/@ai-coustics/aic-sdk-wasm/aic_sdk_wasm_bg.wasm', 'application/wasm']], ['/model.aicmodel', ['model.aicmodel', 'application/octet-stream']], ]); const server = http.createServer(async (req, res) => { res.setHeader('Cache-Control', 'no-store'); res.setHeader('X-Content-Type-Options', 'nosniff'); if (req.headers.host !== '127.0.0.1:4173') { res.writeHead(403).end('Use the loopback URL printed by the server.'); return; } if (req.url === '/session-token' && req.method === 'POST') { // This is a local-only demo. Production needs authenticated users and quotas. if (req.headers.origin !== origin || req.headers['x-aic-demo'] !== '1') { res.writeHead(403).end('Same-origin demo request required.'); return; } try { const payload = JSON.parse(Buffer.from(sdkKey.split('.')[0], 'base64').toString()); if (typeof payload.api_key !== 'string') throw new Error('Invalid SDK key'); const basic = Buffer.from(`${payload.api_key}:`).toString('base64'); const response = await fetch('https://api.ai-coustics.io/v1/sdk/tokens', { method: 'POST', headers: { Authorization: `Basic ${basic}` }, signal: AbortSignal.timeout(10000), }); if (!response.ok) throw new Error('Token request rejected'); const { token } = await response.json(); if (typeof token !== 'string') throw new Error('Missing token'); const { exp } = JSON.parse(Buffer.from(token.split('.')[1], 'base64url').toString()); if (!Number.isFinite(exp) || exp * 1000 <= Date.now() + 120000) { throw new Error('Token lifetime is too short for this demo'); } res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ token })); } catch { // Do not log credentials or return upstream response bodies. res.writeHead(502).end('Token request failed. Check the server key and connectivity.'); } return; } const file = files.get(req.url); if (req.method !== 'GET' || !file) { res.writeHead(404).end('Not found'); return; } try { const bytes = await readFile(new URL(file[0], import.meta.url)); res.writeHead(200, { 'Content-Type': file[1] }).end(bytes); } catch { res.writeHead(404).end('File missing. Check installation and model download.'); } }); server.listen(4173, '127.0.0.1', () => console.log(`Open ${origin}`)); ``` ### Create the browser page Save this as `index.html` beside `server.mjs`. Audio stays in browser memory. The page loads the WASM module and model, requests a token, processes complete frames, pads the tail and removes the reported delay before creating the output file. Session authorization and usage reporting still require network access. ```html index.html theme={null} ai-coustics WASM file example

Enhance a short recording

Select a mono, 16 kHz, PCM16 WAV with speech (up to 60 seconds).

Ready.

``` ### Run and check the result ```bash theme={null} node server.mjs ``` Open `http://127.0.0.1:4173`, select your recording and choose **Enhance**. On success, the page displays the number of processed samples and SDK version and exposes **Download enhanced.wav**. The output has the same sample count as the input, one channel and a 16 kHz sample rate. Compare both files to evaluate quality for your task. Each recording uses a fresh token with at least two minutes of remaining validity. Processing stops after one minute of wall time. These are demo bounds, not SDK limits. Stop the server with Ctrl+C, then run `unset AIC_SDK_LICENSE`. ## Recover from an error | Problem | Cause and retry | | - | - | | Server asks for `AIC_SDK_LICENSE` | Set the key in the server's terminal and restart it. | | Module or model file is missing | Run the installation/download commands in the same directory as `server.mjs`. | | Browser cannot compile WASM | Use a browser with WebAssembly SIMD support and verify that the `.wasm` response is served as `application/wasm`. | | Token unavailable | Check the server key, token-service connectivity and whether the credential can mint a JWT. Do not copy a long-lived key into the browser as a workaround. | | `ProcessingNotAllowed` | Check activation connectivity, credential expiry and authorization. Correct the cause and retry with a fresh token. Do not treat a stopped or bypassed run as enhancement. | | Invalid WAV or empty input | Export nonempty mono PCM16 audio at 16 kHz and select the corrected file. | | Timeout | Try a shorter recording and measure your target device's processing budget before a live integration. | ## Adapt this example Use one processor per independent audio stream. `Processor.process()` mutates its `Float32Array` in place and runs synchronously. Move sustained processing off the main UI thread and design buffering around the [audio format](/reference/concepts/audio-format) and [latency](/reference/concepts/latency) contracts. For a long-running stream, refresh a JWT through your authenticated backend before expiry and update the existing context: ```javascript theme={null} // context came from processor.getContext(). // freshToken came from your authenticated backend. context.updateBearerToken(freshToken); ``` Both the original and replacement credentials must be JWTs. A successful local update does not prove backend acceptance; handle subsequent processing errors. Keep only the current short-lived token in memory. Never log it or save it to local storage. At shutdown, free the context and model, terminate the session and free the processor as shown above. # Models Source: https://docs.ai-coustics.com/reference/sdk/models Choose a model by task and verify model IDs, native audio geometry and SDK compatibility. **ai-coustics** provides enhancement, voice activity detection and audio analysis models. Choose the task first, then compare the available variants with your audio and target hardware. ## Choose by task | Task | Model family | What to evaluate | | - | - | - | | Preserve multiple speakers for speech-to-text | Quail | Word error rate, speech retention and resource use. | | Isolate one primary speaker for a voice agent | Quail Voice Focus | Target-word deletions, background-word insertions and speaker changes. | | Improve audio for human listeners | Rook | Naturalness, intelligibility, artifacts and latency. | | Detect speech activity without modifying audio | ai-coustics VAD | False starts, missed speech and prediction delay. | | Assess audio quality | Tyto | Risk scores and quality dimensions against observed call outcomes. | This catalog covers model file format 8 for core SDK 0.26.0. Packages on core SDK 0.25.2 load format 7 files of the same IDs. For Quail Voice Focus, VAD Voice Focus and Tyto, they use the IDs that [deprecated models](/models/older-models/deprecated-models) lists with last supported core SDK 0.25.2. Match your package in the [compatibility matrix](/reference/sdk/compatibility-matrix). A download ID selects a compatible artifact; the loaded model's ID can also include its build identifier. Record both when reproducing an evaluation. Sizes are approximate decimal MB of model files, not runtime memory. Native rate and optimal block size describe model geometry, not end-to-end latency. > [!NOTE] > > These models process audio rather than a language-specific transcription vocabulary. That does not establish equal quality for every language or acoustic condition. Evaluate the languages and microphones your application supports. Streaming enhancement and VAD support non-native sample rates through the SDK; analysis has separate requirements described below. ## Quail Multi Speaker [Quail Multi Speaker](/models/speech-enhancement/quail-multi-speaker) targets machine listening while retaining speech from multiple participants. Use it when every speaker matters, then compare transcription results and speech retention. It is not a primary-speaker selector. | Model ID | Artifact size | Native sample rate | Optimal native block | | - | - | - | - | | `quail-ms-l-16khz` | 18.80 MB | 16 kHz | 160 samples (10 ms) | | `quail-ms-l-8khz` | 17.93 MB | 8 kHz | 80 samples (10 ms) | | `quail-ms-s-16khz` | 4.81 MB | 16 kHz | 160 samples (10 ms) | | `quail-ms-s-8khz` | 4.56 MB | 8 kHz | 80 samples (10 ms) | ## Quail Voice Focus [Quail Voice Focus](/models/voice-focus/quail-voice-focus) targets one primary speaker for machine listening. Evaluate competing speech, quiet target speech, startup context and changes in speaker prominence. | Model ID | Artifact size | Native sample rate | Optimal native block | | - | - | - | - | | `quail-vf-2.3-l-16khz` | 11.32 MB | 16 kHz | 240 samples (15 ms) | | `quail-vf-2.3-s-16khz` | 2.77 MB | 16 kHz | 240 samples (15 ms) | ## VAD Multi Speaker [VAD Multi Speaker](/models/voice-activity-detection/vad-multi-speaker) detects speech activity from the original audio without producing enhanced audio. Use it when activity from any speaker should count. | Model ID | Artifact size | Native sample rate | Optimal native block | | - | - | - | - | | `vad-ms-2.1-xxs-16khz` | 0.66 MB | 16 kHz | 240 samples (15 ms) | Earlier model IDs include `quail-vad-2.0-xxs-16khz` and `vad-2.1-xxs-16khz`. See [renamed models](/models/older-models/model-naming-changes) before changing an existing deployment. ## VAD Voice Focus [VAD Voice Focus](/models/voice-activity-detection/vad-voice-focus) targets primary-speaker activity. It is a dedicated VAD model, distinct from the Quail Voice Focus enhancement models. | Model ID | Artifact size | Native sample rate | Optimal native block | | - | - | - | - | | `vad-vf-2.1-s-16khz` | 0.81 MB | 16 kHz | 240 samples (15 ms) | Earlier IDs `vad-vf-2.0-s-16khz` and `quail-vf-vad-2.0-s-16khz` are listed in [deprecated models](/models/older-models/deprecated-models#vad-voice-focus). ## Tyto [Tyto](/models/audio-insight/tyto) provides audio-quality analysis. It returns scores rather than enhanced audio or speech-boundary events. Use its 16 kHz analysis path and follow the [real-time](/models/audio-insight/real-time-analysis) or [batch](/models/audio-insight/batch-call-analysis) guide for analysis windows and result interpretation. | Model ID | Artifact size | Native sample rate | Analysis window | | - | - | - | - | | `tyto-1.2-l-16khz` | 13.33 MB | 16 kHz | 5 s | ## Rook Multi Speaker [Rook Multi Speaker](/models/perceptual-speech-enhancement/rook-multi-speaker) targets naturalness and intelligibility for human listeners while retaining multiple speakers. Compare variants using listening tests as well as resource and latency measurements. | Model ID | Artifact size | Native sample rate | Optimal native block | | - | - | - | - | | `rook-ms-l-48khz` | 18.88 MB | 48 kHz | 480 samples (10 ms) | | `rook-ms-l-16khz` | 18.80 MB | 16 kHz | 160 samples (10 ms) | | `rook-ms-l-8khz` | 17.93 MB | 8 kHz | 80 samples (10 ms) | | `rook-ms-s-48khz` | 4.89 MB | 48 kHz | 480 samples (10 ms) | | `rook-ms-s-16khz` | 4.81 MB | 16 kHz | 160 samples (10 ms) | | `rook-ms-s-8khz` | 4.56 MB | 8 kHz | 80 samples (10 ms) | ## Download a model Browse the [public model catalog](https://artifacts.ai-coustics.io/) or use your binding's downloader. It chooses a model-file version compatible with that SDK. Use the returned path; downloaded filenames can include a build identifier. ```python Python SDK 3.4.0 theme={null} from aic_sdk import Model path = Model.download("quail-vf-2.3-l-16khz", "models") model = Model.from_file(path) print(model.get_id()) ``` ```javascript Node.js SDK 0.26.0 theme={null} import { Model } from "@ai-coustics/aic-sdk"; const path = await Model.download("quail-vf-2.3-l-16khz", "models"); const model = Model.fromFile(path); console.log(model.getId()); ``` Before handling audio, provision models and record the SDK version, requested and resolved model IDs and artifact checksum. Keep loaded files unchanged. SDK authentication is still required. ## Loading and reusing models A loaded model is its own object, separate from the processor, VAD or analyzer that runs it. Each model type belongs to exactly one kind of object, and a mismatch fails when you create that object rather than when you process audio: | Model type | Used by | Error on mismatch | | - | - | - | | Enhancement and bypass | `Processor` | `ModelTypeUnsupportedError` / `AIC_ERROR_CODE_MODEL_TYPE_UNSUPPORTED` | | VAD | `Vad` | `ModelTypeUnsupportedError` / `AIC_ERROR_CODE_MODEL_TYPE_UNSUPPORTED` | | Analysis | `Analyzer` and `FileAnalyzer` | `ModelTypeUnsupportedError` / `AIC_ERROR_CODE_MODEL_TYPE_UNSUPPORTED` | ### One model, many streams Share one loaded model across independent processors, VADs or analyzers. Each processing object holds one stream's state while sharing the model weights: ```python theme={null} # With import aic_sdk as aic, a provisioned model_path and your SDK key: model = aic.Model.from_file(model_path) config = aic.ProcessorConfig.optimal(model) # One processor per stream, one copy of the model data. processors = [aic.Processor(model, license_key, config) for _ in range(8)] ``` > [!WARNING] > > Loading the same model file once per stream multiplies memory usage for no benefit. Load it once and create one processing object per stream. Model data is memory-mapped from the file rather than copied into your process, so do not modify or delete a model file while it is loaded. Objects created from a model keep the underlying data alive through reference counting, so the model handle can be released first. In C this means `aic_model_destroy` and the matching `*_destroy` calls may run in any order. ### Loading from memory Use buffer loading to embed a model or fetch it through your own transport: | Binding | API | Notes | | - | - | - | | C | `aic_model_create_from_buffer` | The buffer must be 64-byte aligned, must stay valid and unmodified for the model's lifetime, and is not freed by the SDK. | | Rust | `Model::from_buffer` | Same 64-byte alignment requirement. Use the [`include_model!`](https://docs.rs/aic-sdk/0.25.2/aic_sdk/macro.include_model.html) macro to embed a model file with correct alignment at compile time. | | WASM | `Model.fromBytes` | Takes a `Uint8Array` and copies it into an aligned allocation for you, so there is nothing to align yourself. | An unaligned buffer is rejected with `AIC_ERROR_CODE_MODEL_DATA_UNALIGNED` (`ModelDataUnalignedError` in the bindings that expose it). The Python and Node.js bindings load models from files only. ## Using models with non-native sample rates For Core SDK 0.26.0, streaming enhancement and dedicated VAD accept sample rates from 8 kHz to 192 kHz. The SDK resamples internally to the model's native rate. Query `Model.get_optimal_block_size(sample_rate)` in Python or `model.getOptimalBlockSize(sampleRate)` in Node for the rate your application uses. The optimal block avoids additional adapter buffering; it is not the only accepted block size. **Higher-rate input:** a 16 kHz model processes frequency content up to its native Nyquist limit of 8 kHz, even if input arrives at 48 kHz. Resampling the result back to 48 kHz does not create model enhancement above that range. Blending with the original signal can retain original high-frequency content; the result depends on the model and enhancement setting. **Lower-rate input:** resampling 8 kHz input to a 16 kHz model does not recover missing high-frequency information. Compare a native 8 kHz variant when one is available, using the same recordings and downstream task. Resampling, block adaptation, model size and concurrency all affect resource use. Measure them on your hardware instead of assuming input sample rate has negligible CPU cost. See [performance](/reference/concepts/performance) and [latency](/reference/concepts/latency). Tyto analysis has its own sample-rate and window requirements. Do not apply the streaming Processor rate range to `Analyzer` or `FileAnalyzer`; follow the [Tyto guides](/models/audio-insight/tyto). ## Compatibility Model family, file format, SDK version and framework adapter all matter. A model that loads successfully can still be the wrong type for the component you construct. The [compatibility matrix](/reference/sdk/compatibility-matrix) records the selected releases. The official LiveKit plugin exposes its own enhancement model choices and is the canonical path for LiveKit enhancement. Dedicated VAD and Tyto examples use the ai-coustics LiveKit extras plugin where those capabilities are needed. Review [plugin scope](/reference/livekit/plugin-scope) before installing packages. Pipecat 1.15.0's `aic` extra uses the Python SDK 3.3 series; the [Pipecat quickstart](/models/get-started/pipecat-quickstart) pins 3.3.2 with core SDK 0.25.2. The LiveKit extras plugin 0.26.0 example uses SDK 3.4.0. Follow each framework's pinned [LiveKit](/models/get-started/livekit-quickstart) or [Pipecat](/models/get-started/pipecat-quickstart) recipe rather than applying one dependency set to both. # SDK and model versions Source: https://docs.ai-coustics.com/reference/sdk/upgrading How core SDK releases and model file versions fit together. The core SDK and model files are versioned together. Model file versions change as part of an SDK release, not independently for an unchanged SDK version. | Version | What it identifies | | :- | :- | | **Core SDK version** | The runtime that loads and runs models, such as `0.26.0` | | **Model file format version** | The file format that the core SDK accepts, such as `8` for core `0.26.0` | Several SDK releases can support the same model file format. A new SDK release does not always require new model files. Language packages have their own version numbers. For example, Python `3.4.0` uses core SDK `0.26.0`. Use the [compatibility matrix](/reference/sdk/compatibility-matrix) to match your package to its core SDK and model file format. A product version in a model ID, such as `2.2` in `quail-vf-2.2-l-16khz`, is separate from the file format number. ## Upgrade the SDK and models together Check the [changelog](/changelog) for changes in your target SDK release. If it requires a new model file format, download the models again using the updated SDK's download helper, which selects a compatible file. See [model loading](/reference/sdk/models#loading-and-reusing-models). Keep the previous SDK and model files together until you have tested the updated combination in your application.