# Camb.ai

> Text-to-speech with Camb.ai's MARS models: CambTTSService streams PCM audio over HTTP.

Source: https://polvallverdu.github.io/pipedog/docs/services/tts/camb/



## Overview [#overview]

`CambTTSService` posts each sentence to Camb.ai's `tts-stream` endpoint and pushes the streamed 16-bit PCM, kept aligned to whole samples. Models: `mars-flash` (fast, 22.05 kHz, the default), `mars-pro` (high quality, 48 kHz) and `mars-instruct` (22.05 kHz, takes instructions for tone and style).

<Cards>
  <Card title="Upstream page" href="https://docs.pipecat.ai/api-reference/server/services/tts/camb">
    Pipecat's documentation for the same service.
  </Card>

  <Card title="Source" href="https://github.com/polvallverdu/pipedog/tree/main/packages/camb/src">
    `packages/camb/src/tts.ts`.
  </Card>

  <Card title="Camb.ai docs" href="https://docs.camb.ai/api-reference/endpoint/create-tts-stream">
    The streaming TTS endpoint reference.
  </Card>
</Cards>

## Installation [#installation]

```bash
bun add @pipedog/camb
```

```ts
import { CambTTSService } from "@pipedog/camb/tts";
```

## Prerequisites [#prerequisites]

* A Camb.ai account and an API key.
* Pass the key as `apiKey`. The examples read it from `CAMB_API_KEY`.

## Configuration [#configuration]

| Option | Type | Required | Description |
|---|---|---|---|
| `textAggregationMode` | `TextAggregationMode \| null \| undefined` | no | How to aggregate incoming text before synthesis. `TextAggregationMode.SENTENCE` (default) buffers until sentence boundaries, `TextAggregationMode.TOKEN` streams tokens directly for lower latency. |
| `pushTextFrames` | `boolean \| undefined` | no | Whether to push TextFrames and LLMFullResponseEndFrames. |
| `pushStopFrames` | `boolean \| undefined` | no | Whether to automatically push TTSStoppedFrames. |
| `apiKey` | `string` | yes | Camb.ai API key for authentication. |
| `timeout` | `number \| undefined` | no | Request timeout in seconds. Defaults to 60.0 (minimum recommended by Camb.ai). Applies to the wait for the response and to the wait for each chunk of audio. |
| `baseUrl` | `string \| undefined` | no | Base URL of the Camb.ai API. Defaults to "https://client.camb.ai/apis". DIVERGENCE: not an upstream option. It stands for the SDK's `base_url` / `environment`. |
| `fetch` | `((input: RequestInfo \| URL, init?: RequestInit) => Promise<Response>) \| null \| undefined` | no | `fetch` used for HTTP requests. Defaults to the global `fetch`. DIVERGENCE: upstream calls Camb's Python SDK, which brings its own HTTP client. |
| `settings` | `CambTTSSettings \| null \| undefined` | no | Runtime-updatable settings. |
| `name` | `string \| null \| undefined` | no | Custom name; defaults to `ClassName#count`. |
| `taskManager` | `BaseTaskManager \| null \| undefined` | no | Task manager for handling tasks. |
| `enableDirectMode` | `boolean \| undefined` | no | Process frames immediately instead of using internal queues. |
| `metrics` | `FrameProcessorMetrics \| null \| undefined` | no | Optional metrics collector for this processor. |
| `pushStartFrame` | `boolean \| undefined` | no | Whether to automatically create audio contexts and push TTSStartedFrames. When true, the base class handles `createAudioContext` and yields `TTSStartedFrame` before each synthesis call, so `runTts` implementations do not need to. |
| `stopFrameTimeoutS` | `number \| undefined` | no | Idle time before pushing TTSStoppedFrame when pushStopFrames is true. |
| `pushSilenceAfterStop` | `boolean \| undefined` | no | Whether to push silence audio after TTSStoppedFrame. |
| `silenceTimeS` | `number \| undefined` | no | Duration of silence to push when pushSilenceAfterStop is true. |
| `pauseFrameProcessing` | `boolean \| undefined` | no | Whether to hold incoming frames after a turn until its audio contexts end. Needed by services whose audio doesn't carry its request's context ID. |
| `maxConsecutiveZeroAudioContexts` | `number \| undefined` | no | How many consecutive TTS contexts may complete without producing any audio before the service is reported unable to do its job. Catches a provider that accepts requests and stays silent — an unknown voice ID, say — which no error ever surfaces. Every silent context reports an error the service can carry on from, whatever the limit is; on reaching the limit the service reports a permanent error instead, stops being given work, and the pipeline worker applies its `ProcessorUnusablePolicy`. Set to 0 to report silent contexts without ever writing the service off. |
| `appendTrailingSpace` | `boolean \| undefined` | no | Whether to append a trailing space to text before sending to TTS. This helps prevent some TTS services from vocalizing trailing punctuation (e.g., "dot"). Only applied in sentence aggregation mode; when streaming tokens, the incoming text's own whitespace is preserved. |
| `sampleRate` | `number \| null \| undefined` | no | Output sample rate for generated audio. |
| `skipTextTypes` | `string[] \| null \| undefined` | no | List of text types that should not be spoken. |
| `textTransforms` | `[string, TextTransform][] \| null \| undefined` | no | A list of TextTransforms to transform text just before sending it to TTS. Each TextTransform takes the aggregated text and its type, and returns the transformed text. To register, provide a list of tuples of `[textType \| "*", transformFunction]`. |
| `transportDestination` | `string \| null \| undefined` | no | Destination for generated audio frames. |
| `reuseContextIdWithinTurn` | `boolean \| undefined` | no | Whether the service should reuse context IDs within the same turn. |
| `audioCache` | `TTSAudioCacheStore \| null \| undefined` | no | Where to keep synthesized audio for reuse (e.g. a shared `TTSAudioCache`). Text whose audio is in the cache is served from it, with no request to the provider. Lines get there through `warmAudioCache()`, and also from live synthesis when `cacheSynthesizedAudio` allows it. Only services that yield their audio from `runTts` (HTTP and streaming-RPC services, see `supportsAudioCache`) use it, and only in sentence aggregation mode. Defaults to null (no cache). pipedog only. |
| `cacheSynthesizedAudio` | `boolean \| ((text: string) => boolean) \| undefined` | no | Whether audio synthesized live is stored in `audioCache`, or a function that decides per text. Defaults to false: only warmed lines are stored, since a generated reply can repeat what the user said. pipedog only. |
| `audioCacheNamespace` | `string \| undefined` | no | Extra part of the cache key, for constructor options that change the audio but are not in `settings`. pipedog only. |

### Settings [#settings]

Runtime-updatable settings, passed as `settings: new CambTTSService.Settings({...})`
(`CambTTSSettings`). Any setting you leave out keeps the default below.

| Setting            | Type                 | Default        | Description                                                                                |
| ------------------ | -------------------- | -------------- | ------------------------------------------------------------------------------------------ |
| `model`            | `string`             | `"mars-flash"` | `mars-flash`, `mars-pro` or `mars-instruct`.                                               |
| `voice`            | `number`             | `147320`       | Voice id. Camb.ai uses integer ids.                                                        |
| `language`         | `Language \| string` | `"en-us"`      | Language, as a lowercase BCP-47 tag.                                                       |
| `userInstructions` | `string \| null`     | `null`         | Instructions for `mars-instruct` only, up to 1000 characters. Ignored by the other models. |

## Usage [#usage]

```ts title="tts.ts"
import { CambTTSService } from "@pipedog/camb/tts";
import { TTSUpdateSettingsFrame } from "@pipedog/core/frames/frames";

// mars-flash (22.05 kHz) is the default; mars-pro renders at 48 kHz.
const tts = new CambTTSService({
  apiKey: process.env.CAMB_API_KEY ?? "",
  settings: new CambTTSService.Settings({ model: "mars-pro", voice: 147320 }),
});
```

Change settings mid-call with a `TTSUpdateSettingsFrame`:

```ts
// Queue it on the worker, or push it from a processor upstream of the service.
const update = new TTSUpdateSettingsFrame({
  delta: new CambTTSService.Settings({ voice: 12345 }),
});
```

## Notes [#notes]

* Without a `sampleRate`, the service uses the model's: 22050 Hz for `mars-flash` and `mars-instruct`, 48000 Hz for `mars-pro`. A `sampleRate` that differs from the model's logs a warning.
* Text over 3000 characters is truncated.
* `timeout` (60 seconds by default, the minimum Camb.ai recommends) limits the wait for the response and the wait for each chunk of audio.

## Runtime notes [#runtime-notes]

* Upstream uses Camb's Python SDK. That SDK is a thin client over one endpoint, so this port sends the same request (`POST /tts-stream` with an `x-api-key` header) with the global `fetch`, which works on Bun, Node, Deno and Cloudflare Workers. `baseUrl` and `fetch` are not upstream options.
* The deprecated `params` (`InputParams`), `voiceId` and `model` options are not ported. Use `settings`.
* Upstream has no Camb.ai tests. Ours run against a local fake server, not against Camb.ai itself.

| Runtime            | Works | What it needs |
| ------------------ | ----- | ------------- |
| Bun                | ✅ yes | Nothing.      |
| Node.js            | ✅ yes | Nothing.      |
| Deno               | ✅ yes | Nothing.      |
| Cloudflare Workers | ✅ yes | Nothing.      |

Generated from `pipecat.runtimes` and `pipecat.compat` in `packages/camb/package.json`: ✅ means the compat smoke test passes on that runtime.
