# Speech

# Speech

`@ferret/speech` turns text into speech and speech into text. The work is done by the Camerlengo backend (`ai:tts`, `ai:stt`); the module sends the requests, plays the lines and
captures the microphone. It gives primitives and binds nothing: the game decides when a character speaks and when the player is heard (a key held, a button, a voice prompt).

## Who pays

By default every request goes with the **signed-in player's session** (`AccountService` of `@ferret/accounts`), and the player's wallet pays: synthesis by characters, recognition by
megabytes of audio. A guest has no session: the request is refused with `SpeechError('signed-out')` and nothing is sent. The developer may say otherwise:

```ts
installSpeech(world);                                                // the AccountService's client and session (the default)
installSpeech(world, { client, session: () => mySession, key });     // another client, session or key
installSpeech(world, { backend: myServerBackend });                  // a SpeechBackend of one's own (synthesize, recognize)
```

The page's public key needs the scopes `ai:tts` and `ai:stt`. Requests go to `https://squirrelwisdom.com/`, the proxy to the backend, as every Ferret client does.

## Speaking

```ts
const speech = installSpeech(world);
const line = speech.speak(npc, 'Follow me', { voice: 'echo', language: 'en' });   // on the voice bus at npc's node; null: not positioned
const r = await line.done;                                                        // { interrupted, error? }; never rejects
speech.speak(npc, 'Wait!', { interrupt: true });                                   // cuts what npc says and has queued
const clip = await speech.synthesize('Later line', { voice: 'nova' });            // a clip, nothing played (and cached)
```

- **Voices:** an OpenAI name (`alloy`, `echo`, `fable`, `onyx`, `nova`, `shimmer`), which the server maps to a male or female voice of the language, or an exact Edge voice name
  (`ru-RU-SvetlanaNeural`). There is no list command.
- **Language:** always sent (default `en`). Without it the server spends a language-detection call on every line.
- **Queue:** the lines of one speaker play one after another; different speakers overlap.
- **Cache:** clips are kept by text, voice and language (64 by default), so a repeated line is neither sent nor paid twice. Synthesis starts when `speak` is called, so calling
  `synthesize` ahead of time hides the round trip.
- Sound must be unlocked by the first user action (`AudioService.unlock()`); a line before that fails with `audio-locked`.

## Listening

```ts
const mic = await speech.listen({ language: 'ru' });   // asks for the microphone once, captures
meter.width = mic.level;                               // 0..1, for the UI
const text = await mic.stop();                         // sends one request: the text
mic.cancel();                                          // or: drop it, nothing sent, nothing paid
await speech.recognize(bytesOrClip, { language: 'en' });
```

The capture is resampled to 16 kHz mono and sent as MP3 (recognition is paid by size). A capture that is only silence is not sent (`empty`); one capture runs at a time (`busy`);
a capture ends by itself at `maxSeconds` (60) and keeps what it has. The microphone source is injectable (`microphone` option) for tests and hosts with their own input.

## Events

They are emitted at the fixed step, so game logic sees them in step order.

| event | payload |
|---|---|
| `speech:start` | `{ speaker?, text, voice, language, duration }` |
| `speech:end` | `{ speaker?, text, interrupted }` |
| `speech:heard` | `{ text, language?, duration }` |
| `speech:listening` | `{ on, reason? }` (`stop`, `cancel`, `limit`) |
| `speech:error` | `{ op: 'speak' \| 'recognize' \| 'capture', code, message }` |

`@ferret/micromotion` listens to `speech:start`: a person whose id is the speaking entity's gets beats and nods over the real length of the line.

## Errors

`SpeechError.code`: `signed-out`, `no-funds` (402), `forbidden` (997: the key lacks the scope), `backend`, `network`, `no-microphone`, `mic-denied`, `busy`, `empty`, `no-audio`,
`audio-locked`.

## Commands

`speech.say {text, entity? (id or name), voice?, language?, interrupt?}`, `speech.synthesize`, `speech.hush {entity?}`, `speech.listen {language?}`, `speech.stop` (the text),
`speech.cancel`, `speech.recognize {url | base64, language?}`, `speech.status`.

## The viewer

`?speech[=<backend url>][&appkey=<public key>]`: a sign-in card, a figure that speaks positionally, a text field with voice and language, and a hold-to-talk button the page binds
itself; plus `speech.signin {user, password}`, `speech.signout`, `speech.audio`. Headless, `startServer({ headless: true, speech: true, fakeMic: 'phrase.wav' })` makes a WAV file the
microphone, so the whole round trip runs without a device.

## Unreal build

The UE build hosts the game in Chromium (CEF), where `fetch`, `getUserMedia` and Web Audio work as in a browser; the module needs nothing of its own there.
