---
title: "Text-to-Speech"
canonical: https://docs.qvac.tether.io/sdk/v0.23/ai-capabilities/text-to-speech/
collection: "SDK"
package: "@qvac/sdk"
line: v0.23
current_line: false
---

# Text-to-Speech (/sdk/v0.23/ai-capabilities/text-to-speech)



## Overview

Text-to-Speech uses [`@qvac/tts-ggml`](https://github.com/tetherto/qvac/tree/main/packages/tts-ggml) (GGML) as the inference engine. Load any supported model using `modelType: "tts"`. Then, provide `text` as input (with `inputType: "text"`) to generate speech audio. MOSS-SoundEffect also generates sound effects from descriptions, and MOSS-Speech accepts text or audio questions to generate a reply.

`textToSpeech()` returns synchronously with `buffer`, `bufferStream`, `chunkStream`, `done`, `requestId`, `text`, `sampleRate`, `stats` and `stopReason`; see [Audio output](#audio-output), [Cancelling a run](#cancelling-a-run) and [Runtime statistics](#runtime-statistics) below.

## Functions

Use the following sequence of function calls:

1. [`loadModel()`](/sdk/v0.23/reference/api#loadmodel)
2. [`textToSpeech()`](/sdk/v0.23/reference/api#texttospeech)
3. [`unloadModel()`](/sdk/v0.23/reference/api#unloadmodel)

For how to use each function, see [SDK — API reference](/sdk/v0.23/reference/api/).

## Audio output

The SDK returns raw, mono, signed 16-bit PCM samples as a plain `number[]`. With `stream: false`, the `buffer` promise resolves to the complete sample array and `bufferStream` is empty. With `stream: true`, `buffer` resolves to `[]` and `bufferStream` yields individual samples as they become available. The data has no WAV header or other container metadata; use the [example utility](#utils) to write it as a WAV file.

`chunkStream` is the same audio one frame at a time: an `AsyncGenerator<Int16Array>` that yields one typed array of signed 16-bit samples per response frame (per sentence with `sentenceStream: true`), so a player can hand each chunk to an audio device without rebuilding it from single samples. The samples are integers in the int16 range, not floats; scale by `1 / 32768` for an API that expects `[-1, 1]`. `bufferStream` and `chunkStream` share one run in plain streaming mode, so iterate one of the two; with `stream: false` both are empty and `buffer` holds the audio.

```ts
const result = textToSpeech({ modelId, text: 'Hello.' })
for await (const chunk of result.chunkStream) {
  // The run starts when chunkStream is first iterated, so sampleRate
  // resolves once the first chunk is in; await it inside the loop.
  const sampleRate = await result.sampleRate
  // chunk: Int16Array, one per engine frame
  player.write(chunk, sampleRate)
}
```

`textToSpeech()` also returns a `sampleRate` promise, resolved from the first
audio frame the engine emits. Prefer it over inferring the rate from the load
config — `outputSampleRate` and the LavaSR enhancer both change it. It resolves
to `undefined` when the run produced no audio.

```ts
const result = textToSpeech({ modelId, text: "Hello.", stream: false });
const pcm = await result.buffer;
const sampleRate = await result.sampleRate; // e.g. 48000 with the enhancer
```

For reference, the rate each configuration produces:

| Configuration           | Output sample rate                                                                                                                                       |
| ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Chatterbox              | 24,000 Hz, or `modelConfig.outputSampleRate` when set                                                                                                    |
| Supertonic              | 44,100 Hz, or `modelConfig.outputSampleRate` when set                                                                                                    |
| Parler                  | 44,100 Hz, or `modelConfig.outputSampleRate` when native streaming is disabled; native streaming requires 44,100 Hz unless the LavaSR enhancer is loaded |
| CosyVoice3              | 24,000 Hz, or `modelConfig.outputSampleRate` when native streaming is disabled; native streaming requires 24,000 Hz unless the LavaSR enhancer is loaded |
| Audio8                  | 44,100 Hz, or `modelConfig.outputSampleRate` when set                                                                                                    |
| MOSS                    | 24,000 Hz only; MOSS takes no `outputSampleRate`                                                                                                         |
| MOSS-SoundEffect        | 48,000 Hz only                                                                                                                                           |
| MOSS-Speech             | 24,000 Hz for spoken replies; no audio for `textReply: true`                                                                                             |
| LavaSR enhancer enabled | 48,000 Hz by default, or `modelConfig.outputSampleRate` when set                                                                                         |

## Cancelling a run

`textToSpeech()` surfaces a `requestId` synchronously on its result, and
`textToSpeechStream()` on its session. Pass it to
[`cancel()`](/sdk/v0.23/reference/api#cancel) to stop synthesis:

```ts
const result = textToSpeech({ modelId, text: longArticle });
// …later, e.g. the user navigated away
await cancel({ requestId: result.requestId });
```

<Callout type="warn">
  Abandoning `bufferStream` (or calling `destroy()` on a duplex session) stops
  delivery but leaves the native job running to completion. Only `cancel()`
  stops the engine.
</Callout>

`cancel({ modelId, kind: "tts" })` aborts the run in flight on that model
and every run queued behind it. To stop a single run, cancel by `requestId`:
synthesis is serialised per model (one active run, up to 256 waiting — beyond
that the call rejects with `RequestRejectedByPolicyError`), so cancelling a
queued run by id removes it from the queue without touching the one in flight.

A cancelled run ends cleanly rather than as an error: `done` resolves `true`,
`buffer` / `bufferStream` stop at whatever was delivered, and
`await result.stopReason` is `"cancelled"` (`"completed"` otherwise).

## Runtime statistics

`textToSpeech()` returns a `stats` promise carrying the engine's own runtime
statistics from the final frame (`undefined` if the run reported none).

<Callout type="info">
  The chunked paths — `stream: true` (the default), `sentenceStream: true`,
  and `textToSpeechStream()` — run one native job per sentence. Their
  aggregate sums the timing and sample counts, keeps `firstAudioMs` from the
  first sentence and the backend and Core ML fields from the last sentence
  that reported them, and carries no per-stage timings or counters: those
  describe one native synthesis, so they are reported by batch synthesis
  (`stream: false`) only. MOSS is the exception for `stream: true`: it runs
  the whole text as one native job, so it reports everything there too.
</Callout>

| Field                                                                                                                               | Meaning                                                                                                                                                                                                  |
| ----------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `audioDuration`                                                                                                                     | Length of the synthesized audio, in milliseconds.                                                                                                                                                        |
| `totalTime`                                                                                                                         | Wall-clock synthesis time, in **seconds** (`audioDuration` is milliseconds).                                                                                                                             |
| `realTimeFactor`                                                                                                                    | `totalTime × 1000 / audioDuration`; below 1.0 is faster than real time.                                                                                                                                  |
| `tokensPerSecond`                                                                                                                   | Input characters synthesized per second; on Audio8 and MOSS, codec frames per second.                                                                                                                    |
| `totalSamples`                                                                                                                      | PCM sample count.                                                                                                                                                                                        |
| `generatedFrames`                                                                                                                   | Audio8 and MOSS only: codec frames generated (Audio8 on a fixed 46 ms grid, MOSS at 12.5 per second).                                                                                                    |
| `backendDevice`                                                                                                                     | Compute device chosen at load: `0` CPU, `1` GPU.                                                                                                                                                         |
| `backendId`                                                                                                                         | Backend family: `0` CPU, `1` Metal, `2` CUDA, `3` Vulkan, `4` OpenCL, `99` other GPU.                                                                                                                    |
| `gpuUnsupported`                                                                                                                    | `1` when a GPU is present but unusable by engine policy, so the run fell back to CPU.                                                                                                                    |
| `enhancerBackendDevice`                                                                                                             | LavaSR enhancer device: `-1` not loaded, `0` CPU, `1` GPU.                                                                                                                                               |
| `enhancerBackendId`                                                                                                                 | LavaSR enhancer backend family, same codes as `backendId`.                                                                                                                                               |
| `codecSidecarLoaded`                                                                                                                | Audio8 on macOS/iOS: `1` while the Core ML codec sidecar is attached, `0` without one or once a failing sidecar was retired.                                                                             |
| `codecOnCoreml`                                                                                                                     | Audio8: `1` when the synthesis ran its codec on the Core ML sidecar, `0` when it ran on the ggml backend `backendId` names.                                                                              |
| `firstAudioMs`                                                                                                                      | Milliseconds from the start of the run to the first audio, where the engine reports it.                                                                                                                  |
| `t3Ms`, `s3genMs`, `t3Tokens`                                                                                                       | Chatterbox: T3 decode and S3Gen + HiFT wall times in milliseconds, and the speech tokens T3 emitted.                                                                                                     |
| `stageTotalMs`                                                                                                                      | CosyVoice3 and Audio8: the engine's own wall time in milliseconds, the sum of its stages, excluding the addon's post-processing.                                                                         |
| `lmPrefillMs`, `lmDecodeMs`, `flowFrontendMs`, `ditEulerMs`, `hiftF0Ms`, `hiftSourceMs`, `hiftStftMs`, `hiftDecodeMs`               | CosyVoice3 stage wall times, in milliseconds.                                                                                                                                                            |
| `decodeSteps`, `speechTokens`, `flowFrames`, `melFrames`, `textIds`, `promptSpeechTokens`                                           | CosyVoice3 work counters: LM decode steps, speech tokens generated, flow frames in (prompt + generated), mel frames out, text ids in the LM prefill, and the prompt speech tokens the LM continued from. |
| `voiceEncodeMs`, `promptMs`, `prefillMs`, `sampleMs`, `fastDecodeMs`, `slowDecodeMs`, `codecLatentMs`, `codecSynthMs`, `resampleMs` | Audio8 stage wall times, in milliseconds.                                                                                                                                                                |

```ts
const stats = await result.stats;
console.log(stats?.realTimeFactor, stats?.backendId, stats?.gpuUnsupported);
```

## Models

### Chatterbox

Chatterbox uses a **T3 GGUF** as the top-level `modelSrc` and an **S3Gen companion GGUF** via `modelConfig.s3genModelSrc`. Optional `referenceAudioSrc` supplies a WAV for voice cloning.

```ts
await loadModel({
  modelSrc: TTS_T3_TURBO_EN_CHATTERBOX_Q8_0,
  modelType: "tts",
  modelConfig: {
    ttsEngine: "chatterbox",
    language: "en",
    s3genModelSrc: TTS_S3GEN_EN_CHATTERBOX,
  },
});
```

<Callout type="info">
  Omitting 

  `ttsEngine`

   defaults to Chatterbox.
</Callout>

The multilingual (MTL) GGUFs need a tokenizer asset for two languages:
`mecabDictSrc` is required for Japanese (`language: "ja"`) and `cangjieTsvSrc`
for Chinese (`language: "zh"`). Both are rejected at load if missing.

`ttsSpeed` is Chatterbox's speech-rate control — a pitch-preserving WSOLA
time-stretch bounded to `0.25`–`4.0` (Chatterbox has no `pace` channel).
`nCtx` caps the T3 context length in tokens (\~25 tokens ≈ 1 s of audio); the
KV cache is allocated up front at that length, so it directly bounds memory.
`kvCacheType` picks the KV-cache dtype — `f16` (the safe cross-backend
default), `f32`, or `q8_0` (smaller and faster where the backend implements
its ops). `seed`, `threads`, `nGpuLayers`, `outputSampleRate` and `backendsDir` work
as on the other engines; `openclCacheDir` (the Android OpenCL program cache)
is accepted by Chatterbox, Supertonic and CosyVoice3 only. Chatterbox supports
[LavaSR](#lavasr) post-processing.

Instead of (or alongside) `referenceAudioSrc`, `voiceDir` points at a
directory of pre-baked voice-conditioning tensors — the upstream CLI's
`--save-voice` output — which skips the reference preprocessing; when both are
set, tensors missing from the directory are backfilled from the recording.

T3 sampling is tunable: `temperature` (engine default `0.8`; `0` decodes
greedily), `topK` (`1000`; `0` disables the cutoff), `topP` (`0.95`) and
`repeatPenalty` (`1.2`; `1` turns it off). The multilingual GGUFs also take
`exaggeration` (prosody intensity, default `0.5`; above `0` more expressive,
below `0` flatter), `cfgWeight` (T3 classifier-free-guidance scale, default
`0.5`; `0` disables it, and it is separate from `cfgRate`, which steers S3Gen)
and `minP` (min-p threshold, `0` = off); the Turbo variant ignores the three.

Length and streaming cost: `nPredict` caps the speech tokens T3 decodes per
synthesis (default `1000`, about 40 s); longer single calls also need `nCtx`
to cover the prompt plus the generated tokens, or set `maxSentenceChars` so
T3 + S3Gen run per segment of at most that many bytes (the reference CLI uses
`180`), with `crossfadeMs` (default `30`) blending the segments in batch
synthesis. `batchCfmSteps` sets the CFM Euler steps for batch synthesis (`0`
\= the library default: 2-step meanflow on Turbo, the model's full schedule on
multilingual) while `cfmSteps` keeps driving native streaming, and
`streamLeftContextTokens` bounds the per-chunk cost of long native streams by
keeping only that many already-emitted speech tokens as S3Gen left context
(typically 25–50; `0` = the whole emitted prefix).

### Supertonic

Supertonic uses a **single GGUF** via top-level `modelSrc`. Set `voice`, `ttsSpeed`, and `ttsNumInferenceSteps` in `modelConfig` as needed. Multilingual output is selected by the GGUF (e.g. `TTS_MULTILINGUAL_SUPERTONIC2_Q8_0`) plus `language`.

```ts
await loadModel({
  modelSrc: TTS_EN_SUPERTONIC_Q8_0,
  modelType: "tts",
  modelConfig: {
    ttsEngine: "supertonic",
    language: "en",
    voice: "F1",
  },
});
```

Supertonic takes its speech rate either as an exact multiplier (`ttsSpeed`) or
as the canonical `pace` vocabulary (`slow` / `moderate` / `fast`), which maps
onto the duration multiplier relative to the GGUF's own default. The two are
mutually exclusive and rejected together at load. Unlike Parler and CosyVoice3,
Supertonic conditions `pace` when the engine is built, so it cannot be changed
per request — set it in `modelConfig`.

`seed`, `threads`, `nGpuLayers`, `outputSampleRate` and `backendsDir` work
as on the other engines; `openclCacheDir` is accepted by Chatterbox,
Supertonic and CosyVoice3 only, and `vulkanCacheDir` additionally persists
the compiled Vulkan pipeline cache when `useGPU` is set. `vulkanDevice` picks
the Vulkan adapter (`0` = the first, `N` = the Nth, `-1` = auto-pick by free
VRAM preferring a discrete GPU) and is also used by the LavaSR enhancer;
`prewarmText` is synthesized once at load so GPU pipelines (and a Core ML
vocoder sidecar) are ready before the first request.

Voices: `voice` selects a preset baked into the GGUF (`F1`, `M1`, …), and
`voiceJsonSrc` loads an external voice JSON (`{ style_ttl, style_dp }`, e.g.
a cloned voice) that overrides it; the engine checks the tensor sizes against
the loaded model. `noiseNpySrc` supplies a fixed CFM initial-noise `.npy`
tensor for reproducible output.

Supertonic also streams natively: set `streamChunkTokens` above zero to emit
audio per chunk of that many text tokens (Unicode code points — about 50 for
English, 25–30 for CJK). `streamFirstChunkTokens` shrinks the first chunk for
lower first-audio latency, `streamChunkTolerancePct` (default `20`) is the
window, as a percentage of the chunk target, within which a boundary snaps to
a sentence end, clause or space, and `streamMinChunkTokens` (default `30`)
merges a shorter trailing chunk into the previous one.

<Callout type="warn">
  Supertonic native chunk streaming cannot be combined with the LavaSR
  enhancer or denoiser; the pair is rejected at load. Sentence streaming
  (`stream: true` without `streamChunkTokens`, `sentenceStream: true`, or
  `textToSpeechStream()`) works with either stage loaded.
</Callout>

### Parler-TTS

Parler-TTS uses a **single GGUF** and conditions speech from either a free-text
description or structured voice fields. Load-time fields provide defaults;
`textToSpeech()` and `textToSpeechStream()` can override them per request.
The registry includes Mini v1, Large v1, and Indic variants; the Indic model
supports 21 languages and script-native digit normalization.

```ts
const modelId = await loadModel({
  modelSrc: TTS_MINI_V1_EN_PARLER_TTS_Q8_0,
  modelType: "tts",
  modelConfig: {
    ttsEngine: "parler",
    voice: "Laura",
    seed: 42,
    topK: 1,
  },
});

const result = textToSpeech({
  modelId,
  text: "Welcome to Parler text-to-speech.",
  inputType: "text",
  stream: false,
  emotion: "happy",
  pace: "moderate",
});

const pcm = await result.buffer;
```

For free-form conditioning, use `description` or its alias
`voiceDescription`. Otherwise, compose a description from `voice`, `emotion`,
`pitch`, `pace`, `expressivity`, `noise`, `reverb`, and `quality`.

<Callout type="warn">
  `description` and `voiceDescription` cannot be combined with each other or
  with the structured voice fields. `description`, `voiceDescription` and the
  descriptor fields (`voice`, `pitch`, `expressivity`, `noise`, `reverb`,
  `quality`) are Parler-only; `emotion` and `pace` are also accepted per
  request by CosyVoice3 (emotion limited to `anger`, `happy`, `neutral`,
  `sad`). Sending any of them to Chatterbox, Supertonic or Audio8 returns a
  request-validation error.
</Callout>

Supported emotions are `command`, `anger`, `narration`, `conversation`,
`disgust`, `fear`, `happy`, `neutral`, `proper noun`, `news`, `sad`, and
`surprise`.

Parler supports all three SDK streaming surfaces:

* `textToSpeech({ stream: true })` for incremental PCM samples.
* `textToSpeech({ stream: true, sentenceStream: true })` for PCM plus
  sentence/chunk metadata.
* `textToSpeechStream()` when text itself arrives incrementally.

Set `streamChunkTokens` above zero to enable native chunk streaming;
`streamFirstChunkTokens` only tunes the first chunk and does not enable
streaming by itself. Native streaming emits at 44.1 kHz, so omit
`outputSampleRate`, set it to `44100`, or load the LavaSR enhancer (which
resamples seam-free) when `streamChunkTokens > 0`.
Integer generation controls use signed 32-bit values. Parler also supports
[LavaSR](#lavasr) post-processing via `lavasrEnhancerModelSrc` and
`lavasrDenoiserModelSrc` (the denoiser is batch-only — disable native chunk
streaming to use it).

The generated Python client uses the same contract:

```python
from tetherto.qvac_sdk import TextToSpeechRequest, load_model, text_to_speech
from tetherto.qvac_sdk.models import TTS_MINI_V1_EN_PARLER_TTS_Q8_0

model_id = await load_model(
    transport,
    model_src=TTS_MINI_V1_EN_PARLER_TTS_Q8_0,
    model_config={
        "ttsEngine": "parler",
        "voice": "Laura",
        "seed": 42,
        "topK": 1,
    },
)

request = TextToSpeechRequest.model_validate({
    "type": "textToSpeech",
    "modelId": model_id,
    "text": "Welcome to Parler text-to-speech.",
    "inputType": "text",
    "stream": False,
    "emotion": "happy",
})

samples = []
async for response in text_to_speech(transport, request):
    samples.extend(response.buffer)
```

### CosyVoice3

CosyVoice3 uses the **LLM GGUF** as the top-level `modelSrc`; its registry
companion set auto-downloads the flow and HiFT GGUFs, the baked `voice.gguf`,
and the tokenizer files alongside it. Speech is synthesized with the baked
default voice unless you supply a reference recording (see
[voice cloning](#cosyvoice3-voice-cloning) below), and emits native 24 kHz
audio.

```ts
const modelId = await loadModel({
  modelSrc: TTS_COSYVOICE3_LLM_COSYVOICE_Q8_0,
  modelType: "tts",
  modelConfig: {
    ttsEngine: "cosyvoice3",
    seed: 42,
  },
});

const result = textToSpeech({
  modelId,
  text: "Hey, how are you doing today?",
  inputType: "text",
  stream: false,
  emotion: "happy",
});

const pcm = await result.buffer;
```

Conditioning uses one of three controls:

* `emotion` — `anger`, `happy`, `neutral`, or `sad`.
* `pace` — `slow`, `moderate`, or `fast`; `moderate` engages nothing and
  takes the plain zero-shot path.
* `instruct` — a raw instruction string, or a structured object with
  `dialect`, `volume` (`loud` / `soft`), or `style` (`peppa` / `robot`),
  resolved by precedence `dialect > volume > style`. Supported dialects:
  `cantonese`, `northeastern`, `gansu`, `guizhou`, `henan`, `hubei`, `hunan`,
  `jiangxi`, `minnan`, `ningxia`, `shanxi`, `shaanxi`, `shandong`,
  `shanghai`, `sichuan`, `tianjin`, and `yunnan`.

<Callout type="warn">
  CosyVoice3 accepts **one conditioning control per synthesis** — an
  `emotion`, a non-`moderate` `pace`, or an `instruct`. Combining them is
  rejected at load and request validation. All three can also be set per
  request on `textToSpeech()` and `textToSpeechStream()`, where the request's
  control replaces the loaded one for that synthesis.
</Callout>

```ts
const result = textToSpeech({
  modelId,
  text: "今天天气真好。",
  stream: false,
  // Per-request control; a raw string is passed to the engine verbatim.
  instruct: { dialect: "cantonese" },
});
```

Set `streamChunkTokens` above zero for native chunk streaming
(`streamFirstChunkTokens` tunes the first chunk only). Native streaming emits
at 24 kHz, so omit `outputSampleRate` or set it to `24000` unless the LavaSR
enhancer is loaded. `useGPU` offloads to Metal on macOS/iOS, Vulkan on
desktop Linux/Windows, and OpenCL on Adreno Android devices; `vulkanDevice`
picks the Vulkan adapter (`0` = the first, `N` = the Nth, `-1` = auto-pick by
free VRAM preferring a discrete GPU) and is also used by the LavaSR enhancer.
`flowCutPrompt` treats the baked-voice prompt frames as attention-only
conditioning in the flow — a faster flow whose output deviates slightly from
the reference (off by default). `threads`, `nGpuLayers`, `seed`, and
`outputSampleRate` (8,000–192,000 Hz) work as on the other engines.
CosyVoice3 also supports [LavaSR](#lavasr) post-processing via
`lavasrEnhancerModelSrc` (48 kHz bandwidth extension) and
`lavasrDenoiserModelSrc` (batch-only; runs before the enhancer).

#### CosyVoice3 voice cloning

Supply `referenceAudioSrc` — a WAV of 0.5–30 s (5–15 s of clean speech is the
sweet spot; multichannel input is downmixed to mono) — to replace the baked
voice with the speaker in the recording. Cloning needs two extra GGUFs that are
**not** part of the LLM's companion set, because they are a \~300 MB opt-in:

* `cosyvoice3S3tokModelSrc` — the speech tokenizer (`speech_tokenizer_v3`).
  Constants: `TTS_COSYVOICE3_S3TOK_COSYVOICE_Q8_0`,
  `TTS_COSYVOICE3_S3TOK_COSYVOICE_FP16`, `TTS_COSYVOICE3_S3TOK_COSYVOICE_FP32`.
* `cosyvoice3CampplusModelSrc` — the CAM++ speaker encoder. Constant:
  `TTS_COSYVOICE3_CAMPPLUS_COSYVOICE_FP32`.

`promptText` selects the cloning mode: set it to the verbatim transcript of the
recording for **zero-shot** cloning (best fidelity in the reference's own
language), or omit it for **cross-lingual** cloning (timbre only, so you can
synthesize a different language than the reference speaks). Cloning composes
with `instruct`.

```ts
const modelId = await loadModel({
  modelSrc: TTS_COSYVOICE3_LLM_COSYVOICE_Q8_0,
  modelType: "tts",
  modelConfig: {
    ttsEngine: "cosyvoice3",
    referenceAudioSrc: "/path/to/reference.wav",
    cosyvoice3S3tokModelSrc: TTS_COSYVOICE3_S3TOK_COSYVOICE_Q8_0.src,
    cosyvoice3CampplusModelSrc: TTS_COSYVOICE3_CAMPPLUS_COSYVOICE_FP32.src,
    // Zero-shot: the exact words spoken in reference.wav.
    // Omit promptText for cross-lingual cloning.
    promptText: "This is exactly what the reference recording says.",
  },
});
```

<Callout type="warn">
  The reference is baked at load. All three fields are validated together — a
  reference without either cloning GGUF is rejected at load rather than
  silently falling back to the baked voice. Changing voices means loading the
  model again.
</Callout>

### Audio8

Audio8 uses the **DualAR LM GGUF** as the top-level `modelSrc`
(`TTS_LM_MULTILINGUAL_AUDIO8_Q8_0` or `TTS_LM_MULTILINGUAL_AUDIO8_FP16`) and
a required **codec decoder** via `modelConfig.audio8CodecDecoderModelSrc`.
The model is multilingual — the language is inferred from the text itself —
and emits native 44.1 kHz audio.

```ts
const modelId = await loadModel({
  modelSrc: TTS_LM_MULTILINGUAL_AUDIO8_Q8_0,
  modelType: "tts",
  modelConfig: {
    ttsEngine: "audio8",
    audio8CodecDecoderModelSrc: TTS_CODEC_DECODER_AUDIO8_Q8_0,
    temperature: 0.7,
    topP: 0.9,
    seed: 42,
  },
});

const result = textToSpeech({
  modelId,
  text: "Hey, how are you doing today?",
  inputType: "text",
  stream: false,
});

const pcm = await result.buffer;
```

For zero-shot voice cloning, add the optional **codec encoder**
(`audio8CodecEncoderModelSrc`, e.g. `TTS_CODEC_ENCODER_AUDIO8_Q8_0`) and
supply `referenceAudioSrc` (a reference recording) together with
`referenceText` (its exact transcript). The three fields are validated
together — a reference without its transcript or without the encoder is
rejected at load.

With the encoder loaded, the voice can also change per request:
`textToSpeech()` and `textToSpeechStream()` take `referenceAudioSrc` and
`referenceText` too. A request-level recording replaces the loaded voice for
that synthesis and must bring its own `referenceText` (the loaded transcript
describes a different recording, so it is not inherited); a request-level
`referenceText` on its own corrects the transcript of the loaded recording.
The engine caches the codes of the most recent reference, so repeating one
across requests skips the encoder.

```ts
const result = textToSpeech({
  modelId,
  text: "Spoken in another voice.",
  stream: false,
  referenceAudioSrc: "/path/to/someone-else.wav",
  referenceText: "Exactly what that recording says.",
});
```

<Callout type="warn">
  A request-level `referenceAudioSrc` is resolved inside the request. A local
  path or an already cached source costs nothing, but a remote source that is
  not cached yet downloads first, with no progress events, while the request
  holds the model: every other speech request for that model waits behind it.
  Pre-fetch remote recordings with `downloadAsset({ assetSrc })`, which fills
  the same cache, and pass the same source to the request afterwards.
  `cancel()` stops a download that is already in flight.
</Callout>

Generation is sampled by default: `temperature` (default `0.7`), `topK`
(`50`), and `topP` (`0.9`) tune it, `greedy: true` takes the argmax instead
and ignores all three, and `maxFrames` caps generation in codec frames
(\~21.5 frames per second of audio). `seed`, `threads`, `nGpuLayers`, and
`outputSampleRate` work as on the other engines; `useGPU` offloads to Metal
on macOS/iOS, Vulkan on desktop Linux/Windows, and OpenCL on Android/Adreno —
elsewhere it falls back to CPU and sets `stats.gpuUnsupported` in the
response.

On macOS and iOS, loading the codec decoder from its registry constant also
downloads its Apple Core ML bundle (`audio8-codec-decoder.mlmodelc`, about
150 MB, the same bundle for every decoder tier) and places it beside the
decoder GGUF.
The codec's synthesis stack — the upsampling stages and the DAC decoder — then
runs on Core ML, while the language model stays on `useGPU`'s backend. Other
platforms download only the GGUF. If the bundle is unavailable at load, or a
synthesis fails on it, Audio8 runs the codec on ggml instead; the
`codecSidecarLoaded` and `codecOnCoreml` stats report which path ran.

<Callout type="warn">
  Audio8 has no `emotion`, `pace`, or description fields (at load or per
  request), no LavaSR post-processing, and no native chunk streaming.
  Sentence streaming (`sentenceStream: true`) and duplex
  `textToSpeechStream()` work as with every engine. The request-level
  `referenceAudioSrc` / `referenceText` pair is Audio8-only; other engines
  reject it.
</Callout>

For model constants, see [SDK — Models](/sdk/v0.23/#models).

### MOSS

MOSS runs OpenMOSS **MOSS-TTS v1.5** (single speaker) and **MOSS-TTSD**
(multi-speaker dialogue) on the MOSS Delay engine. The top-level `modelSrc` is
the **backbone GGUF** (`TTS_DELAY_LLM_MOSS_TTS_F16`, or a local
`moss-ttsd-*.gguf` for dialogue) and a **codec decoder** is required via
`modelConfig.mossCodecDecoderModelSrc` (`TTS_CODEC_DECODER_MOSS_TTS_F16`).
Output is native 24 kHz. The backbones have 8B parameters (about 17 GB at
f16), so MOSS targets desktop hosts; mobile is not supported.

```ts
const modelId = await loadModel({
  modelSrc: TTS_DELAY_LLM_MOSS_TTS_F16,
  modelType: "tts",
  modelConfig: {
    ttsEngine: "moss",
    language: "en",
    mossCodecDecoderModelSrc: TTS_CODEC_DECODER_MOSS_TTS_F16,
    streamChunkTokens: 25,
    useGPU: true,
  },
});

const result = textToSpeech({
  modelId,
  text: "Hold on [pause 1.0s] here it comes.",
});

for await (const sample of result.bufferStream) {
  // Chunks of 25 codec frames (2 s) arrive while the backbone is still generating.
}
```

The speech is directable from the text itself: `[pause 2.0s]` markers insert
a silence of roughly that length, and inline Pinyin (`ni3 hao3`) or IPA
(`/həloʊ/`) steers pronunciation. `durationTokens` asks for a target length in
codec frames (12.5 per second, so `38` is about 3 s; `0` or unset keeps the
length free; at most `2015`). `language` is written into the model prompt as a
hint (default `en`).

MOSS streams natively. With `streamChunkTokens` set, `stream: true` (the
default) delivers audio every that-many codec frames while generation
continues; without it the audio arrives in one piece when synthesis ends.
Either way the text is synthesized as one utterance rather than sentence by
sentence, so `durationTokens` and the pause markers apply to all of it.
`sentenceStream: true` and `textToSpeechStream()` still split a single-speaker
text into sentences; `sentenceStreamLocale` and `sentenceStreamMaxChunkScalars`
only apply there, and a MOSS request without `sentenceStream: true` rejects
them.

`seed` (engine default `1234`), `threads` and `backendsDir` work as on the
other engines. MOSS runs on the CPU by default; `useGPU: true` or a non-zero
`nGpuLayers` asks for a GPU backend, and when none is usable it falls back to
the CPU and sets `stats.gpuUnsupported`.

#### MOSS voice cloning

Add the **codec encoder** (`mossCodecEncoderModelSrc`,
`TTS_CODEC_ENCODER_MOSS_TTS_F16`) and a reference recording
(`referenceAudioSrc`). Unlike Audio8, MOSS needs no transcript. The
recording must already be sampled at **24 kHz** (there is no resampling;
multichannel audio is downmixed, and recordings are capped at 60 s). The voice is
encoded once at load and fixed for the loaded model, so changing voices means
loading again.

```ts
const modelId = await loadModel({
  modelSrc: TTS_DELAY_LLM_MOSS_TTS_F16,
  modelType: "tts",
  modelConfig: {
    ttsEngine: "moss",
    mossCodecDecoderModelSrc: TTS_CODEC_DECODER_MOSS_TTS_F16,
    mossCodecEncoderModelSrc: TTS_CODEC_ENCODER_MOSS_TTS_F16,
    referenceAudioSrc: "/voices/speaker-24k.wav",
  },
});
```

#### MOSS-TTSD dialogue

The MOSS-TTSD backbone is not in the QVAC Registry yet, so pass it as a local
file; it shares the codec halves with MOSS-TTS. Load it with
`dialogueReferenceSrcs`: one 24 kHz recording per speaker, in the order the
text tags them (`[S1]`, `[S2]`, …; one to five speakers, at most 60 s of
reference audio combined). The model continues the references, so the text
must open with what each recording says under its tag, followed by the lines
to generate; only the new lines come out as audio. Dialogue needs the codec
encoder and excludes `referenceAudioSrc`.

```ts
const modelId = await loadModel({
  modelSrc: "/models/moss-ttsd-f16.gguf",
  modelType: "tts",
  modelConfig: {
    ttsEngine: "moss",
    mossCodecDecoderModelSrc: TTS_CODEC_DECODER_MOSS_TTS_F16,
    mossCodecEncoderModelSrc: TTS_CODEC_ENCODER_MOSS_TTS_F16,
    dialogueReferenceSrcs: ["/voices/alice.wav", "/voices/bob.wav"],
    streamChunkTokens: 25,
  },
});

const result = textToSpeech({
  modelId,
  text:
    "[S1] What alice.wav says. [S2] What bob.wav says. " +
    "[S1] Did the build finish? [S2] Yes, every test passed.",
});
```

<Callout type="warn">
  A dialogue cannot be split into sentences, because every synthesis has to
  open with the reference transcripts: `sentenceStream: true` and
  `textToSpeechStream()` are rejected on a dialogue model. Use
  `textToSpeech()` with `stream: true` and `streamChunkTokens` for chunked
  audio. MOSS has no `emotion`, `pace`, or description fields, no LavaSR
  post-processing, and no `streamFirstChunkTokens`.
</Callout>

### MOSS-SoundEffect-v2

Load a single sound-effect GGUF with `modelType: "tts-ggml"` and
`modelConfig.ttsEngine: "moss-sfx"`. Pass `AUDIOGEN_MOSS_SFX_V2_Q8_0.src`
as `modelSrc`: the full catalog descriptor selects the audiogen plugin. To
assess its fit, pass a downloaded local file with explicit `modelType` and
`ttsEngine`.
Use `textToSpeech({ modelId, text, stream: false })` with a sound description.
The output is 48 kHz mono PCM.

Set `seconds` (up to 30), `negativePrompt`, `steps`, `guidance` and `shift`
per request or as load defaults. The examples use `steps: 20`; omitting it
uses the slower baked default of 100 diffusion steps. Each clip denoises a
30-second latent regardless of the requested output duration.

For metadata-only fit, pass `ttsWorkload: { prompt, seconds }` beside
`modelConfig` on the [`assessModelFit()`](/sdk/v0.23/reference/api#assessmodelfit)
candidate. MOSS-TTS/TTSD instead uses
`ttsWorkload: { promptRows, referenceSamples, streaming }`, where `promptRows`
covers the complete native prompt. These workloads are fit-only and do not
belong in `loadModel` configuration. Missing workloads return `unknown`;
MOSS-Speech has no native fitter.

### MOSS-Speech

Load `TTS_MOSS_SPEECH_Q8_0` as `modelSrc` with
`modelConfig: { ttsEngine: "moss-speech", mossSpeechCodecModelSrc: TTS_CODEC_MOSS_SPEECH_F16 }`.
Use either `text`, or `audio` plus `sampleRate`.
Input audio is a JSON array of normalized mono samples in `[-1, 1]`.
Earlier turns go in `messages`; each turn has a `role` and either `text`
or `audio` plus `sampleRate`.

Request controls include `systemPrompt`, `replyVoice` plus
`replyVoiceSampleRate`, `maxReplySeconds`, `maxNewTokens`, `textReply`,
`greedy`, `temperature`, `topP` and `topK`. Consume `result.bufferStream`
with the default streaming mode, or await `result.buffer` with `stream: false`,
then await `result.text` for any reply text. Spoken mode can return audio without text;
use `textReply: true` when text is required, which returns an empty audio
buffer. Omitting `maxNewTokens` preserves the remaining-context budget.

<Callout type="warn">
  MOSS-SoundEffect and MOSS-Speech are desktop batch engines. The default
  `stream: true` returns completed audio in one chunk; `stream: false` collects
  it in `buffer`. Sentence streaming and
  [`textToSpeechStream()`](/sdk/v0.23/reference/api#texttospeechstream) are
  unsupported. The examples recommend a GPU with enough memory for the model and
  codec.
</Callout>

### LavaSR

With Chatterbox, Supertonic, Parler, or CosyVoice3, you can choose to perform post-processing using **LavaSR** models. They are applied to the synthesized audio before it is returned, and each stage is enabled purely by supplying its model source — i.e., there is no separate on/off flag. (Audio8 and MOSS do not support them.)

* `lavasrDenoiserModelSrc` — a denoiser GGUF that cleans the speech (noise reduction). It runs **first** and is rate-preserving. Constants: `TTS_DENOISER_LAVASR_FP16`, `TTS_DENOISER_LAVASR_FP32`.
* `lavasrEnhancerModelSrc` — an enhancer GGUF that neurally bandwidth-extends the output to **48 kHz**. It runs **after** the denoiser. Constants: `TTS_ENHANCER_LAVASR_FP16`, `TTS_ENHANCER_LAVASR_FP32`.

<Callout type="warn">
  The denoiser needs the whole utterance, so it cannot be combined with native
  chunk streaming (`streamChunkTokens > 0`) on Chatterbox, Parler, or
  CosyVoice3. The combination is rejected at load. The enhancer has no such
  restriction there — it resamples seam-free across chunk boundaries.
  Supertonic native chunk streaming rejects both stages; use sentence
  streaming for enhanced or denoised Supertonic output.
</Callout>

```ts
await loadModel({
  modelSrc: TTS_MULTILINGUAL_SUPERTONIC3_Q8_0,
  modelType: "tts",
  modelConfig: {
    ttsEngine: "supertonic",
    language: "en",
    voice: "F1",
    // Denoiser runs first (rate-preserving)…
    lavasrDenoiserModelSrc: TTS_DENOISER_LAVASR_FP16.src,
    // …then the enhancer bandwidth-extends to 48 kHz.
    lavasrEnhancerModelSrc: TTS_ENHANCER_LAVASR_FP16.src,
  },
});
```

## Examples

### Chatterbox

This example generates speech from text using Chatterbox. It clones the voice of a reference audio when you pass one, saves the speech to `tts-output.wav`, and plays it. Arguments: `[reference-audio]` (optional). Helper (JS/TS): [`utils`](#utils), in the same folder as the script.

<Tabs>
  <Tab value="js" label="JavaScript" default>
    <WrapCode>
      ```js file=<rootDir>/packages/sdk/dist/examples/tts/chatterbox.js title="tts-chatterbox.js" lineNumbers
      import { loadModel, textToSpeech, unloadModel, TTS_T3_TURBO_EN_CHATTERBOX_Q8_0, TTS_S3GEN_EN_CHATTERBOX } from '@qvac/sdk';
      import { createWav, playAudio, int16ArrayToBuffer, createWavHeader } from './utils.js';
      // Chatterbox TTS (GGML): voice cloning with optional reference audio.
      // Uses registry model constants — downloads automatically from QVAC Registry.
      // Usage: node chatterbox.ts [referenceAudioSrc]
      const [referenceAudioSrc] = process.argv.slice(2);
      // Only a fallback: the engine reports the rate it actually produced, and
      // `outputSampleRate` (plus the LavaSR enhancer) can move it off this default.
      const CHATTERBOX_SAMPLE_RATE = 24000;
      try {
          const modelId = await loadModel({
              modelSrc: TTS_T3_TURBO_EN_CHATTERBOX_Q8_0,
              modelConfig: {
                  ttsEngine: 'chatterbox',
                  language: 'en',
                  s3genModelSrc: TTS_S3GEN_EN_CHATTERBOX.src,
                  streamChunkTokens: 25,
                  streamFirstChunkTokens: 10,
                  cfmSteps: 1,
                  threads: 8,
                  ...(referenceAudioSrc ? { referenceAudioSrc } : {})
              },
              onProgress: (p) => {
                  const mb = (n) => (n / 1e6).toFixed(1);
                  const line = `▸ Downloading ${p.percentage.toFixed(0)}% (${mb(p.downloaded)}/${mb(p.total)} MB)`;
                  process.stderr.write(process.stderr.isTTY ? `\r${line}` : `${line}\n`);
                  if (p.percentage >= 100)
                      process.stderr.write('\n');
              }
          });
          console.log(`▸ Model loaded: ${modelId}`);
          console.log('▸ Testing Text-to-Speech...');
          const result = textToSpeech({
              modelId,
              text: `QVAC SDK is the canonical entry point to QVAC. Written in TypeScript, it provides all QVAC capabilities through a unified interface while also abstracting away the complexity of running your application in a JS environment other than Bare. Supported JS environments include Bare, Node.js, Expo and Bun.`,
              inputType: 'text',
              stream: false
          });
          const audioBuffer = await result.buffer;
          const sampleRate = (await result.sampleRate) ?? CHATTERBOX_SAMPLE_RATE;
          console.log(`▸ TTS complete. Total bytes: ${audioBuffer.length}`);
          console.log('▸ Saving audio to file...');
          createWav(audioBuffer, sampleRate, 'tts-output.wav');
          console.log('▸ Audio saved to tts-output.wav');
          console.log('▸ Playing audio...');
          const audioData = int16ArrayToBuffer(audioBuffer);
          const wavBuffer = Buffer.concat([createWavHeader(audioData.length, sampleRate), audioData]);
          playAudio(wavBuffer);
          console.log('▸ Audio playback complete');
          await unloadModel({ modelId });
          console.log('▸ Model unloaded');
          process.exit(0);
      }
      catch (error) {
          console.error('✖', error);
          process.exit(1);
      }
      ```
    </WrapCode>
  </Tab>

  <Tab value="ts" label="TypeScript">
    <WrapCode>
      ```ts file=<rootDir>/packages/sdk/examples/tts/chatterbox.ts title="tts-chatterbox.ts" lineNumbers
      import {
        loadModel,
        textToSpeech,
        unloadModel,
        type ModelProgressUpdate,
        TTS_T3_TURBO_EN_CHATTERBOX_Q8_0,
        TTS_S3GEN_EN_CHATTERBOX
      } from '@qvac/sdk'
      import { createWav, playAudio, int16ArrayToBuffer, createWavHeader } from './utils.js'

      // Chatterbox TTS (GGML): voice cloning with optional reference audio.
      // Uses registry model constants — downloads automatically from QVAC Registry.
      // Usage: node chatterbox.ts [referenceAudioSrc]
      const [referenceAudioSrc] = process.argv.slice(2)

      // Only a fallback: the engine reports the rate it actually produced, and
      // `outputSampleRate` (plus the LavaSR enhancer) can move it off this default.
      const CHATTERBOX_SAMPLE_RATE = 24000

      try {
        const modelId = await loadModel({
          modelSrc: TTS_T3_TURBO_EN_CHATTERBOX_Q8_0,
          modelConfig: {
            ttsEngine: 'chatterbox',
            language: 'en',
            s3genModelSrc: TTS_S3GEN_EN_CHATTERBOX.src,
            streamChunkTokens: 25,
            streamFirstChunkTokens: 10,
            cfmSteps: 1,
            threads: 8,
            ...(referenceAudioSrc ? { referenceAudioSrc } : {})
          },
          onProgress: (p: ModelProgressUpdate) => {
            const mb = (n: number) => (n / 1e6).toFixed(1)
            const line = `▸ Downloading ${p.percentage.toFixed(0)}% (${mb(p.downloaded)}/${mb(p.total)} MB)`
            process.stderr.write(process.stderr.isTTY ? `\r${line}` : `${line}\n`)
            if (p.percentage >= 100) process.stderr.write('\n')
          }
        })

        console.log(`▸ Model loaded: ${modelId}`)

        console.log('▸ Testing Text-to-Speech...')
        const result = textToSpeech({
          modelId,
          text: `QVAC SDK is the canonical entry point to QVAC. Written in TypeScript, it provides all QVAC capabilities through a unified interface while also abstracting away the complexity of running your application in a JS environment other than Bare. Supported JS environments include Bare, Node.js, Expo and Bun.`,
          inputType: 'text',
          stream: false
        })

        const audioBuffer = await result.buffer
        const sampleRate = (await result.sampleRate) ?? CHATTERBOX_SAMPLE_RATE
        console.log(`▸ TTS complete. Total bytes: ${audioBuffer.length}`)

        console.log('▸ Saving audio to file...')
        createWav(audioBuffer, sampleRate, 'tts-output.wav')
        console.log('▸ Audio saved to tts-output.wav')

        console.log('▸ Playing audio...')
        const audioData = int16ArrayToBuffer(audioBuffer)
        const wavBuffer = Buffer.concat([createWavHeader(audioData.length, sampleRate), audioData])
        playAudio(wavBuffer)
        console.log('▸ Audio playback complete')

        await unloadModel({ modelId })
        console.log('▸ Model unloaded')
        process.exit(0)
      } catch (error) {
        console.error('✖', error)
        process.exit(1)
      }
      ```
    </WrapCode>
  </Tab>

  <Tab value="python" label="Python">
    <WrapCode>
      ```python file=<rootDir>/packages/sdk-python/examples/text_to_speech_chatterbox.py title="text_to_speech_chatterbox.py" lineNumbers
      """Python port of packages/sdk/examples/tts/chatterbox.ts.

      Chatterbox TTS (GGML): voice cloning with an optional reference audio file.
      Uses registry model constants, which download automatically from the QVAC
      Registry. `text_to_speech` is a server-stream; in non-stream mode it yields the
      full audio as one frame. Samples come back as int16 PCM values. The helpers
      below, ported from the JS example's `utils`, save them to a WAV and play it
      through ffplay.

      RUN: python examples/text_to_speech_chatterbox.py [reference-audio]
      """

      from __future__ import annotations

      import asyncio
      import struct
      import subprocess
      import sys

      from tetherto.qvac_sdk import (
          Client,
          TextToSpeechRequest,
          load_model,
          text_to_speech,
          unload_model,
      )
      from tetherto.qvac_sdk.models import (
          TTS_S3GEN_EN_CHATTERBOX,
          TTS_T3_TURBO_EN_CHATTERBOX_Q8_0,
      )

      # Only a fallback: the engine reports the rate it actually produced, and
      # `outputSampleRate` (plus the LavaSR enhancer) can move it off this default.
      CHATTERBOX_SAMPLE_RATE = 24000


      def print_progress(p) -> None:
          """Print model download progress; pass as `on_progress=` to `load_model`."""
          line = (
              f"▸ Downloading {p.percentage:.0f}% "
              f"({p.downloaded / 1e6:.1f}/{p.total / 1e6:.1f} MB)"
          )
          print(line, end="\r" if sys.stderr.isatty() else "\n", file=sys.stderr)
          if p.percentage >= 100:
              print(file=sys.stderr)


      def create_wav_header(data_length: int, sample_rate: int) -> bytes:
          """Create a WAV header for 16-bit mono PCM audio."""
          return (
              b"RIFF"
              + struct.pack("<I", 36 + data_length)
              + b"WAVE"
              + b"fmt "
              + struct.pack("<IHHIIHH", 16, 1, 1, sample_rate, sample_rate * 2, 2, 16)
              + b"data"
              + struct.pack("<I", data_length)
          )


      def int16_array_to_buffer(samples) -> bytes:
          """Convert int16 PCM samples to little-endian bytes."""
          return struct.pack(
              f"<{len(samples)}h",
              *(max(-32768, min(32767, round(s))) for s in samples),
          )


      def create_wav(audio_buffer, sample_rate: int, filename: str) -> None:
          """Create and save a WAV file."""
          audio_data = int16_array_to_buffer(audio_buffer)
          with open(filename, "wb") as f:
              f.write(create_wav_header(len(audio_data), sample_rate) + audio_data)
          print(f"▸ WAV file saved as: {filename}")


      def play_audio(audio_buffer: bytes) -> None:
          """Play a WAV buffer by streaming it into ffplay over stdin."""
          try:
              result = subprocess.run(
                  [
                      "ffplay",
                      "-hide_banner",
                      "-loglevel",
                      "error",
                      "-autoexit",
                      "-nodisp",
                      "-i",
                      "pipe:0",
                  ],
                  input=audio_buffer,
                  check=False,
              )
          except FileNotFoundError:
              raise RuntimeError(
                  "ffplay not found on PATH. Install ffmpeg (ffplay ships with it) and retry."
              ) from None
          if result.returncode != 0:
              raise RuntimeError(f"ffplay exited with code {result.returncode}")


      async def main() -> int:
          reference_audio_src = sys.argv[1] if len(sys.argv) > 1 else None

          model_config = {
              "ttsEngine": "chatterbox",
              "language": "en",
              "s3genModelSrc": TTS_S3GEN_EN_CHATTERBOX.src,
              "streamChunkTokens": 25,
              "streamFirstChunkTokens": 10,
              "cfmSteps": 1,
              "threads": 8,
          }
          if reference_audio_src:
              model_config["referenceAudioSrc"] = reference_audio_src

          async with Client() as client:
              t = client.transport
              try:
                  model_id = await load_model(
                      t,
                      model_src=TTS_T3_TURBO_EN_CHATTERBOX_Q8_0,
                      model_config=model_config,
                      on_progress=print_progress,
                  )
                  print(f"▸ Model loaded: {model_id}")

                  print("▸ Testing Text-to-Speech...")
                  request = TextToSpeechRequest.model_validate(
                      {
                          "type": "textToSpeech",
                          "modelId": model_id,
                          "text": (
                              "QVAC SDK is the canonical entry point to QVAC. Written in "
                              "TypeScript, it provides all QVAC capabilities through a "
                              "unified interface while also abstracting away the "
                              "complexity of running your application in a JS environment "
                              "other than Bare. Supported JS environments include Bare, "
                              "Node.js, Expo and Bun."
                          ),
                          "inputType": "text",
                          "stream": False,
                      }
                  )

                  samples: list[float] = []
                  sample_rate = None
                  async for response in text_to_speech(t, request):
                      samples.extend(response.buffer)
                      if response.sample_rate is not None:
                          sample_rate = response.sample_rate
                  sample_rate = int(sample_rate or CHATTERBOX_SAMPLE_RATE)
                  print(f"▸ TTS complete. Total samples: {len(samples)}")

                  print("▸ Saving audio to file...")
                  create_wav(samples, sample_rate, "tts-output.wav")
                  print("▸ Audio saved to tts-output.wav")

                  print("▸ Playing audio...")
                  audio_data = int16_array_to_buffer(samples)
                  play_audio(create_wav_header(len(audio_data), sample_rate) + audio_data)

                  await unload_model(t, model_id)
                  print("▸ Model unloaded")
              except Exception as error:
                  print(f"✖ {error}", file=sys.stderr)
                  return 1
          return 0


      if __name__ == "__main__":
          sys.exit(asyncio.run(main()))
      ```
    </WrapCode>
  </Tab>

  <Tab value="kotlin" label="Kotlin">
    <WrapCode>
      ```kotlin file=<rootDir>/packages/sdk-kotlin/examples/src/TextToSpeechChatterbox.kt title="TextToSpeechChatterbox.kt" lineNumbers
      // Kotlin port of packages/sdk/examples/tts/chatterbox.ts.
      //
      // Chatterbox TTS (GGML): voice cloning with an optional reference audio file.
      // Uses registry model constants, which download automatically from the QVAC
      // Registry. The S3Gen companion model loads through `modelConfig` as its `src`
      // string, the same wire shape as the TS and Python examples.
      //
      // `client.textToSpeech()` is the generated typed method: it takes a
      // `TextToSpeechRequest` data class and returns a `Flow<TextToSpeechResponse>`.
      // In non-stream mode it emits the full audio as one frame. Samples come back as
      // int16 PCM values; the frame also carries the `sampleRate` the engine actually
      // produced. The helpers below, ported from the JS example's `utils`, save them
      // to a WAV and play it through ffplay.
      //
      // RUN: ./gradlew -p examples run -Pexample=TextToSpeechChatterbox [--args="<reference-audio>"]

      import io.tether.qvac.sdk.QvacClient
      import io.tether.qvac.sdk.QvacProgressEvent
      import io.tether.qvac.sdk.generated.ModelConstant
      import io.tether.qvac.sdk.generated.Models
      import io.tether.qvac.sdk.generated.schema.LoadModelResponse
      import io.tether.qvac.sdk.generated.schema.ModelProgressResponse
      import io.tether.qvac.sdk.generated.schema.TextToSpeechRequest
      import io.tether.qvac.sdk.jvm.JvmBareKitTransport
      import io.tether.qvac.sdk.models
      import io.tether.qvac.sdk.textToSpeech
      import java.io.File
      import java.io.IOException
      import java.nio.ByteBuffer
      import java.nio.ByteOrder
      import kotlin.math.roundToInt
      import kotlinx.coroutines.runBlocking
      import kotlinx.serialization.json.JsonObject
      import kotlinx.serialization.json.buildJsonObject
      import kotlinx.serialization.json.put

      // Only a fallback: the engine reports the rate it actually produced, and
      // `outputSampleRate` (plus the LavaSR enhancer) can move it off this default.
      private const val CHATTERBOX_SAMPLE_RATE = 24000

      fun main(args: Array<String>): Unit = runBlocking {
          val referenceAudioSrc = args.firstOrNull()

          val modelConfig = buildJsonObject {
              put("ttsEngine", "chatterbox")
              put("language", "en")
              put("s3genModelSrc", Models.TTS_S3GEN_EN_CHATTERBOX.src)
              put("streamChunkTokens", 25)
              put("streamFirstChunkTokens", 10)
              put("cfmSteps", 1)
              put("threads", 8)
              if (referenceAudioSrc != null) put("referenceAudioSrc", referenceAudioSrc)
          }

          val client = QvacClient(JvmBareKitTransport.connect())
          try {
              val modelId = client.loadWithProgress(Models.TTS_T3_TURBO_EN_CHATTERBOX_Q8_0, modelConfig)
              println("▸ Model loaded: $modelId")

              println("▸ Testing Text-to-Speech...")
              val request = TextToSpeechRequest(
                  modelId = modelId,
                  text = "QVAC SDK is the canonical entry point to QVAC. Written in TypeScript, it provides all " +
                      "QVAC capabilities through a unified interface while also abstracting away the complexity " +
                      "of running your application in a JS environment other than Bare. Supported JS " +
                      "environments include Bare, Node.js, Expo and Bun.",
                  inputType = "text",
                  stream = false,
              )

              val samples = mutableListOf<Double>()
              var sampleRate = CHATTERBOX_SAMPLE_RATE
              client.textToSpeech(request).collect { response ->
                  samples += response.buffer
                  response.sampleRate?.let { sampleRate = it.toInt() }
              }
              println("▸ TTS complete. Total samples: ${samples.size}")

              println("▸ Saving audio to file...")
              createWav(samples, sampleRate, "tts-output.wav")
              println("▸ Audio saved to tts-output.wav")

              println("▸ Playing audio...")
              val audioData = int16ArrayToBuffer(samples)
              playAudio(createWavHeader(audioData.size, sampleRate) + audioData)

              client.models.unload(modelId)
              println("▸ Model unloaded")
          } finally {
              client.close()
          }
      }

      /** Load [model], printing download progress, and return its model id. */
      private suspend fun QvacClient.loadWithProgress(model: ModelConstant, modelConfig: JsonObject? = null): String {
          var result: LoadModelResponse? = null
          models.loadWithProgress(model.src, model.engine, model.name, modelConfig = modelConfig).collect { event ->
              when (event) {
                  is QvacProgressEvent.Progress -> printProgress(event.value)
                  is QvacProgressEvent.Result -> result = event.value
              }
          }
          val loaded = checkNotNull(result) { "loadModel ended without a result" }
          return loaded.modelId ?: error(loaded.error ?: "loadModel failed")
      }

      private fun printProgress(p: ModelProgressResponse) {
          val line = "▸ Downloading %.0f%% (%.1f/%.1f MB)".format(p.percentage, p.downloaded / 1e6, p.total / 1e6)
          if (System.console() != null) System.err.print("\r$line") else System.err.println(line)
          if (p.percentage >= 100) System.err.println()
      }

      /** Create a WAV header for 16-bit mono PCM audio. */
      private fun createWavHeader(dataLength: Int, sampleRate: Int): ByteArray =
          ByteBuffer.allocate(44).order(ByteOrder.LITTLE_ENDIAN)
              .put("RIFF".toByteArray(Charsets.US_ASCII)).putInt(36 + dataLength)
              .put("WAVEfmt ".toByteArray(Charsets.US_ASCII))
              .putInt(16).putShort(1).putShort(1).putInt(sampleRate).putInt(sampleRate * 2).putShort(2).putShort(16)
              .put("data".toByteArray(Charsets.US_ASCII)).putInt(dataLength)
              .array()

      /** Convert int16 PCM samples to little-endian bytes. */
      private fun int16ArrayToBuffer(samples: List<Double>): ByteArray {
          val buffer = ByteBuffer.allocate(samples.size * 2).order(ByteOrder.LITTLE_ENDIAN)
          for (sample in samples) buffer.putShort(sample.roundToInt().coerceIn(-32768, 32767).toShort())
          return buffer.array()
      }

      /** Create and save a WAV file. */
      private fun createWav(samples: List<Double>, sampleRate: Int, filename: String) {
          val audioData = int16ArrayToBuffer(samples)
          File(filename).writeBytes(createWavHeader(audioData.size, sampleRate) + audioData)
          println("▸ WAV file saved as: $filename")
      }

      /** Play a WAV buffer by streaming it into ffplay over stdin. */
      private fun playAudio(wav: ByteArray) {
          val ffplay = try {
              ProcessBuilder("ffplay", "-hide_banner", "-loglevel", "error", "-autoexit", "-nodisp", "-i", "pipe:0")
                  .redirectOutput(ProcessBuilder.Redirect.INHERIT)
                  .redirectError(ProcessBuilder.Redirect.INHERIT)
                  .start()
          } catch (e: IOException) {
              throw IllegalStateException("ffplay not found on PATH. Install ffmpeg (ffplay ships with it) and retry.", e)
          }
          ffplay.outputStream.use { it.write(wav) }
          val code = ffplay.waitFor()
          check(code == 0) { "ffplay exited with code $code" }
      }
      ```
    </WrapCode>
  </Tab>
</Tabs>

### Supertonic

This example generates speech from text using Supertonic. It saves the speech to `supertonic-output.wav` and plays it. Arguments: none. Helper (JS/TS): [`utils`](#utils), in the same folder as the script.

<Tabs>
  <Tab value="js" label="JavaScript" default>
    <WrapCode>
      ```js file=<rootDir>/packages/sdk/dist/examples/tts/supertonic.js title="tts-supertonic.js" lineNumbers
      import { loadModel, textToSpeech, unloadModel, TTS_MULTILINGUAL_SUPERTONIC3_Q8_0 } from '@qvac/sdk';
      import { createWav, playAudio, int16ArrayToBuffer, createWavHeader } from './utils.js';
      // Supertonic 3 TTS (GGML): fast multilingual synthesis with baked-in voices.
      // Uses registry model constants — downloads automatically from QVAC Registry.
      // Only a fallback: the engine reports the rate it actually produced, and
      // `outputSampleRate` (plus the LavaSR enhancer) can move it off this default.
      const SUPERTONIC_SAMPLE_RATE = 44100;
      try {
          const modelId = await loadModel({
              modelSrc: TTS_MULTILINGUAL_SUPERTONIC3_Q8_0,
              modelConfig: {
                  ttsEngine: 'supertonic',
                  language: 'en',
                  voice: 'F1',
                  ttsSpeed: 1.05,
                  ttsNumInferenceSteps: 5
              },
              onProgress: (p) => {
                  const mb = (n) => (n / 1e6).toFixed(1);
                  const line = `▸ Downloading ${p.percentage.toFixed(0)}% (${mb(p.downloaded)}/${mb(p.total)} MB)`;
                  process.stderr.write(process.stderr.isTTY ? `\r${line}` : `${line}\n`);
                  if (p.percentage >= 100)
                      process.stderr.write('\n');
              }
          });
          console.log(`▸ Model loaded: ${modelId}`);
          console.log('▸ Testing Text-to-Speech...');
          const result = textToSpeech({
              modelId,
              text: `QVAC SDK is the canonical entry point to QVAC. Written in TypeScript, it provides all QVAC capabilities through a unified interface while also abstracting away the complexity of running your application in a JS environment other than Bare. Supported JS environments include Bare, Node.js, Expo and Bun.`,
              inputType: 'text',
              stream: false
          });
          const audioBuffer = await result.buffer;
          const sampleRate = (await result.sampleRate) ?? SUPERTONIC_SAMPLE_RATE;
          console.log(`▸ TTS complete. Total samples: ${audioBuffer.length}`);
          console.log('▸ Saving audio to file...');
          createWav(audioBuffer, sampleRate, 'supertonic-output.wav');
          console.log('▸ Audio saved to supertonic-output.wav');
          console.log('▸ Playing audio...');
          const audioData = int16ArrayToBuffer(audioBuffer);
          const wavBuffer = Buffer.concat([createWavHeader(audioData.length, sampleRate), audioData]);
          playAudio(wavBuffer);
          console.log('▸ Audio playback complete');
          await unloadModel({ modelId });
          console.log('▸ Model unloaded');
          process.exit(0);
      }
      catch (error) {
          console.error('✖', error);
          process.exit(1);
      }
      ```
    </WrapCode>
  </Tab>

  <Tab value="ts" label="TypeScript">
    <WrapCode>
      ```ts file=<rootDir>/packages/sdk/examples/tts/supertonic.ts title="tts-supertonic.ts" lineNumbers
      import {
        loadModel,
        textToSpeech,
        unloadModel,
        type ModelProgressUpdate,
        TTS_MULTILINGUAL_SUPERTONIC3_Q8_0
      } from '@qvac/sdk'
      import { createWav, playAudio, int16ArrayToBuffer, createWavHeader } from './utils.js'

      // Supertonic 3 TTS (GGML): fast multilingual synthesis with baked-in voices.
      // Uses registry model constants — downloads automatically from QVAC Registry.
      // Only a fallback: the engine reports the rate it actually produced, and
      // `outputSampleRate` (plus the LavaSR enhancer) can move it off this default.
      const SUPERTONIC_SAMPLE_RATE = 44100

      try {
        const modelId = await loadModel({
          modelSrc: TTS_MULTILINGUAL_SUPERTONIC3_Q8_0,
          modelConfig: {
            ttsEngine: 'supertonic',
            language: 'en',
            voice: 'F1',
            ttsSpeed: 1.05,
            ttsNumInferenceSteps: 5
          },
          onProgress: (p: ModelProgressUpdate) => {
            const mb = (n: number) => (n / 1e6).toFixed(1)
            const line = `▸ Downloading ${p.percentage.toFixed(0)}% (${mb(p.downloaded)}/${mb(p.total)} MB)`
            process.stderr.write(process.stderr.isTTY ? `\r${line}` : `${line}\n`)
            if (p.percentage >= 100) process.stderr.write('\n')
          }
        })

        console.log(`▸ Model loaded: ${modelId}`)

        console.log('▸ Testing Text-to-Speech...')
        const result = textToSpeech({
          modelId,
          text: `QVAC SDK is the canonical entry point to QVAC. Written in TypeScript, it provides all QVAC capabilities through a unified interface while also abstracting away the complexity of running your application in a JS environment other than Bare. Supported JS environments include Bare, Node.js, Expo and Bun.`,
          inputType: 'text',
          stream: false
        })

        const audioBuffer = await result.buffer
        const sampleRate = (await result.sampleRate) ?? SUPERTONIC_SAMPLE_RATE
        console.log(`▸ TTS complete. Total samples: ${audioBuffer.length}`)

        console.log('▸ Saving audio to file...')
        createWav(audioBuffer, sampleRate, 'supertonic-output.wav')
        console.log('▸ Audio saved to supertonic-output.wav')

        console.log('▸ Playing audio...')
        const audioData = int16ArrayToBuffer(audioBuffer)
        const wavBuffer = Buffer.concat([createWavHeader(audioData.length, sampleRate), audioData])
        playAudio(wavBuffer)
        console.log('▸ Audio playback complete')

        await unloadModel({ modelId })
        console.log('▸ Model unloaded')
        process.exit(0)
      } catch (error) {
        console.error('✖', error)
        process.exit(1)
      }
      ```
    </WrapCode>
  </Tab>

  <Tab value="python" label="Python">
    <WrapCode>
      ```python file=<rootDir>/packages/sdk-python/examples/text_to_speech.py title="text_to_speech.py" lineNumbers
      """Python port of packages/sdk/examples/tts/supertonic.ts.

      Text-to-speech with Supertonic 3 (GGML). `text_to_speech` is a server-stream;
      in non-stream mode it yields the full audio as one frame. Samples come back as
      int16 PCM values. The helpers below, ported from the JS example's `utils`, save
      them to a WAV and play it through ffplay.

      RUN: python examples/text_to_speech.py
      """

      from __future__ import annotations

      import asyncio
      import struct
      import subprocess
      import sys

      from tetherto.qvac_sdk import (
          Client,
          TextToSpeechRequest,
          load_model,
          text_to_speech,
          unload_model,
      )
      from tetherto.qvac_sdk.models import TTS_MULTILINGUAL_SUPERTONIC3_Q8_0

      # Only a fallback: the engine reports the rate it actually produced, and
      # `outputSampleRate` (plus the LavaSR enhancer) can move it off this default.
      SUPERTONIC_SAMPLE_RATE = 44100


      def print_progress(p) -> None:
          """Print model download progress; pass as `on_progress=` to `load_model`."""
          line = (
              f"▸ Downloading {p.percentage:.0f}% "
              f"({p.downloaded / 1e6:.1f}/{p.total / 1e6:.1f} MB)"
          )
          print(line, end="\r" if sys.stderr.isatty() else "\n", file=sys.stderr)
          if p.percentage >= 100:
              print(file=sys.stderr)


      def create_wav_header(data_length: int, sample_rate: int) -> bytes:
          """Create a WAV header for 16-bit mono PCM audio."""
          return (
              b"RIFF"
              + struct.pack("<I", 36 + data_length)
              + b"WAVE"
              + b"fmt "
              + struct.pack("<IHHIIHH", 16, 1, 1, sample_rate, sample_rate * 2, 2, 16)
              + b"data"
              + struct.pack("<I", data_length)
          )


      def int16_array_to_buffer(samples) -> bytes:
          """Convert int16 PCM samples to little-endian bytes."""
          return struct.pack(
              f"<{len(samples)}h",
              *(max(-32768, min(32767, round(s))) for s in samples),
          )


      def create_wav(audio_buffer, sample_rate: int, filename: str) -> None:
          """Create and save a WAV file."""
          audio_data = int16_array_to_buffer(audio_buffer)
          with open(filename, "wb") as f:
              f.write(create_wav_header(len(audio_data), sample_rate) + audio_data)
          print(f"▸ WAV file saved as: {filename}")


      def play_audio(audio_buffer: bytes) -> None:
          """Play a WAV buffer by streaming it into ffplay over stdin."""
          try:
              result = subprocess.run(
                  [
                      "ffplay",
                      "-hide_banner",
                      "-loglevel",
                      "error",
                      "-autoexit",
                      "-nodisp",
                      "-i",
                      "pipe:0",
                  ],
                  input=audio_buffer,
                  check=False,
              )
          except FileNotFoundError:
              raise RuntimeError(
                  "ffplay not found on PATH. Install ffmpeg (ffplay ships with it) and retry."
              ) from None
          if result.returncode != 0:
              raise RuntimeError(f"ffplay exited with code {result.returncode}")


      async def main() -> int:
          async with Client() as client:
              t = client.transport
              try:
                  model_id = await load_model(
                      t,
                      model_src=TTS_MULTILINGUAL_SUPERTONIC3_Q8_0,
                      model_config={
                          "ttsEngine": "supertonic",
                          "language": "en",
                          "voice": "F1",
                          "ttsSpeed": 1.05,
                          "ttsNumInferenceSteps": 5,
                      },
                      on_progress=print_progress,
                  )
                  print(f"▸ Model loaded: {model_id}")

                  print("▸ Testing Text-to-Speech...")
                  request = TextToSpeechRequest.model_validate(
                      {
                          "type": "textToSpeech",
                          "modelId": model_id,
                          "text": (
                              "QVAC SDK is the canonical entry point to QVAC. Written in "
                              "TypeScript, it provides all QVAC capabilities through a "
                              "unified interface while also abstracting away the "
                              "complexity of running your application in a JS environment "
                              "other than Bare. Supported JS environments include Bare, "
                              "Node.js, Expo and Bun."
                          ),
                          "inputType": "text",
                          "stream": False,
                      }
                  )

                  samples: list[float] = []
                  sample_rate = None
                  async for response in text_to_speech(t, request):
                      samples.extend(response.buffer)
                      if response.sample_rate is not None:
                          sample_rate = response.sample_rate
                  sample_rate = int(sample_rate or SUPERTONIC_SAMPLE_RATE)
                  print(f"▸ TTS complete. Total samples: {len(samples)}")

                  print("▸ Saving audio to file...")
                  create_wav(samples, sample_rate, "supertonic-output.wav")
                  print("▸ Audio saved to supertonic-output.wav")

                  print("▸ Playing audio...")
                  audio_data = int16_array_to_buffer(samples)
                  play_audio(create_wav_header(len(audio_data), sample_rate) + audio_data)

                  await unload_model(t, model_id)
                  print("▸ Model unloaded")
              except Exception as error:
                  print(f"✖ {error}", file=sys.stderr)
                  return 1
          return 0


      if __name__ == "__main__":
          sys.exit(asyncio.run(main()))
      ```
    </WrapCode>
  </Tab>

  <Tab value="kotlin" label="Kotlin">
    <WrapCode>
      ```kotlin file=<rootDir>/packages/sdk-kotlin/examples/src/TextToSpeech.kt title="TextToSpeech.kt" lineNumbers
      // Kotlin port of packages/sdk/examples/tts/supertonic.ts.
      //
      // Text-to-speech with Supertonic 3 (GGML). `client.textToSpeech()` is the
      // generated typed method: it takes a `TextToSpeechRequest` data class and
      // returns a `Flow<TextToSpeechResponse>`. In non-stream mode it emits the full
      // audio as one frame. Samples come back as int16 PCM values; the frame also
      // carries the `sampleRate` the engine actually produced. The helpers below,
      // ported from the JS example's `utils`, save them to a WAV and play it through
      // ffplay.
      //
      // RUN: ./gradlew -p examples run -Pexample=TextToSpeech

      import io.tether.qvac.sdk.QvacClient
      import io.tether.qvac.sdk.QvacProgressEvent
      import io.tether.qvac.sdk.generated.ModelConstant
      import io.tether.qvac.sdk.generated.Models
      import io.tether.qvac.sdk.generated.schema.LoadModelResponse
      import io.tether.qvac.sdk.generated.schema.ModelProgressResponse
      import io.tether.qvac.sdk.generated.schema.TextToSpeechRequest
      import io.tether.qvac.sdk.jvm.JvmBareKitTransport
      import io.tether.qvac.sdk.models
      import io.tether.qvac.sdk.textToSpeech
      import java.io.File
      import java.io.IOException
      import java.nio.ByteBuffer
      import java.nio.ByteOrder
      import kotlin.math.roundToInt
      import kotlinx.coroutines.runBlocking
      import kotlinx.serialization.json.JsonObject
      import kotlinx.serialization.json.buildJsonObject
      import kotlinx.serialization.json.put

      // Only a fallback: the engine reports the rate it actually produced, and
      // `outputSampleRate` (plus the LavaSR enhancer) can move it off this default.
      private const val SUPERTONIC_SAMPLE_RATE = 44100

      fun main(): Unit = runBlocking {
          val client = QvacClient(JvmBareKitTransport.connect())
          try {
              val modelId = client.loadWithProgress(
                  Models.TTS_MULTILINGUAL_SUPERTONIC3_Q8_0,
                  modelConfig = buildJsonObject {
                      put("ttsEngine", "supertonic")
                      put("language", "en")
                      put("voice", "F1")
                      put("ttsSpeed", 1.05)
                      put("ttsNumInferenceSteps", 5)
                  },
              )
              println("▸ Model loaded: $modelId")

              println("▸ Testing Text-to-Speech...")
              val request = TextToSpeechRequest(
                  modelId = modelId,
                  text = "QVAC SDK is the canonical entry point to QVAC. Written in TypeScript, it provides all " +
                      "QVAC capabilities through a unified interface while also abstracting away the complexity " +
                      "of running your application in a JS environment other than Bare. Supported JS " +
                      "environments include Bare, Node.js, Expo and Bun.",
                  inputType = "text",
                  stream = false,
              )

              val samples = mutableListOf<Double>()
              var sampleRate = SUPERTONIC_SAMPLE_RATE
              client.textToSpeech(request).collect { response ->
                  samples += response.buffer
                  response.sampleRate?.let { sampleRate = it.toInt() }
              }
              println("▸ TTS complete. Total samples: ${samples.size}")

              println("▸ Saving audio to file...")
              createWav(samples, sampleRate, "supertonic-output.wav")
              println("▸ Audio saved to supertonic-output.wav")

              println("▸ Playing audio...")
              val audioData = int16ArrayToBuffer(samples)
              playAudio(createWavHeader(audioData.size, sampleRate) + audioData)

              client.models.unload(modelId)
              println("▸ Model unloaded")
          } finally {
              client.close()
          }
      }

      /** Load [model], printing download progress, and return its model id. */
      private suspend fun QvacClient.loadWithProgress(model: ModelConstant, modelConfig: JsonObject? = null): String {
          var result: LoadModelResponse? = null
          models.loadWithProgress(model.src, model.engine, model.name, modelConfig = modelConfig).collect { event ->
              when (event) {
                  is QvacProgressEvent.Progress -> printProgress(event.value)
                  is QvacProgressEvent.Result -> result = event.value
              }
          }
          val loaded = checkNotNull(result) { "loadModel ended without a result" }
          return loaded.modelId ?: error(loaded.error ?: "loadModel failed")
      }

      private fun printProgress(p: ModelProgressResponse) {
          val line = "▸ Downloading %.0f%% (%.1f/%.1f MB)".format(p.percentage, p.downloaded / 1e6, p.total / 1e6)
          if (System.console() != null) System.err.print("\r$line") else System.err.println(line)
          if (p.percentage >= 100) System.err.println()
      }

      /** Create a WAV header for 16-bit mono PCM audio. */
      private fun createWavHeader(dataLength: Int, sampleRate: Int): ByteArray =
          ByteBuffer.allocate(44).order(ByteOrder.LITTLE_ENDIAN)
              .put("RIFF".toByteArray(Charsets.US_ASCII)).putInt(36 + dataLength)
              .put("WAVEfmt ".toByteArray(Charsets.US_ASCII))
              .putInt(16).putShort(1).putShort(1).putInt(sampleRate).putInt(sampleRate * 2).putShort(2).putShort(16)
              .put("data".toByteArray(Charsets.US_ASCII)).putInt(dataLength)
              .array()

      /** Convert int16 PCM samples to little-endian bytes. */
      private fun int16ArrayToBuffer(samples: List<Double>): ByteArray {
          val buffer = ByteBuffer.allocate(samples.size * 2).order(ByteOrder.LITTLE_ENDIAN)
          for (sample in samples) buffer.putShort(sample.roundToInt().coerceIn(-32768, 32767).toShort())
          return buffer.array()
      }

      /** Create and save a WAV file. */
      private fun createWav(samples: List<Double>, sampleRate: Int, filename: String) {
          val audioData = int16ArrayToBuffer(samples)
          File(filename).writeBytes(createWavHeader(audioData.size, sampleRate) + audioData)
          println("▸ WAV file saved as: $filename")
      }

      /** Play a WAV buffer by streaming it into ffplay over stdin. */
      private fun playAudio(wav: ByteArray) {
          val ffplay = try {
              ProcessBuilder("ffplay", "-hide_banner", "-loglevel", "error", "-autoexit", "-nodisp", "-i", "pipe:0")
                  .redirectOutput(ProcessBuilder.Redirect.INHERIT)
                  .redirectError(ProcessBuilder.Redirect.INHERIT)
                  .start()
          } catch (e: IOException) {
              throw IllegalStateException("ffplay not found on PATH. Install ffmpeg (ffplay ships with it) and retry.", e)
          }
          ffplay.outputStream.use { it.write(wav) }
          val code = ffplay.waitFor()
          check(code == 0) { "ffplay exited with code $code" }
      }
      ```
    </WrapCode>
  </Tab>
</Tabs>

### Parler-TTS

This example generates speech from text using Parler-TTS. It sets an emotion on the request, saves the speech to `parler-output.wav`, and plays it. Arguments: none. Helper (JS/TS): [`utils`](#utils), in the same folder as the script.

<Tabs>
  <Tab value="js" label="JavaScript" default>
    <WrapCode>
      ```js file=<rootDir>/packages/sdk/dist/examples/tts/parler.js title="tts-parler.js" lineNumbers
      import { loadModel, textToSpeech, unloadModel, TTS_MINI_V1_EN_PARLER_TTS_Q8_0 } from '@qvac/sdk';
      import { createWav, playAudio, int16ArrayToBuffer, createWavHeader } from './utils.js';
      // Parler-TTS (GGML): description-conditioned speech with per-call voice controls.
      // Uses the registry-hosted Mini v1 Q8_0 model and its native 44.1 kHz output.
      // Only a fallback: the engine reports the rate it actually produced, and
      // `outputSampleRate` (plus the LavaSR enhancer) can move it off this default.
      const PARLER_SAMPLE_RATE = 44100;
      try {
          const modelId = await loadModel({
              modelSrc: TTS_MINI_V1_EN_PARLER_TTS_Q8_0,
              modelConfig: {
                  ttsEngine: 'parler',
                  voice: 'Laura',
                  seed: 42
              },
              onProgress: (p) => {
                  const mb = (n) => (n / 1e6).toFixed(1);
                  const line = `▸ Downloading ${p.percentage.toFixed(0)}% (${mb(p.downloaded)}/${mb(p.total)} MB)`;
                  process.stderr.write(process.stderr.isTTY ? `\r${line}` : `${line}\n`);
                  if (p.percentage >= 100)
                      process.stderr.write('\n');
              }
          });
          console.log(`▸ Model loaded: ${modelId}`);
          console.log('▸ Testing Parler Text-to-Speech...');
          const result = textToSpeech({
              modelId,
              text: 'Hey, how are you doing today?',
              inputType: 'text',
              stream: false,
              emotion: 'happy'
          });
          const audioBuffer = await result.buffer;
          const sampleRate = (await result.sampleRate) ?? PARLER_SAMPLE_RATE;
          console.log(`▸ TTS complete. Total samples: ${audioBuffer.length}`);
          console.log('▸ Saving audio to file...');
          createWav(audioBuffer, sampleRate, 'parler-output.wav');
          console.log('▸ Audio saved to parler-output.wav');
          console.log('▸ Playing audio...');
          const audioData = int16ArrayToBuffer(audioBuffer);
          const wavBuffer = Buffer.concat([createWavHeader(audioData.length, sampleRate), audioData]);
          playAudio(wavBuffer);
          console.log('▸ Audio playback complete');
          await unloadModel({ modelId });
          console.log('▸ Model unloaded');
          process.exit(0);
      }
      catch (error) {
          console.error('✖', error);
          process.exit(1);
      }
      ```
    </WrapCode>
  </Tab>

  <Tab value="ts" label="TypeScript">
    <WrapCode>
      ```ts file=<rootDir>/packages/sdk/examples/tts/parler.ts title="tts-parler.ts" lineNumbers
      import {
        loadModel,
        textToSpeech,
        unloadModel,
        type ModelProgressUpdate,
        TTS_MINI_V1_EN_PARLER_TTS_Q8_0
      } from '@qvac/sdk'
      import { createWav, playAudio, int16ArrayToBuffer, createWavHeader } from './utils.js'

      // Parler-TTS (GGML): description-conditioned speech with per-call voice controls.
      // Uses the registry-hosted Mini v1 Q8_0 model and its native 44.1 kHz output.
      // Only a fallback: the engine reports the rate it actually produced, and
      // `outputSampleRate` (plus the LavaSR enhancer) can move it off this default.
      const PARLER_SAMPLE_RATE = 44100

      try {
        const modelId = await loadModel({
          modelSrc: TTS_MINI_V1_EN_PARLER_TTS_Q8_0,
          modelConfig: {
            ttsEngine: 'parler',
            voice: 'Laura',
            seed: 42
          },
          onProgress: (p: ModelProgressUpdate) => {
            const mb = (n: number) => (n / 1e6).toFixed(1)
            const line = `▸ Downloading ${p.percentage.toFixed(0)}% (${mb(p.downloaded)}/${mb(p.total)} MB)`
            process.stderr.write(process.stderr.isTTY ? `\r${line}` : `${line}\n`)
            if (p.percentage >= 100) process.stderr.write('\n')
          }
        })

        console.log(`▸ Model loaded: ${modelId}`)

        console.log('▸ Testing Parler Text-to-Speech...')
        const result = textToSpeech({
          modelId,
          text: 'Hey, how are you doing today?',
          inputType: 'text',
          stream: false,
          emotion: 'happy'
        })

        const audioBuffer = await result.buffer
        const sampleRate = (await result.sampleRate) ?? PARLER_SAMPLE_RATE
        console.log(`▸ TTS complete. Total samples: ${audioBuffer.length}`)

        console.log('▸ Saving audio to file...')
        createWav(audioBuffer, sampleRate, 'parler-output.wav')
        console.log('▸ Audio saved to parler-output.wav')

        console.log('▸ Playing audio...')
        const audioData = int16ArrayToBuffer(audioBuffer)
        const wavBuffer = Buffer.concat([createWavHeader(audioData.length, sampleRate), audioData])
        playAudio(wavBuffer)
        console.log('▸ Audio playback complete')

        await unloadModel({ modelId })
        console.log('▸ Model unloaded')
        process.exit(0)
      } catch (error) {
        console.error('✖', error)
        process.exit(1)
      }
      ```
    </WrapCode>
  </Tab>

  <Tab value="python" label="Python">
    <WrapCode>
      ```python file=<rootDir>/packages/sdk-python/examples/text_to_speech_parler.py title="text_to_speech_parler.py" lineNumbers
      """Python port of packages/sdk/examples/tts/parler.ts.

      Parler-TTS (GGML): description-conditioned speech with per-call voice controls.
      Uses the registry-hosted Mini v1 Q8_0 model and its native 44.1 kHz output,
      with a per-request `emotion`. `text_to_speech` is a server-stream; in non-
      stream mode it yields the full audio as one frame. Samples come back as int16
      PCM values. The helpers below, ported from the JS example's `utils`, save them
      to a WAV and play it through ffplay.

      RUN: python examples/text_to_speech_parler.py
      """

      from __future__ import annotations

      import asyncio
      import struct
      import subprocess
      import sys

      from tetherto.qvac_sdk import (
          Client,
          TextToSpeechRequest,
          load_model,
          text_to_speech,
          unload_model,
      )
      from tetherto.qvac_sdk.models import TTS_MINI_V1_EN_PARLER_TTS_Q8_0

      # Only a fallback: the engine reports the rate it actually produced, and
      # `outputSampleRate` (plus the LavaSR enhancer) can move it off this default.
      PARLER_SAMPLE_RATE = 44100


      def print_progress(p) -> None:
          """Print model download progress; pass as `on_progress=` to `load_model`."""
          line = (
              f"▸ Downloading {p.percentage:.0f}% "
              f"({p.downloaded / 1e6:.1f}/{p.total / 1e6:.1f} MB)"
          )
          print(line, end="\r" if sys.stderr.isatty() else "\n", file=sys.stderr)
          if p.percentage >= 100:
              print(file=sys.stderr)


      def create_wav_header(data_length: int, sample_rate: int) -> bytes:
          """Create a WAV header for 16-bit mono PCM audio."""
          return (
              b"RIFF"
              + struct.pack("<I", 36 + data_length)
              + b"WAVE"
              + b"fmt "
              + struct.pack("<IHHIIHH", 16, 1, 1, sample_rate, sample_rate * 2, 2, 16)
              + b"data"
              + struct.pack("<I", data_length)
          )


      def int16_array_to_buffer(samples) -> bytes:
          """Convert int16 PCM samples to little-endian bytes."""
          return struct.pack(
              f"<{len(samples)}h",
              *(max(-32768, min(32767, round(s))) for s in samples),
          )


      def create_wav(audio_buffer, sample_rate: int, filename: str) -> None:
          """Create and save a WAV file."""
          audio_data = int16_array_to_buffer(audio_buffer)
          with open(filename, "wb") as f:
              f.write(create_wav_header(len(audio_data), sample_rate) + audio_data)
          print(f"▸ WAV file saved as: {filename}")


      def play_audio(audio_buffer: bytes) -> None:
          """Play a WAV buffer by streaming it into ffplay over stdin."""
          try:
              result = subprocess.run(
                  [
                      "ffplay",
                      "-hide_banner",
                      "-loglevel",
                      "error",
                      "-autoexit",
                      "-nodisp",
                      "-i",
                      "pipe:0",
                  ],
                  input=audio_buffer,
                  check=False,
              )
          except FileNotFoundError:
              raise RuntimeError(
                  "ffplay not found on PATH. Install ffmpeg (ffplay ships with it) and retry."
              ) from None
          if result.returncode != 0:
              raise RuntimeError(f"ffplay exited with code {result.returncode}")


      async def main() -> int:
          async with Client() as client:
              t = client.transport
              try:
                  model_id = await load_model(
                      t,
                      model_src=TTS_MINI_V1_EN_PARLER_TTS_Q8_0,
                      model_config={
                          "ttsEngine": "parler",
                          "voice": "Laura",
                          "seed": 42,
                      },
                      on_progress=print_progress,
                  )
                  print(f"▸ Model loaded: {model_id}")

                  print("▸ Testing Parler Text-to-Speech...")
                  request = TextToSpeechRequest.model_validate(
                      {
                          "type": "textToSpeech",
                          "modelId": model_id,
                          "text": "Hey, how are you doing today?",
                          "inputType": "text",
                          "stream": False,
                          "emotion": "happy",
                      }
                  )

                  samples: list[float] = []
                  sample_rate = None
                  async for response in text_to_speech(t, request):
                      samples.extend(response.buffer)
                      if response.sample_rate is not None:
                          sample_rate = response.sample_rate
                  sample_rate = int(sample_rate or PARLER_SAMPLE_RATE)
                  print(f"▸ TTS complete. Total samples: {len(samples)}")

                  print("▸ Saving audio to file...")
                  create_wav(samples, sample_rate, "parler-output.wav")
                  print("▸ Audio saved to parler-output.wav")

                  print("▸ Playing audio...")
                  audio_data = int16_array_to_buffer(samples)
                  play_audio(create_wav_header(len(audio_data), sample_rate) + audio_data)

                  await unload_model(t, model_id)
                  print("▸ Model unloaded")
              except Exception as error:
                  print(f"✖ {error}", file=sys.stderr)
                  return 1
          return 0


      if __name__ == "__main__":
          sys.exit(asyncio.run(main()))
      ```
    </WrapCode>
  </Tab>

  <Tab value="kotlin" label="Kotlin">
    <WrapCode>
      ```kotlin file=<rootDir>/packages/sdk-kotlin/examples/src/TextToSpeechParler.kt title="TextToSpeechParler.kt" lineNumbers
      // Kotlin port of packages/sdk/examples/tts/parler.ts.
      //
      // Parler-TTS (GGML): description-conditioned speech with per-call voice
      // controls. Uses the registry-hosted Mini v1 Q8_0 model and its native
      // 44.1 kHz output, with a per-request `emotion`.
      //
      // `client.textToSpeech()` is the generated typed method: it takes a
      // `TextToSpeechRequest` data class and returns a `Flow<TextToSpeechResponse>`.
      // `emotion` is the generated `TextToSpeechRequestEmotion` enum, so a misspelled
      // emotion fails at compile time instead of at the worker. In non-stream mode
      // the flow emits the full audio as one frame. Samples come back as int16 PCM
      // values. The helpers below, ported from the JS example's `utils`, save them to
      // a WAV and play it through ffplay.
      //
      // RUN: ./gradlew -p examples run -Pexample=TextToSpeechParler

      import io.tether.qvac.sdk.QvacClient
      import io.tether.qvac.sdk.QvacProgressEvent
      import io.tether.qvac.sdk.generated.ModelConstant
      import io.tether.qvac.sdk.generated.Models
      import io.tether.qvac.sdk.generated.schema.LoadModelResponse
      import io.tether.qvac.sdk.generated.schema.ModelProgressResponse
      import io.tether.qvac.sdk.generated.schema.TextToSpeechRequest
      import io.tether.qvac.sdk.generated.schema.TextToSpeechRequestEmotion
      import io.tether.qvac.sdk.jvm.JvmBareKitTransport
      import io.tether.qvac.sdk.models
      import io.tether.qvac.sdk.textToSpeech
      import java.io.File
      import java.io.IOException
      import java.nio.ByteBuffer
      import java.nio.ByteOrder
      import kotlin.math.roundToInt
      import kotlinx.coroutines.runBlocking
      import kotlinx.serialization.json.JsonObject
      import kotlinx.serialization.json.buildJsonObject
      import kotlinx.serialization.json.put

      // Only a fallback: the engine reports the rate it actually produced, and
      // `outputSampleRate` (plus the LavaSR enhancer) can move it off this default.
      private const val PARLER_SAMPLE_RATE = 44100

      fun main(): Unit = runBlocking {
          val client = QvacClient(JvmBareKitTransport.connect())
          try {
              val modelId = client.loadWithProgress(
                  Models.TTS_MINI_V1_EN_PARLER_TTS_Q8_0,
                  modelConfig = buildJsonObject {
                      put("ttsEngine", "parler")
                      put("voice", "Laura")
                      put("seed", 42)
                  },
              )
              println("▸ Model loaded: $modelId")

              println("▸ Testing Parler Text-to-Speech...")
              val request = TextToSpeechRequest(
                  modelId = modelId,
                  text = "Hey, how are you doing today?",
                  inputType = "text",
                  stream = false,
                  emotion = TextToSpeechRequestEmotion.HAPPY,
              )

              val samples = mutableListOf<Double>()
              var sampleRate = PARLER_SAMPLE_RATE
              client.textToSpeech(request).collect { response ->
                  samples += response.buffer
                  response.sampleRate?.let { sampleRate = it.toInt() }
              }
              println("▸ TTS complete. Total samples: ${samples.size}")

              println("▸ Saving audio to file...")
              createWav(samples, sampleRate, "parler-output.wav")
              println("▸ Audio saved to parler-output.wav")

              println("▸ Playing audio...")
              val audioData = int16ArrayToBuffer(samples)
              playAudio(createWavHeader(audioData.size, sampleRate) + audioData)

              client.models.unload(modelId)
              println("▸ Model unloaded")
          } finally {
              client.close()
          }
      }

      /** Load [model], printing download progress, and return its model id. */
      private suspend fun QvacClient.loadWithProgress(model: ModelConstant, modelConfig: JsonObject? = null): String {
          var result: LoadModelResponse? = null
          models.loadWithProgress(model.src, model.engine, model.name, modelConfig = modelConfig).collect { event ->
              when (event) {
                  is QvacProgressEvent.Progress -> printProgress(event.value)
                  is QvacProgressEvent.Result -> result = event.value
              }
          }
          val loaded = checkNotNull(result) { "loadModel ended without a result" }
          return loaded.modelId ?: error(loaded.error ?: "loadModel failed")
      }

      private fun printProgress(p: ModelProgressResponse) {
          val line = "▸ Downloading %.0f%% (%.1f/%.1f MB)".format(p.percentage, p.downloaded / 1e6, p.total / 1e6)
          if (System.console() != null) System.err.print("\r$line") else System.err.println(line)
          if (p.percentage >= 100) System.err.println()
      }

      /** Create a WAV header for 16-bit mono PCM audio. */
      private fun createWavHeader(dataLength: Int, sampleRate: Int): ByteArray =
          ByteBuffer.allocate(44).order(ByteOrder.LITTLE_ENDIAN)
              .put("RIFF".toByteArray(Charsets.US_ASCII)).putInt(36 + dataLength)
              .put("WAVEfmt ".toByteArray(Charsets.US_ASCII))
              .putInt(16).putShort(1).putShort(1).putInt(sampleRate).putInt(sampleRate * 2).putShort(2).putShort(16)
              .put("data".toByteArray(Charsets.US_ASCII)).putInt(dataLength)
              .array()

      /** Convert int16 PCM samples to little-endian bytes. */
      private fun int16ArrayToBuffer(samples: List<Double>): ByteArray {
          val buffer = ByteBuffer.allocate(samples.size * 2).order(ByteOrder.LITTLE_ENDIAN)
          for (sample in samples) buffer.putShort(sample.roundToInt().coerceIn(-32768, 32767).toShort())
          return buffer.array()
      }

      /** Create and save a WAV file. */
      private fun createWav(samples: List<Double>, sampleRate: Int, filename: String) {
          val audioData = int16ArrayToBuffer(samples)
          File(filename).writeBytes(createWavHeader(audioData.size, sampleRate) + audioData)
          println("▸ WAV file saved as: $filename")
      }

      /** Play a WAV buffer by streaming it into ffplay over stdin. */
      private fun playAudio(wav: ByteArray) {
          val ffplay = try {
              ProcessBuilder("ffplay", "-hide_banner", "-loglevel", "error", "-autoexit", "-nodisp", "-i", "pipe:0")
                  .redirectOutput(ProcessBuilder.Redirect.INHERIT)
                  .redirectError(ProcessBuilder.Redirect.INHERIT)
                  .start()
          } catch (e: IOException) {
              throw IllegalStateException("ffplay not found on PATH. Install ffmpeg (ffplay ships with it) and retry.", e)
          }
          ffplay.outputStream.use { it.write(wav) }
          val code = ffplay.waitFor()
          check(code == 0) { "ffplay exited with code $code" }
      }
      ```
    </WrapCode>
  </Tab>
</Tabs>

### CosyVoice3

This example generates speech from text using CosyVoice3. It sets an emotion on the request, saves the speech to `cosyvoice3-output.wav`, and plays it. Arguments: none. Helper (JS/TS): [`utils`](#utils), in the same folder as the script.

<Tabs>
  <Tab value="js" label="JavaScript" default>
    <WrapCode>
      ```js file=<rootDir>/packages/sdk/dist/examples/tts/cosyvoice3.js title="tts-cosyvoice3.js" lineNumbers
      import { loadModel, textToSpeech, unloadModel, TTS_COSYVOICE3_LLM_COSYVOICE_Q8_0 } from '@qvac/sdk';
      import { createWav, playAudio, int16ArrayToBuffer, createWavHeader } from './utils.js';
      // CosyVoice3 (GGML): zero-shot speech with one conditioning control per
      // synthesis (emotion, pace, or instruct). The LLM GGUF's registry companion
      // set downloads the flow/HiFT models, baked voice and tokenizer alongside it.
      // Native output is 24 kHz.
      // Only a fallback: the engine reports the rate it actually produced, and
      // `outputSampleRate` (plus the LavaSR enhancer) can move it off this default.
      const COSYVOICE3_SAMPLE_RATE = 24000;
      try {
          const modelId = await loadModel({
              modelSrc: TTS_COSYVOICE3_LLM_COSYVOICE_Q8_0,
              modelConfig: {
                  ttsEngine: 'cosyvoice3',
                  seed: 42
              },
              onProgress: (p) => {
                  const mb = (n) => (n / 1e6).toFixed(1);
                  const line = `▸ Downloading ${p.percentage.toFixed(0)}% (${mb(p.downloaded)}/${mb(p.total)} MB)`;
                  process.stderr.write(process.stderr.isTTY ? `\r${line}` : `${line}\n`);
                  if (p.percentage >= 100)
                      process.stderr.write('\n');
              }
          });
          console.log(`▸ Model loaded: ${modelId}`);
          console.log('▸ Testing CosyVoice3 Text-to-Speech...');
          const result = textToSpeech({
              modelId,
              text: 'Hey, how are you doing today?',
              inputType: 'text',
              stream: false,
              emotion: 'happy'
          });
          const audioBuffer = await result.buffer;
          const sampleRate = (await result.sampleRate) ?? COSYVOICE3_SAMPLE_RATE;
          console.log(`▸ TTS complete. Total samples: ${audioBuffer.length}`);
          console.log('▸ Saving audio to file...');
          createWav(audioBuffer, sampleRate, 'cosyvoice3-output.wav');
          console.log('▸ Audio saved to cosyvoice3-output.wav');
          console.log('▸ Playing audio...');
          const audioData = int16ArrayToBuffer(audioBuffer);
          const wavBuffer = Buffer.concat([createWavHeader(audioData.length, sampleRate), audioData]);
          playAudio(wavBuffer);
          console.log('▸ Audio playback complete');
          await unloadModel({ modelId });
          console.log('▸ Model unloaded');
          process.exit(0);
      }
      catch (error) {
          console.error('✖', error);
          process.exit(1);
      }
      ```
    </WrapCode>
  </Tab>

  <Tab value="ts" label="TypeScript">
    <WrapCode>
      ```ts file=<rootDir>/packages/sdk/examples/tts/cosyvoice3.ts title="tts-cosyvoice3.ts" lineNumbers
      import {
        loadModel,
        textToSpeech,
        unloadModel,
        type ModelProgressUpdate,
        TTS_COSYVOICE3_LLM_COSYVOICE_Q8_0
      } from '@qvac/sdk'
      import { createWav, playAudio, int16ArrayToBuffer, createWavHeader } from './utils.js'

      // CosyVoice3 (GGML): zero-shot speech with one conditioning control per
      // synthesis (emotion, pace, or instruct). The LLM GGUF's registry companion
      // set downloads the flow/HiFT models, baked voice and tokenizer alongside it.
      // Native output is 24 kHz.
      // Only a fallback: the engine reports the rate it actually produced, and
      // `outputSampleRate` (plus the LavaSR enhancer) can move it off this default.
      const COSYVOICE3_SAMPLE_RATE = 24000

      try {
        const modelId = await loadModel({
          modelSrc: TTS_COSYVOICE3_LLM_COSYVOICE_Q8_0,
          modelConfig: {
            ttsEngine: 'cosyvoice3',
            seed: 42
          },
          onProgress: (p: ModelProgressUpdate) => {
            const mb = (n: number) => (n / 1e6).toFixed(1)
            const line = `▸ Downloading ${p.percentage.toFixed(0)}% (${mb(p.downloaded)}/${mb(p.total)} MB)`
            process.stderr.write(process.stderr.isTTY ? `\r${line}` : `${line}\n`)
            if (p.percentage >= 100) process.stderr.write('\n')
          }
        })

        console.log(`▸ Model loaded: ${modelId}`)

        console.log('▸ Testing CosyVoice3 Text-to-Speech...')
        const result = textToSpeech({
          modelId,
          text: 'Hey, how are you doing today?',
          inputType: 'text',
          stream: false,
          emotion: 'happy'
        })

        const audioBuffer = await result.buffer
        const sampleRate = (await result.sampleRate) ?? COSYVOICE3_SAMPLE_RATE
        console.log(`▸ TTS complete. Total samples: ${audioBuffer.length}`)

        console.log('▸ Saving audio to file...')
        createWav(audioBuffer, sampleRate, 'cosyvoice3-output.wav')
        console.log('▸ Audio saved to cosyvoice3-output.wav')

        console.log('▸ Playing audio...')
        const audioData = int16ArrayToBuffer(audioBuffer)
        const wavBuffer = Buffer.concat([createWavHeader(audioData.length, sampleRate), audioData])
        playAudio(wavBuffer)
        console.log('▸ Audio playback complete')

        await unloadModel({ modelId })
        console.log('▸ Model unloaded')
        process.exit(0)
      } catch (error) {
        console.error('✖', error)
        process.exit(1)
      }
      ```
    </WrapCode>
  </Tab>

  <Tab value="python" label="Python">
    <WrapCode>
      ```python file=<rootDir>/packages/sdk-python/examples/text_to_speech_cosyvoice3.py title="text_to_speech_cosyvoice3.py" lineNumbers
      """Python port of packages/sdk/examples/tts/cosyvoice3.ts.

      CosyVoice3 (GGML): zero-shot speech with one conditioning control per
      synthesis (emotion, pace, or instruct). The LLM GGUF's registry companion set
      downloads the flow/HiFT models, baked voice and tokenizer alongside it. Native
      output is 24 kHz.

      `text_to_speech` is a server-stream; in non-stream mode it yields the full
      audio as one frame. Samples come back as int16 PCM values. The helpers below,
      ported from the JS example's `utils`, save them to a WAV and play it through
      ffplay.

      RUN: python examples/text_to_speech_cosyvoice3.py
      """

      from __future__ import annotations

      import asyncio
      import struct
      import subprocess
      import sys

      from tetherto.qvac_sdk import (
          Client,
          TextToSpeechRequest,
          load_model,
          text_to_speech,
          unload_model,
      )
      from tetherto.qvac_sdk.models import (
          TTS_COSYVOICE3_LLM_COSYVOICE_Q8_0,
      )

      # Only a fallback: the engine reports the rate it actually produced.
      COSYVOICE3_SAMPLE_RATE = 24000


      def print_progress(p) -> None:
          """Print model download progress; pass as `on_progress=` to `load_model`."""
          line = (
              f"▸ Downloading {p.percentage:.0f}% "
              f"({p.downloaded / 1e6:.1f}/{p.total / 1e6:.1f} MB)"
          )
          print(line, end="\r" if sys.stderr.isatty() else "\n", file=sys.stderr)
          if p.percentage >= 100:
              print(file=sys.stderr)


      def create_wav_header(data_length: int, sample_rate: int) -> bytes:
          """Create a WAV header for 16-bit mono PCM audio."""
          return (
              b"RIFF"
              + struct.pack("<I", 36 + data_length)
              + b"WAVE"
              + b"fmt "
              + struct.pack("<IHHIIHH", 16, 1, 1, sample_rate, sample_rate * 2, 2, 16)
              + b"data"
              + struct.pack("<I", data_length)
          )


      def int16_array_to_buffer(samples) -> bytes:
          """Convert int16 PCM samples to little-endian bytes."""
          return struct.pack(
              f"<{len(samples)}h",
              *(max(-32768, min(32767, round(s))) for s in samples),
          )


      def create_wav(audio_buffer, sample_rate: int, filename: str) -> None:
          """Create and save a WAV file."""
          audio_data = int16_array_to_buffer(audio_buffer)
          with open(filename, "wb") as f:
              f.write(create_wav_header(len(audio_data), sample_rate) + audio_data)
          print(f"▸ WAV file saved as: {filename}")


      def play_audio(audio_buffer: bytes) -> None:
          """Play a WAV buffer by streaming it into ffplay over stdin."""
          try:
              result = subprocess.run(
                  [
                      "ffplay",
                      "-hide_banner",
                      "-loglevel",
                      "error",
                      "-autoexit",
                      "-nodisp",
                      "-i",
                      "pipe:0",
                  ],
                  input=audio_buffer,
                  check=False,
              )
          except FileNotFoundError:
              raise RuntimeError(
                  "ffplay not found on PATH. Install ffmpeg (ffplay ships with it) and retry."
              ) from None
          if result.returncode != 0:
              raise RuntimeError(f"ffplay exited with code {result.returncode}")


      async def main() -> int:
          model_config = {"ttsEngine": "cosyvoice3", "seed": 42}

          async with Client() as client:
              t = client.transport
              try:
                  model_id = await load_model(
                      t,
                      model_src=TTS_COSYVOICE3_LLM_COSYVOICE_Q8_0,
                      model_config=model_config,
                      on_progress=print_progress,
                  )
                  print(f"▸ Model loaded: {model_id}")

                  print("▸ Testing CosyVoice3 Text-to-Speech...")
                  request = TextToSpeechRequest.model_validate(
                      {
                          "type": "textToSpeech",
                          "modelId": model_id,
                          "text": "Hey, how are you doing today?",
                          "inputType": "text",
                          "stream": False,
                          "emotion": "happy",
                      }
                  )

                  samples: list[float] = []
                  sample_rate = None
                  async for response in text_to_speech(t, request):
                      samples.extend(response.buffer)
                      if response.sample_rate is not None:
                          sample_rate = response.sample_rate
                  sample_rate = int(sample_rate or COSYVOICE3_SAMPLE_RATE)
                  print(f"▸ TTS complete. Total samples: {len(samples)}")

                  print("▸ Saving audio to file...")
                  create_wav(samples, sample_rate, "cosyvoice3-output.wav")
                  print("▸ Audio saved to cosyvoice3-output.wav")

                  print("▸ Playing audio...")
                  audio_data = int16_array_to_buffer(samples)
                  play_audio(create_wav_header(len(audio_data), sample_rate) + audio_data)

                  await unload_model(t, model_id)
                  print("▸ Model unloaded")
              except Exception as error:
                  print(f"✖ {error}", file=sys.stderr)
                  return 1
          return 0


      if __name__ == "__main__":
          sys.exit(asyncio.run(main()))
      ```
    </WrapCode>
  </Tab>

  <Tab value="kotlin" label="Kotlin">
    <WrapCode>
      ```kotlin file=<rootDir>/packages/sdk-kotlin/examples/src/TextToSpeechCosyvoice3.kt title="TextToSpeechCosyvoice3.kt" lineNumbers
      // Kotlin port of packages/sdk/examples/tts/cosyvoice3.ts.
      //
      // CosyVoice3 (GGML): zero-shot speech with one conditioning control per
      // synthesis (emotion, pace, or instruct). The LLM GGUF's registry companion set
      // downloads the flow/HiFT models, baked voice and tokenizer alongside it.
      // Native output is 24 kHz.
      //
      // `client.textToSpeech()` is the generated typed method: it takes a
      // `TextToSpeechRequest` data class and returns a `Flow<TextToSpeechResponse>`.
      // `emotion` is the generated `TextToSpeechRequestEmotion` enum, so a misspelled
      // emotion fails at compile time instead of at the worker. In non-stream mode
      // the flow emits the full audio as one frame. Samples come back as int16 PCM
      // values. The helpers below, ported from the JS example's `utils`, save them to
      // a WAV and play it through ffplay.
      //
      // RUN: ./gradlew -p examples run -Pexample=TextToSpeechCosyvoice3

      import io.tether.qvac.sdk.QvacClient
      import io.tether.qvac.sdk.QvacProgressEvent
      import io.tether.qvac.sdk.generated.ModelConstant
      import io.tether.qvac.sdk.generated.Models
      import io.tether.qvac.sdk.generated.schema.LoadModelResponse
      import io.tether.qvac.sdk.generated.schema.ModelProgressResponse
      import io.tether.qvac.sdk.generated.schema.TextToSpeechRequest
      import io.tether.qvac.sdk.generated.schema.TextToSpeechRequestEmotion
      import io.tether.qvac.sdk.jvm.JvmBareKitTransport
      import io.tether.qvac.sdk.models
      import io.tether.qvac.sdk.textToSpeech
      import java.io.File
      import java.io.IOException
      import java.nio.ByteBuffer
      import java.nio.ByteOrder
      import kotlin.math.roundToInt
      import kotlinx.coroutines.runBlocking
      import kotlinx.serialization.json.JsonObject
      import kotlinx.serialization.json.buildJsonObject
      import kotlinx.serialization.json.put

      // Only a fallback: the engine reports the rate it actually produced.
      private const val COSYVOICE3_SAMPLE_RATE = 24000

      fun main(): Unit = runBlocking {
          val modelConfig = buildJsonObject {
              put("ttsEngine", "cosyvoice3")
              put("seed", 42)
          }

          val client = QvacClient(JvmBareKitTransport.connect())
          try {
              val modelId = client.loadWithProgress(Models.TTS_COSYVOICE3_LLM_COSYVOICE_Q8_0, modelConfig)
              println("▸ Model loaded: $modelId")

              println("▸ Testing CosyVoice3 Text-to-Speech...")
              val request = TextToSpeechRequest(
                  modelId = modelId,
                  text = "Hey, how are you doing today?",
                  inputType = "text",
                  stream = false,
                  emotion = TextToSpeechRequestEmotion.HAPPY,
              )

              val samples = mutableListOf<Double>()
              var sampleRate = COSYVOICE3_SAMPLE_RATE
              client.textToSpeech(request).collect { response ->
                  samples += response.buffer
                  response.sampleRate?.let { sampleRate = it.toInt() }
              }
              println("▸ TTS complete. Total samples: ${samples.size}")

              println("▸ Saving audio to file...")
              createWav(samples, sampleRate, "cosyvoice3-output.wav")
              println("▸ Audio saved to cosyvoice3-output.wav")

              println("▸ Playing audio...")
              val audioData = int16ArrayToBuffer(samples)
              playAudio(createWavHeader(audioData.size, sampleRate) + audioData)

              client.models.unload(modelId)
              println("▸ Model unloaded")
          } finally {
              client.close()
          }
      }

      /** Load [model], printing download progress, and return its model id. */
      private suspend fun QvacClient.loadWithProgress(model: ModelConstant, modelConfig: JsonObject? = null): String {
          var result: LoadModelResponse? = null
          models.loadWithProgress(model.src, model.engine, model.name, modelConfig = modelConfig).collect { event ->
              when (event) {
                  is QvacProgressEvent.Progress -> printProgress(event.value)
                  is QvacProgressEvent.Result -> result = event.value
              }
          }
          val loaded = checkNotNull(result) { "loadModel ended without a result" }
          return loaded.modelId ?: error(loaded.error ?: "loadModel failed")
      }

      private fun printProgress(p: ModelProgressResponse) {
          val line = "▸ Downloading %.0f%% (%.1f/%.1f MB)".format(p.percentage, p.downloaded / 1e6, p.total / 1e6)
          if (System.console() != null) System.err.print("\r$line") else System.err.println(line)
          if (p.percentage >= 100) System.err.println()
      }

      /** Create a WAV header for 16-bit mono PCM audio. */
      private fun createWavHeader(dataLength: Int, sampleRate: Int): ByteArray =
          ByteBuffer.allocate(44).order(ByteOrder.LITTLE_ENDIAN)
              .put("RIFF".toByteArray(Charsets.US_ASCII)).putInt(36 + dataLength)
              .put("WAVEfmt ".toByteArray(Charsets.US_ASCII))
              .putInt(16).putShort(1).putShort(1).putInt(sampleRate).putInt(sampleRate * 2).putShort(2).putShort(16)
              .put("data".toByteArray(Charsets.US_ASCII)).putInt(dataLength)
              .array()

      /** Convert int16 PCM samples to little-endian bytes. */
      private fun int16ArrayToBuffer(samples: List<Double>): ByteArray {
          val buffer = ByteBuffer.allocate(samples.size * 2).order(ByteOrder.LITTLE_ENDIAN)
          for (sample in samples) buffer.putShort(sample.roundToInt().coerceIn(-32768, 32767).toShort())
          return buffer.array()
      }

      /** Create and save a WAV file. */
      private fun createWav(samples: List<Double>, sampleRate: Int, filename: String) {
          val audioData = int16ArrayToBuffer(samples)
          File(filename).writeBytes(createWavHeader(audioData.size, sampleRate) + audioData)
          println("▸ WAV file saved as: $filename")
      }

      /** Play a WAV buffer by streaming it into ffplay over stdin. */
      private fun playAudio(wav: ByteArray) {
          val ffplay = try {
              ProcessBuilder("ffplay", "-hide_banner", "-loglevel", "error", "-autoexit", "-nodisp", "-i", "pipe:0")
                  .redirectOutput(ProcessBuilder.Redirect.INHERIT)
                  .redirectError(ProcessBuilder.Redirect.INHERIT)
                  .start()
          } catch (e: IOException) {
              throw IllegalStateException("ffplay not found on PATH. Install ffmpeg (ffplay ships with it) and retry.", e)
          }
          ffplay.outputStream.use { it.write(wav) }
          val code = ffplay.waitFor()
          check(code == 0) { "ffplay exited with code $code" }
      }
      ```
    </WrapCode>
  </Tab>
</Tabs>

### Audio8

This example generates speech from text using Audio8. It prints whether the codec ran on Core ML, saves the 44.1 kHz speech to `audio8-output.wav`, and plays it. Arguments: none. Helper (JS/TS): [`utils`](#utils), in the same folder as the script.

<Tabs>
  <Tab value="js" label="JavaScript" default>
    <WrapCode>
      ```js file=<rootDir>/packages/sdk/dist/examples/tts/audio8.js title="tts-audio8.js" lineNumbers
      import { loadModel, textToSpeech, unloadModel, TTS_LM_MULTILINGUAL_AUDIO8_Q8_0, TTS_CODEC_DECODER_AUDIO8_Q8_0 } from '@qvac/sdk';
      import { createWav, playAudio, int16ArrayToBuffer, createWavHeader } from './utils.js';
      // Audio8 (GGML): DualAR LM + codec decoder, native 44.1 kHz output. The
      // primary modelSrc is the LM GGUF; the codec decoder loads via modelConfig.
      // For zero-shot voice cloning also pass audio8CodecEncoderModelSrc plus
      // referenceAudioSrc/referenceText (a recording and its exact transcript).
      // On macOS and iOS the decoder downloads with its Core ML bundle, which runs
      // the codec's synthesis stack; `stats.codecOnCoreml` reports whether it did.
      // Only a fallback: the engine reports the rate it actually produced, and
      // `outputSampleRate` (plus the LavaSR enhancer) can move it off this default.
      const AUDIO8_SAMPLE_RATE = 44100;
      try {
          const modelId = await loadModel({
              modelSrc: TTS_LM_MULTILINGUAL_AUDIO8_Q8_0,
              modelConfig: {
                  ttsEngine: 'audio8',
                  audio8CodecDecoderModelSrc: TTS_CODEC_DECODER_AUDIO8_Q8_0,
                  temperature: 0.7,
                  topP: 0.9,
                  seed: 42
              },
              onProgress: (p) => {
                  const mb = (n) => (n / 1e6).toFixed(1);
                  const line = `▸ Downloading ${p.percentage.toFixed(0)}% (${mb(p.downloaded)}/${mb(p.total)} MB)`;
                  process.stderr.write(process.stderr.isTTY ? `\r${line}` : `${line}\n`);
                  if (p.percentage >= 100)
                      process.stderr.write('\n');
              }
          });
          console.log(`▸ Model loaded: ${modelId}`);
          console.log('▸ Testing Audio8 Text-to-Speech...');
          const result = textToSpeech({
              modelId,
              text: 'Hey, how are you doing today?',
              inputType: 'text',
              stream: false
          });
          const audioBuffer = await result.buffer;
          const sampleRate = (await result.sampleRate) ?? AUDIO8_SAMPLE_RATE;
          const stats = await result.stats;
          console.log(`▸ TTS complete. Total samples: ${audioBuffer.length}`);
          console.log(`▸ Codec ran on ${stats?.codecOnCoreml === 1 ? 'Core ML' : 'ggml'}`);
          console.log('▸ Saving audio to file...');
          createWav(audioBuffer, sampleRate, 'audio8-output.wav');
          console.log('▸ Audio saved to audio8-output.wav');
          console.log('▸ Playing audio...');
          const audioData = int16ArrayToBuffer(audioBuffer);
          const wavBuffer = Buffer.concat([createWavHeader(audioData.length, sampleRate), audioData]);
          playAudio(wavBuffer);
          console.log('▸ Audio playback complete');
          await unloadModel({ modelId });
          console.log('▸ Model unloaded');
          process.exit(0);
      }
      catch (error) {
          console.error('✖', error);
          process.exit(1);
      }
      ```
    </WrapCode>
  </Tab>

  <Tab value="ts" label="TypeScript">
    <WrapCode>
      ```ts file=<rootDir>/packages/sdk/examples/tts/audio8.ts title="tts-audio8.ts" lineNumbers
      import {
        loadModel,
        textToSpeech,
        unloadModel,
        type ModelProgressUpdate,
        TTS_LM_MULTILINGUAL_AUDIO8_Q8_0,
        TTS_CODEC_DECODER_AUDIO8_Q8_0
      } from '@qvac/sdk'
      import { createWav, playAudio, int16ArrayToBuffer, createWavHeader } from './utils.js'

      // Audio8 (GGML): DualAR LM + codec decoder, native 44.1 kHz output. The
      // primary modelSrc is the LM GGUF; the codec decoder loads via modelConfig.
      // For zero-shot voice cloning also pass audio8CodecEncoderModelSrc plus
      // referenceAudioSrc/referenceText (a recording and its exact transcript).
      // On macOS and iOS the decoder downloads with its Core ML bundle, which runs
      // the codec's synthesis stack; `stats.codecOnCoreml` reports whether it did.
      // Only a fallback: the engine reports the rate it actually produced, and
      // `outputSampleRate` (plus the LavaSR enhancer) can move it off this default.
      const AUDIO8_SAMPLE_RATE = 44100

      try {
        const modelId = await loadModel({
          modelSrc: TTS_LM_MULTILINGUAL_AUDIO8_Q8_0,
          modelConfig: {
            ttsEngine: 'audio8',
            audio8CodecDecoderModelSrc: TTS_CODEC_DECODER_AUDIO8_Q8_0,
            temperature: 0.7,
            topP: 0.9,
            seed: 42
          },
          onProgress: (p: ModelProgressUpdate) => {
            const mb = (n: number) => (n / 1e6).toFixed(1)
            const line = `▸ Downloading ${p.percentage.toFixed(0)}% (${mb(p.downloaded)}/${mb(p.total)} MB)`
            process.stderr.write(process.stderr.isTTY ? `\r${line}` : `${line}\n`)
            if (p.percentage >= 100) process.stderr.write('\n')
          }
        })

        console.log(`▸ Model loaded: ${modelId}`)

        console.log('▸ Testing Audio8 Text-to-Speech...')
        const result = textToSpeech({
          modelId,
          text: 'Hey, how are you doing today?',
          inputType: 'text',
          stream: false
        })

        const audioBuffer = await result.buffer
        const sampleRate = (await result.sampleRate) ?? AUDIO8_SAMPLE_RATE
        const stats = await result.stats
        console.log(`▸ TTS complete. Total samples: ${audioBuffer.length}`)
        console.log(`▸ Codec ran on ${stats?.codecOnCoreml === 1 ? 'Core ML' : 'ggml'}`)

        console.log('▸ Saving audio to file...')
        createWav(audioBuffer, sampleRate, 'audio8-output.wav')
        console.log('▸ Audio saved to audio8-output.wav')

        console.log('▸ Playing audio...')
        const audioData = int16ArrayToBuffer(audioBuffer)
        const wavBuffer = Buffer.concat([createWavHeader(audioData.length, sampleRate), audioData])
        playAudio(wavBuffer)
        console.log('▸ Audio playback complete')

        await unloadModel({ modelId })
        console.log('▸ Model unloaded')
        process.exit(0)
      } catch (error) {
        console.error('✖', error)
        process.exit(1)
      }
      ```
    </WrapCode>
  </Tab>

  <Tab value="python" label="Python">
    <WrapCode>
      ```python file=<rootDir>/packages/sdk-python/examples/text_to_speech_audio8.py title="text_to_speech_audio8.py" lineNumbers
      """Python port of packages/sdk/examples/tts/audio8.ts.

      Audio8 (GGML): DualAR LM + codec decoder, native 44.1 kHz output. The primary
      `model_src` is the LM GGUF; the codec decoder loads via `model_config`. For
      zero-shot voice cloning also pass `audio8CodecEncoderModelSrc` plus
      `referenceAudioSrc`/`referenceText` (a recording and its exact transcript). On
      macOS and iOS the decoder downloads with its Core ML bundle, which runs the
      codec's synthesis stack; `stats.codec_on_coreml` reports whether it did.

      `text_to_speech` is a server-stream; in non-stream mode it yields the full
      audio as one frame. Samples come back as int16 PCM values. The helpers below,
      ported from the JS example's `utils`, save them to a WAV and play it through
      ffplay.

      RUN: python examples/text_to_speech_audio8.py
      """

      from __future__ import annotations

      import asyncio
      import struct
      import subprocess
      import sys

      from tetherto.qvac_sdk import (
          Client,
          TextToSpeechRequest,
          load_model,
          text_to_speech,
          unload_model,
      )
      from tetherto.qvac_sdk.models import (
          TTS_CODEC_DECODER_AUDIO8_Q8_0,
          TTS_LM_MULTILINGUAL_AUDIO8_Q8_0,
      )

      # Only a fallback: the engine reports the rate it actually produced.
      AUDIO8_SAMPLE_RATE = 44100


      def print_progress(p) -> None:
          """Print model download progress; pass as `on_progress=` to `load_model`."""
          line = (
              f"▸ Downloading {p.percentage:.0f}% "
              f"({p.downloaded / 1e6:.1f}/{p.total / 1e6:.1f} MB)"
          )
          print(line, end="\r" if sys.stderr.isatty() else "\n", file=sys.stderr)
          if p.percentage >= 100:
              print(file=sys.stderr)


      def create_wav_header(data_length: int, sample_rate: int) -> bytes:
          """Create a WAV header for 16-bit mono PCM audio."""
          return (
              b"RIFF"
              + struct.pack("<I", 36 + data_length)
              + b"WAVE"
              + b"fmt "
              + struct.pack("<IHHIIHH", 16, 1, 1, sample_rate, sample_rate * 2, 2, 16)
              + b"data"
              + struct.pack("<I", data_length)
          )


      def int16_array_to_buffer(samples) -> bytes:
          """Convert int16 PCM samples to little-endian bytes."""
          return struct.pack(
              f"<{len(samples)}h",
              *(max(-32768, min(32767, round(s))) for s in samples),
          )


      def create_wav(audio_buffer, sample_rate: int, filename: str) -> None:
          """Create and save a WAV file."""
          audio_data = int16_array_to_buffer(audio_buffer)
          with open(filename, "wb") as f:
              f.write(create_wav_header(len(audio_data), sample_rate) + audio_data)
          print(f"▸ WAV file saved as: {filename}")


      def play_audio(audio_buffer: bytes) -> None:
          """Play a WAV buffer by streaming it into ffplay over stdin."""
          try:
              result = subprocess.run(
                  [
                      "ffplay",
                      "-hide_banner",
                      "-loglevel",
                      "error",
                      "-autoexit",
                      "-nodisp",
                      "-i",
                      "pipe:0",
                  ],
                  input=audio_buffer,
                  check=False,
              )
          except FileNotFoundError:
              raise RuntimeError(
                  "ffplay not found on PATH. Install ffmpeg (ffplay ships with it) and retry."
              ) from None
          if result.returncode != 0:
              raise RuntimeError(f"ffplay exited with code {result.returncode}")


      async def main() -> int:
          model_config = {
              "ttsEngine": "audio8",
              "audio8CodecDecoderModelSrc": TTS_CODEC_DECODER_AUDIO8_Q8_0,
              "temperature": 0.7,
              "topP": 0.9,
              "seed": 42,
          }

          async with Client() as client:
              t = client.transport
              try:
                  model_id = await load_model(
                      t,
                      model_src=TTS_LM_MULTILINGUAL_AUDIO8_Q8_0,
                      model_config=model_config,
                      on_progress=print_progress,
                  )
                  print(f"▸ Model loaded: {model_id}")

                  print("▸ Testing Audio8 Text-to-Speech...")
                  request = TextToSpeechRequest.model_validate(
                      {
                          "type": "textToSpeech",
                          "modelId": model_id,
                          "text": "Hey, how are you doing today?",
                          "inputType": "text",
                          "stream": False,
                      }
                  )

                  samples: list[float] = []
                  sample_rate = None
                  stats = None
                  async for response in text_to_speech(t, request):
                      samples.extend(response.buffer)
                      if response.sample_rate is not None:
                          sample_rate = response.sample_rate
                      if response.stats is not None:
                          stats = response.stats
                  sample_rate = int(sample_rate or AUDIO8_SAMPLE_RATE)
                  print(f"▸ TTS complete. Total samples: {len(samples)}")
                  codec = "Core ML" if stats and stats.codec_on_coreml == 1 else "ggml"
                  print(f"▸ Codec ran on {codec}")

                  print("▸ Saving audio to file...")
                  create_wav(samples, sample_rate, "audio8-output.wav")
                  print("▸ Audio saved to audio8-output.wav")

                  print("▸ Playing audio...")
                  audio_data = int16_array_to_buffer(samples)
                  play_audio(create_wav_header(len(audio_data), sample_rate) + audio_data)

                  await unload_model(t, model_id)
                  print("▸ Model unloaded")
              except Exception as error:
                  print(f"✖ {error}", file=sys.stderr)
                  return 1
          return 0


      if __name__ == "__main__":
          sys.exit(asyncio.run(main()))
      ```
    </WrapCode>
  </Tab>

  <Tab value="kotlin" label="Kotlin">
    <WrapCode>
      ```kotlin file=<rootDir>/packages/sdk-kotlin/examples/src/TextToSpeechAudio8.kt title="TextToSpeechAudio8.kt" lineNumbers
      // Kotlin port of packages/sdk/examples/tts/audio8.ts.
      //
      // Audio8 (GGML): DualAR LM + codec decoder, native 44.1 kHz output. The primary
      // model source is the LM GGUF; the codec decoder loads via `modelConfig` as its
      // `src` string. For zero-shot voice cloning also pass
      // `audio8CodecEncoderModelSrc` plus `referenceAudioSrc`/`referenceText` (a
      // recording and its exact transcript). On macOS and iOS the decoder downloads
      // with its Core ML bundle, which runs the codec's synthesis stack;
      // `stats.codecOnCoreml` reports whether it did.
      //
      // `client.textToSpeech()` is the generated typed method: it takes a
      // `TextToSpeechRequest` data class and returns a `Flow<TextToSpeechResponse>`.
      // In non-stream mode it emits the full audio as one frame. Samples come back as
      // int16 PCM values, and `stats` arrives as the typed
      // `TextToSpeechResponseStats`. The helpers below, ported from the JS example's
      // `utils`, save them to a WAV and play it through ffplay.
      //
      // RUN: ./gradlew -p examples run -Pexample=TextToSpeechAudio8

      import io.tether.qvac.sdk.QvacClient
      import io.tether.qvac.sdk.QvacProgressEvent
      import io.tether.qvac.sdk.generated.ModelConstant
      import io.tether.qvac.sdk.generated.Models
      import io.tether.qvac.sdk.generated.schema.LoadModelResponse
      import io.tether.qvac.sdk.generated.schema.ModelProgressResponse
      import io.tether.qvac.sdk.generated.schema.TextToSpeechRequest
      import io.tether.qvac.sdk.generated.schema.TextToSpeechResponseStats
      import io.tether.qvac.sdk.jvm.JvmBareKitTransport
      import io.tether.qvac.sdk.models
      import io.tether.qvac.sdk.textToSpeech
      import java.io.File
      import java.io.IOException
      import java.nio.ByteBuffer
      import java.nio.ByteOrder
      import kotlin.math.roundToInt
      import kotlinx.coroutines.runBlocking
      import kotlinx.serialization.json.JsonObject
      import kotlinx.serialization.json.buildJsonObject
      import kotlinx.serialization.json.put

      // Only a fallback: the engine reports the rate it actually produced.
      private const val AUDIO8_SAMPLE_RATE = 44100

      fun main(): Unit = runBlocking {
          val modelConfig = buildJsonObject {
              put("ttsEngine", "audio8")
              put("audio8CodecDecoderModelSrc", Models.TTS_CODEC_DECODER_AUDIO8_Q8_0.src)
              put("temperature", 0.7)
              put("topP", 0.9)
              put("seed", 42)
          }

          val client = QvacClient(JvmBareKitTransport.connect())
          try {
              val modelId = client.loadWithProgress(Models.TTS_LM_MULTILINGUAL_AUDIO8_Q8_0, modelConfig)
              println("▸ Model loaded: $modelId")

              println("▸ Testing Audio8 Text-to-Speech...")
              val request = TextToSpeechRequest(
                  modelId = modelId,
                  text = "Hey, how are you doing today?",
                  inputType = "text",
                  stream = false,
              )

              val samples = mutableListOf<Double>()
              var sampleRate = AUDIO8_SAMPLE_RATE
              var stats: TextToSpeechResponseStats? = null
              client.textToSpeech(request).collect { response ->
                  samples += response.buffer
                  response.sampleRate?.let { sampleRate = it.toInt() }
                  response.stats?.let { stats = it }
              }
              println("▸ TTS complete. Total samples: ${samples.size}")
              val codec = if (stats?.codecOnCoreml == 1.0) "Core ML" else "ggml"
              println("▸ Codec ran on $codec")

              println("▸ Saving audio to file...")
              createWav(samples, sampleRate, "audio8-output.wav")
              println("▸ Audio saved to audio8-output.wav")

              println("▸ Playing audio...")
              val audioData = int16ArrayToBuffer(samples)
              playAudio(createWavHeader(audioData.size, sampleRate) + audioData)

              client.models.unload(modelId)
              println("▸ Model unloaded")
          } finally {
              client.close()
          }
      }

      /** Load [model], printing download progress, and return its model id. */
      private suspend fun QvacClient.loadWithProgress(model: ModelConstant, modelConfig: JsonObject? = null): String {
          var result: LoadModelResponse? = null
          models.loadWithProgress(model.src, model.engine, model.name, modelConfig = modelConfig).collect { event ->
              when (event) {
                  is QvacProgressEvent.Progress -> printProgress(event.value)
                  is QvacProgressEvent.Result -> result = event.value
              }
          }
          val loaded = checkNotNull(result) { "loadModel ended without a result" }
          return loaded.modelId ?: error(loaded.error ?: "loadModel failed")
      }

      private fun printProgress(p: ModelProgressResponse) {
          val line = "▸ Downloading %.0f%% (%.1f/%.1f MB)".format(p.percentage, p.downloaded / 1e6, p.total / 1e6)
          if (System.console() != null) System.err.print("\r$line") else System.err.println(line)
          if (p.percentage >= 100) System.err.println()
      }

      /** Create a WAV header for 16-bit mono PCM audio. */
      private fun createWavHeader(dataLength: Int, sampleRate: Int): ByteArray =
          ByteBuffer.allocate(44).order(ByteOrder.LITTLE_ENDIAN)
              .put("RIFF".toByteArray(Charsets.US_ASCII)).putInt(36 + dataLength)
              .put("WAVEfmt ".toByteArray(Charsets.US_ASCII))
              .putInt(16).putShort(1).putShort(1).putInt(sampleRate).putInt(sampleRate * 2).putShort(2).putShort(16)
              .put("data".toByteArray(Charsets.US_ASCII)).putInt(dataLength)
              .array()

      /** Convert int16 PCM samples to little-endian bytes. */
      private fun int16ArrayToBuffer(samples: List<Double>): ByteArray {
          val buffer = ByteBuffer.allocate(samples.size * 2).order(ByteOrder.LITTLE_ENDIAN)
          for (sample in samples) buffer.putShort(sample.roundToInt().coerceIn(-32768, 32767).toShort())
          return buffer.array()
      }

      /** Create and save a WAV file. */
      private fun createWav(samples: List<Double>, sampleRate: Int, filename: String) {
          val audioData = int16ArrayToBuffer(samples)
          File(filename).writeBytes(createWavHeader(audioData.size, sampleRate) + audioData)
          println("▸ WAV file saved as: $filename")
      }

      /** Play a WAV buffer by streaming it into ffplay over stdin. */
      private fun playAudio(wav: ByteArray) {
          val ffplay = try {
              ProcessBuilder("ffplay", "-hide_banner", "-loglevel", "error", "-autoexit", "-nodisp", "-i", "pipe:0")
                  .redirectOutput(ProcessBuilder.Redirect.INHERIT)
                  .redirectError(ProcessBuilder.Redirect.INHERIT)
                  .start()
          } catch (e: IOException) {
              throw IllegalStateException("ffplay not found on PATH. Install ffmpeg (ffplay ships with it) and retry.", e)
          }
          ffplay.outputStream.use { it.write(wav) }
          val code = ffplay.waitFor()
          check(code == 0) { "ffplay exited with code $code" }
      }
      ```
    </WrapCode>
  </Tab>
</Tabs>

### MOSS

The first example generates speech from text using MOSS-TTS. It streams the audio, prints the time to first audio, clones the voice of a 24 kHz reference recording when you pass one, saves the speech to `moss-output.wav`, and plays it. Arguments: `[reference-audio]` (optional). Helper (JS/TS): [`utils`](#utils), in the same folder as the script.

The second example generates a two-speaker dialogue using MOSS-TTSD. It clones each speaker's voice from a 24 kHz reference recording and its exact transcript, saves the dialogue to `moss-dialogue-output.wav`, and plays it. Arguments: `<moss-ttsd-gguf> <speaker1-audio> "<speaker1-transcript>" <speaker2-audio> "<speaker2-transcript>"`. Helper (JS/TS): [`utils`](#utils), in the same folder as the script.

<Tabs>
  <Tab value="js" label="JavaScript" default>
    <WrapCode>
      ```js file=<rootDir>/packages/sdk/dist/examples/tts/moss.js title="tts-moss.js" lineNumbers
      import { loadModel, textToSpeech, unloadModel, TTS_DELAY_LLM_MOSS_TTS_F16, TTS_CODEC_DECODER_MOSS_TTS_F16, TTS_CODEC_ENCODER_MOSS_TTS_F16 } from '@qvac/sdk';
      import { createWav, playAudio, int16ArrayToBuffer, createWavHeader } from './utils.js';
      // MOSS (GGML): OpenMOSS MOSS-TTS v1.5 Delay, an 8B backbone (about 17 GB)
      // plus a codec, so desktop only. The primary modelSrc is the backbone; the
      // codec decoder loads via modelConfig, and the codec encoder is only needed to
      // clone a voice from a 24 kHz reference recording (no transcript needed).
      //
      // MOSS streams natively: with `streamChunkTokens` set, `stream: true` emits a
      // chunk every that-many codec frames (12.5 per second) while the backbone is
      // still generating, and the text is synthesized as one utterance, so the
      // `[pause 1.0s]` marker below and `durationTokens` apply to all of it.
      //
      // Uses registry model constants — downloads automatically from QVAC Registry.
      // Usage: node moss.ts [referenceAudio.wav]
      const [referenceAudioSrc] = process.argv.slice(2);
      // Only a fallback: the engine reports the rate it actually produced.
      const MOSS_SAMPLE_RATE = 24000;
      try {
          const modelId = await loadModel({
              modelSrc: TTS_DELAY_LLM_MOSS_TTS_F16,
              modelConfig: {
                  ttsEngine: 'moss',
                  language: 'en',
                  mossCodecDecoderModelSrc: TTS_CODEC_DECODER_MOSS_TTS_F16,
                  ...(referenceAudioSrc
                      ? { mossCodecEncoderModelSrc: TTS_CODEC_ENCODER_MOSS_TTS_F16, referenceAudioSrc }
                      : {}),
                  streamChunkTokens: 25,
                  useGPU: true,
                  seed: 7
              },
              onProgress: (p) => {
                  const mb = (n) => (n / 1e6).toFixed(1);
                  const line = `▸ Downloading ${p.percentage.toFixed(0)}% (${mb(p.downloaded)}/${mb(p.total)} MB)`;
                  process.stderr.write(process.stderr.isTTY ? `\r${line}` : `${line}\n`);
                  if (p.percentage >= 100)
                      process.stderr.write('\n');
              }
          });
          console.log(`▸ Model loaded: ${modelId}`);
          console.log('▸ Streaming MOSS Text-to-Speech...');
          const started = Date.now();
          const result = textToSpeech({
              modelId,
              text: 'Hold on [pause 1.0s] here it comes: speech that starts playing while the rest is still being generated.',
              stream: true
          });
          const samples = [];
          for await (const sample of result.bufferStream) {
              if (samples.length === 0)
                  console.log(`▸ First audio after ${Date.now() - started} ms`);
              samples.push(sample);
          }
          const sampleRate = (await result.sampleRate) ?? MOSS_SAMPLE_RATE;
          const stats = await result.stats;
          console.log(`▸ TTS complete: ${samples.length} samples, ${stats?.generatedFrames ?? '?'} codec frames, RTF ${stats?.realTimeFactor?.toFixed(2) ?? '?'}`);
          createWav(samples, sampleRate, 'moss-output.wav');
          console.log('▸ Audio saved to moss-output.wav');
          console.log('▸ Playing audio...');
          const audioData = int16ArrayToBuffer(samples);
          const wavBuffer = Buffer.concat([createWavHeader(audioData.length, sampleRate), audioData]);
          playAudio(wavBuffer);
          console.log('▸ Audio playback complete');
          await unloadModel({ modelId });
          console.log('▸ Model unloaded');
          process.exit(0);
      }
      catch (error) {
          console.error('✖', error);
          process.exit(1);
      }
      ```
    </WrapCode>
  </Tab>

  <Tab value="ts" label="TypeScript">
    <WrapCode>
      ```ts file=<rootDir>/packages/sdk/examples/tts/moss.ts title="tts-moss.ts" lineNumbers
      import {
        loadModel,
        textToSpeech,
        unloadModel,
        type ModelProgressUpdate,
        TTS_DELAY_LLM_MOSS_TTS_F16,
        TTS_CODEC_DECODER_MOSS_TTS_F16,
        TTS_CODEC_ENCODER_MOSS_TTS_F16
      } from '@qvac/sdk'
      import { createWav, playAudio, int16ArrayToBuffer, createWavHeader } from './utils.js'

      // MOSS (GGML): OpenMOSS MOSS-TTS v1.5 Delay, an 8B backbone (about 17 GB)
      // plus a codec, so desktop only. The primary modelSrc is the backbone; the
      // codec decoder loads via modelConfig, and the codec encoder is only needed to
      // clone a voice from a 24 kHz reference recording (no transcript needed).
      //
      // MOSS streams natively: with `streamChunkTokens` set, `stream: true` emits a
      // chunk every that-many codec frames (12.5 per second) while the backbone is
      // still generating, and the text is synthesized as one utterance, so the
      // `[pause 1.0s]` marker below and `durationTokens` apply to all of it.
      //
      // Uses registry model constants — downloads automatically from QVAC Registry.
      // Usage: node moss.ts [referenceAudio.wav]
      const [referenceAudioSrc] = process.argv.slice(2)

      // Only a fallback: the engine reports the rate it actually produced.
      const MOSS_SAMPLE_RATE = 24000

      try {
        const modelId = await loadModel({
          modelSrc: TTS_DELAY_LLM_MOSS_TTS_F16,
          modelConfig: {
            ttsEngine: 'moss',
            language: 'en',
            mossCodecDecoderModelSrc: TTS_CODEC_DECODER_MOSS_TTS_F16,
            ...(referenceAudioSrc
              ? { mossCodecEncoderModelSrc: TTS_CODEC_ENCODER_MOSS_TTS_F16, referenceAudioSrc }
              : {}),
            streamChunkTokens: 25,
            useGPU: true,
            seed: 7
          },
          onProgress: (p: ModelProgressUpdate) => {
            const mb = (n: number) => (n / 1e6).toFixed(1)
            const line = `▸ Downloading ${p.percentage.toFixed(0)}% (${mb(p.downloaded)}/${mb(p.total)} MB)`
            process.stderr.write(process.stderr.isTTY ? `\r${line}` : `${line}\n`)
            if (p.percentage >= 100) process.stderr.write('\n')
          }
        })

        console.log(`▸ Model loaded: ${modelId}`)

        console.log('▸ Streaming MOSS Text-to-Speech...')
        const started = Date.now()
        const result = textToSpeech({
          modelId,
          text: 'Hold on [pause 1.0s] here it comes: speech that starts playing while the rest is still being generated.',
          stream: true
        })

        const samples: number[] = []
        for await (const sample of result.bufferStream) {
          if (samples.length === 0) console.log(`▸ First audio after ${Date.now() - started} ms`)
          samples.push(sample)
        }

        const sampleRate = (await result.sampleRate) ?? MOSS_SAMPLE_RATE
        const stats = await result.stats
        console.log(
          `▸ TTS complete: ${samples.length} samples, ${stats?.generatedFrames ?? '?'} codec frames, RTF ${stats?.realTimeFactor?.toFixed(2) ?? '?'}`
        )

        createWav(samples, sampleRate, 'moss-output.wav')
        console.log('▸ Audio saved to moss-output.wav')

        console.log('▸ Playing audio...')
        const audioData = int16ArrayToBuffer(samples)
        const wavBuffer = Buffer.concat([createWavHeader(audioData.length, sampleRate), audioData])
        playAudio(wavBuffer)
        console.log('▸ Audio playback complete')

        await unloadModel({ modelId })
        console.log('▸ Model unloaded')
        process.exit(0)
      } catch (error) {
        console.error('✖', error)
        process.exit(1)
      }
      ```
    </WrapCode>
  </Tab>

  <Tab value="python" label="Python">
    <WrapCode>
      ```python file=<rootDir>/packages/sdk-python/examples/text_to_speech_moss.py title="text_to_speech_moss.py" lineNumbers
      """Python port of packages/sdk/examples/tts/moss.ts.

      MOSS (GGML): OpenMOSS MOSS-TTS v1.5 Delay, an 8B backbone (about 17 GB) plus a
      codec, so desktop only. The primary `model_src` is the backbone; the codec
      decoder loads via `model_config`, and the codec encoder is only needed to clone
      a voice from a 24 kHz reference recording (no transcript needed).

      MOSS streams natively: with `streamChunkTokens` set, `stream: True` emits a
      chunk every that-many codec frames (12.5 per second) while the backbone is
      still generating, and the text is synthesized as one utterance, so the
      `[pause 1.0s]` marker below and `durationTokens` apply to all of it.

      TypeScript reads the stream from `bufferStream` and the rate and stats from
      separate promises. Python's `text_to_speech` yields frames: the example
      collects each frame's `buffer` and reads `sample_rate` and `stats` off them.
      The helpers below, ported from the JS example's `utils`, save the samples to a
      WAV and play it through ffplay.

      RUN: python examples/text_to_speech_moss.py [reference-audio.wav]
      """

      from __future__ import annotations

      import asyncio
      import struct
      import subprocess
      import sys
      import time

      from tetherto.qvac_sdk import (
          Client,
          TextToSpeechRequest,
          load_model,
          text_to_speech,
          unload_model,
      )
      from tetherto.qvac_sdk.models import (
          TTS_CODEC_DECODER_MOSS_TTS_F16,
          TTS_CODEC_ENCODER_MOSS_TTS_F16,
          TTS_DELAY_LLM_MOSS_TTS_F16,
      )

      # Only a fallback: the engine reports the rate it actually produced.
      MOSS_SAMPLE_RATE = 24000


      def print_progress(p) -> None:
          """Print model download progress; pass as `on_progress=` to `load_model`."""
          line = (
              f"▸ Downloading {p.percentage:.0f}% "
              f"({p.downloaded / 1e6:.1f}/{p.total / 1e6:.1f} MB)"
          )
          print(line, end="\r" if sys.stderr.isatty() else "\n", file=sys.stderr)
          if p.percentage >= 100:
              print(file=sys.stderr)


      def create_wav_header(data_length: int, sample_rate: int) -> bytes:
          """Create a WAV header for 16-bit mono PCM audio."""
          return (
              b"RIFF"
              + struct.pack("<I", 36 + data_length)
              + b"WAVE"
              + b"fmt "
              + struct.pack("<IHHIIHH", 16, 1, 1, sample_rate, sample_rate * 2, 2, 16)
              + b"data"
              + struct.pack("<I", data_length)
          )


      def int16_array_to_buffer(samples) -> bytes:
          """Convert int16 PCM samples to little-endian bytes."""
          return struct.pack(
              f"<{len(samples)}h",
              *(max(-32768, min(32767, round(s))) for s in samples),
          )


      def create_wav(audio_buffer, sample_rate: int, filename: str) -> None:
          """Create and save a WAV file."""
          audio_data = int16_array_to_buffer(audio_buffer)
          with open(filename, "wb") as f:
              f.write(create_wav_header(len(audio_data), sample_rate) + audio_data)
          print(f"▸ WAV file saved as: {filename}")


      def play_audio(audio_buffer: bytes) -> None:
          """Play a WAV buffer by streaming it into ffplay over stdin."""
          try:
              result = subprocess.run(
                  [
                      "ffplay",
                      "-hide_banner",
                      "-loglevel",
                      "error",
                      "-autoexit",
                      "-nodisp",
                      "-i",
                      "pipe:0",
                  ],
                  input=audio_buffer,
                  check=False,
              )
          except FileNotFoundError:
              raise RuntimeError(
                  "ffplay not found on PATH. Install ffmpeg (ffplay ships with it) and retry."
              ) from None
          if result.returncode != 0:
              raise RuntimeError(f"ffplay exited with code {result.returncode}")


      async def main() -> int:
          reference_audio_src = sys.argv[1] if len(sys.argv) > 1 else None

          model_config = {
              "ttsEngine": "moss",
              "language": "en",
              "mossCodecDecoderModelSrc": TTS_CODEC_DECODER_MOSS_TTS_F16,
              "streamChunkTokens": 25,
              "useGPU": True,
              "seed": 7,
          }
          if reference_audio_src:
              model_config["mossCodecEncoderModelSrc"] = TTS_CODEC_ENCODER_MOSS_TTS_F16
              model_config["referenceAudioSrc"] = reference_audio_src

          async with Client() as client:
              t = client.transport
              try:
                  model_id = await load_model(
                      t,
                      model_src=TTS_DELAY_LLM_MOSS_TTS_F16,
                      model_config=model_config,
                      on_progress=print_progress,
                  )
                  print(f"▸ Model loaded: {model_id}")

                  print("▸ Streaming MOSS Text-to-Speech...")
                  started = time.monotonic()
                  request = TextToSpeechRequest.model_validate(
                      {
                          "type": "textToSpeech",
                          "modelId": model_id,
                          "text": (
                              "Hold on [pause 1.0s] here it comes: speech that starts "
                              "playing while the rest is still being generated."
                          ),
                          "stream": True,
                      }
                  )

                  samples: list[float] = []
                  sample_rate = None
                  stats = None
                  async for response in text_to_speech(t, request):
                      if response.buffer and not samples:
                          elapsed_ms = (time.monotonic() - started) * 1000
                          print(f"▸ First audio after {elapsed_ms:.0f} ms")
                      samples.extend(response.buffer)
                      if response.sample_rate is not None:
                          sample_rate = response.sample_rate
                      if response.stats is not None:
                          stats = response.stats

                  sample_rate = int(sample_rate or MOSS_SAMPLE_RATE)
                  frames = "?"
                  rtf = "?"
                  if stats is not None:
                      if stats.generated_frames is not None:
                          frames = f"{stats.generated_frames:g}"
                      if stats.real_time_factor is not None:
                          rtf = f"{stats.real_time_factor:.2f}"
                  print(
                      f"▸ TTS complete: {len(samples)} samples, {frames} codec frames, "
                      f"RTF {rtf}"
                  )

                  create_wav(samples, sample_rate, "moss-output.wav")
                  print("▸ Audio saved to moss-output.wav")

                  print("▸ Playing audio...")
                  audio_data = int16_array_to_buffer(samples)
                  play_audio(create_wav_header(len(audio_data), sample_rate) + audio_data)

                  await unload_model(t, model_id)
                  print("▸ Model unloaded")
              except Exception as error:
                  print(f"✖ {error}", file=sys.stderr)
                  return 1
          return 0


      if __name__ == "__main__":
          sys.exit(asyncio.run(main()))
      ```
    </WrapCode>
  </Tab>

  <Tab value="kotlin" label="Kotlin">
    <WrapCode>
      ```kotlin file=<rootDir>/packages/sdk-kotlin/examples/src/TextToSpeechMoss.kt title="TextToSpeechMoss.kt" lineNumbers
      // Kotlin port of packages/sdk/examples/tts/moss.ts.
      //
      // MOSS (GGML): OpenMOSS MOSS-TTS v1.5 Delay, an 8B backbone (about 17 GB) plus
      // a codec, so desktop only. The primary model source is the backbone; the codec
      // decoder loads via `modelConfig`, and the codec encoder is only needed to
      // clone a voice from a 24 kHz reference recording (no transcript needed).
      //
      // MOSS streams natively: with `streamChunkTokens` set, `stream = true` emits a
      // chunk every that-many codec frames (12.5 per second) while the backbone is
      // still generating, and the text is synthesized as one utterance, so the
      // `[pause 1.0s]` marker below and `durationTokens` apply to all of it.
      //
      // TypeScript reads the stream from `bufferStream` and the rate and stats from
      // separate promises. In Kotlin, `client.textToSpeech()` returns a
      // `Flow<TextToSpeechResponse>`: the collector sees each chunk as it arrives
      // (timing the first one with a monotonic `TimeSource` mark) and reads
      // `sampleRate` and the typed `TextToSpeechResponseStats` off the frames. The
      // helpers below, ported from the JS example's `utils`, save the samples to a
      // WAV and play it through ffplay.
      //
      // RUN: ./gradlew -p examples run -Pexample=TextToSpeechMoss [--args="<reference-audio.wav>"]

      import io.tether.qvac.sdk.QvacClient
      import io.tether.qvac.sdk.QvacProgressEvent
      import io.tether.qvac.sdk.generated.ModelConstant
      import io.tether.qvac.sdk.generated.Models
      import io.tether.qvac.sdk.generated.schema.LoadModelResponse
      import io.tether.qvac.sdk.generated.schema.ModelProgressResponse
      import io.tether.qvac.sdk.generated.schema.TextToSpeechRequest
      import io.tether.qvac.sdk.generated.schema.TextToSpeechResponseStats
      import io.tether.qvac.sdk.jvm.JvmBareKitTransport
      import io.tether.qvac.sdk.models
      import io.tether.qvac.sdk.textToSpeech
      import java.io.File
      import java.io.IOException
      import java.nio.ByteBuffer
      import java.nio.ByteOrder
      import kotlin.math.roundToInt
      import kotlin.time.TimeSource
      import kotlinx.coroutines.runBlocking
      import kotlinx.serialization.json.JsonObject
      import kotlinx.serialization.json.buildJsonObject
      import kotlinx.serialization.json.put

      // Only a fallback: the engine reports the rate it actually produced.
      private const val MOSS_SAMPLE_RATE = 24000

      fun main(args: Array<String>): Unit = runBlocking {
          val referenceAudioSrc = args.firstOrNull()

          val modelConfig = buildJsonObject {
              put("ttsEngine", "moss")
              put("language", "en")
              put("mossCodecDecoderModelSrc", Models.TTS_CODEC_DECODER_MOSS_TTS_F16.src)
              put("streamChunkTokens", 25)
              put("useGPU", true)
              put("seed", 7)
              if (referenceAudioSrc != null) {
                  put("mossCodecEncoderModelSrc", Models.TTS_CODEC_ENCODER_MOSS_TTS_F16.src)
                  put("referenceAudioSrc", referenceAudioSrc)
              }
          }

          val client = QvacClient(JvmBareKitTransport.connect())
          try {
              val modelId = client.loadWithProgress(Models.TTS_DELAY_LLM_MOSS_TTS_F16, modelConfig)
              println("▸ Model loaded: $modelId")

              println("▸ Streaming MOSS Text-to-Speech...")
              val started = TimeSource.Monotonic.markNow()
              val request = TextToSpeechRequest(
                  modelId = modelId,
                  text = "Hold on [pause 1.0s] here it comes: speech that starts playing while the rest is " +
                      "still being generated.",
                  stream = true,
              )

              val samples = mutableListOf<Double>()
              var sampleRate = MOSS_SAMPLE_RATE
              var stats: TextToSpeechResponseStats? = null
              client.textToSpeech(request).collect { response ->
                  if (response.buffer.isNotEmpty() && samples.isEmpty()) {
                      println("▸ First audio after ${started.elapsedNow().inWholeMilliseconds} ms")
                  }
                  samples += response.buffer
                  response.sampleRate?.let { sampleRate = it.toInt() }
                  response.stats?.let { stats = it }
              }

              val frames = stats?.generatedFrames?.let { "%.0f".format(it) } ?: "?"
              val rtf = stats?.realTimeFactor?.let { "%.2f".format(it) } ?: "?"
              println("▸ TTS complete: ${samples.size} samples, $frames codec frames, RTF $rtf")

              createWav(samples, sampleRate, "moss-output.wav")
              println("▸ Audio saved to moss-output.wav")

              println("▸ Playing audio...")
              val audioData = int16ArrayToBuffer(samples)
              playAudio(createWavHeader(audioData.size, sampleRate) + audioData)

              client.models.unload(modelId)
              println("▸ Model unloaded")
          } finally {
              client.close()
          }
      }

      /** Load [model], printing download progress, and return its model id. */
      private suspend fun QvacClient.loadWithProgress(model: ModelConstant, modelConfig: JsonObject? = null): String {
          var result: LoadModelResponse? = null
          models.loadWithProgress(model.src, model.engine, model.name, modelConfig = modelConfig).collect { event ->
              when (event) {
                  is QvacProgressEvent.Progress -> printProgress(event.value)
                  is QvacProgressEvent.Result -> result = event.value
              }
          }
          val loaded = checkNotNull(result) { "loadModel ended without a result" }
          return loaded.modelId ?: error(loaded.error ?: "loadModel failed")
      }

      private fun printProgress(p: ModelProgressResponse) {
          val line = "▸ Downloading %.0f%% (%.1f/%.1f MB)".format(p.percentage, p.downloaded / 1e6, p.total / 1e6)
          if (System.console() != null) System.err.print("\r$line") else System.err.println(line)
          if (p.percentage >= 100) System.err.println()
      }

      /** Create a WAV header for 16-bit mono PCM audio. */
      private fun createWavHeader(dataLength: Int, sampleRate: Int): ByteArray =
          ByteBuffer.allocate(44).order(ByteOrder.LITTLE_ENDIAN)
              .put("RIFF".toByteArray(Charsets.US_ASCII)).putInt(36 + dataLength)
              .put("WAVEfmt ".toByteArray(Charsets.US_ASCII))
              .putInt(16).putShort(1).putShort(1).putInt(sampleRate).putInt(sampleRate * 2).putShort(2).putShort(16)
              .put("data".toByteArray(Charsets.US_ASCII)).putInt(dataLength)
              .array()

      /** Convert int16 PCM samples to little-endian bytes. */
      private fun int16ArrayToBuffer(samples: List<Double>): ByteArray {
          val buffer = ByteBuffer.allocate(samples.size * 2).order(ByteOrder.LITTLE_ENDIAN)
          for (sample in samples) buffer.putShort(sample.roundToInt().coerceIn(-32768, 32767).toShort())
          return buffer.array()
      }

      /** Create and save a WAV file. */
      private fun createWav(samples: List<Double>, sampleRate: Int, filename: String) {
          val audioData = int16ArrayToBuffer(samples)
          File(filename).writeBytes(createWavHeader(audioData.size, sampleRate) + audioData)
          println("▸ WAV file saved as: $filename")
      }

      /** Play a WAV buffer by streaming it into ffplay over stdin. */
      private fun playAudio(wav: ByteArray) {
          val ffplay = try {
              ProcessBuilder("ffplay", "-hide_banner", "-loglevel", "error", "-autoexit", "-nodisp", "-i", "pipe:0")
                  .redirectOutput(ProcessBuilder.Redirect.INHERIT)
                  .redirectError(ProcessBuilder.Redirect.INHERIT)
                  .start()
          } catch (e: IOException) {
              throw IllegalStateException("ffplay not found on PATH. Install ffmpeg (ffplay ships with it) and retry.", e)
          }
          ffplay.outputStream.use { it.write(wav) }
          val code = ffplay.waitFor()
          check(code == 0) { "ffplay exited with code $code" }
      }
      ```
    </WrapCode>
  </Tab>
</Tabs>

<Tabs>
  <Tab value="js" label="JavaScript" default>
    <WrapCode>
      ```js file=<rootDir>/packages/sdk/dist/examples/tts/moss-dialogue.js title="tts-moss-dialogue.js" lineNumbers
      import { loadModel, textToSpeech, unloadModel, TTS_CODEC_DECODER_MOSS_TTS_F16, TTS_CODEC_ENCODER_MOSS_TTS_F16 } from '@qvac/sdk';
      import { createWav, playAudio, int16ArrayToBuffer, createWavHeader } from './utils.js';
      // MOSS-TTSD (GGML): multi-speaker dialogue in one pass, each voice cloned from
      // a 24 kHz reference recording. The model continues the references, so the
      // text opens with what each recording says under its speaker tag, followed by
      // the lines to generate; only the new lines come out as audio. A dialogue is
      // never split into sentences, so `stream: true` delivers the native chunks of
      // the whole conversation (set `streamChunkTokens` to get them while it is
      // still being generated).
      //
      // The MOSS-TTSD backbone is not in the QVAC Registry yet, so it is a local
      // file; the codec halves it shares with MOSS-TTS download from the registry.
      // Usage: node moss-dialogue.ts <moss-ttsd.gguf> <s1.wav> "<s1 transcript>" <s2.wav> "<s2 transcript>"
      const [backbone, s1Audio, s1Text, s2Audio, s2Text] = process.argv.slice(2);
      if (!backbone || !s1Audio || !s1Text || !s2Audio || !s2Text) {
          console.error('Usage: node moss-dialogue.ts <moss-ttsd.gguf> <s1.wav> "<s1 transcript>" <s2.wav> "<s2 transcript>"');
          process.exit(1);
      }
      // Only a fallback: the engine reports the rate it actually produced.
      const MOSS_SAMPLE_RATE = 24000;
      try {
          const modelId = await loadModel({
              modelSrc: backbone,
              modelType: 'tts-ggml',
              modelConfig: {
                  ttsEngine: 'moss',
                  language: 'en',
                  mossCodecDecoderModelSrc: TTS_CODEC_DECODER_MOSS_TTS_F16,
                  mossCodecEncoderModelSrc: TTS_CODEC_ENCODER_MOSS_TTS_F16,
                  // One recording per speaker, in the order the text tags them.
                  dialogueReferenceSrcs: [s1Audio, s2Audio],
                  streamChunkTokens: 25,
                  useGPU: true
              }
          });
          console.log(`▸ Model loaded: ${modelId}`);
          console.log('▸ Synthesizing the dialogue...');
          const result = textToSpeech({
              modelId,
              text: `[S1] ${s1Text} [S2] ${s2Text} ` +
                  '[S1] Did the build finish? [S2] Yes, every test passed. [S1] Great, ship it.',
              stream: true
          });
          const samples = [];
          for await (const sample of result.bufferStream)
              samples.push(sample);
          const sampleRate = (await result.sampleRate) ?? MOSS_SAMPLE_RATE;
          console.log(`▸ Dialogue complete: ${samples.length} samples`);
          createWav(samples, sampleRate, 'moss-dialogue-output.wav');
          console.log('▸ Audio saved to moss-dialogue-output.wav');
          console.log('▸ Playing audio...');
          const audioData = int16ArrayToBuffer(samples);
          const wavBuffer = Buffer.concat([createWavHeader(audioData.length, sampleRate), audioData]);
          playAudio(wavBuffer);
          console.log('▸ Audio playback complete');
          await unloadModel({ modelId });
          console.log('▸ Model unloaded');
          process.exit(0);
      }
      catch (error) {
          console.error('✖', error);
          process.exit(1);
      }
      ```
    </WrapCode>
  </Tab>

  <Tab value="ts" label="TypeScript">
    <WrapCode>
      ```ts file=<rootDir>/packages/sdk/examples/tts/moss-dialogue.ts title="tts-moss-dialogue.ts" lineNumbers
      import {
        loadModel,
        textToSpeech,
        unloadModel,
        TTS_CODEC_DECODER_MOSS_TTS_F16,
        TTS_CODEC_ENCODER_MOSS_TTS_F16
      } from '@qvac/sdk'
      import { createWav, playAudio, int16ArrayToBuffer, createWavHeader } from './utils.js'

      // MOSS-TTSD (GGML): multi-speaker dialogue in one pass, each voice cloned from
      // a 24 kHz reference recording. The model continues the references, so the
      // text opens with what each recording says under its speaker tag, followed by
      // the lines to generate; only the new lines come out as audio. A dialogue is
      // never split into sentences, so `stream: true` delivers the native chunks of
      // the whole conversation (set `streamChunkTokens` to get them while it is
      // still being generated).
      //
      // The MOSS-TTSD backbone is not in the QVAC Registry yet, so it is a local
      // file; the codec halves it shares with MOSS-TTS download from the registry.
      // Usage: node moss-dialogue.ts <moss-ttsd.gguf> <s1.wav> "<s1 transcript>" <s2.wav> "<s2 transcript>"
      const [backbone, s1Audio, s1Text, s2Audio, s2Text] = process.argv.slice(2)
      if (!backbone || !s1Audio || !s1Text || !s2Audio || !s2Text) {
        console.error(
          'Usage: node moss-dialogue.ts <moss-ttsd.gguf> <s1.wav> "<s1 transcript>" <s2.wav> "<s2 transcript>"'
        )
        process.exit(1)
      }

      // Only a fallback: the engine reports the rate it actually produced.
      const MOSS_SAMPLE_RATE = 24000

      try {
        const modelId = await loadModel({
          modelSrc: backbone,
          modelType: 'tts-ggml',
          modelConfig: {
            ttsEngine: 'moss',
            language: 'en',
            mossCodecDecoderModelSrc: TTS_CODEC_DECODER_MOSS_TTS_F16,
            mossCodecEncoderModelSrc: TTS_CODEC_ENCODER_MOSS_TTS_F16,
            // One recording per speaker, in the order the text tags them.
            dialogueReferenceSrcs: [s1Audio, s2Audio],
            streamChunkTokens: 25,
            useGPU: true
          }
        })

        console.log(`▸ Model loaded: ${modelId}`)

        console.log('▸ Synthesizing the dialogue...')
        const result = textToSpeech({
          modelId,
          text:
            `[S1] ${s1Text} [S2] ${s2Text} ` +
            '[S1] Did the build finish? [S2] Yes, every test passed. [S1] Great, ship it.',
          stream: true
        })

        const samples: number[] = []
        for await (const sample of result.bufferStream) samples.push(sample)

        const sampleRate = (await result.sampleRate) ?? MOSS_SAMPLE_RATE
        console.log(`▸ Dialogue complete: ${samples.length} samples`)

        createWav(samples, sampleRate, 'moss-dialogue-output.wav')
        console.log('▸ Audio saved to moss-dialogue-output.wav')

        console.log('▸ Playing audio...')
        const audioData = int16ArrayToBuffer(samples)
        const wavBuffer = Buffer.concat([createWavHeader(audioData.length, sampleRate), audioData])
        playAudio(wavBuffer)
        console.log('▸ Audio playback complete')

        await unloadModel({ modelId })
        console.log('▸ Model unloaded')
        process.exit(0)
      } catch (error) {
        console.error('✖', error)
        process.exit(1)
      }
      ```
    </WrapCode>
  </Tab>

  <Tab value="python" label="Python">
    <WrapCode>
      ```python file=<rootDir>/packages/sdk-python/examples/text_to_speech_moss_dialogue.py title="text_to_speech_moss_dialogue.py" lineNumbers
      """Python port of packages/sdk/examples/tts/moss-dialogue.ts.

      MOSS-TTSD (GGML): multi-speaker dialogue in one pass, each voice cloned from a
      24 kHz reference recording. The model continues the references, so the text
      opens with what each recording says under its speaker tag, followed by the
      lines to generate; only the new lines come out as audio. A dialogue is never
      split into sentences, so `stream: True` delivers the native chunks of the whole
      conversation (set `streamChunkTokens` to get them while it is still being
      generated).

      The MOSS-TTSD backbone is not in the QVAC Registry yet, so it is a local file;
      the codec halves it shares with MOSS-TTS download from the registry.

      Python's `text_to_speech` yields frames: the example collects each frame's
      `buffer` and reads `sample_rate` off them. The helpers below, ported from the
      JS example's `utils`, save the samples to a WAV and play it through ffplay.

      RUN: python examples/text_to_speech_moss_dialogue.py <moss-ttsd.gguf> <s1.wav> "<s1 transcript>" <s2.wav> "<s2 transcript>"
      """

      from __future__ import annotations

      import asyncio
      import struct
      import subprocess
      import sys

      from tetherto.qvac_sdk import (
          Client,
          TextToSpeechRequest,
          load_model,
          text_to_speech,
          unload_model,
      )
      from tetherto.qvac_sdk.models import (
          TTS_CODEC_DECODER_MOSS_TTS_F16,
          TTS_CODEC_ENCODER_MOSS_TTS_F16,
      )

      # Only a fallback: the engine reports the rate it actually produced.
      MOSS_SAMPLE_RATE = 24000


      def create_wav_header(data_length: int, sample_rate: int) -> bytes:
          """Create a WAV header for 16-bit mono PCM audio."""
          return (
              b"RIFF"
              + struct.pack("<I", 36 + data_length)
              + b"WAVE"
              + b"fmt "
              + struct.pack("<IHHIIHH", 16, 1, 1, sample_rate, sample_rate * 2, 2, 16)
              + b"data"
              + struct.pack("<I", data_length)
          )


      def int16_array_to_buffer(samples) -> bytes:
          """Convert int16 PCM samples to little-endian bytes."""
          return struct.pack(
              f"<{len(samples)}h",
              *(max(-32768, min(32767, round(s))) for s in samples),
          )


      def create_wav(audio_buffer, sample_rate: int, filename: str) -> None:
          """Create and save a WAV file."""
          audio_data = int16_array_to_buffer(audio_buffer)
          with open(filename, "wb") as f:
              f.write(create_wav_header(len(audio_data), sample_rate) + audio_data)
          print(f"▸ WAV file saved as: {filename}")


      def play_audio(audio_buffer: bytes) -> None:
          """Play a WAV buffer by streaming it into ffplay over stdin."""
          try:
              result = subprocess.run(
                  [
                      "ffplay",
                      "-hide_banner",
                      "-loglevel",
                      "error",
                      "-autoexit",
                      "-nodisp",
                      "-i",
                      "pipe:0",
                  ],
                  input=audio_buffer,
                  check=False,
              )
          except FileNotFoundError:
              raise RuntimeError(
                  "ffplay not found on PATH. Install ffmpeg (ffplay ships with it) and retry."
              ) from None
          if result.returncode != 0:
              raise RuntimeError(f"ffplay exited with code {result.returncode}")


      async def main() -> int:
          if len(sys.argv) < 6 or not all(sys.argv[1:6]):
              print(
                  "Usage: python examples/text_to_speech_moss_dialogue.py <moss-ttsd.gguf> "
                  '<s1.wav> "<s1 transcript>" <s2.wav> "<s2 transcript>"',
                  file=sys.stderr,
              )
              return 1
          backbone, s1_audio, s1_text, s2_audio, s2_text = sys.argv[1:6]

          async with Client() as client:
              t = client.transport
              try:
                  model_id = await load_model(
                      t,
                      model_src=backbone,
                      model_type="tts-ggml",
                      model_config={
                          "ttsEngine": "moss",
                          "language": "en",
                          "mossCodecDecoderModelSrc": TTS_CODEC_DECODER_MOSS_TTS_F16,
                          "mossCodecEncoderModelSrc": TTS_CODEC_ENCODER_MOSS_TTS_F16,
                          # One recording per speaker, in the order the text tags them.
                          "dialogueReferenceSrcs": [s1_audio, s2_audio],
                          "streamChunkTokens": 25,
                          "useGPU": True,
                      },
                  )
                  print(f"▸ Model loaded: {model_id}")

                  print("▸ Synthesizing the dialogue...")
                  request = TextToSpeechRequest.model_validate(
                      {
                          "type": "textToSpeech",
                          "modelId": model_id,
                          "text": (
                              f"[S1] {s1_text} [S2] {s2_text} "
                              "[S1] Did the build finish? [S2] Yes, every test passed. "
                              "[S1] Great, ship it."
                          ),
                          "stream": True,
                      }
                  )

                  samples: list[float] = []
                  sample_rate = None
                  async for response in text_to_speech(t, request):
                      samples.extend(response.buffer)
                      if response.sample_rate is not None:
                          sample_rate = response.sample_rate

                  sample_rate = int(sample_rate or MOSS_SAMPLE_RATE)
                  print(f"▸ Dialogue complete: {len(samples)} samples")

                  create_wav(samples, sample_rate, "moss-dialogue-output.wav")
                  print("▸ Audio saved to moss-dialogue-output.wav")

                  print("▸ Playing audio...")
                  audio_data = int16_array_to_buffer(samples)
                  play_audio(create_wav_header(len(audio_data), sample_rate) + audio_data)

                  await unload_model(t, model_id)
                  print("▸ Model unloaded")
              except Exception as error:
                  print(f"✖ {error}", file=sys.stderr)
                  return 1
          return 0


      if __name__ == "__main__":
          sys.exit(asyncio.run(main()))
      ```
    </WrapCode>
  </Tab>

  <Tab value="kotlin" label="Kotlin">
    <WrapCode>
      ```kotlin file=<rootDir>/packages/sdk-kotlin/examples/src/TextToSpeechMossDialogue.kt title="TextToSpeechMossDialogue.kt" lineNumbers
      // Kotlin port of packages/sdk/examples/tts/moss-dialogue.ts.
      //
      // MOSS-TTSD (GGML): multi-speaker dialogue in one pass, each voice cloned from
      // a 24 kHz reference recording. The model continues the references, so the
      // text opens with what each recording says under its speaker tag, followed by
      // the lines to generate; only the new lines come out as audio. A dialogue is
      // never split into sentences, so `stream = true` delivers the native chunks of
      // the whole conversation (set `streamChunkTokens` to get them while it is still
      // being generated).
      //
      // The MOSS-TTSD backbone is not in the QVAC Registry yet, so it is a local file
      // loaded by path with an explicit `tts-ggml` model type; the codec halves it
      // shares with MOSS-TTS download from the registry.
      //
      // `client.textToSpeech()` returns a `Flow<TextToSpeechResponse>`: the example
      // collects each frame's `buffer` and reads `sampleRate` off them. The helpers
      // below, ported from the JS example's `utils`, save the samples to a WAV and
      // play it through ffplay.
      //
      // RUN: ./gradlew -p examples run -Pexample=TextToSpeechMossDialogue
      //      --args='<moss-ttsd.gguf> <s1.wav> "<s1 transcript>" <s2.wav> "<s2 transcript>"'

      import io.tether.qvac.sdk.QvacClient
      import io.tether.qvac.sdk.generated.Models
      import io.tether.qvac.sdk.generated.schema.TextToSpeechRequest
      import io.tether.qvac.sdk.jvm.JvmBareKitTransport
      import io.tether.qvac.sdk.models
      import io.tether.qvac.sdk.textToSpeech
      import java.io.File
      import java.io.IOException
      import java.nio.ByteBuffer
      import java.nio.ByteOrder
      import kotlin.math.roundToInt
      import kotlin.system.exitProcess
      import kotlinx.coroutines.runBlocking
      import kotlinx.serialization.json.add
      import kotlinx.serialization.json.buildJsonObject
      import kotlinx.serialization.json.put
      import kotlinx.serialization.json.putJsonArray

      // Only a fallback: the engine reports the rate it actually produced.
      private const val MOSS_SAMPLE_RATE = 24000

      fun main(args: Array<String>): Unit = runBlocking {
          if (args.size < 5 || args.take(5).any { it.isEmpty() }) {
              System.err.println(
                  "Usage: ./gradlew -p examples run -Pexample=TextToSpeechMossDialogue " +
                      "--args='<moss-ttsd.gguf> <s1.wav> \"<s1 transcript>\" <s2.wav> \"<s2 transcript>\"'",
              )
              exitProcess(1)
          }
          val (backbone, s1Audio, s1Text, s2Audio, s2Text) = args

          val client = QvacClient(JvmBareKitTransport.connect())
          try {
              val loaded = client.models.load(
                  source = backbone,
                  modelType = "tts-ggml",
                  modelConfig = buildJsonObject {
                      put("ttsEngine", "moss")
                      put("language", "en")
                      put("mossCodecDecoderModelSrc", Models.TTS_CODEC_DECODER_MOSS_TTS_F16.src)
                      put("mossCodecEncoderModelSrc", Models.TTS_CODEC_ENCODER_MOSS_TTS_F16.src)
                      // One recording per speaker, in the order the text tags them.
                      putJsonArray("dialogueReferenceSrcs") {
                          add(s1Audio)
                          add(s2Audio)
                      }
                      put("streamChunkTokens", 25)
                      put("useGPU", true)
                  },
              )
              val modelId = loaded.modelId ?: error(loaded.error ?: "loadModel failed")
              println("▸ Model loaded: $modelId")

              println("▸ Synthesizing the dialogue...")
              val request = TextToSpeechRequest(
                  modelId = modelId,
                  text = "[S1] $s1Text [S2] $s2Text " +
                      "[S1] Did the build finish? [S2] Yes, every test passed. " +
                      "[S1] Great, ship it.",
                  stream = true,
              )

              val samples = mutableListOf<Double>()
              var sampleRate = MOSS_SAMPLE_RATE
              client.textToSpeech(request).collect { response ->
                  samples += response.buffer
                  response.sampleRate?.let { sampleRate = it.toInt() }
              }
              println("▸ Dialogue complete: ${samples.size} samples")

              createWav(samples, sampleRate, "moss-dialogue-output.wav")
              println("▸ Audio saved to moss-dialogue-output.wav")

              println("▸ Playing audio...")
              val audioData = int16ArrayToBuffer(samples)
              playAudio(createWavHeader(audioData.size, sampleRate) + audioData)

              client.models.unload(modelId)
              println("▸ Model unloaded")
          } finally {
              client.close()
          }
      }

      /** Create a WAV header for 16-bit mono PCM audio. */
      private fun createWavHeader(dataLength: Int, sampleRate: Int): ByteArray =
          ByteBuffer.allocate(44).order(ByteOrder.LITTLE_ENDIAN)
              .put("RIFF".toByteArray(Charsets.US_ASCII)).putInt(36 + dataLength)
              .put("WAVEfmt ".toByteArray(Charsets.US_ASCII))
              .putInt(16).putShort(1).putShort(1).putInt(sampleRate).putInt(sampleRate * 2).putShort(2).putShort(16)
              .put("data".toByteArray(Charsets.US_ASCII)).putInt(dataLength)
              .array()

      /** Convert int16 PCM samples to little-endian bytes. */
      private fun int16ArrayToBuffer(samples: List<Double>): ByteArray {
          val buffer = ByteBuffer.allocate(samples.size * 2).order(ByteOrder.LITTLE_ENDIAN)
          for (sample in samples) buffer.putShort(sample.roundToInt().coerceIn(-32768, 32767).toShort())
          return buffer.array()
      }

      /** Create and save a WAV file. */
      private fun createWav(samples: List<Double>, sampleRate: Int, filename: String) {
          val audioData = int16ArrayToBuffer(samples)
          File(filename).writeBytes(createWavHeader(audioData.size, sampleRate) + audioData)
          println("▸ WAV file saved as: $filename")
      }

      /** Play a WAV buffer by streaming it into ffplay over stdin. */
      private fun playAudio(wav: ByteArray) {
          val ffplay = try {
              ProcessBuilder("ffplay", "-hide_banner", "-loglevel", "error", "-autoexit", "-nodisp", "-i", "pipe:0")
                  .redirectOutput(ProcessBuilder.Redirect.INHERIT)
                  .redirectError(ProcessBuilder.Redirect.INHERIT)
                  .start()
          } catch (e: IOException) {
              throw IllegalStateException("ffplay not found on PATH. Install ffmpeg (ffplay ships with it) and retry.", e)
          }
          ffplay.outputStream.use { it.write(wav) }
          val code = ffplay.waitFor()
          check(code == 0) { "ffplay exited with code $code" }
      }
      ```
    </WrapCode>
  </Tab>
</Tabs>

### MOSS-SoundEffect

This example generates a sound effect from text using MOSS-SoundEffect. It saves the 2-second, 48 kHz clip to `moss-sound-effect-output.wav`. Arguments: none.

<Tabs>
  <Tab value="js" label="JavaScript" default>
    <WrapCode>
      ```js file=<rootDir>/packages/sdk/dist/examples/tts/moss-sound-effect.js title="moss-sound-effect.js" lineNumbers
      import { writeFileSync } from 'node:fs';
      import { loadModel, textToSpeech, unloadModel, close, AUDIOGEN_MOSS_SFX_V2_Q8_0 } from '@qvac/sdk';
      // Desktop MOSS-SoundEffect-v2, 48 kHz mono output. A GPU is recommended.
      // Run from packages/sdk: node --import tsx examples/tts/moss-sound-effect.ts
      // Optional: QVAC_MOSS_SFX_MODEL=/absolute/path/moss-sfx-v2-q8_0.gguf
      // Use the catalog source URL: its full descriptor selects the audiogen plugin.
      // Each clip denoises a 30-second latent, regardless of its requested output duration.
      // Use 20 steps for a practical demo; omitting steps uses the slower baked default (100).
      function saveWav(samples, sampleRate, filename) {
          if (samples.length === 0 || samples.some((sample) => !Number.isFinite(sample))) {
              throw new Error('The model returned no usable audio.');
          }
          const wav = Buffer.alloc(44 + samples.length * 2);
          wav.write('RIFF', 0);
          wav.writeUInt32LE(wav.length - 8, 4);
          wav.write('WAVEfmt ', 8);
          wav.writeUInt32LE(16, 16);
          wav.writeUInt16LE(1, 20);
          wav.writeUInt16LE(1, 22);
          wav.writeUInt32LE(sampleRate, 24);
          wav.writeUInt32LE(sampleRate * 2, 28);
          wav.writeUInt16LE(2, 32);
          wav.writeUInt16LE(16, 34);
          wav.write('data', 36);
          wav.writeUInt32LE(samples.length * 2, 40);
          for (let i = 0; i < samples.length; i++) {
              wav.writeInt16LE(Math.max(-32768, Math.min(32767, Math.round(samples[i]))), 44 + i * 2);
          }
          writeFileSync(filename, wav);
          console.error(`▸ Saved ${filename}: ${sampleRate} Hz, ${(samples.length / sampleRate).toFixed(2)} seconds`);
      }
      let lastPercentage = -1;
      function progress(p) {
          const percentage = Math.floor(p.percentage);
          if (percentage === lastPercentage)
              return;
          lastPercentage = percentage;
          const line = `▸ Downloading ${p.percentage.toFixed(0)}% (${(p.downloaded / 1e6).toFixed(1)}/${(p.total / 1e6).toFixed(1)} MB)`;
          process.stderr.write(process.stderr.isTTY ? `\r${line}` : `${line}\n`);
          if (p.percentage >= 100)
              process.stderr.write('\n');
      }
      async function main() {
          const modelId = await loadModel({
              modelSrc: process.env['QVAC_MOSS_SFX_MODEL'] ?? AUDIOGEN_MOSS_SFX_V2_Q8_0.src,
              modelType: 'tts-ggml',
              modelConfig: { ttsEngine: 'moss-sfx', useGPU: true, seed: 42 },
              onProgress: progress
          });
          try {
              console.error('▸ Generating a sound effect...');
              const result = textToSpeech({
                  modelId,
                  text: 'Heavy rain falling on a tin roof.',
                  stream: false,
                  seconds: 2,
                  steps: 20
              });
              const samples = await result.buffer;
              if (!(await result.done))
                  throw new Error('Sound-effect generation did not complete.');
              const sampleRate = await result.sampleRate;
              if (sampleRate !== 48000)
                  throw new Error(`Unexpected sound-effect sample rate: ${sampleRate}`);
              saveWav(samples, sampleRate, 'moss-sound-effect-output.wav');
          }
          finally {
              await unloadModel({ modelId });
          }
      }
      try {
          await main();
      }
      catch (error) {
          console.error('✖', error);
          process.exitCode = 1;
      }
      finally {
          try {
              await close();
          }
          catch (error) {
              console.error('✖ Cleanup failed:', error);
              process.exitCode = 1;
          }
      }
      ```
    </WrapCode>
  </Tab>

  <Tab value="ts" label="TypeScript">
    <WrapCode>
      ```ts file=<rootDir>/packages/sdk/examples/tts/moss-sound-effect.ts title="moss-sound-effect.ts" lineNumbers
      import { writeFileSync } from 'node:fs'
      import {
        loadModel,
        textToSpeech,
        unloadModel,
        close,
        AUDIOGEN_MOSS_SFX_V2_Q8_0,
        type ModelProgressUpdate
      } from '@qvac/sdk'

      // Desktop MOSS-SoundEffect-v2, 48 kHz mono output. A GPU is recommended.
      // Run from packages/sdk: node --import tsx examples/tts/moss-sound-effect.ts
      // Optional: QVAC_MOSS_SFX_MODEL=/absolute/path/moss-sfx-v2-q8_0.gguf
      // Use the catalog source URL: its full descriptor selects the audiogen plugin.
      // Each clip denoises a 30-second latent, regardless of its requested output duration.
      // Use 20 steps for a practical demo; omitting steps uses the slower baked default (100).

      function saveWav(samples: number[], sampleRate: number, filename: string) {
        if (samples.length === 0 || samples.some((sample) => !Number.isFinite(sample))) {
          throw new Error('The model returned no usable audio.')
        }
        const wav = Buffer.alloc(44 + samples.length * 2)
        wav.write('RIFF', 0)
        wav.writeUInt32LE(wav.length - 8, 4)
        wav.write('WAVEfmt ', 8)
        wav.writeUInt32LE(16, 16)
        wav.writeUInt16LE(1, 20)
        wav.writeUInt16LE(1, 22)
        wav.writeUInt32LE(sampleRate, 24)
        wav.writeUInt32LE(sampleRate * 2, 28)
        wav.writeUInt16LE(2, 32)
        wav.writeUInt16LE(16, 34)
        wav.write('data', 36)
        wav.writeUInt32LE(samples.length * 2, 40)
        for (let i = 0; i < samples.length; i++) {
          wav.writeInt16LE(Math.max(-32768, Math.min(32767, Math.round(samples[i]!))), 44 + i * 2)
        }
        writeFileSync(filename, wav)
        console.error(
          `▸ Saved ${filename}: ${sampleRate} Hz, ${(samples.length / sampleRate).toFixed(2)} seconds`
        )
      }

      let lastPercentage = -1
      function progress(p: ModelProgressUpdate) {
        const percentage = Math.floor(p.percentage)
        if (percentage === lastPercentage) return
        lastPercentage = percentage
        const line = `▸ Downloading ${p.percentage.toFixed(0)}% (${(p.downloaded / 1e6).toFixed(1)}/${(p.total / 1e6).toFixed(1)} MB)`
        process.stderr.write(process.stderr.isTTY ? `\r${line}` : `${line}\n`)
        if (p.percentage >= 100) process.stderr.write('\n')
      }

      async function main() {
        const modelId = await loadModel({
          modelSrc: process.env['QVAC_MOSS_SFX_MODEL'] ?? AUDIOGEN_MOSS_SFX_V2_Q8_0.src,
          modelType: 'tts-ggml',
          modelConfig: { ttsEngine: 'moss-sfx', useGPU: true, seed: 42 },
          onProgress: progress
        })
        try {
          console.error('▸ Generating a sound effect...')
          const result = textToSpeech({
            modelId,
            text: 'Heavy rain falling on a tin roof.',
            stream: false,
            seconds: 2,
            steps: 20
          })
          const samples = await result.buffer
          if (!(await result.done)) throw new Error('Sound-effect generation did not complete.')
          const sampleRate = await result.sampleRate
          if (sampleRate !== 48000) throw new Error(`Unexpected sound-effect sample rate: ${sampleRate}`)
          saveWav(samples, sampleRate, 'moss-sound-effect-output.wav')
        } finally {
          await unloadModel({ modelId })
        }
      }

      try {
        await main()
      } catch (error) {
        console.error('✖', error)
        process.exitCode = 1
      } finally {
        try {
          await close()
        } catch (error) {
          console.error('✖ Cleanup failed:', error)
          process.exitCode = 1
        }
      }
      ```
    </WrapCode>
  </Tab>

  <Tab value="python" label="Python">
    <WrapCode>
      ```python file=<rootDir>/packages/sdk-python/examples/text_to_speech_moss_sound_effect.py title="text_to_speech_moss_sound_effect.py" lineNumbers
      """Python port of packages/sdk/examples/tts/moss-sound-effect.ts.

      Desktop MOSS-SoundEffect-v2, 48 kHz mono output. A GPU is recommended.
      Optional: QVAC_MOSS_SFX_MODEL=/absolute/path/moss-sfx-v2-q8_0.gguf
      Use the catalog source URL: its full descriptor selects the audiogen plugin.
      Each clip denoises a 30-second latent, regardless of its requested output
      duration. Use 20 steps for a practical demo; omitting steps uses the slower
      baked default (100).

      Python's `text_to_speech` yields frames: the example collects each frame's
      `buffer` and reads `sample_rate` and `done` off them. `Client` closes the SDK
      on exit, which the TypeScript example does with `close()`.

      RUN: python examples/text_to_speech_moss_sound_effect.py
      """

      from __future__ import annotations

      import array
      import asyncio
      import contextlib
      import math
      import os
      import sys
      import wave

      from tetherto.qvac_sdk import (
          Client,
          TextToSpeechRequest,
          load_model,
          text_to_speech,
          unload_model,
      )
      from tetherto.qvac_sdk.models import AUDIOGEN_MOSS_SFX_V2_Q8_0

      _last_percentage = -1


      def print_progress(p) -> None:
          """Print model download progress once per whole percent."""
          global _last_percentage
          percentage = math.floor(p.percentage)
          if percentage == _last_percentage:
              return
          _last_percentage = percentage
          line = (
              f"▸ Downloading {p.percentage:.0f}% "
              f"({p.downloaded / 1e6:.1f}/{p.total / 1e6:.1f} MB)"
          )
          print(line, end="\r" if sys.stderr.isatty() else "\n", file=sys.stderr)
          if p.percentage >= 100:
              print(file=sys.stderr)


      def save_wav(samples, sample_rate, path) -> None:
          if not samples or not all(math.isfinite(s) for s in samples):
              raise RuntimeError("The model returned no usable audio.")
          pcm = array.array("h", (max(-32768, min(32767, round(s))) for s in samples))
          with wave.open(path, "wb") as w:
              w.setnchannels(1)
              w.setsampwidth(2)
              w.setframerate(sample_rate)
              w.writeframes(pcm.tobytes())
          print(
              f"▸ Saved {path}: {sample_rate} Hz, {len(samples) / sample_rate:.2f} seconds",
              file=sys.stderr,
          )


      async def main() -> int:
          async with Client() as client:
              t = client.transport
              model_id = None
              try:
                  model_id = await load_model(
                      t,
                      model_src=os.environ.get("QVAC_MOSS_SFX_MODEL")
                      or AUDIOGEN_MOSS_SFX_V2_Q8_0.src,
                      model_type="tts-ggml",
                      model_config={"ttsEngine": "moss-sfx", "useGPU": True, "seed": 42},
                      on_progress=print_progress,
                  )

                  print("▸ Generating a sound effect...", file=sys.stderr)
                  request = TextToSpeechRequest.model_validate(
                      {
                          "type": "textToSpeech",
                          "modelId": model_id,
                          "text": "Heavy rain falling on a tin roof.",
                          "stream": False,
                          "seconds": 2,
                          "steps": 20,
                      }
                  )

                  samples: list[float] = []
                  sample_rate = None
                  done = False
                  async for response in text_to_speech(t, request):
                      samples.extend(response.buffer)
                      if response.sample_rate is not None:
                          sample_rate = response.sample_rate
                      done = done or response.done

                  if not done:
                      raise RuntimeError("Sound-effect generation did not complete.")
                  if sample_rate != 48000:
                      raise RuntimeError(
                          f"Unexpected sound-effect sample rate: {sample_rate}"
                      )
                  save_wav(samples, sample_rate, "moss-sound-effect-output.wav")
              except Exception as error:
                  print(f"✖ {error}", file=sys.stderr)
                  return 1
              finally:
                  if model_id is not None:
                      with contextlib.suppress(Exception):
                          await unload_model(t, model_id)
          return 0


      if __name__ == "__main__":
          sys.exit(asyncio.run(main()))
      ```
    </WrapCode>
  </Tab>

  <Tab value="kotlin" label="Kotlin">
    <WrapCode>
      ```kotlin file=<rootDir>/packages/sdk-kotlin/examples/src/TextToSpeechMossSoundEffect.kt title="TextToSpeechMossSoundEffect.kt" lineNumbers
      // Kotlin port of packages/sdk/examples/tts/moss-sound-effect.ts.
      //
      // Desktop MOSS-SoundEffect-v2, 48 kHz mono output. A GPU is recommended.
      // Optional: QVAC_MOSS_SFX_MODEL=/absolute/path/moss-sfx-v2-q8_0.gguf
      // Use the catalog source URL: its full descriptor selects the audiogen plugin.
      // Each clip denoises a 30-second latent, regardless of its requested output
      // duration. Use 20 steps for a practical demo; omitting steps uses the slower
      // baked default (100).
      //
      // The sound-effect fields (`seconds`, `steps`) are typed properties of the
      // generated `TextToSpeechRequest`. `client.textToSpeech()` returns a
      // `Flow<TextToSpeechResponse>`: the example collects each frame's `buffer` and
      // reads `sampleRate` and `done` off them. The model is unloaded in a `finally`
      // block, as the TypeScript example does.
      //
      // RUN: ./gradlew -p examples run -Pexample=TextToSpeechMossSoundEffect

      import io.tether.qvac.sdk.QvacClient
      import io.tether.qvac.sdk.QvacProgressEvent
      import io.tether.qvac.sdk.generated.Models
      import io.tether.qvac.sdk.generated.schema.LoadModelResponse
      import io.tether.qvac.sdk.generated.schema.ModelProgressResponse
      import io.tether.qvac.sdk.generated.schema.TextToSpeechRequest
      import io.tether.qvac.sdk.jvm.JvmBareKitTransport
      import io.tether.qvac.sdk.models
      import io.tether.qvac.sdk.textToSpeech
      import java.io.File
      import java.nio.ByteBuffer
      import java.nio.ByteOrder
      import kotlin.math.floor
      import kotlin.math.roundToInt
      import kotlinx.coroutines.runBlocking
      import kotlinx.serialization.json.JsonObject
      import kotlinx.serialization.json.buildJsonObject
      import kotlinx.serialization.json.put

      fun main(): Unit = runBlocking {
          val client = QvacClient(JvmBareKitTransport.connect())
          try {
              val modelId = client.loadWithProgress(
                  source = System.getenv("QVAC_MOSS_SFX_MODEL") ?: Models.AUDIOGEN_MOSS_SFX_V2_Q8_0.src,
                  modelType = "tts-ggml",
                  modelConfig = buildJsonObject {
                      put("ttsEngine", "moss-sfx")
                      put("useGPU", true)
                      put("seed", 42)
                  },
              )
              try {
                  System.err.println("▸ Generating a sound effect...")
                  val request = TextToSpeechRequest(
                      modelId = modelId,
                      text = "Heavy rain falling on a tin roof.",
                      stream = false,
                      seconds = 2.0,
                      steps = 20,
                  )

                  val samples = mutableListOf<Double>()
                  var sampleRate: Long? = null
                  var done = false
                  client.textToSpeech(request).collect { response ->
                      samples += response.buffer
                      response.sampleRate?.let { sampleRate = it }
                      done = done || response.done
                  }

                  check(done) { "Sound-effect generation did not complete." }
                  check(sampleRate == 48000L) { "Unexpected sound-effect sample rate: $sampleRate" }
                  saveWav(samples, 48000, "moss-sound-effect-output.wav")
              } finally {
                  client.models.unload(modelId)
              }
          } finally {
              client.close()
          }
      }

      /** Load [source] as [modelType], printing download progress, and return its model id. */
      private suspend fun QvacClient.loadWithProgress(source: String, modelType: String, modelConfig: JsonObject): String {
          var result: LoadModelResponse? = null
          models.loadWithProgress(source, modelType, modelConfig = modelConfig).collect { event ->
              when (event) {
                  is QvacProgressEvent.Progress -> printProgress(event.value)
                  is QvacProgressEvent.Result -> result = event.value
              }
          }
          val loaded = checkNotNull(result) { "loadModel ended without a result" }
          return loaded.modelId ?: error(loaded.error ?: "loadModel failed")
      }

      private var lastPercentage = -1

      /** Print model download progress once per whole percent. */
      private fun printProgress(p: ModelProgressResponse) {
          val percentage = floor(p.percentage).toInt()
          if (percentage == lastPercentage) return
          lastPercentage = percentage
          val line = "▸ Downloading %.0f%% (%.1f/%.1f MB)".format(p.percentage, p.downloaded / 1e6, p.total / 1e6)
          if (System.console() != null) System.err.print("\r$line") else System.err.println(line)
          if (p.percentage >= 100) System.err.println()
      }

      /** Save int16 PCM samples as a 16-bit mono WAV. */
      private fun saveWav(samples: List<Double>, sampleRate: Int, path: String) {
          check(samples.isNotEmpty() && samples.all { it.isFinite() }) { "The model returned no usable audio." }
          val wav = ByteBuffer.allocate(44 + samples.size * 2).order(ByteOrder.LITTLE_ENDIAN)
              .put("RIFF".toByteArray(Charsets.US_ASCII)).putInt(36 + samples.size * 2)
              .put("WAVEfmt ".toByteArray(Charsets.US_ASCII))
              .putInt(16).putShort(1).putShort(1).putInt(sampleRate).putInt(sampleRate * 2).putShort(2).putShort(16)
              .put("data".toByteArray(Charsets.US_ASCII)).putInt(samples.size * 2)
          for (sample in samples) wav.putShort(sample.roundToInt().coerceIn(-32768, 32767).toShort())
          File(path).writeBytes(wav.array())
          System.err.println("▸ Saved %s: %d Hz, %.2f seconds".format(path, sampleRate, samples.size.toDouble() / sampleRate))
      }
      ```
    </WrapCode>
  </Tab>
</Tabs>

### MOSS-SoundEffect controls

This example generates a sound effect from text using MOSS-SoundEffect with generation controls. It adds a negative prompt, guidance, and shift, and saves the 3-second, 48 kHz clip to `moss-sound-effect-controls-output.wav`. Arguments: none.

<Tabs>
  <Tab value="js" label="JavaScript" default>
    <WrapCode>
      ```js file=<rootDir>/packages/sdk/dist/examples/tts/moss-sound-effect-controls.js title="moss-sound-effect-controls.js" lineNumbers
      import { writeFileSync } from 'node:fs';
      import { loadModel, textToSpeech, unloadModel, close, AUDIOGEN_MOSS_SFX_V2_Q8_0 } from '@qvac/sdk';
      // Desktop MOSS-SoundEffect-v2, 48 kHz mono output. A GPU is recommended.
      // Run from packages/sdk: node --import tsx examples/tts/moss-sound-effect-controls.ts
      // Optional: QVAC_MOSS_SFX_MODEL=/absolute/path/moss-sfx-v2-q8_0.gguf
      // Use the catalog source URL: its full descriptor selects the audiogen plugin.
      // Each clip denoises a 30-second latent, regardless of its requested output duration.
      function saveWav(samples, sampleRate, filename) {
          if (samples.length === 0 || samples.some((sample) => !Number.isFinite(sample))) {
              throw new Error('The model returned no usable audio.');
          }
          const wav = Buffer.alloc(44 + samples.length * 2);
          wav.write('RIFF', 0);
          wav.writeUInt32LE(wav.length - 8, 4);
          wav.write('WAVEfmt ', 8);
          wav.writeUInt32LE(16, 16);
          wav.writeUInt16LE(1, 20);
          wav.writeUInt16LE(1, 22);
          wav.writeUInt32LE(sampleRate, 24);
          wav.writeUInt32LE(sampleRate * 2, 28);
          wav.writeUInt16LE(2, 32);
          wav.writeUInt16LE(16, 34);
          wav.write('data', 36);
          wav.writeUInt32LE(samples.length * 2, 40);
          for (let i = 0; i < samples.length; i++) {
              wav.writeInt16LE(Math.max(-32768, Math.min(32767, Math.round(samples[i]))), 44 + i * 2);
          }
          writeFileSync(filename, wav);
          console.error(`▸ Saved ${filename}: ${sampleRate} Hz, ${(samples.length / sampleRate).toFixed(2)} seconds`);
      }
      let lastPercentage = -1;
      function progress(p) {
          const percentage = Math.floor(p.percentage);
          if (percentage === lastPercentage)
              return;
          lastPercentage = percentage;
          const line = `▸ Downloading ${p.percentage.toFixed(0)}% (${(p.downloaded / 1e6).toFixed(1)}/${(p.total / 1e6).toFixed(1)} MB)`;
          process.stderr.write(process.stderr.isTTY ? `\r${line}` : `${line}\n`);
          if (p.percentage >= 100)
              process.stderr.write('\n');
      }
      async function main() {
          const modelId = await loadModel({
              modelSrc: process.env['QVAC_MOSS_SFX_MODEL'] ?? AUDIOGEN_MOSS_SFX_V2_Q8_0.src,
              modelType: 'tts-ggml',
              modelConfig: { ttsEngine: 'moss-sfx', useGPU: true, seed: 42 },
              onProgress: progress
          });
          try {
              console.error('▸ Generating a sound effect...');
              const result = textToSpeech({
                  modelId,
                  text: 'A dog barking twice in a quiet room.',
                  stream: false,
                  seconds: 3,
                  negativePrompt: 'Speech, music, background voices.',
                  steps: 20,
                  guidance: 4,
                  shift: 5
              });
              const samples = await result.buffer;
              if (!(await result.done))
                  throw new Error('Sound-effect generation did not complete.');
              const sampleRate = await result.sampleRate;
              if (sampleRate !== 48000)
                  throw new Error(`Unexpected sound-effect sample rate: ${sampleRate}`);
              saveWav(samples, sampleRate, 'moss-sound-effect-controls-output.wav');
          }
          finally {
              await unloadModel({ modelId });
          }
      }
      try {
          await main();
      }
      catch (error) {
          console.error('✖', error);
          process.exitCode = 1;
      }
      finally {
          try {
              await close();
          }
          catch (error) {
              console.error('✖ Cleanup failed:', error);
              process.exitCode = 1;
          }
      }
      ```
    </WrapCode>
  </Tab>

  <Tab value="ts" label="TypeScript">
    <WrapCode>
      ```ts file=<rootDir>/packages/sdk/examples/tts/moss-sound-effect-controls.ts title="moss-sound-effect-controls.ts" lineNumbers
      import { writeFileSync } from 'node:fs'
      import {
        loadModel,
        textToSpeech,
        unloadModel,
        close,
        AUDIOGEN_MOSS_SFX_V2_Q8_0,
        type ModelProgressUpdate
      } from '@qvac/sdk'

      // Desktop MOSS-SoundEffect-v2, 48 kHz mono output. A GPU is recommended.
      // Run from packages/sdk: node --import tsx examples/tts/moss-sound-effect-controls.ts
      // Optional: QVAC_MOSS_SFX_MODEL=/absolute/path/moss-sfx-v2-q8_0.gguf
      // Use the catalog source URL: its full descriptor selects the audiogen plugin.
      // Each clip denoises a 30-second latent, regardless of its requested output duration.

      function saveWav(samples: number[], sampleRate: number, filename: string) {
        if (samples.length === 0 || samples.some((sample) => !Number.isFinite(sample))) {
          throw new Error('The model returned no usable audio.')
        }
        const wav = Buffer.alloc(44 + samples.length * 2)
        wav.write('RIFF', 0)
        wav.writeUInt32LE(wav.length - 8, 4)
        wav.write('WAVEfmt ', 8)
        wav.writeUInt32LE(16, 16)
        wav.writeUInt16LE(1, 20)
        wav.writeUInt16LE(1, 22)
        wav.writeUInt32LE(sampleRate, 24)
        wav.writeUInt32LE(sampleRate * 2, 28)
        wav.writeUInt16LE(2, 32)
        wav.writeUInt16LE(16, 34)
        wav.write('data', 36)
        wav.writeUInt32LE(samples.length * 2, 40)
        for (let i = 0; i < samples.length; i++) {
          wav.writeInt16LE(Math.max(-32768, Math.min(32767, Math.round(samples[i]!))), 44 + i * 2)
        }
        writeFileSync(filename, wav)
        console.error(
          `▸ Saved ${filename}: ${sampleRate} Hz, ${(samples.length / sampleRate).toFixed(2)} seconds`
        )
      }

      let lastPercentage = -1
      function progress(p: ModelProgressUpdate) {
        const percentage = Math.floor(p.percentage)
        if (percentage === lastPercentage) return
        lastPercentage = percentage
        const line = `▸ Downloading ${p.percentage.toFixed(0)}% (${(p.downloaded / 1e6).toFixed(1)}/${(p.total / 1e6).toFixed(1)} MB)`
        process.stderr.write(process.stderr.isTTY ? `\r${line}` : `${line}\n`)
        if (p.percentage >= 100) process.stderr.write('\n')
      }

      async function main() {
        const modelId = await loadModel({
          modelSrc: process.env['QVAC_MOSS_SFX_MODEL'] ?? AUDIOGEN_MOSS_SFX_V2_Q8_0.src,
          modelType: 'tts-ggml',
          modelConfig: { ttsEngine: 'moss-sfx', useGPU: true, seed: 42 },
          onProgress: progress
        })
        try {
          console.error('▸ Generating a sound effect...')
          const result = textToSpeech({
            modelId,
            text: 'A dog barking twice in a quiet room.',
            stream: false,
            seconds: 3,
            negativePrompt: 'Speech, music, background voices.',
            steps: 20,
            guidance: 4,
            shift: 5
          })
          const samples = await result.buffer
          if (!(await result.done)) throw new Error('Sound-effect generation did not complete.')
          const sampleRate = await result.sampleRate
          if (sampleRate !== 48000) throw new Error(`Unexpected sound-effect sample rate: ${sampleRate}`)
          saveWav(samples, sampleRate, 'moss-sound-effect-controls-output.wav')
        } finally {
          await unloadModel({ modelId })
        }
      }

      try {
        await main()
      } catch (error) {
        console.error('✖', error)
        process.exitCode = 1
      } finally {
        try {
          await close()
        } catch (error) {
          console.error('✖ Cleanup failed:', error)
          process.exitCode = 1
        }
      }
      ```
    </WrapCode>
  </Tab>

  <Tab value="python" label="Python">
    <WrapCode>
      ```python file=<rootDir>/packages/sdk-python/examples/text_to_speech_moss_sound_effect_controls.py title="text_to_speech_moss_sound_effect_controls.py" lineNumbers
      """Python port of packages/sdk/examples/tts/moss-sound-effect-controls.ts.

      Desktop MOSS-SoundEffect-v2, 48 kHz mono output. A GPU is recommended.
      Optional: QVAC_MOSS_SFX_MODEL=/absolute/path/moss-sfx-v2-q8_0.gguf
      Use the catalog source URL: its full descriptor selects the audiogen plugin.
      Each clip denoises a 30-second latent, regardless of its requested output
      duration. This example adds the generation controls: a `negativePrompt`, the
      number of `steps`, the `guidance` scale and the scheduler `shift`.

      Python's `text_to_speech` yields frames: the example collects each frame's
      `buffer` and reads `sample_rate` and `done` off them. `Client` closes the SDK
      on exit, which the TypeScript example does with `close()`.

      RUN: python examples/text_to_speech_moss_sound_effect_controls.py
      """

      from __future__ import annotations

      import array
      import asyncio
      import contextlib
      import math
      import os
      import sys
      import wave

      from tetherto.qvac_sdk import (
          Client,
          TextToSpeechRequest,
          load_model,
          text_to_speech,
          unload_model,
      )
      from tetherto.qvac_sdk.models import AUDIOGEN_MOSS_SFX_V2_Q8_0

      _last_percentage = -1


      def print_progress(p) -> None:
          """Print model download progress once per whole percent."""
          global _last_percentage
          percentage = math.floor(p.percentage)
          if percentage == _last_percentage:
              return
          _last_percentage = percentage
          line = (
              f"▸ Downloading {p.percentage:.0f}% "
              f"({p.downloaded / 1e6:.1f}/{p.total / 1e6:.1f} MB)"
          )
          print(line, end="\r" if sys.stderr.isatty() else "\n", file=sys.stderr)
          if p.percentage >= 100:
              print(file=sys.stderr)


      def save_wav(samples, sample_rate, path) -> None:
          if not samples or not all(math.isfinite(s) for s in samples):
              raise RuntimeError("The model returned no usable audio.")
          pcm = array.array("h", (max(-32768, min(32767, round(s))) for s in samples))
          with wave.open(path, "wb") as w:
              w.setnchannels(1)
              w.setsampwidth(2)
              w.setframerate(sample_rate)
              w.writeframes(pcm.tobytes())
          print(
              f"▸ Saved {path}: {sample_rate} Hz, {len(samples) / sample_rate:.2f} seconds",
              file=sys.stderr,
          )


      async def main() -> int:
          async with Client() as client:
              t = client.transport
              model_id = None
              try:
                  model_id = await load_model(
                      t,
                      model_src=os.environ.get("QVAC_MOSS_SFX_MODEL")
                      or AUDIOGEN_MOSS_SFX_V2_Q8_0.src,
                      model_type="tts-ggml",
                      model_config={"ttsEngine": "moss-sfx", "useGPU": True, "seed": 42},
                      on_progress=print_progress,
                  )

                  print("▸ Generating a sound effect...", file=sys.stderr)
                  request = TextToSpeechRequest.model_validate(
                      {
                          "type": "textToSpeech",
                          "modelId": model_id,
                          "text": "A dog barking twice in a quiet room.",
                          "stream": False,
                          "seconds": 3,
                          "negativePrompt": "Speech, music, background voices.",
                          "steps": 20,
                          "guidance": 4,
                          "shift": 5,
                      }
                  )

                  samples: list[float] = []
                  sample_rate = None
                  done = False
                  async for response in text_to_speech(t, request):
                      samples.extend(response.buffer)
                      if response.sample_rate is not None:
                          sample_rate = response.sample_rate
                      done = done or response.done

                  if not done:
                      raise RuntimeError("Sound-effect generation did not complete.")
                  if sample_rate != 48000:
                      raise RuntimeError(
                          f"Unexpected sound-effect sample rate: {sample_rate}"
                      )
                  save_wav(samples, sample_rate, "moss-sound-effect-controls-output.wav")
              except Exception as error:
                  print(f"✖ {error}", file=sys.stderr)
                  return 1
              finally:
                  if model_id is not None:
                      with contextlib.suppress(Exception):
                          await unload_model(t, model_id)
          return 0


      if __name__ == "__main__":
          sys.exit(asyncio.run(main()))
      ```
    </WrapCode>
  </Tab>

  <Tab value="kotlin" label="Kotlin">
    <WrapCode>
      ```kotlin file=<rootDir>/packages/sdk-kotlin/examples/src/TextToSpeechMossSoundEffectControls.kt title="TextToSpeechMossSoundEffectControls.kt" lineNumbers
      // Kotlin port of packages/sdk/examples/tts/moss-sound-effect-controls.ts.
      //
      // Desktop MOSS-SoundEffect-v2, 48 kHz mono output. A GPU is recommended.
      // Optional: QVAC_MOSS_SFX_MODEL=/absolute/path/moss-sfx-v2-q8_0.gguf
      // Use the catalog source URL: its full descriptor selects the audiogen plugin.
      // Each clip denoises a 30-second latent, regardless of its requested output
      // duration. This example adds the generation controls: a `negativePrompt`, the
      // number of `steps`, the `guidance` scale and the scheduler `shift`.
      //
      // The controls are typed properties of the generated `TextToSpeechRequest`
      // (`steps: Long?`, `guidance: Double?`, `shift: Double?`), so the compiler
      // checks names and types. `client.textToSpeech()` returns a
      // `Flow<TextToSpeechResponse>`: the example collects each frame's `buffer` and
      // reads `sampleRate` and `done` off them. The model is unloaded in a `finally`
      // block, as the TypeScript example does.
      //
      // RUN: ./gradlew -p examples run -Pexample=TextToSpeechMossSoundEffectControls

      import io.tether.qvac.sdk.QvacClient
      import io.tether.qvac.sdk.QvacProgressEvent
      import io.tether.qvac.sdk.generated.Models
      import io.tether.qvac.sdk.generated.schema.LoadModelResponse
      import io.tether.qvac.sdk.generated.schema.ModelProgressResponse
      import io.tether.qvac.sdk.generated.schema.TextToSpeechRequest
      import io.tether.qvac.sdk.jvm.JvmBareKitTransport
      import io.tether.qvac.sdk.models
      import io.tether.qvac.sdk.textToSpeech
      import java.io.File
      import java.nio.ByteBuffer
      import java.nio.ByteOrder
      import kotlin.math.floor
      import kotlin.math.roundToInt
      import kotlinx.coroutines.runBlocking
      import kotlinx.serialization.json.JsonObject
      import kotlinx.serialization.json.buildJsonObject
      import kotlinx.serialization.json.put

      fun main(): Unit = runBlocking {
          val client = QvacClient(JvmBareKitTransport.connect())
          try {
              val modelId = client.loadWithProgress(
                  source = System.getenv("QVAC_MOSS_SFX_MODEL") ?: Models.AUDIOGEN_MOSS_SFX_V2_Q8_0.src,
                  modelType = "tts-ggml",
                  modelConfig = buildJsonObject {
                      put("ttsEngine", "moss-sfx")
                      put("useGPU", true)
                      put("seed", 42)
                  },
              )
              try {
                  System.err.println("▸ Generating a sound effect...")
                  val request = TextToSpeechRequest(
                      modelId = modelId,
                      text = "A dog barking twice in a quiet room.",
                      stream = false,
                      seconds = 3.0,
                      negativePrompt = "Speech, music, background voices.",
                      steps = 20,
                      guidance = 4.0,
                      shift = 5.0,
                  )

                  val samples = mutableListOf<Double>()
                  var sampleRate: Long? = null
                  var done = false
                  client.textToSpeech(request).collect { response ->
                      samples += response.buffer
                      response.sampleRate?.let { sampleRate = it }
                      done = done || response.done
                  }

                  check(done) { "Sound-effect generation did not complete." }
                  check(sampleRate == 48000L) { "Unexpected sound-effect sample rate: $sampleRate" }
                  saveWav(samples, 48000, "moss-sound-effect-controls-output.wav")
              } finally {
                  client.models.unload(modelId)
              }
          } finally {
              client.close()
          }
      }

      /** Load [source] as [modelType], printing download progress, and return its model id. */
      private suspend fun QvacClient.loadWithProgress(source: String, modelType: String, modelConfig: JsonObject): String {
          var result: LoadModelResponse? = null
          models.loadWithProgress(source, modelType, modelConfig = modelConfig).collect { event ->
              when (event) {
                  is QvacProgressEvent.Progress -> printProgress(event.value)
                  is QvacProgressEvent.Result -> result = event.value
              }
          }
          val loaded = checkNotNull(result) { "loadModel ended without a result" }
          return loaded.modelId ?: error(loaded.error ?: "loadModel failed")
      }

      private var lastPercentage = -1

      /** Print model download progress once per whole percent. */
      private fun printProgress(p: ModelProgressResponse) {
          val percentage = floor(p.percentage).toInt()
          if (percentage == lastPercentage) return
          lastPercentage = percentage
          val line = "▸ Downloading %.0f%% (%.1f/%.1f MB)".format(p.percentage, p.downloaded / 1e6, p.total / 1e6)
          if (System.console() != null) System.err.print("\r$line") else System.err.println(line)
          if (p.percentage >= 100) System.err.println()
      }

      /** Save int16 PCM samples as a 16-bit mono WAV. */
      private fun saveWav(samples: List<Double>, sampleRate: Int, path: String) {
          check(samples.isNotEmpty() && samples.all { it.isFinite() }) { "The model returned no usable audio." }
          val wav = ByteBuffer.allocate(44 + samples.size * 2).order(ByteOrder.LITTLE_ENDIAN)
              .put("RIFF".toByteArray(Charsets.US_ASCII)).putInt(36 + samples.size * 2)
              .put("WAVEfmt ".toByteArray(Charsets.US_ASCII))
              .putInt(16).putShort(1).putShort(1).putInt(sampleRate).putInt(sampleRate * 2).putShort(2).putShort(16)
              .put("data".toByteArray(Charsets.US_ASCII)).putInt(samples.size * 2)
          for (sample in samples) wav.putShort(sample.roundToInt().coerceIn(-32768, 32767).toShort())
          File(path).writeBytes(wav.array())
          System.err.println("▸ Saved %s: %d Hz, %.2f seconds".format(path, sampleRate, samples.size.toDouble() / sampleRate))
      }
      ```
    </WrapCode>
  </Tab>
</Tabs>

### MOSS-Speech text reply

This example answers a typed question using MOSS-Speech. It prints a text-only reply. Arguments: none.

<Tabs>
  <Tab value="js" label="JavaScript" default>
    <WrapCode>
      ```js file=<rootDir>/packages/sdk/dist/examples/tts/moss-speech.js title="moss-speech.js" lineNumbers
      import { loadModel, textToSpeech, unloadModel, close, TTS_MOSS_SPEECH_Q8_0, TTS_CODEC_MOSS_SPEECH_F16 } from '@qvac/sdk';
      // Desktop MOSS-Speech: answer a typed question with textReply: true.
      // This mode skips audio decoding and returns text with an empty PCM buffer.
      // Run from packages/sdk: node --import tsx examples/tts/moss-speech.ts
      // Use a GPU with enough memory. Registry sources download automatically.
      // Optional local paths: QVAC_MOSS_SPEECH_MODEL and QVAC_MOSS_SPEECH_CODEC.
      // Both engines run a batch job; stream: false collects the complete reply.
      let lastPercentage = -1;
      function progress(p) {
          const percentage = Math.floor(p.percentage);
          if (percentage === lastPercentage)
              return;
          lastPercentage = percentage;
          const line = `▸ Downloading ${p.percentage.toFixed(0)}% (${(p.downloaded / 1e6).toFixed(1)}/${(p.total / 1e6).toFixed(1)} MB)`;
          process.stderr.write(process.stderr.isTTY ? `\r${line}` : `${line}\n`);
          if (p.percentage >= 100)
              process.stderr.write('\n');
      }
      async function main() {
          const modelId = await loadModel({
              modelSrc: process.env['QVAC_MOSS_SPEECH_MODEL'] ?? TTS_MOSS_SPEECH_Q8_0,
              modelType: 'tts-ggml',
              modelConfig: {
                  ttsEngine: 'moss-speech',
                  mossSpeechCodecModelSrc: process.env['QVAC_MOSS_SPEECH_CODEC'] ?? TTS_CODEC_MOSS_SPEECH_F16,
                  useGPU: true,
                  seed: 42
              },
              onProgress: progress
          });
          try {
              console.error('▸ Generating a text-only reply...');
              const result = textToSpeech({
                  modelId,
                  text: 'What is two plus two? Answer in one short sentence.',
                  stream: false,
                  textReply: true,
                  greedy: true,
                  maxNewTokens: 128,
                  maxReplySeconds: 5,
                  systemPrompt: 'You are a helpful assistant. Give short, direct answers.'
              });
              const samples = await result.buffer;
              const reply = await result.text;
              if (!(await result.done) || !reply?.trim())
                  throw new Error('The model returned no reply text.');
              console.log(reply);
              if (samples.length !== 0)
                  throw new Error('A text-only reply must not contain PCM audio.');
          }
          finally {
              await unloadModel({ modelId });
          }
      }
      try {
          await main();
      }
      catch (error) {
          console.error('✖', error);
          process.exitCode = 1;
      }
      finally {
          try {
              await close();
          }
          catch (error) {
              console.error('✖ Cleanup failed:', error);
              process.exitCode = 1;
          }
      }
      ```
    </WrapCode>
  </Tab>

  <Tab value="ts" label="TypeScript">
    <WrapCode>
      ```ts file=<rootDir>/packages/sdk/examples/tts/moss-speech.ts title="moss-speech.ts" lineNumbers
      import {
        loadModel,
        textToSpeech,
        unloadModel,
        close,
        TTS_MOSS_SPEECH_Q8_0,
        TTS_CODEC_MOSS_SPEECH_F16,
        type ModelProgressUpdate
      } from '@qvac/sdk'

      // Desktop MOSS-Speech: answer a typed question with textReply: true.
      // This mode skips audio decoding and returns text with an empty PCM buffer.
      // Run from packages/sdk: node --import tsx examples/tts/moss-speech.ts
      // Use a GPU with enough memory. Registry sources download automatically.
      // Optional local paths: QVAC_MOSS_SPEECH_MODEL and QVAC_MOSS_SPEECH_CODEC.
      // Both engines run a batch job; stream: false collects the complete reply.

      let lastPercentage = -1
      function progress(p: ModelProgressUpdate) {
        const percentage = Math.floor(p.percentage)
        if (percentage === lastPercentage) return
        lastPercentage = percentage
        const line = `▸ Downloading ${p.percentage.toFixed(0)}% (${(p.downloaded / 1e6).toFixed(1)}/${(p.total / 1e6).toFixed(1)} MB)`
        process.stderr.write(process.stderr.isTTY ? `\r${line}` : `${line}\n`)
        if (p.percentage >= 100) process.stderr.write('\n')
      }

      async function main() {
        const modelId = await loadModel({
          modelSrc: process.env['QVAC_MOSS_SPEECH_MODEL'] ?? TTS_MOSS_SPEECH_Q8_0,
          modelType: 'tts-ggml',
          modelConfig: {
            ttsEngine: 'moss-speech',
            mossSpeechCodecModelSrc: process.env['QVAC_MOSS_SPEECH_CODEC'] ?? TTS_CODEC_MOSS_SPEECH_F16,
            useGPU: true,
            seed: 42
          },
          onProgress: progress
        })
        try {
          console.error('▸ Generating a text-only reply...')
          const result = textToSpeech({
            modelId,
            text: 'What is two plus two? Answer in one short sentence.',
            stream: false,
            textReply: true,
            greedy: true,
            maxNewTokens: 128,
            maxReplySeconds: 5,
            systemPrompt: 'You are a helpful assistant. Give short, direct answers.'
          })
          const samples = await result.buffer
          const reply = await result.text
          if (!(await result.done) || !reply?.trim()) throw new Error('The model returned no reply text.')
          console.log(reply)
          if (samples.length !== 0) throw new Error('A text-only reply must not contain PCM audio.')
        } finally {
          await unloadModel({ modelId })
        }
      }

      try {
        await main()
      } catch (error) {
        console.error('✖', error)
        process.exitCode = 1
      } finally {
        try {
          await close()
        } catch (error) {
          console.error('✖ Cleanup failed:', error)
          process.exitCode = 1
        }
      }
      ```
    </WrapCode>
  </Tab>

  <Tab value="python" label="Python">
    <WrapCode>
      ```python file=<rootDir>/packages/sdk-python/examples/text_to_speech_moss_speech.py title="text_to_speech_moss_speech.py" lineNumbers
      """Python port of packages/sdk/examples/tts/moss-speech.ts.

      Desktop MOSS-Speech: answer a typed question with `textReply: True`. This mode
      skips audio decoding and returns text with an empty PCM buffer. Use a GPU with
      enough memory. Registry sources download automatically. Optional local paths:
      QVAC_MOSS_SPEECH_MODEL and QVAC_MOSS_SPEECH_CODEC. Both engines run a batch
      job; `stream: False` collects the complete reply.

      Python's `text_to_speech` yields frames: the example joins each frame's `text`
      and `buffer` and reads `done` off them. `Client` closes the SDK on exit, which
      the TypeScript example does with `close()`.

      RUN: python examples/text_to_speech_moss_speech.py
      """

      from __future__ import annotations

      import asyncio
      import contextlib
      import math
      import os
      import sys

      from tetherto.qvac_sdk import (
          Client,
          TextToSpeechRequest,
          load_model,
          text_to_speech,
          unload_model,
      )
      from tetherto.qvac_sdk.models import TTS_CODEC_MOSS_SPEECH_F16, TTS_MOSS_SPEECH_Q8_0

      _last_percentage = -1


      def print_progress(p) -> None:
          """Print model download progress once per whole percent."""
          global _last_percentage
          percentage = math.floor(p.percentage)
          if percentage == _last_percentage:
              return
          _last_percentage = percentage
          line = (
              f"▸ Downloading {p.percentage:.0f}% "
              f"({p.downloaded / 1e6:.1f}/{p.total / 1e6:.1f} MB)"
          )
          print(line, end="\r" if sys.stderr.isatty() else "\n", file=sys.stderr)
          if p.percentage >= 100:
              print(file=sys.stderr)


      async def main() -> int:
          async with Client() as client:
              t = client.transport
              model_id = None
              try:
                  model_id = await load_model(
                      t,
                      model_src=os.environ.get("QVAC_MOSS_SPEECH_MODEL")
                      or TTS_MOSS_SPEECH_Q8_0,
                      model_type="tts-ggml",
                      model_config={
                          "ttsEngine": "moss-speech",
                          "mossSpeechCodecModelSrc": os.environ.get("QVAC_MOSS_SPEECH_CODEC")
                          or TTS_CODEC_MOSS_SPEECH_F16,
                          "useGPU": True,
                          "seed": 42,
                      },
                      on_progress=print_progress,
                  )

                  print("▸ Generating a text-only reply...", file=sys.stderr)
                  request = TextToSpeechRequest.model_validate(
                      {
                          "type": "textToSpeech",
                          "modelId": model_id,
                          "text": "What is two plus two? Answer in one short sentence.",
                          "stream": False,
                          "textReply": True,
                          "greedy": True,
                          "maxNewTokens": 128,
                          "maxReplySeconds": 5,
                          "systemPrompt": (
                              "You are a helpful assistant. Give short, direct answers."
                          ),
                      }
                  )

                  samples: list[float] = []
                  reply = ""
                  done = False
                  async for response in text_to_speech(t, request):
                      samples.extend(response.buffer)
                      if response.text:
                          reply += response.text
                      done = done or response.done

                  if not done or not reply.strip():
                      raise RuntimeError("The model returned no reply text.")
                  print(reply)
                  if samples:
                      raise RuntimeError("A text-only reply must not contain PCM audio.")
              except Exception as error:
                  print(f"✖ {error}", file=sys.stderr)
                  return 1
              finally:
                  if model_id is not None:
                      with contextlib.suppress(Exception):
                          await unload_model(t, model_id)
          return 0


      if __name__ == "__main__":
          sys.exit(asyncio.run(main()))
      ```
    </WrapCode>
  </Tab>

  <Tab value="kotlin" label="Kotlin">
    <WrapCode>
      ```kotlin file=<rootDir>/packages/sdk-kotlin/examples/src/TextToSpeechMossSpeech.kt title="TextToSpeechMossSpeech.kt" lineNumbers
      // Kotlin port of packages/sdk/examples/tts/moss-speech.ts.
      //
      // Desktop MOSS-Speech: answer a typed question with `textReply = true`. This
      // mode skips audio decoding and returns text with an empty PCM buffer. Use a
      // GPU with enough memory. Registry sources download automatically. Optional
      // local paths: QVAC_MOSS_SPEECH_MODEL and QVAC_MOSS_SPEECH_CODEC. Both engines
      // run a batch job; `stream = false` collects the complete reply.
      //
      // The MOSS-Speech fields (`textReply`, `greedy`, `maxNewTokens`,
      // `maxReplySeconds`, `systemPrompt`) are typed properties of the generated
      // `TextToSpeechRequest`. `client.textToSpeech()` returns a
      // `Flow<TextToSpeechResponse>`: the example joins each frame's `text` and
      // `buffer` and reads `done` off them. The model is unloaded in a `finally`
      // block, as the TypeScript example does.
      //
      // RUN: ./gradlew -p examples run -Pexample=TextToSpeechMossSpeech

      import io.tether.qvac.sdk.QvacClient
      import io.tether.qvac.sdk.QvacProgressEvent
      import io.tether.qvac.sdk.generated.Models
      import io.tether.qvac.sdk.generated.schema.LoadModelResponse
      import io.tether.qvac.sdk.generated.schema.ModelProgressResponse
      import io.tether.qvac.sdk.generated.schema.TextToSpeechRequest
      import io.tether.qvac.sdk.jvm.JvmBareKitTransport
      import io.tether.qvac.sdk.models
      import io.tether.qvac.sdk.textToSpeech
      import kotlin.math.floor
      import kotlinx.coroutines.runBlocking
      import kotlinx.serialization.json.JsonObject
      import kotlinx.serialization.json.buildJsonObject
      import kotlinx.serialization.json.put

      fun main(): Unit = runBlocking {
          val client = QvacClient(JvmBareKitTransport.connect())
          try {
              val modelId = client.loadWithProgress(
                  source = System.getenv("QVAC_MOSS_SPEECH_MODEL") ?: Models.TTS_MOSS_SPEECH_Q8_0.src,
                  modelType = "tts-ggml",
                  modelConfig = buildJsonObject {
                      put("ttsEngine", "moss-speech")
                      put(
                          "mossSpeechCodecModelSrc",
                          System.getenv("QVAC_MOSS_SPEECH_CODEC") ?: Models.TTS_CODEC_MOSS_SPEECH_F16.src,
                      )
                      put("useGPU", true)
                      put("seed", 42)
                  },
              )
              try {
                  System.err.println("▸ Generating a text-only reply...")
                  val request = TextToSpeechRequest(
                      modelId = modelId,
                      text = "What is two plus two? Answer in one short sentence.",
                      stream = false,
                      textReply = true,
                      greedy = true,
                      maxNewTokens = 128,
                      maxReplySeconds = 5.0,
                      systemPrompt = "You are a helpful assistant. Give short, direct answers.",
                  )

                  val samples = mutableListOf<Double>()
                  val reply = StringBuilder()
                  var done = false
                  client.textToSpeech(request).collect { response ->
                      samples += response.buffer
                      response.text?.let(reply::append)
                      done = done || response.done
                  }

                  check(done && reply.isNotBlank()) { "The model returned no reply text." }
                  println(reply)
                  check(samples.isEmpty()) { "A text-only reply must not contain PCM audio." }
              } finally {
                  client.models.unload(modelId)
              }
          } finally {
              client.close()
          }
      }

      /** Load [source] as [modelType], printing download progress, and return its model id. */
      private suspend fun QvacClient.loadWithProgress(source: String, modelType: String, modelConfig: JsonObject): String {
          var result: LoadModelResponse? = null
          models.loadWithProgress(source, modelType, modelConfig = modelConfig).collect { event ->
              when (event) {
                  is QvacProgressEvent.Progress -> printProgress(event.value)
                  is QvacProgressEvent.Result -> result = event.value
              }
          }
          val loaded = checkNotNull(result) { "loadModel ended without a result" }
          return loaded.modelId ?: error(loaded.error ?: "loadModel failed")
      }

      private var lastPercentage = -1

      /** Print model download progress once per whole percent. */
      private fun printProgress(p: ModelProgressResponse) {
          val percentage = floor(p.percentage).toInt()
          if (percentage == lastPercentage) return
          lastPercentage = percentage
          val line = "▸ Downloading %.0f%% (%.1f/%.1f MB)".format(p.percentage, p.downloaded / 1e6, p.total / 1e6)
          if (System.console() != null) System.err.print("\r$line") else System.err.println(line)
          if (p.percentage >= 100) System.err.println()
      }
      ```
    </WrapCode>
  </Tab>
</Tabs>

### MOSS-Speech audio reply

This example answers a spoken question using MOSS-Speech. It reads the question from a WAV file (mono or stereo, PCM16 or float32, up to 60 seconds), prints any reply text, and saves the 24 kHz spoken reply to `moss-speech-audio-output.wav`. Arguments: `<question-wav>`.

<Tabs>
  <Tab value="js" label="JavaScript" default>
    <WrapCode>
      ```js file=<rootDir>/packages/sdk/dist/examples/tts/moss-speech-audio.js title="moss-speech-audio.js" lineNumbers
      import { readFileSync, writeFileSync } from 'node:fs';
      import { loadModel, textToSpeech, unloadModel, close, TTS_MOSS_SPEECH_Q8_0, TTS_CODEC_MOSS_SPEECH_F16 } from '@qvac/sdk';
      // Desktop MOSS-Speech: 9B language model + codec, 24 kHz spoken reply and text.
      // Run from packages/sdk: node --import tsx examples/tts/moss-speech-audio.ts question.wav
      // Use a GPU with enough memory. Registry sources download automatically.
      // Optional local paths: QVAC_MOSS_SPEECH_MODEL and QVAC_MOSS_SPEECH_CODEC.
      // Both engines run a batch job; stream: false collects the complete reply.
      function saveWav(samples, sampleRate, filename) {
          if (samples.length === 0 || samples.some((sample) => !Number.isFinite(sample))) {
              throw new Error('The model returned no usable audio.');
          }
          const wav = Buffer.alloc(44 + samples.length * 2);
          wav.write('RIFF', 0);
          wav.writeUInt32LE(wav.length - 8, 4);
          wav.write('WAVEfmt ', 8);
          wav.writeUInt32LE(16, 16);
          wav.writeUInt16LE(1, 20);
          wav.writeUInt16LE(1, 22);
          wav.writeUInt32LE(sampleRate, 24);
          wav.writeUInt32LE(sampleRate * 2, 28);
          wav.writeUInt16LE(2, 32);
          wav.writeUInt16LE(16, 34);
          wav.write('data', 36);
          wav.writeUInt32LE(samples.length * 2, 40);
          for (let i = 0; i < samples.length; i++) {
              wav.writeInt16LE(Math.max(-32768, Math.min(32767, Math.round(samples[i]))), 44 + i * 2);
          }
          writeFileSync(filename, wav);
          console.error(`▸ Saved ${filename}: ${sampleRate} Hz, ${(samples.length / sampleRate).toFixed(2)} seconds`);
      }
      let lastPercentage = -1;
      function progress(p) {
          const percentage = Math.floor(p.percentage);
          if (percentage === lastPercentage)
              return;
          lastPercentage = percentage;
          const line = `▸ Downloading ${p.percentage.toFixed(0)}% (${(p.downloaded / 1e6).toFixed(1)}/${(p.total / 1e6).toFixed(1)} MB)`;
          process.stderr.write(process.stderr.isTTY ? `\r${line}` : `${line}\n`);
          if (p.percentage >= 100)
              process.stderr.write('\n');
      }
      // Read standard mono/stereo PCM16 or float32 WAV without an audio-library dependency.
      function readQuestion(filename) {
          const wav = readFileSync(filename);
          if (wav.length < 12 ||
              wav.toString('ascii', 0, 4) !== 'RIFF' ||
              wav.toString('ascii', 8, 12) !== 'WAVE') {
              throw new Error('Question must be a RIFF WAV file.');
          }
          let format = 0;
          let channels = 0;
          let sampleRate = 0;
          let bits = 0;
          let data;
          for (let offset = 12; offset + 8 <= wav.length;) {
              const size = wav.readUInt32LE(offset + 4);
              const start = offset + 8;
              if (start + size > wav.length)
                  throw new Error('Truncated WAV chunk.');
              const id = wav.toString('ascii', offset, offset + 4);
              if (id === 'fmt ') {
                  if (size < 16)
                      throw new Error('Invalid WAV format chunk.');
                  format = wav.readUInt16LE(start);
                  channels = wav.readUInt16LE(start + 2);
                  sampleRate = wav.readUInt32LE(start + 4);
                  bits = wav.readUInt16LE(start + 14);
              }
              else if (id === 'data')
                  data = wav.subarray(start, start + size);
              offset = start + size + (size % 2);
          }
          if (!data ||
              ![1, 2].includes(channels) ||
              !((format === 1 && bits === 16) || (format === 3 && bits === 32))) {
              throw new Error('Use a mono/stereo PCM16 or float32 WAV question.');
          }
          if (sampleRate < 8000 || sampleRate > 192000) {
              throw new Error('WAV sample rate must be 8000–192000 Hz.');
          }
          const bytesPerSample = bits / 8;
          const frameBytes = bytesPerSample * channels;
          if (data.length % frameBytes !== 0)
              throw new Error('Incomplete WAV audio frame.');
          const audio = [];
          for (let offset = 0; offset < data.length; offset += frameBytes) {
              let sample = 0;
              for (let channel = 0; channel < channels; channel++) {
                  const at = offset + channel * bytesPerSample;
                  sample += format === 1 ? data.readInt16LE(at) / 32768 : data.readFloatLE(at);
              }
              audio.push(sample / channels);
          }
          if (audio.length === 0 || audio.length > sampleRate * 60) {
              throw new Error('Use a non-empty question of at most 60 seconds.');
          }
          return { audio, sampleRate };
      }
      async function main() {
          const filename = process.argv[2];
          if (!filename) {
              throw new Error('Usage: node --import tsx examples/tts/moss-speech-audio.ts question.wav');
          }
          const question = readQuestion(filename);
          const modelId = await loadModel({
              modelSrc: process.env['QVAC_MOSS_SPEECH_MODEL'] ?? TTS_MOSS_SPEECH_Q8_0,
              modelType: 'tts-ggml',
              modelConfig: {
                  ttsEngine: 'moss-speech',
                  mossSpeechCodecModelSrc: process.env['QVAC_MOSS_SPEECH_CODEC'] ?? TTS_CODEC_MOSS_SPEECH_F16,
                  useGPU: true,
                  seed: 42
              },
              onProgress: progress
          });
          try {
              console.error('▸ Generating a spoken reply...');
              const result = textToSpeech({
                  modelId,
                  ...question,
                  stream: false,
                  greedy: true,
                  maxNewTokens: 128,
                  maxReplySeconds: 5,
                  messages: [{ role: 'user', text: 'Please answer the next spoken turn briefly.' }]
              });
              const samples = await result.buffer;
              const reply = await result.text;
              if (!(await result.done))
                  throw new Error('Speech generation did not complete.');
              if (reply?.trim())
                  console.log(reply);
              else
                  console.error('▸ The model returned an audio-only reply.');
              const sampleRate = await result.sampleRate;
              if (sampleRate !== 24000)
                  throw new Error(`Unexpected reply sample rate: ${sampleRate}`);
              saveWav(samples, sampleRate, 'moss-speech-audio-output.wav');
          }
          finally {
              await unloadModel({ modelId });
          }
      }
      try {
          await main();
      }
      catch (error) {
          console.error('✖', error);
          process.exitCode = 1;
      }
      finally {
          try {
              await close();
          }
          catch (error) {
              console.error('✖ Cleanup failed:', error);
              process.exitCode = 1;
          }
      }
      ```
    </WrapCode>
  </Tab>

  <Tab value="ts" label="TypeScript">
    <WrapCode>
      ```ts file=<rootDir>/packages/sdk/examples/tts/moss-speech-audio.ts title="moss-speech-audio.ts" lineNumbers
      import { readFileSync, writeFileSync } from 'node:fs'
      import {
        loadModel,
        textToSpeech,
        unloadModel,
        close,
        TTS_MOSS_SPEECH_Q8_0,
        TTS_CODEC_MOSS_SPEECH_F16,
        type ModelProgressUpdate
      } from '@qvac/sdk'

      // Desktop MOSS-Speech: 9B language model + codec, 24 kHz spoken reply and text.
      // Run from packages/sdk: node --import tsx examples/tts/moss-speech-audio.ts question.wav
      // Use a GPU with enough memory. Registry sources download automatically.
      // Optional local paths: QVAC_MOSS_SPEECH_MODEL and QVAC_MOSS_SPEECH_CODEC.
      // Both engines run a batch job; stream: false collects the complete reply.

      function saveWav(samples: number[], sampleRate: number, filename: string) {
        if (samples.length === 0 || samples.some((sample) => !Number.isFinite(sample))) {
          throw new Error('The model returned no usable audio.')
        }
        const wav = Buffer.alloc(44 + samples.length * 2)
        wav.write('RIFF', 0)
        wav.writeUInt32LE(wav.length - 8, 4)
        wav.write('WAVEfmt ', 8)
        wav.writeUInt32LE(16, 16)
        wav.writeUInt16LE(1, 20)
        wav.writeUInt16LE(1, 22)
        wav.writeUInt32LE(sampleRate, 24)
        wav.writeUInt32LE(sampleRate * 2, 28)
        wav.writeUInt16LE(2, 32)
        wav.writeUInt16LE(16, 34)
        wav.write('data', 36)
        wav.writeUInt32LE(samples.length * 2, 40)
        for (let i = 0; i < samples.length; i++) {
          wav.writeInt16LE(Math.max(-32768, Math.min(32767, Math.round(samples[i]!))), 44 + i * 2)
        }
        writeFileSync(filename, wav)
        console.error(
          `▸ Saved ${filename}: ${sampleRate} Hz, ${(samples.length / sampleRate).toFixed(2)} seconds`
        )
      }

      let lastPercentage = -1
      function progress(p: ModelProgressUpdate) {
        const percentage = Math.floor(p.percentage)
        if (percentage === lastPercentage) return
        lastPercentage = percentage
        const line = `▸ Downloading ${p.percentage.toFixed(0)}% (${(p.downloaded / 1e6).toFixed(1)}/${(p.total / 1e6).toFixed(1)} MB)`
        process.stderr.write(process.stderr.isTTY ? `\r${line}` : `${line}\n`)
        if (p.percentage >= 100) process.stderr.write('\n')
      }

      // Read standard mono/stereo PCM16 or float32 WAV without an audio-library dependency.
      function readQuestion(filename: string) {
        const wav = readFileSync(filename)
        if (
          wav.length < 12 ||
          wav.toString('ascii', 0, 4) !== 'RIFF' ||
          wav.toString('ascii', 8, 12) !== 'WAVE'
        ) {
          throw new Error('Question must be a RIFF WAV file.')
        }
        let format = 0
        let channels = 0
        let sampleRate = 0
        let bits = 0
        let data: Buffer | undefined
        for (let offset = 12; offset + 8 <= wav.length;) {
          const size = wav.readUInt32LE(offset + 4)
          const start = offset + 8
          if (start + size > wav.length) throw new Error('Truncated WAV chunk.')
          const id = wav.toString('ascii', offset, offset + 4)
          if (id === 'fmt ') {
            if (size < 16) throw new Error('Invalid WAV format chunk.')
            format = wav.readUInt16LE(start)
            channels = wav.readUInt16LE(start + 2)
            sampleRate = wav.readUInt32LE(start + 4)
            bits = wav.readUInt16LE(start + 14)
          } else if (id === 'data') data = wav.subarray(start, start + size)
          offset = start + size + (size % 2)
        }
        if (
          !data ||
          ![1, 2].includes(channels) ||
          !((format === 1 && bits === 16) || (format === 3 && bits === 32))
        ) {
          throw new Error('Use a mono/stereo PCM16 or float32 WAV question.')
        }
        if (sampleRate < 8000 || sampleRate > 192000) {
          throw new Error('WAV sample rate must be 8000–192000 Hz.')
        }
        const bytesPerSample = bits / 8
        const frameBytes = bytesPerSample * channels
        if (data.length % frameBytes !== 0) throw new Error('Incomplete WAV audio frame.')
        const audio: number[] = []
        for (let offset = 0; offset < data.length; offset += frameBytes) {
          let sample = 0
          for (let channel = 0; channel < channels; channel++) {
            const at = offset + channel * bytesPerSample
            sample += format === 1 ? data.readInt16LE(at) / 32768 : data.readFloatLE(at)
          }
          audio.push(sample / channels)
        }
        if (audio.length === 0 || audio.length > sampleRate * 60) {
          throw new Error('Use a non-empty question of at most 60 seconds.')
        }
        return { audio, sampleRate }
      }

      async function main() {
        const filename = process.argv[2]
        if (!filename) {
          throw new Error('Usage: node --import tsx examples/tts/moss-speech-audio.ts question.wav')
        }
        const question = readQuestion(filename)
        const modelId = await loadModel({
          modelSrc: process.env['QVAC_MOSS_SPEECH_MODEL'] ?? TTS_MOSS_SPEECH_Q8_0,
          modelType: 'tts-ggml',
          modelConfig: {
            ttsEngine: 'moss-speech',
            mossSpeechCodecModelSrc: process.env['QVAC_MOSS_SPEECH_CODEC'] ?? TTS_CODEC_MOSS_SPEECH_F16,
            useGPU: true,
            seed: 42
          },
          onProgress: progress
        })
        try {
          console.error('▸ Generating a spoken reply...')
          const result = textToSpeech({
            modelId,
            ...question,
            stream: false,
            greedy: true,
            maxNewTokens: 128,
            maxReplySeconds: 5,
            messages: [{ role: 'user', text: 'Please answer the next spoken turn briefly.' }]
          })
          const samples = await result.buffer
          const reply = await result.text
          if (!(await result.done)) throw new Error('Speech generation did not complete.')
          if (reply?.trim()) console.log(reply)
          else console.error('▸ The model returned an audio-only reply.')
          const sampleRate = await result.sampleRate
          if (sampleRate !== 24000) throw new Error(`Unexpected reply sample rate: ${sampleRate}`)
          saveWav(samples, sampleRate, 'moss-speech-audio-output.wav')
        } finally {
          await unloadModel({ modelId })
        }
      }

      try {
        await main()
      } catch (error) {
        console.error('✖', error)
        process.exitCode = 1
      } finally {
        try {
          await close()
        } catch (error) {
          console.error('✖ Cleanup failed:', error)
          process.exitCode = 1
        }
      }
      ```
    </WrapCode>
  </Tab>

  <Tab value="python" label="Python">
    <WrapCode>
      ```python file=<rootDir>/packages/sdk-python/examples/text_to_speech_moss_speech_audio.py title="text_to_speech_moss_speech_audio.py" lineNumbers
      """Python port of packages/sdk/examples/tts/moss-speech-audio.ts.

      Desktop MOSS-Speech: 9B language model + codec, 24 kHz spoken reply and text.
      Pass a spoken question as a WAV file. Use a GPU with enough memory. Registry
      sources download automatically. Optional local paths: QVAC_MOSS_SPEECH_MODEL
      and QVAC_MOSS_SPEECH_CODEC. Both engines run a batch job; `stream: False`
      collects the complete reply.

      The question is read with `struct` instead of the stdlib `wave` module because
      `wave` rejects float32 WAVs, which the TypeScript example accepts. Python's
      `text_to_speech` yields frames: the example joins each frame's `text` and
      `buffer` and reads `sample_rate` and `done` off them. `Client` closes the SDK
      on exit, which the TypeScript example does with `close()`.

      RUN: python examples/text_to_speech_moss_speech_audio.py <question.wav>
      """

      from __future__ import annotations

      import array
      import asyncio
      import contextlib
      import math
      import os
      import struct
      import sys
      import wave
      from pathlib import Path

      from tetherto.qvac_sdk import (
          Client,
          TextToSpeechRequest,
          load_model,
          text_to_speech,
          unload_model,
      )
      from tetherto.qvac_sdk.models import TTS_CODEC_MOSS_SPEECH_F16, TTS_MOSS_SPEECH_Q8_0

      _last_percentage = -1


      def print_progress(p) -> None:
          """Print model download progress once per whole percent."""
          global _last_percentage
          percentage = math.floor(p.percentage)
          if percentage == _last_percentage:
              return
          _last_percentage = percentage
          line = (
              f"▸ Downloading {p.percentage:.0f}% "
              f"({p.downloaded / 1e6:.1f}/{p.total / 1e6:.1f} MB)"
          )
          print(line, end="\r" if sys.stderr.isatty() else "\n", file=sys.stderr)
          if p.percentage >= 100:
              print(file=sys.stderr)


      def save_wav(samples, sample_rate, path) -> None:
          if not samples or not all(math.isfinite(s) for s in samples):
              raise RuntimeError("The model returned no usable audio.")
          pcm = array.array("h", (max(-32768, min(32767, round(s))) for s in samples))
          with wave.open(path, "wb") as w:
              w.setnchannels(1)
              w.setsampwidth(2)
              w.setframerate(sample_rate)
              w.writeframes(pcm.tobytes())
          print(
              f"▸ Saved {path}: {sample_rate} Hz, {len(samples) / sample_rate:.2f} seconds",
              file=sys.stderr,
          )


      def read_question(path: str) -> tuple[list[float], int]:
          """Read a mono/stereo PCM16 or float32 WAV as mono float samples."""
          wav = Path(path).read_bytes()
          if len(wav) < 12 or wav[0:4] != b"RIFF" or wav[8:12] != b"WAVE":
              raise ValueError("Question must be a RIFF WAV file.")

          fmt = channels = sample_rate = bits = 0
          data = None
          offset = 12
          while offset + 8 <= len(wav):
              chunk_id = wav[offset : offset + 4]
              (size,) = struct.unpack_from("<I", wav, offset + 4)
              start = offset + 8
              if start + size > len(wav):
                  raise ValueError("Truncated WAV chunk.")
              if chunk_id == b"fmt ":
                  if size < 16:
                      raise ValueError("Invalid WAV format chunk.")
                  fmt, channels, sample_rate = struct.unpack_from("<HHI", wav, start)
                  (bits,) = struct.unpack_from("<H", wav, start + 14)
              elif chunk_id == b"data":
                  data = wav[start : start + size]
              offset = start + size + (size % 2)

          if (
              data is None
              or channels not in (1, 2)
              or not ((fmt == 1 and bits == 16) or (fmt == 3 and bits == 32))
          ):
              raise ValueError("Use a mono/stereo PCM16 or float32 WAV question.")
          if not 8000 <= sample_rate <= 192000:
              raise ValueError("WAV sample rate must be 8000–192000 Hz.")
          frame_bytes = bits // 8 * channels
          if len(data) % frame_bytes != 0:
              raise ValueError("Incomplete WAV audio frame.")

          # array reads native byte order; WAV samples are little-endian.
          if sys.byteorder != "little":
              raise ValueError("This example reads WAV samples on little-endian hosts only.")
          if fmt == 1:
              values = [v / 32768 for v in array.array("h", data)]
          else:
              values = list(array.array("f", data))
          audio = [
              sum(values[i : i + channels]) / channels
              for i in range(0, len(values), channels)
          ]
          if not audio or len(audio) > sample_rate * 60:
              raise ValueError("Use a non-empty question of at most 60 seconds.")
          return audio, sample_rate


      async def main() -> int:
          if len(sys.argv) < 2:
              print(
                  "Usage: python examples/text_to_speech_moss_speech_audio.py <question.wav>",
                  file=sys.stderr,
              )
              return 1

          try:
              audio, question_rate = read_question(sys.argv[1])
          except (OSError, ValueError) as error:
              print(f"✖ {error}", file=sys.stderr)
              return 1

          async with Client() as client:
              t = client.transport
              model_id = None
              try:
                  model_id = await load_model(
                      t,
                      model_src=os.environ.get("QVAC_MOSS_SPEECH_MODEL")
                      or TTS_MOSS_SPEECH_Q8_0,
                      model_type="tts-ggml",
                      model_config={
                          "ttsEngine": "moss-speech",
                          "mossSpeechCodecModelSrc": os.environ.get("QVAC_MOSS_SPEECH_CODEC")
                          or TTS_CODEC_MOSS_SPEECH_F16,
                          "useGPU": True,
                          "seed": 42,
                      },
                      on_progress=print_progress,
                  )

                  print("▸ Generating a spoken reply...", file=sys.stderr)
                  request = TextToSpeechRequest.model_validate(
                      {
                          "type": "textToSpeech",
                          "modelId": model_id,
                          "audio": audio,
                          "sampleRate": question_rate,
                          "stream": False,
                          "greedy": True,
                          "maxNewTokens": 128,
                          "maxReplySeconds": 5,
                          "messages": [
                              {
                                  "role": "user",
                                  "text": "Please answer the next spoken turn briefly.",
                              }
                          ],
                      }
                  )

                  samples: list[float] = []
                  reply = ""
                  sample_rate = None
                  done = False
                  async for response in text_to_speech(t, request):
                      samples.extend(response.buffer)
                      if response.text:
                          reply += response.text
                      if response.sample_rate is not None:
                          sample_rate = response.sample_rate
                      done = done or response.done

                  if not done:
                      raise RuntimeError("Speech generation did not complete.")
                  if reply.strip():
                      print(reply)
                  else:
                      print("▸ The model returned an audio-only reply.", file=sys.stderr)
                  if sample_rate != 24000:
                      raise RuntimeError(f"Unexpected reply sample rate: {sample_rate}")
                  save_wav(samples, sample_rate, "moss-speech-audio-output.wav")
              except Exception as error:
                  print(f"✖ {error}", file=sys.stderr)
                  return 1
              finally:
                  if model_id is not None:
                      with contextlib.suppress(Exception):
                          await unload_model(t, model_id)
          return 0


      if __name__ == "__main__":
          sys.exit(asyncio.run(main()))
      ```
    </WrapCode>
  </Tab>

  <Tab value="kotlin" label="Kotlin">
    <WrapCode>
      ```kotlin file=<rootDir>/packages/sdk-kotlin/examples/src/TextToSpeechMossSpeechAudio.kt title="TextToSpeechMossSpeechAudio.kt" lineNumbers
      // Kotlin port of packages/sdk/examples/tts/moss-speech-audio.ts.
      //
      // Desktop MOSS-Speech: 9B language model + codec, 24 kHz spoken reply and
      // text. Pass a spoken question as a WAV file. Use a GPU with enough memory.
      // Registry sources download automatically. Optional local paths:
      // QVAC_MOSS_SPEECH_MODEL and QVAC_MOSS_SPEECH_CODEC. Both engines run a batch
      // job; `stream = false` collects the complete reply.
      //
      // The question is parsed with a little-endian `ByteBuffer`, which reads the
      // same mono/stereo PCM16 and float32 WAVs as the TypeScript example on any host
      // byte order (the Python port reads them on little-endian hosts only). The question
      // audio, its `sampleRate` and the `messages` turns are typed properties of the
      // generated `TextToSpeechRequest`. `client.textToSpeech()` returns a
      // `Flow<TextToSpeechResponse>`: the example joins each frame's `text` and
      // `buffer` and reads `sampleRate` and `done` off them. The model is unloaded in
      // a `finally` block, as the TypeScript example does.
      //
      // RUN: ./gradlew -p examples run -Pexample=TextToSpeechMossSpeechAudio --args="<question.wav>"

      import io.tether.qvac.sdk.QvacClient
      import io.tether.qvac.sdk.QvacProgressEvent
      import io.tether.qvac.sdk.generated.Models
      import io.tether.qvac.sdk.generated.schema.LoadModelResponse
      import io.tether.qvac.sdk.generated.schema.ModelProgressResponse
      import io.tether.qvac.sdk.generated.schema.TextToSpeechRequest
      import io.tether.qvac.sdk.generated.schema.TextToSpeechRequestMessagesItem
      import io.tether.qvac.sdk.generated.schema.TextToSpeechRequestMessagesItemRole
      import io.tether.qvac.sdk.jvm.JvmBareKitTransport
      import io.tether.qvac.sdk.models
      import io.tether.qvac.sdk.textToSpeech
      import java.io.File
      import java.nio.ByteBuffer
      import java.nio.ByteOrder
      import kotlin.math.floor
      import kotlin.math.roundToInt
      import kotlin.system.exitProcess
      import kotlinx.coroutines.runBlocking
      import kotlinx.serialization.json.JsonObject
      import kotlinx.serialization.json.buildJsonObject
      import kotlinx.serialization.json.put

      fun main(args: Array<String>): Unit = runBlocking {
          if (args.isEmpty()) {
              System.err.println(
                  "Usage: ./gradlew -p examples run -Pexample=TextToSpeechMossSpeechAudio " +
                      "--args=\"<question.wav>\"",
              )
              exitProcess(1)
          }
          val (audio, questionRate) = readQuestion(args[0])

          val client = QvacClient(JvmBareKitTransport.connect())
          try {
              val modelId = client.loadWithProgress(
                  source = System.getenv("QVAC_MOSS_SPEECH_MODEL") ?: Models.TTS_MOSS_SPEECH_Q8_0.src,
                  modelType = "tts-ggml",
                  modelConfig = buildJsonObject {
                      put("ttsEngine", "moss-speech")
                      put(
                          "mossSpeechCodecModelSrc",
                          System.getenv("QVAC_MOSS_SPEECH_CODEC") ?: Models.TTS_CODEC_MOSS_SPEECH_F16.src,
                      )
                      put("useGPU", true)
                      put("seed", 42)
                  },
              )
              try {
                  System.err.println("▸ Generating a spoken reply...")
                  val request = TextToSpeechRequest(
                      modelId = modelId,
                      audio = audio,
                      sampleRate = questionRate.toLong(),
                      stream = false,
                      greedy = true,
                      maxNewTokens = 128,
                      maxReplySeconds = 5.0,
                      messages = listOf(
                          TextToSpeechRequestMessagesItem(
                              role = TextToSpeechRequestMessagesItemRole.USER,
                              text = "Please answer the next spoken turn briefly.",
                          ),
                      ),
                  )

                  val samples = mutableListOf<Double>()
                  val reply = StringBuilder()
                  var sampleRate: Long? = null
                  var done = false
                  client.textToSpeech(request).collect { response ->
                      samples += response.buffer
                      response.text?.let(reply::append)
                      response.sampleRate?.let { sampleRate = it }
                      done = done || response.done
                  }

                  check(done) { "Speech generation did not complete." }
                  if (reply.isNotBlank()) println(reply) else System.err.println("▸ The model returned an audio-only reply.")
                  check(sampleRate == 24000L) { "Unexpected reply sample rate: $sampleRate" }
                  saveWav(samples, 24000, "moss-speech-audio-output.wav")
              } finally {
                  client.models.unload(modelId)
              }
          } finally {
              client.close()
          }
      }

      /** Read a mono/stereo PCM16 or float32 WAV as mono float samples. */
      private fun readQuestion(path: String): Pair<List<Double>, Int> {
          val bytes = File(path).readBytes()
          val wav = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN)
          fun tag(at: Int) = String(bytes, at, 4, Charsets.US_ASCII)
          require(bytes.size >= 12 && tag(0) == "RIFF" && tag(8) == "WAVE") { "Question must be a RIFF WAV file." }

          var format = 0
          var channels = 0
          var sampleRate = 0
          var bits = 0
          var data: ByteArray? = null
          var offset = 12
          while (offset + 8 <= bytes.size) {
              val chunkId = tag(offset)
              val size = wav.getInt(offset + 4).toLong() and 0xFFFFFFFFL
              val start = offset + 8
              require(start + size <= bytes.size) { "Truncated WAV chunk." }
              val length = size.toInt()
              when (chunkId) {
                  "fmt " -> {
                      require(length >= 16) { "Invalid WAV format chunk." }
                      format = wav.getShort(start).toInt() and 0xFFFF
                      channels = wav.getShort(start + 2).toInt() and 0xFFFF
                      sampleRate = wav.getInt(start + 4)
                      bits = wav.getShort(start + 14).toInt() and 0xFFFF
                  }
                  "data" -> data = bytes.copyOfRange(start, start + length)
              }
              offset = start + length + length % 2
          }

          val pcm = requireNotNull(data) { "Use a mono/stereo PCM16 or float32 WAV question." }
          require(channels in 1..2 && ((format == 1 && bits == 16) || (format == 3 && bits == 32))) {
              "Use a mono/stereo PCM16 or float32 WAV question."
          }
          require(sampleRate in 8000..192000) { "WAV sample rate must be 8000–192000 Hz." }
          val frameBytes = bits / 8 * channels
          require(pcm.size % frameBytes == 0) { "Incomplete WAV audio frame." }

          val samples = ByteBuffer.wrap(pcm).order(ByteOrder.LITTLE_ENDIAN)
          val values = if (format == 1) {
              DoubleArray(pcm.size / 2) { samples.getShort(it * 2) / 32768.0 }
          } else {
              DoubleArray(pcm.size / 4) { samples.getFloat(it * 4).toDouble() }
          }
          val audio = List(values.size / channels) { frame ->
              (0 until channels).sumOf { values[frame * channels + it] } / channels
          }
          require(audio.isNotEmpty() && audio.size <= sampleRate * 60) { "Use a non-empty question of at most 60 seconds." }
          return audio to sampleRate
      }

      /** Load [source] as [modelType], printing download progress, and return its model id. */
      private suspend fun QvacClient.loadWithProgress(source: String, modelType: String, modelConfig: JsonObject): String {
          var result: LoadModelResponse? = null
          models.loadWithProgress(source, modelType, modelConfig = modelConfig).collect { event ->
              when (event) {
                  is QvacProgressEvent.Progress -> printProgress(event.value)
                  is QvacProgressEvent.Result -> result = event.value
              }
          }
          val loaded = checkNotNull(result) { "loadModel ended without a result" }
          return loaded.modelId ?: error(loaded.error ?: "loadModel failed")
      }

      private var lastPercentage = -1

      /** Print model download progress once per whole percent. */
      private fun printProgress(p: ModelProgressResponse) {
          val percentage = floor(p.percentage).toInt()
          if (percentage == lastPercentage) return
          lastPercentage = percentage
          val line = "▸ Downloading %.0f%% (%.1f/%.1f MB)".format(p.percentage, p.downloaded / 1e6, p.total / 1e6)
          if (System.console() != null) System.err.print("\r$line") else System.err.println(line)
          if (p.percentage >= 100) System.err.println()
      }

      /** Save int16 PCM samples as a 16-bit mono WAV. */
      private fun saveWav(samples: List<Double>, sampleRate: Int, path: String) {
          check(samples.isNotEmpty() && samples.all { it.isFinite() }) { "The model returned no usable audio." }
          val wav = ByteBuffer.allocate(44 + samples.size * 2).order(ByteOrder.LITTLE_ENDIAN)
              .put("RIFF".toByteArray(Charsets.US_ASCII)).putInt(36 + samples.size * 2)
              .put("WAVEfmt ".toByteArray(Charsets.US_ASCII))
              .putInt(16).putShort(1).putShort(1).putInt(sampleRate).putInt(sampleRate * 2).putShort(2).putShort(16)
              .put("data".toByteArray(Charsets.US_ASCII)).putInt(samples.size * 2)
          for (sample in samples) wav.putShort(sample.roundToInt().coerceIn(-32768, 32767).toShort())
          File(path).writeBytes(wav.array())
          System.err.println("▸ Saved %s: %d Hz, %.2f seconds".format(path, sampleRate, samples.size.toDouble() / sampleRate))
      }
      ```
    </WrapCode>
  </Tab>
</Tabs>

### Chatterbox with LavaSR enhancer

This example generates speech from text using Chatterbox with the LavaSR enhancer. It clones the voice of a reference audio when you pass one, upsamples the speech to 48 kHz, saves it to `chatterbox-enhanced-output.wav`, and plays it. Arguments: `[reference-audio]` (optional). Helper (JS/TS): [`utils`](#utils), in the same folder as the script.

<Tabs>
  <Tab value="js" label="JavaScript" default>
    <WrapCode>
      ```js file=<rootDir>/packages/sdk/dist/examples/tts/chatterbox-enhanced.js title="tts-chatterbox-enhanced.js" lineNumbers
      import { loadModel, textToSpeech, unloadModel, TTS_T3_TURBO_EN_CHATTERBOX_Q8_0, TTS_S3GEN_EN_CHATTERBOX, TTS_ENHANCER_LAVASR_FP16 } from '@qvac/sdk';
      import { createWav, playAudio, int16ArrayToBuffer, createWavHeader } from './utils.js';
      // Chatterbox TTS (GGML) with the LavaSR enhancer: synthesized audio is neurally
      // bandwidth-extended to 48 kHz. Supplying the enhancer GGUF is what enables
      // enhancement — there is no on/off flag — and it forces the output to 48 kHz.
      // Usage: node chatterbox-enhanced.ts [referenceAudioSrc]
      const [referenceAudioSrc] = process.argv.slice(2);
      // Only a fallback; the engine reports the rate it actually produced.
      const ENHANCED_SAMPLE_RATE = 48000;
      try {
          const modelId = await loadModel({
              modelSrc: TTS_T3_TURBO_EN_CHATTERBOX_Q8_0,
              modelConfig: {
                  ttsEngine: 'chatterbox',
                  language: 'en',
                  s3genModelSrc: TTS_S3GEN_EN_CHATTERBOX.src,
                  lavasrEnhancerModelSrc: TTS_ENHANCER_LAVASR_FP16.src,
                  ...(referenceAudioSrc ? { referenceAudioSrc } : {})
              },
              onProgress: (p) => {
                  const mb = (n) => (n / 1e6).toFixed(1);
                  const line = `▸ Downloading ${p.percentage.toFixed(0)}% (${mb(p.downloaded)}/${mb(p.total)} MB)`;
                  process.stderr.write(process.stderr.isTTY ? `\r${line}` : `${line}\n`);
                  if (p.percentage >= 100)
                      process.stderr.write('\n');
              }
          });
          console.log(`▸ Model loaded: ${modelId}`);
          console.log('▸ Testing Text-to-Speech (LavaSR enhancer)...');
          const result = textToSpeech({
              modelId,
              text: `QVAC SDK is the canonical entry point to QVAC. Written in TypeScript, it provides all QVAC capabilities through a unified interface while also abstracting away the complexity of running your application in a JS environment other than Bare. Supported JS environments include Bare, Node.js, Expo and Bun.`,
              inputType: 'text',
              stream: false
          });
          const audioBuffer = await result.buffer;
          const sampleRate = (await result.sampleRate) ?? ENHANCED_SAMPLE_RATE;
          console.log(`▸ TTS complete. Total samples: ${audioBuffer.length}`);
          console.log('▸ Saving audio to file...');
          createWav(audioBuffer, sampleRate, 'chatterbox-enhanced-output.wav');
          console.log('▸ Audio saved to chatterbox-enhanced-output.wav');
          console.log('▸ Playing audio...');
          const audioData = int16ArrayToBuffer(audioBuffer);
          const wavBuffer = Buffer.concat([createWavHeader(audioData.length, sampleRate), audioData]);
          playAudio(wavBuffer);
          console.log('▸ Audio playback complete');
          await unloadModel({ modelId });
          console.log('▸ Model unloaded');
          process.exit(0);
      }
      catch (error) {
          console.error('✖', error);
          process.exit(1);
      }
      ```
    </WrapCode>
  </Tab>

  <Tab value="ts" label="TypeScript">
    <WrapCode>
      ```ts file=<rootDir>/packages/sdk/examples/tts/chatterbox-enhanced.ts title="tts-chatterbox-enhanced.ts" lineNumbers
      import {
        loadModel,
        textToSpeech,
        unloadModel,
        type ModelProgressUpdate,
        TTS_T3_TURBO_EN_CHATTERBOX_Q8_0,
        TTS_S3GEN_EN_CHATTERBOX,
        TTS_ENHANCER_LAVASR_FP16
      } from '@qvac/sdk'
      import { createWav, playAudio, int16ArrayToBuffer, createWavHeader } from './utils.js'

      // Chatterbox TTS (GGML) with the LavaSR enhancer: synthesized audio is neurally
      // bandwidth-extended to 48 kHz. Supplying the enhancer GGUF is what enables
      // enhancement — there is no on/off flag — and it forces the output to 48 kHz.
      // Usage: node chatterbox-enhanced.ts [referenceAudioSrc]
      const [referenceAudioSrc] = process.argv.slice(2)

      // Only a fallback; the engine reports the rate it actually produced.
      const ENHANCED_SAMPLE_RATE = 48000

      try {
        const modelId = await loadModel({
          modelSrc: TTS_T3_TURBO_EN_CHATTERBOX_Q8_0,
          modelConfig: {
            ttsEngine: 'chatterbox',
            language: 'en',
            s3genModelSrc: TTS_S3GEN_EN_CHATTERBOX.src,
            lavasrEnhancerModelSrc: TTS_ENHANCER_LAVASR_FP16.src,
            ...(referenceAudioSrc ? { referenceAudioSrc } : {})
          },
          onProgress: (p: ModelProgressUpdate) => {
            const mb = (n: number) => (n / 1e6).toFixed(1)
            const line = `▸ Downloading ${p.percentage.toFixed(0)}% (${mb(p.downloaded)}/${mb(p.total)} MB)`
            process.stderr.write(process.stderr.isTTY ? `\r${line}` : `${line}\n`)
            if (p.percentage >= 100) process.stderr.write('\n')
          }
        })

        console.log(`▸ Model loaded: ${modelId}`)

        console.log('▸ Testing Text-to-Speech (LavaSR enhancer)...')
        const result = textToSpeech({
          modelId,
          text: `QVAC SDK is the canonical entry point to QVAC. Written in TypeScript, it provides all QVAC capabilities through a unified interface while also abstracting away the complexity of running your application in a JS environment other than Bare. Supported JS environments include Bare, Node.js, Expo and Bun.`,
          inputType: 'text',
          stream: false
        })

        const audioBuffer = await result.buffer
        const sampleRate = (await result.sampleRate) ?? ENHANCED_SAMPLE_RATE
        console.log(`▸ TTS complete. Total samples: ${audioBuffer.length}`)

        console.log('▸ Saving audio to file...')
        createWav(audioBuffer, sampleRate, 'chatterbox-enhanced-output.wav')
        console.log('▸ Audio saved to chatterbox-enhanced-output.wav')

        console.log('▸ Playing audio...')
        const audioData = int16ArrayToBuffer(audioBuffer)
        const wavBuffer = Buffer.concat([createWavHeader(audioData.length, sampleRate), audioData])
        playAudio(wavBuffer)
        console.log('▸ Audio playback complete')

        await unloadModel({ modelId })
        console.log('▸ Model unloaded')
        process.exit(0)
      } catch (error) {
        console.error('✖', error)
        process.exit(1)
      }
      ```
    </WrapCode>
  </Tab>

  <Tab value="python" label="Python">
    <WrapCode>
      ```python file=<rootDir>/packages/sdk-python/examples/text_to_speech_chatterbox_enhanced.py title="text_to_speech_chatterbox_enhanced.py" lineNumbers
      """Python port of packages/sdk/examples/tts/chatterbox-enhanced.ts.

      Chatterbox TTS (GGML) with the LavaSR enhancer: synthesized audio is neurally
      bandwidth-extended to 48 kHz. Supplying the enhancer GGUF is what enables
      enhancement (there is no on/off flag), and it forces the output to 48 kHz.
      An optional reference audio file clones its voice.

      `text_to_speech` is a server-stream; in non-stream mode it yields the full
      audio as one frame. Samples come back as int16 PCM values. The helpers below,
      ported from the JS example's `utils`, save them to a WAV and play it through
      ffplay.

      RUN: python examples/text_to_speech_chatterbox_enhanced.py [reference-audio]
      """

      from __future__ import annotations

      import asyncio
      import struct
      import subprocess
      import sys

      from tetherto.qvac_sdk import (
          Client,
          TextToSpeechRequest,
          load_model,
          text_to_speech,
          unload_model,
      )
      from tetherto.qvac_sdk.models import (
          TTS_ENHANCER_LAVASR_FP16,
          TTS_S3GEN_EN_CHATTERBOX,
          TTS_T3_TURBO_EN_CHATTERBOX_Q8_0,
      )

      # Only a fallback: the engine reports the rate it actually produced.
      ENHANCED_SAMPLE_RATE = 48000


      def print_progress(p) -> None:
          """Print model download progress; pass as `on_progress=` to `load_model`."""
          line = (
              f"▸ Downloading {p.percentage:.0f}% "
              f"({p.downloaded / 1e6:.1f}/{p.total / 1e6:.1f} MB)"
          )
          print(line, end="\r" if sys.stderr.isatty() else "\n", file=sys.stderr)
          if p.percentage >= 100:
              print(file=sys.stderr)


      def create_wav_header(data_length: int, sample_rate: int) -> bytes:
          """Create a WAV header for 16-bit mono PCM audio."""
          return (
              b"RIFF"
              + struct.pack("<I", 36 + data_length)
              + b"WAVE"
              + b"fmt "
              + struct.pack("<IHHIIHH", 16, 1, 1, sample_rate, sample_rate * 2, 2, 16)
              + b"data"
              + struct.pack("<I", data_length)
          )


      def int16_array_to_buffer(samples) -> bytes:
          """Convert int16 PCM samples to little-endian bytes."""
          return struct.pack(
              f"<{len(samples)}h",
              *(max(-32768, min(32767, round(s))) for s in samples),
          )


      def create_wav(audio_buffer, sample_rate: int, filename: str) -> None:
          """Create and save a WAV file."""
          audio_data = int16_array_to_buffer(audio_buffer)
          with open(filename, "wb") as f:
              f.write(create_wav_header(len(audio_data), sample_rate) + audio_data)
          print(f"▸ WAV file saved as: {filename}")


      def play_audio(audio_buffer: bytes) -> None:
          """Play a WAV buffer by streaming it into ffplay over stdin."""
          try:
              result = subprocess.run(
                  [
                      "ffplay",
                      "-hide_banner",
                      "-loglevel",
                      "error",
                      "-autoexit",
                      "-nodisp",
                      "-i",
                      "pipe:0",
                  ],
                  input=audio_buffer,
                  check=False,
              )
          except FileNotFoundError:
              raise RuntimeError(
                  "ffplay not found on PATH. Install ffmpeg (ffplay ships with it) and retry."
              ) from None
          if result.returncode != 0:
              raise RuntimeError(f"ffplay exited with code {result.returncode}")


      async def main() -> int:
          reference_audio_src = sys.argv[1] if len(sys.argv) > 1 else None

          model_config = {
              "ttsEngine": "chatterbox",
              "language": "en",
              "s3genModelSrc": TTS_S3GEN_EN_CHATTERBOX.src,
              "lavasrEnhancerModelSrc": TTS_ENHANCER_LAVASR_FP16.src,
          }
          if reference_audio_src:
              model_config["referenceAudioSrc"] = reference_audio_src

          async with Client() as client:
              t = client.transport
              try:
                  model_id = await load_model(
                      t,
                      model_src=TTS_T3_TURBO_EN_CHATTERBOX_Q8_0,
                      model_config=model_config,
                      on_progress=print_progress,
                  )
                  print(f"▸ Model loaded: {model_id}")

                  print("▸ Testing Text-to-Speech (LavaSR enhancer)...")
                  request = TextToSpeechRequest.model_validate(
                      {
                          "type": "textToSpeech",
                          "modelId": model_id,
                          "text": (
                              "QVAC SDK is the canonical entry point to QVAC. Written in "
                              "TypeScript, it provides all QVAC capabilities through a "
                              "unified interface while also abstracting away the "
                              "complexity of running your application in a JS environment "
                              "other than Bare. Supported JS environments include Bare, "
                              "Node.js, Expo and Bun."
                          ),
                          "inputType": "text",
                          "stream": False,
                      }
                  )

                  samples: list[float] = []
                  sample_rate = None
                  async for response in text_to_speech(t, request):
                      samples.extend(response.buffer)
                      if response.sample_rate is not None:
                          sample_rate = response.sample_rate
                  sample_rate = int(sample_rate or ENHANCED_SAMPLE_RATE)
                  print(f"▸ TTS complete. Total samples: {len(samples)}")

                  print("▸ Saving audio to file...")
                  create_wav(samples, sample_rate, "chatterbox-enhanced-output.wav")
                  print("▸ Audio saved to chatterbox-enhanced-output.wav")

                  print("▸ Playing audio...")
                  audio_data = int16_array_to_buffer(samples)
                  play_audio(create_wav_header(len(audio_data), sample_rate) + audio_data)

                  await unload_model(t, model_id)
                  print("▸ Model unloaded")
              except Exception as error:
                  print(f"✖ {error}", file=sys.stderr)
                  return 1
          return 0


      if __name__ == "__main__":
          sys.exit(asyncio.run(main()))
      ```
    </WrapCode>
  </Tab>

  <Tab value="kotlin" label="Kotlin">
    <WrapCode>
      ```kotlin file=<rootDir>/packages/sdk-kotlin/examples/src/TextToSpeechChatterboxEnhanced.kt title="TextToSpeechChatterboxEnhanced.kt" lineNumbers
      // Kotlin port of packages/sdk/examples/tts/chatterbox-enhanced.ts.
      //
      // Chatterbox TTS (GGML) with the LavaSR enhancer: synthesized audio is neurally
      // bandwidth-extended to 48 kHz. Supplying the enhancer GGUF is what enables
      // enhancement (there is no on/off flag), and it forces the output to 48 kHz.
      // An optional reference audio file clones its voice. The S3Gen and enhancer
      // companion models load through `modelConfig` as their `src` strings.
      //
      // `client.textToSpeech()` is the generated typed method: it takes a
      // `TextToSpeechRequest` data class and returns a `Flow<TextToSpeechResponse>`.
      // In non-stream mode it emits the full audio as one frame. Samples come back as
      // int16 PCM values. The helpers below, ported from the JS example's `utils`,
      // save them to a WAV and play it through ffplay.
      //
      // RUN: ./gradlew -p examples run -Pexample=TextToSpeechChatterboxEnhanced [--args="<reference-audio>"]

      import io.tether.qvac.sdk.QvacClient
      import io.tether.qvac.sdk.QvacProgressEvent
      import io.tether.qvac.sdk.generated.ModelConstant
      import io.tether.qvac.sdk.generated.Models
      import io.tether.qvac.sdk.generated.schema.LoadModelResponse
      import io.tether.qvac.sdk.generated.schema.ModelProgressResponse
      import io.tether.qvac.sdk.generated.schema.TextToSpeechRequest
      import io.tether.qvac.sdk.jvm.JvmBareKitTransport
      import io.tether.qvac.sdk.models
      import io.tether.qvac.sdk.textToSpeech
      import java.io.File
      import java.io.IOException
      import java.nio.ByteBuffer
      import java.nio.ByteOrder
      import kotlin.math.roundToInt
      import kotlinx.coroutines.runBlocking
      import kotlinx.serialization.json.JsonObject
      import kotlinx.serialization.json.buildJsonObject
      import kotlinx.serialization.json.put

      // Only a fallback: the engine reports the rate it actually produced.
      private const val ENHANCED_SAMPLE_RATE = 48000

      fun main(args: Array<String>): Unit = runBlocking {
          val referenceAudioSrc = args.firstOrNull()

          val modelConfig = buildJsonObject {
              put("ttsEngine", "chatterbox")
              put("language", "en")
              put("s3genModelSrc", Models.TTS_S3GEN_EN_CHATTERBOX.src)
              put("lavasrEnhancerModelSrc", Models.TTS_ENHANCER_LAVASR_FP16.src)
              if (referenceAudioSrc != null) put("referenceAudioSrc", referenceAudioSrc)
          }

          val client = QvacClient(JvmBareKitTransport.connect())
          try {
              val modelId = client.loadWithProgress(Models.TTS_T3_TURBO_EN_CHATTERBOX_Q8_0, modelConfig)
              println("▸ Model loaded: $modelId")

              println("▸ Testing Text-to-Speech (LavaSR enhancer)...")
              val request = TextToSpeechRequest(
                  modelId = modelId,
                  text = "QVAC SDK is the canonical entry point to QVAC. Written in TypeScript, it provides all " +
                      "QVAC capabilities through a unified interface while also abstracting away the complexity " +
                      "of running your application in a JS environment other than Bare. Supported JS " +
                      "environments include Bare, Node.js, Expo and Bun.",
                  inputType = "text",
                  stream = false,
              )

              val samples = mutableListOf<Double>()
              var sampleRate = ENHANCED_SAMPLE_RATE
              client.textToSpeech(request).collect { response ->
                  samples += response.buffer
                  response.sampleRate?.let { sampleRate = it.toInt() }
              }
              println("▸ TTS complete. Total samples: ${samples.size}")

              println("▸ Saving audio to file...")
              createWav(samples, sampleRate, "chatterbox-enhanced-output.wav")
              println("▸ Audio saved to chatterbox-enhanced-output.wav")

              println("▸ Playing audio...")
              val audioData = int16ArrayToBuffer(samples)
              playAudio(createWavHeader(audioData.size, sampleRate) + audioData)

              client.models.unload(modelId)
              println("▸ Model unloaded")
          } finally {
              client.close()
          }
      }

      /** Load [model], printing download progress, and return its model id. */
      private suspend fun QvacClient.loadWithProgress(model: ModelConstant, modelConfig: JsonObject? = null): String {
          var result: LoadModelResponse? = null
          models.loadWithProgress(model.src, model.engine, model.name, modelConfig = modelConfig).collect { event ->
              when (event) {
                  is QvacProgressEvent.Progress -> printProgress(event.value)
                  is QvacProgressEvent.Result -> result = event.value
              }
          }
          val loaded = checkNotNull(result) { "loadModel ended without a result" }
          return loaded.modelId ?: error(loaded.error ?: "loadModel failed")
      }

      private fun printProgress(p: ModelProgressResponse) {
          val line = "▸ Downloading %.0f%% (%.1f/%.1f MB)".format(p.percentage, p.downloaded / 1e6, p.total / 1e6)
          if (System.console() != null) System.err.print("\r$line") else System.err.println(line)
          if (p.percentage >= 100) System.err.println()
      }

      /** Create a WAV header for 16-bit mono PCM audio. */
      private fun createWavHeader(dataLength: Int, sampleRate: Int): ByteArray =
          ByteBuffer.allocate(44).order(ByteOrder.LITTLE_ENDIAN)
              .put("RIFF".toByteArray(Charsets.US_ASCII)).putInt(36 + dataLength)
              .put("WAVEfmt ".toByteArray(Charsets.US_ASCII))
              .putInt(16).putShort(1).putShort(1).putInt(sampleRate).putInt(sampleRate * 2).putShort(2).putShort(16)
              .put("data".toByteArray(Charsets.US_ASCII)).putInt(dataLength)
              .array()

      /** Convert int16 PCM samples to little-endian bytes. */
      private fun int16ArrayToBuffer(samples: List<Double>): ByteArray {
          val buffer = ByteBuffer.allocate(samples.size * 2).order(ByteOrder.LITTLE_ENDIAN)
          for (sample in samples) buffer.putShort(sample.roundToInt().coerceIn(-32768, 32767).toShort())
          return buffer.array()
      }

      /** Create and save a WAV file. */
      private fun createWav(samples: List<Double>, sampleRate: Int, filename: String) {
          val audioData = int16ArrayToBuffer(samples)
          File(filename).writeBytes(createWavHeader(audioData.size, sampleRate) + audioData)
          println("▸ WAV file saved as: $filename")
      }

      /** Play a WAV buffer by streaming it into ffplay over stdin. */
      private fun playAudio(wav: ByteArray) {
          val ffplay = try {
              ProcessBuilder("ffplay", "-hide_banner", "-loglevel", "error", "-autoexit", "-nodisp", "-i", "pipe:0")
                  .redirectOutput(ProcessBuilder.Redirect.INHERIT)
                  .redirectError(ProcessBuilder.Redirect.INHERIT)
                  .start()
          } catch (e: IOException) {
              throw IllegalStateException("ffplay not found on PATH. Install ffmpeg (ffplay ships with it) and retry.", e)
          }
          ffplay.outputStream.use { it.write(wav) }
          val code = ffplay.waitFor()
          check(code == 0) { "ffplay exited with code $code" }
      }
      ```
    </WrapCode>
  </Tab>
</Tabs>

### Supertonic with LavaSR denoiser + enhancer

This example generates speech from text using Supertonic with the LavaSR denoiser and enhancer. It cleans the speech, upsamples it to 48 kHz, saves it to `supertonic-enhanced-output.wav`, and plays it. Arguments: none. Helper (JS/TS): [`utils`](#utils), in the same folder as the script.

<Tabs>
  <Tab value="js" label="JavaScript" default>
    <WrapCode>
      ```js file=<rootDir>/packages/sdk/dist/examples/tts/supertonic-enhanced.js title="tts-supertonic-enhanced.js" lineNumbers
      import { loadModel, textToSpeech, unloadModel, TTS_MULTILINGUAL_SUPERTONIC3_Q8_0, TTS_DENOISER_LAVASR_FP16, TTS_ENHANCER_LAVASR_FP16 } from '@qvac/sdk';
      import { createWav, playAudio, int16ArrayToBuffer, createWavHeader } from './utils.js';
      // Supertonic 3 TTS (GGML) with LavaSR post-processing: the denoiser cleans the
      // synthesized signal first, then the enhancer bandwidth-extends it to 48 kHz.
      // Supplying the enhancer GGUF is what enables enhancement — there is no on/off
      // flag — and it forces the output to 48 kHz regardless of the engine's native
      // rate.
      // Only a fallback; the engine reports the rate it actually produced.
      const ENHANCED_SAMPLE_RATE = 48000;
      try {
          const modelId = await loadModel({
              modelSrc: TTS_MULTILINGUAL_SUPERTONIC3_Q8_0,
              modelConfig: {
                  ttsEngine: 'supertonic',
                  language: 'en',
                  voice: 'F1',
                  // Denoiser runs first (rate-preserving)…
                  lavasrDenoiserModelSrc: TTS_DENOISER_LAVASR_FP16.src,
                  // …then the enhancer bandwidth-extends to 48 kHz.
                  lavasrEnhancerModelSrc: TTS_ENHANCER_LAVASR_FP16.src
              },
              onProgress: (p) => {
                  const mb = (n) => (n / 1e6).toFixed(1);
                  const line = `▸ Downloading ${p.percentage.toFixed(0)}% (${mb(p.downloaded)}/${mb(p.total)} MB)`;
                  process.stderr.write(process.stderr.isTTY ? `\r${line}` : `${line}\n`);
                  if (p.percentage >= 100)
                      process.stderr.write('\n');
              }
          });
          console.log(`▸ Model loaded: ${modelId}`);
          console.log('▸ Testing Text-to-Speech (LavaSR denoiser + enhancer)...');
          const result = textToSpeech({
              modelId,
              text: `QVAC SDK is the canonical entry point to QVAC. Written in TypeScript, it provides all QVAC capabilities through a unified interface while also abstracting away the complexity of running your application in a JS environment other than Bare. Supported JS environments include Bare, Node.js, Expo and Bun.`,
              inputType: 'text',
              stream: false
          });
          const audioBuffer = await result.buffer;
          const sampleRate = (await result.sampleRate) ?? ENHANCED_SAMPLE_RATE;
          console.log(`▸ TTS complete. Total samples: ${audioBuffer.length}`);
          console.log('▸ Saving audio to file...');
          createWav(audioBuffer, sampleRate, 'supertonic-enhanced-output.wav');
          console.log('▸ Audio saved to supertonic-enhanced-output.wav');
          console.log('▸ Playing audio...');
          const audioData = int16ArrayToBuffer(audioBuffer);
          const wavBuffer = Buffer.concat([createWavHeader(audioData.length, sampleRate), audioData]);
          playAudio(wavBuffer);
          console.log('▸ Audio playback complete');
          await unloadModel({ modelId });
          console.log('▸ Model unloaded');
          process.exit(0);
      }
      catch (error) {
          console.error('✖', error);
          process.exit(1);
      }
      ```
    </WrapCode>
  </Tab>

  <Tab value="ts" label="TypeScript">
    <WrapCode>
      ```ts file=<rootDir>/packages/sdk/examples/tts/supertonic-enhanced.ts title="tts-supertonic-enhanced.ts" lineNumbers
      import {
        loadModel,
        textToSpeech,
        unloadModel,
        type ModelProgressUpdate,
        TTS_MULTILINGUAL_SUPERTONIC3_Q8_0,
        TTS_DENOISER_LAVASR_FP16,
        TTS_ENHANCER_LAVASR_FP16
      } from '@qvac/sdk'
      import { createWav, playAudio, int16ArrayToBuffer, createWavHeader } from './utils.js'

      // Supertonic 3 TTS (GGML) with LavaSR post-processing: the denoiser cleans the
      // synthesized signal first, then the enhancer bandwidth-extends it to 48 kHz.
      // Supplying the enhancer GGUF is what enables enhancement — there is no on/off
      // flag — and it forces the output to 48 kHz regardless of the engine's native
      // rate.
      // Only a fallback; the engine reports the rate it actually produced.
      const ENHANCED_SAMPLE_RATE = 48000

      try {
        const modelId = await loadModel({
          modelSrc: TTS_MULTILINGUAL_SUPERTONIC3_Q8_0,
          modelConfig: {
            ttsEngine: 'supertonic',
            language: 'en',
            voice: 'F1',
            // Denoiser runs first (rate-preserving)…
            lavasrDenoiserModelSrc: TTS_DENOISER_LAVASR_FP16.src,
            // …then the enhancer bandwidth-extends to 48 kHz.
            lavasrEnhancerModelSrc: TTS_ENHANCER_LAVASR_FP16.src
          },
          onProgress: (p: ModelProgressUpdate) => {
            const mb = (n: number) => (n / 1e6).toFixed(1)
            const line = `▸ Downloading ${p.percentage.toFixed(0)}% (${mb(p.downloaded)}/${mb(p.total)} MB)`
            process.stderr.write(process.stderr.isTTY ? `\r${line}` : `${line}\n`)
            if (p.percentage >= 100) process.stderr.write('\n')
          }
        })

        console.log(`▸ Model loaded: ${modelId}`)

        console.log('▸ Testing Text-to-Speech (LavaSR denoiser + enhancer)...')
        const result = textToSpeech({
          modelId,
          text: `QVAC SDK is the canonical entry point to QVAC. Written in TypeScript, it provides all QVAC capabilities through a unified interface while also abstracting away the complexity of running your application in a JS environment other than Bare. Supported JS environments include Bare, Node.js, Expo and Bun.`,
          inputType: 'text',
          stream: false
        })

        const audioBuffer = await result.buffer
        const sampleRate = (await result.sampleRate) ?? ENHANCED_SAMPLE_RATE
        console.log(`▸ TTS complete. Total samples: ${audioBuffer.length}`)

        console.log('▸ Saving audio to file...')
        createWav(audioBuffer, sampleRate, 'supertonic-enhanced-output.wav')
        console.log('▸ Audio saved to supertonic-enhanced-output.wav')

        console.log('▸ Playing audio...')
        const audioData = int16ArrayToBuffer(audioBuffer)
        const wavBuffer = Buffer.concat([createWavHeader(audioData.length, sampleRate), audioData])
        playAudio(wavBuffer)
        console.log('▸ Audio playback complete')

        await unloadModel({ modelId })
        console.log('▸ Model unloaded')
        process.exit(0)
      } catch (error) {
        console.error('✖', error)
        process.exit(1)
      }
      ```
    </WrapCode>
  </Tab>

  <Tab value="python" label="Python">
    <WrapCode>
      ```python file=<rootDir>/packages/sdk-python/examples/text_to_speech_supertonic_enhanced.py title="text_to_speech_supertonic_enhanced.py" lineNumbers
      """Python port of packages/sdk/examples/tts/supertonic-enhanced.ts.

      Supertonic 3 TTS (GGML) with LavaSR post-processing: the denoiser cleans the
      synthesized signal first, then the enhancer bandwidth-extends it to 48 kHz.
      Supplying the enhancer GGUF is what enables enhancement (there is no on/off
      flag), and it forces the output to 48 kHz regardless of the engine's native
      rate.

      `text_to_speech` is a server-stream; in non-stream mode it yields the full
      audio as one frame. Samples come back as int16 PCM values. The helpers below,
      ported from the JS example's `utils`, save them to a WAV and play it through
      ffplay.

      RUN: python examples/text_to_speech_supertonic_enhanced.py
      """

      from __future__ import annotations

      import asyncio
      import struct
      import subprocess
      import sys

      from tetherto.qvac_sdk import (
          Client,
          TextToSpeechRequest,
          load_model,
          text_to_speech,
          unload_model,
      )
      from tetherto.qvac_sdk.models import (
          TTS_DENOISER_LAVASR_FP16,
          TTS_ENHANCER_LAVASR_FP16,
          TTS_MULTILINGUAL_SUPERTONIC3_Q8_0,
      )

      # Only a fallback: the engine reports the rate it actually produced.
      ENHANCED_SAMPLE_RATE = 48000


      def print_progress(p) -> None:
          """Print model download progress; pass as `on_progress=` to `load_model`."""
          line = (
              f"▸ Downloading {p.percentage:.0f}% "
              f"({p.downloaded / 1e6:.1f}/{p.total / 1e6:.1f} MB)"
          )
          print(line, end="\r" if sys.stderr.isatty() else "\n", file=sys.stderr)
          if p.percentage >= 100:
              print(file=sys.stderr)


      def create_wav_header(data_length: int, sample_rate: int) -> bytes:
          """Create a WAV header for 16-bit mono PCM audio."""
          return (
              b"RIFF"
              + struct.pack("<I", 36 + data_length)
              + b"WAVE"
              + b"fmt "
              + struct.pack("<IHHIIHH", 16, 1, 1, sample_rate, sample_rate * 2, 2, 16)
              + b"data"
              + struct.pack("<I", data_length)
          )


      def int16_array_to_buffer(samples) -> bytes:
          """Convert int16 PCM samples to little-endian bytes."""
          return struct.pack(
              f"<{len(samples)}h",
              *(max(-32768, min(32767, round(s))) for s in samples),
          )


      def create_wav(audio_buffer, sample_rate: int, filename: str) -> None:
          """Create and save a WAV file."""
          audio_data = int16_array_to_buffer(audio_buffer)
          with open(filename, "wb") as f:
              f.write(create_wav_header(len(audio_data), sample_rate) + audio_data)
          print(f"▸ WAV file saved as: {filename}")


      def play_audio(audio_buffer: bytes) -> None:
          """Play a WAV buffer by streaming it into ffplay over stdin."""
          try:
              result = subprocess.run(
                  [
                      "ffplay",
                      "-hide_banner",
                      "-loglevel",
                      "error",
                      "-autoexit",
                      "-nodisp",
                      "-i",
                      "pipe:0",
                  ],
                  input=audio_buffer,
                  check=False,
              )
          except FileNotFoundError:
              raise RuntimeError(
                  "ffplay not found on PATH. Install ffmpeg (ffplay ships with it) and retry."
              ) from None
          if result.returncode != 0:
              raise RuntimeError(f"ffplay exited with code {result.returncode}")


      async def main() -> int:
          model_config = {
              "ttsEngine": "supertonic",
              "language": "en",
              "voice": "F1",
              # Denoiser runs first (rate-preserving)...
              "lavasrDenoiserModelSrc": TTS_DENOISER_LAVASR_FP16.src,
              # ...then the enhancer bandwidth-extends to 48 kHz.
              "lavasrEnhancerModelSrc": TTS_ENHANCER_LAVASR_FP16.src,
          }

          async with Client() as client:
              t = client.transport
              try:
                  model_id = await load_model(
                      t,
                      model_src=TTS_MULTILINGUAL_SUPERTONIC3_Q8_0,
                      model_config=model_config,
                      on_progress=print_progress,
                  )
                  print(f"▸ Model loaded: {model_id}")

                  print("▸ Testing Text-to-Speech (LavaSR denoiser + enhancer)...")
                  request = TextToSpeechRequest.model_validate(
                      {
                          "type": "textToSpeech",
                          "modelId": model_id,
                          "text": (
                              "QVAC SDK is the canonical entry point to QVAC. Written in "
                              "TypeScript, it provides all QVAC capabilities through a "
                              "unified interface while also abstracting away the "
                              "complexity of running your application in a JS environment "
                              "other than Bare. Supported JS environments include Bare, "
                              "Node.js, Expo and Bun."
                          ),
                          "inputType": "text",
                          "stream": False,
                      }
                  )

                  samples: list[float] = []
                  sample_rate = None
                  async for response in text_to_speech(t, request):
                      samples.extend(response.buffer)
                      if response.sample_rate is not None:
                          sample_rate = response.sample_rate
                  sample_rate = int(sample_rate or ENHANCED_SAMPLE_RATE)
                  print(f"▸ TTS complete. Total samples: {len(samples)}")

                  print("▸ Saving audio to file...")
                  create_wav(samples, sample_rate, "supertonic-enhanced-output.wav")
                  print("▸ Audio saved to supertonic-enhanced-output.wav")

                  print("▸ Playing audio...")
                  audio_data = int16_array_to_buffer(samples)
                  play_audio(create_wav_header(len(audio_data), sample_rate) + audio_data)

                  await unload_model(t, model_id)
                  print("▸ Model unloaded")
              except Exception as error:
                  print(f"✖ {error}", file=sys.stderr)
                  return 1
          return 0


      if __name__ == "__main__":
          sys.exit(asyncio.run(main()))
      ```
    </WrapCode>
  </Tab>

  <Tab value="kotlin" label="Kotlin">
    <WrapCode>
      ```kotlin file=<rootDir>/packages/sdk-kotlin/examples/src/TextToSpeechSupertonicEnhanced.kt title="TextToSpeechSupertonicEnhanced.kt" lineNumbers
      // Kotlin port of packages/sdk/examples/tts/supertonic-enhanced.ts.
      //
      // Supertonic 3 TTS (GGML) with LavaSR post-processing: the denoiser cleans the
      // synthesized signal first, then the enhancer bandwidth-extends it to 48 kHz.
      // Supplying the enhancer GGUF is what enables enhancement (there is no on/off
      // flag), and it forces the output to 48 kHz regardless of the engine's native
      // rate. Both LavaSR models load through `modelConfig` as their `src` strings.
      //
      // `client.textToSpeech()` is the generated typed method: it takes a
      // `TextToSpeechRequest` data class and returns a `Flow<TextToSpeechResponse>`.
      // In non-stream mode it emits the full audio as one frame. Samples come back as
      // int16 PCM values. The helpers below, ported from the JS example's `utils`,
      // save them to a WAV and play it through ffplay.
      //
      // RUN: ./gradlew -p examples run -Pexample=TextToSpeechSupertonicEnhanced

      import io.tether.qvac.sdk.QvacClient
      import io.tether.qvac.sdk.QvacProgressEvent
      import io.tether.qvac.sdk.generated.ModelConstant
      import io.tether.qvac.sdk.generated.Models
      import io.tether.qvac.sdk.generated.schema.LoadModelResponse
      import io.tether.qvac.sdk.generated.schema.ModelProgressResponse
      import io.tether.qvac.sdk.generated.schema.TextToSpeechRequest
      import io.tether.qvac.sdk.jvm.JvmBareKitTransport
      import io.tether.qvac.sdk.models
      import io.tether.qvac.sdk.textToSpeech
      import java.io.File
      import java.io.IOException
      import java.nio.ByteBuffer
      import java.nio.ByteOrder
      import kotlin.math.roundToInt
      import kotlinx.coroutines.runBlocking
      import kotlinx.serialization.json.JsonObject
      import kotlinx.serialization.json.buildJsonObject
      import kotlinx.serialization.json.put

      // Only a fallback: the engine reports the rate it actually produced.
      private const val ENHANCED_SAMPLE_RATE = 48000

      fun main(): Unit = runBlocking {
          val modelConfig = buildJsonObject {
              put("ttsEngine", "supertonic")
              put("language", "en")
              put("voice", "F1")
              // Denoiser runs first (rate-preserving)...
              put("lavasrDenoiserModelSrc", Models.TTS_DENOISER_LAVASR_FP16.src)
              // ...then the enhancer bandwidth-extends to 48 kHz.
              put("lavasrEnhancerModelSrc", Models.TTS_ENHANCER_LAVASR_FP16.src)
          }

          val client = QvacClient(JvmBareKitTransport.connect())
          try {
              val modelId = client.loadWithProgress(Models.TTS_MULTILINGUAL_SUPERTONIC3_Q8_0, modelConfig)
              println("▸ Model loaded: $modelId")

              println("▸ Testing Text-to-Speech (LavaSR denoiser + enhancer)...")
              val request = TextToSpeechRequest(
                  modelId = modelId,
                  text = "QVAC SDK is the canonical entry point to QVAC. Written in TypeScript, it provides all " +
                      "QVAC capabilities through a unified interface while also abstracting away the complexity " +
                      "of running your application in a JS environment other than Bare. Supported JS " +
                      "environments include Bare, Node.js, Expo and Bun.",
                  inputType = "text",
                  stream = false,
              )

              val samples = mutableListOf<Double>()
              var sampleRate = ENHANCED_SAMPLE_RATE
              client.textToSpeech(request).collect { response ->
                  samples += response.buffer
                  response.sampleRate?.let { sampleRate = it.toInt() }
              }
              println("▸ TTS complete. Total samples: ${samples.size}")

              println("▸ Saving audio to file...")
              createWav(samples, sampleRate, "supertonic-enhanced-output.wav")
              println("▸ Audio saved to supertonic-enhanced-output.wav")

              println("▸ Playing audio...")
              val audioData = int16ArrayToBuffer(samples)
              playAudio(createWavHeader(audioData.size, sampleRate) + audioData)

              client.models.unload(modelId)
              println("▸ Model unloaded")
          } finally {
              client.close()
          }
      }

      /** Load [model], printing download progress, and return its model id. */
      private suspend fun QvacClient.loadWithProgress(model: ModelConstant, modelConfig: JsonObject? = null): String {
          var result: LoadModelResponse? = null
          models.loadWithProgress(model.src, model.engine, model.name, modelConfig = modelConfig).collect { event ->
              when (event) {
                  is QvacProgressEvent.Progress -> printProgress(event.value)
                  is QvacProgressEvent.Result -> result = event.value
              }
          }
          val loaded = checkNotNull(result) { "loadModel ended without a result" }
          return loaded.modelId ?: error(loaded.error ?: "loadModel failed")
      }

      private fun printProgress(p: ModelProgressResponse) {
          val line = "▸ Downloading %.0f%% (%.1f/%.1f MB)".format(p.percentage, p.downloaded / 1e6, p.total / 1e6)
          if (System.console() != null) System.err.print("\r$line") else System.err.println(line)
          if (p.percentage >= 100) System.err.println()
      }

      /** Create a WAV header for 16-bit mono PCM audio. */
      private fun createWavHeader(dataLength: Int, sampleRate: Int): ByteArray =
          ByteBuffer.allocate(44).order(ByteOrder.LITTLE_ENDIAN)
              .put("RIFF".toByteArray(Charsets.US_ASCII)).putInt(36 + dataLength)
              .put("WAVEfmt ".toByteArray(Charsets.US_ASCII))
              .putInt(16).putShort(1).putShort(1).putInt(sampleRate).putInt(sampleRate * 2).putShort(2).putShort(16)
              .put("data".toByteArray(Charsets.US_ASCII)).putInt(dataLength)
              .array()

      /** Convert int16 PCM samples to little-endian bytes. */
      private fun int16ArrayToBuffer(samples: List<Double>): ByteArray {
          val buffer = ByteBuffer.allocate(samples.size * 2).order(ByteOrder.LITTLE_ENDIAN)
          for (sample in samples) buffer.putShort(sample.roundToInt().coerceIn(-32768, 32767).toShort())
          return buffer.array()
      }

      /** Create and save a WAV file. */
      private fun createWav(samples: List<Double>, sampleRate: Int, filename: String) {
          val audioData = int16ArrayToBuffer(samples)
          File(filename).writeBytes(createWavHeader(audioData.size, sampleRate) + audioData)
          println("▸ WAV file saved as: $filename")
      }

      /** Play a WAV buffer by streaming it into ffplay over stdin. */
      private fun playAudio(wav: ByteArray) {
          val ffplay = try {
              ProcessBuilder("ffplay", "-hide_banner", "-loglevel", "error", "-autoexit", "-nodisp", "-i", "pipe:0")
                  .redirectOutput(ProcessBuilder.Redirect.INHERIT)
                  .redirectError(ProcessBuilder.Redirect.INHERIT)
                  .start()
          } catch (e: IOException) {
              throw IllegalStateException("ffplay not found on PATH. Install ffmpeg (ffplay ships with it) and retry.", e)
          }
          ffplay.outputStream.use { it.write(wav) }
          val code = ffplay.waitFor()
          check(code == 0) { "ffplay exited with code $code" }
      }
      ```
    </WrapCode>
  </Tab>
</Tabs>

### Utils

The JS and TS examples above import these helpers to save the PCM samples as a WAV file and play it. Save the file in the same folder as the example. The Python and Kotlin examples include the same helpers inline. Playback requires `ffplay`, which ships with ffmpeg.

<Tabs>
  <Tab value="js" label="JavaScript" default>
    <WrapCode>
      ```js file=<rootDir>/packages/sdk/dist/examples/tts/utils.js title="utils.js" lineNumbers
      import { writeFileSync, unlinkSync } from 'fs';
      import { spawn, spawnSync } from 'child_process';
      import { platform, tmpdir } from 'os';
      import { join } from 'path';
      /**
       * Create WAV header for 16-bit PCM audio
       */
      export function createWavHeader(dataLength, sampleRate) {
          const header = Buffer.alloc(44);
          // RIFF header
          header.write('RIFF', 0);
          header.writeUInt32LE(36 + dataLength, 4);
          header.write('WAVE', 8);
          // fmt chunk
          header.write('fmt ', 12);
          header.writeUInt32LE(16, 16); // fmt chunk size
          header.writeUInt16LE(1, 20); // PCM format
          header.writeUInt16LE(1, 22); // mono
          header.writeUInt32LE(sampleRate, 24);
          header.writeUInt32LE(sampleRate * 2, 28); // byte rate
          header.writeUInt16LE(2, 32); // block align
          header.writeUInt16LE(16, 34); // bits per sample
          // data chunk
          header.write('data', 36);
          header.writeUInt32LE(dataLength, 40);
          return header;
      }
      /**
       * Convert Int16Array to Buffer
       */
      export function int16ArrayToBuffer(samples) {
          const buffer = Buffer.alloc(samples.length * 2);
          for (let i = 0; i < samples.length; i++) {
              const value = Math.max(-32768, Math.min(32767, Math.round(samples[i] ?? 0)));
              buffer.writeInt16LE(value, i * 2);
          }
          return buffer;
      }
      /**
       * Create and save WAV file
       */
      export function createWav(audioBuffer, sampleRate, filename) {
          const audioData = int16ArrayToBuffer(audioBuffer);
          const wavHeader = createWavHeader(audioData.length, sampleRate);
          const wavFile = Buffer.concat([wavHeader, audioData]);
          writeFileSync(filename, wavFile);
          console.log(`▸ WAV file saved as: ${filename}`);
      }
      /**
       * Play a WAV buffer by streaming it into ffplay over stdin.
       *
       * ffplay ships with ffmpeg and is cross-platform (macOS/Linux/Windows), so
       * we avoid the old "write to /tmp then shell out to afplay/aplay/powershell"
       * dance — no temp files, no platform switch, no hardcoded /tmp path (which
       * doesn't exist on Windows). Requires ffplay on PATH.
       */
      /**
       * Play one mono s16le PCM chunk (as a minimal WAV) and wait for the player to finish.
       * Chunks are played sequentially when awaited in order — suitable for streaming TTS output.
       */
      export function playPcmInt16Chunk(samples, sampleRate) {
          if (samples.length === 0) {
              return Promise.resolve();
          }
          const audioData = int16ArrayToBuffer(samples);
          const wavHeader = createWavHeader(audioData.length, sampleRate);
          const wavFile = Buffer.concat([wavHeader, audioData]);
          // `os.tmpdir()` resolves to the OS-specific temp directory (e.g. `%TEMP%`
          // on Windows), so the Windows branch below no longer tries to read a
          // POSIX-only `/tmp/...` path.
          const tempFile = join(tmpdir(), `qvac-tts-chunk-${Date.now()}-${Math.random().toString(16).slice(2)}.wav`);
          writeFileSync(tempFile, wavFile);
          const currentPlatform = platform();
          let audioPlayer;
          let args;
          switch (currentPlatform) {
              case 'darwin':
                  audioPlayer = 'afplay';
                  args = [tempFile];
                  break;
              case 'linux':
                  audioPlayer = 'aplay';
                  args = [tempFile];
                  break;
              case 'win32':
                  audioPlayer = 'powershell';
                  args = [
                      '-Command',
                      `Add-Type -AssemblyName presentationCore; (New-Object Media.SoundPlayer).LoadStream([System.IO.File]::ReadAllBytes('${tempFile}')).PlaySync()`
                  ];
                  break;
              default:
                  audioPlayer = 'aplay';
                  args = [tempFile];
          }
          return new Promise(function (resolve, reject) {
              const proc = spawn(audioPlayer, args, { stdio: 'ignore' });
              proc.on('error', function (err) {
                  try {
                      unlinkSync(tempFile);
                  }
                  catch {
                      // ignore
                  }
                  reject(err);
              });
              proc.on('close', function (code) {
                  try {
                      unlinkSync(tempFile);
                  }
                  catch {
                      // ignore
                  }
                  if (code === 0) {
                      resolve();
                  }
                  else {
                      reject(new Error(`Audio player exited with code ${code}`));
                  }
              });
          });
      }
      export function playAudio(audioBuffer) {
          const result = spawnSync('ffplay', ['-hide_banner', '-loglevel', 'error', '-autoexit', '-nodisp', '-i', 'pipe:0'], {
              input: audioBuffer,
              stdio: ['pipe', 'inherit', 'inherit']
          });
          if (result.error) {
              const code = result.error.code;
              if (code === 'ENOENT') {
                  throw new Error('ffplay not found on PATH. Install ffmpeg (ffplay ships with it) and retry.');
              }
              throw new Error(`ffplay failed: ${result.error.message}`);
          }
          if (result.status !== 0) {
              throw new Error(`ffplay exited with code ${result.status}`);
          }
      }
      ```
    </WrapCode>
  </Tab>

  <Tab value="ts" label="TypeScript">
    <WrapCode>
      ```ts file=<rootDir>/packages/sdk/examples/tts/utils.ts title="utils.ts" lineNumbers
      import { writeFileSync, unlinkSync } from 'fs'
      import { spawn, spawnSync } from 'child_process'
      import { platform, tmpdir } from 'os'
      import { join } from 'path'

      /**
       * Create WAV header for 16-bit PCM audio
       */
      export function createWavHeader(dataLength: number, sampleRate: number): Buffer {
        const header = Buffer.alloc(44)

        // RIFF header
        header.write('RIFF', 0)
        header.writeUInt32LE(36 + dataLength, 4)
        header.write('WAVE', 8)

        // fmt chunk
        header.write('fmt ', 12)
        header.writeUInt32LE(16, 16) // fmt chunk size
        header.writeUInt16LE(1, 20) // PCM format
        header.writeUInt16LE(1, 22) // mono
        header.writeUInt32LE(sampleRate, 24)
        header.writeUInt32LE(sampleRate * 2, 28) // byte rate
        header.writeUInt16LE(2, 32) // block align
        header.writeUInt16LE(16, 34) // bits per sample

        // data chunk
        header.write('data', 36)
        header.writeUInt32LE(dataLength, 40)

        return header
      }

      /**
       * Convert Int16Array to Buffer
       */
      export function int16ArrayToBuffer(samples: number[]): Buffer {
        const buffer = Buffer.alloc(samples.length * 2)
        for (let i = 0; i < samples.length; i++) {
          const value = Math.max(-32768, Math.min(32767, Math.round(samples[i] ?? 0)))
          buffer.writeInt16LE(value, i * 2)
        }
        return buffer
      }

      /**
       * Create and save WAV file
       */
      export function createWav(audioBuffer: number[], sampleRate: number, filename: string): void {
        const audioData = int16ArrayToBuffer(audioBuffer)
        const wavHeader = createWavHeader(audioData.length, sampleRate)
        const wavFile = Buffer.concat([wavHeader, audioData])

        writeFileSync(filename, wavFile)
        console.log(`▸ WAV file saved as: ${filename}`)
      }

      /**
       * Play a WAV buffer by streaming it into ffplay over stdin.
       *
       * ffplay ships with ffmpeg and is cross-platform (macOS/Linux/Windows), so
       * we avoid the old "write to /tmp then shell out to afplay/aplay/powershell"
       * dance — no temp files, no platform switch, no hardcoded /tmp path (which
       * doesn't exist on Windows). Requires ffplay on PATH.
       */
      /**
       * Play one mono s16le PCM chunk (as a minimal WAV) and wait for the player to finish.
       * Chunks are played sequentially when awaited in order — suitable for streaming TTS output.
       */
      export function playPcmInt16Chunk(samples: number[], sampleRate: number): Promise<void> {
        if (samples.length === 0) {
          return Promise.resolve()
        }

        const audioData = int16ArrayToBuffer(samples)
        const wavHeader = createWavHeader(audioData.length, sampleRate)
        const wavFile = Buffer.concat([wavHeader, audioData])
        // `os.tmpdir()` resolves to the OS-specific temp directory (e.g. `%TEMP%`
        // on Windows), so the Windows branch below no longer tries to read a
        // POSIX-only `/tmp/...` path.
        const tempFile = join(
          tmpdir(),
          `qvac-tts-chunk-${Date.now()}-${Math.random().toString(16).slice(2)}.wav`
        )
        writeFileSync(tempFile, wavFile)

        const currentPlatform = platform()
        let audioPlayer: string
        let args: string[]

        switch (currentPlatform) {
          case 'darwin':
            audioPlayer = 'afplay'
            args = [tempFile]
            break
          case 'linux':
            audioPlayer = 'aplay'
            args = [tempFile]
            break
          case 'win32':
            audioPlayer = 'powershell'
            args = [
              '-Command',
              `Add-Type -AssemblyName presentationCore; (New-Object Media.SoundPlayer).LoadStream([System.IO.File]::ReadAllBytes('${tempFile}')).PlaySync()`
            ]
            break
          default:
            audioPlayer = 'aplay'
            args = [tempFile]
        }

        return new Promise(function (resolve, reject) {
          const proc = spawn(audioPlayer, args, { stdio: 'ignore' })
          proc.on('error', function (err) {
            try {
              unlinkSync(tempFile)
            } catch {
              // ignore
            }
            reject(err)
          })
          proc.on('close', function (code) {
            try {
              unlinkSync(tempFile)
            } catch {
              // ignore
            }
            if (code === 0) {
              resolve()
            } else {
              reject(new Error(`Audio player exited with code ${code}`))
            }
          })
        })
      }

      export function playAudio(audioBuffer: Buffer): void {
        const result = spawnSync(
          'ffplay',
          ['-hide_banner', '-loglevel', 'error', '-autoexit', '-nodisp', '-i', 'pipe:0'],
          {
            input: audioBuffer,
            stdio: ['pipe', 'inherit', 'inherit']
          }
        )

        if (result.error) {
          const code = (result.error as NodeJS.ErrnoException).code
          if (code === 'ENOENT') {
            throw new Error('ffplay not found on PATH. Install ffmpeg (ffplay ships with it) and retry.')
          }
          throw new Error(`ffplay failed: ${result.error.message}`)
        }
        if (result.status !== 0) {
          throw new Error(`ffplay exited with code ${result.status}`)
        }
      }
      ```
    </WrapCode>
  </Tab>
</Tabs>

<Callout type="success">
  **Tip:** all examples throughout this documentation are self-contained and
  runnable. For instructions on how to run them, see the [JS/TS
  quickstart](/sdk/v0.23/js-ts-sdk#quickstart), the [Python
  quickstart](/sdk/v0.23/python-sdk#quickstart), or the [Kotlin
  quickstart](/sdk/v0.23/kotlin-sdk#quickstart).
</Callout>
