diff --git a/README.md b/README.md index e321b81..bf4f532 100644 --- a/README.md +++ b/README.md @@ -30,7 +30,11 @@ mix audio_flow.bench --runs 20 --concurrency 4 For a browser chat with typed and spoken messages, see [examples/chat](examples/chat/README.md). Its Linux demo needs no model download; the app also exposes server-configured speech providers, languages, redacted -recordings, playback progress and provisional pause/resume. +recordings, playback progress and provisional pause/resume. Its always-on +modes use `AudioFlow.Duplex` with OpenAI Realtime or a local Moshi server: the +microphone stays open from Start to Stop and the model audio plays at the same +time. OpenAI detects each utterance, replies by voice and stops the reply when +you speak. To build agents as node graphs, see [ui](ui/README.md). It is a local dashboard with a canvas editor and an MCP endpoint for coding agents. A session runs an @@ -66,7 +70,10 @@ For OpenAI Realtime, Gemini Live or a local [Moshi](docs/providers.md#local-moshi-speech-to-speech) server without chained stages, use the explicit [Session speech-to-speech mode](docs/providers.md#session-speech-to-speech-mode). -It accepts committed PCM and does not replay cross-turn history. +It accepts committed PCM and does not replay cross-turn history. For a +continuous conversation with the microphone open, use `AudioFlow.Duplex` with +[OpenAI Realtime](docs/providers.md#continuous-openai-realtime-conversation) or +[Moshi](docs/providers.md#continuous-full-duplex-moshi). The owner receives transcript, text, audio, and terminal events. See `AudioFlow` for the event format. Each turn has a unique reference. A session diff --git a/docs/providers.md b/docs/providers.md index 2a6eaff..f3aed1f 100644 --- a/docs/providers.md +++ b/docs/providers.md @@ -49,6 +49,10 @@ not decoded and are not requested. ## Direct speech-to-speech calls +These calls send one committed utterance per connection. For an always-on +OpenAI conversation with the microphone open, use +[`AudioFlow.Duplex.OpenAIRealtime`](#continuous-openai-realtime-conversation). + `AudioFlow.Adapters.OpenAIRealtime.run/3` and `AudioFlow.Adapters.GeminiLive.run/3` accept a committed `AudioFlow.Audio` and invoke an arity-one callback with `{:transcript, text}`, `{:text, delta}` and @@ -129,7 +133,8 @@ explicit typed event ports (transcript, text and audio), routing/validation for each, and a dedicated history capability contract. Registering either adapter as an existing STT/LLM/TTS node would misrepresent its contract. Use the explicit Session mode or direct API today. There is no continuous duplex input, tool -execution, automatic reconnect, resampling or WebRTC in this mode. +execution, automatic reconnect, resampling or WebRTC in this mode. For +continuous input, see `AudioFlow.Duplex` below. ## Local Moshi speech-to-speech @@ -190,6 +195,136 @@ AUDIOFLOW_MOSHI_PCM=question.s16le mix test test/moshi_test.exs `AUDIOFLOW_MOSHI_ENDPOINT` overrides the default endpoint. +### Continuous full-duplex Moshi + +`AudioFlow.Duplex` keeps one Moshi connection open. Microphone input and model +output flow at the same time. There is no committed turn, no end-of-turn +detection, no silence gate, and no output drop while the user speaks. Use it +for a live conversation. Use `AudioFlow.Adapters.Moshi` for one committed turn. + +```elixir +{:ok, duplex} = + AudioFlow.Duplex.start_link( + owner: self(), + adapter: {AudioFlow.Duplex.Moshi, endpoint: "ws://127.0.0.1:8998/api/chat"}) + +# Wait for {AudioFlow.Duplex, ^duplex, :ready}, then push 80 ms chunks: +:ok = AudioFlow.Duplex.push(duplex, %AudioFlow.Audio{data: pcm_3840_bytes, sample_rate: 24_000}) +:ok = AudioFlow.Duplex.stop(duplex) +``` + +`start_link/1` returns before the connection opens. The owner receives +`{AudioFlow.Duplex, pid, event}`, where `event` is `:ready` (after the Moshi +handshake), `{:audio, %AudioFlow.Audio{}}`, `{:text, token}`, +`{:error, reason}` or `:closed`. `:closed` comes last, also after an error. +`push/2` returns `{:error, :not_ready}` before `:ready` and `{:error, :closed}` +after the session stops. Keep the endpoint in server configuration; the browser +does not need it. + +`start/1` starts an unlinked session with the same API. Use it when the owner +must also survive an unexpected adapter crash, as the chat UI does. Monitor +the returned process to detect these crashes. Both start functions monitor +the owner and close the connection when it exits. + +The adapter sends each complete 80 ms frame (3,840 bytes at 24 kHz) as one Ogg +page at once. A shorter remainder waits for the next push. Moshi answers each +input frame with one output frame, so the client must push continuous audio, +silence included, to get continuous output. + +Bounds (defaults): + +- `:connect_timeout_ms` (15,000) from start to the Moshi handshake. +- `:idle_timeout_ms` (30,000) without an accepted push. +- `:max_session_ms` (1,800,000) in total. +- `:max_chunk_bytes` (48,000) for each push, else `{:error, :too_large}`. +- `:max_response_bytes` (67,108,864) for all incoming WebSocket bytes in a + session, including fragments. The session fails with `:response_too_large` + at this bound. Incomplete Ogg packets are limited to 256 KiB. +- `:max_input_lead_ms` (2,000). For Moshi (adapter input flow `:answered`): + pushed audio that model audio has not answered. For OpenAI (`:realtime`): + pushed audio ahead of the wall clock since `:ready`, so continuous silence + never fills it. A push past it returns `{:error, :overloaded}` and is not + sent, for example while MLX warms up. +- `:max_owner_queue` (250): when the owner mailbox has this many messages, the + session fails with `:owner_overloaded`. Output is not buffered or dropped. +- `:send_timeout_ms` (5,000) for each TCP write. + +The session monitors the owner and closes the connection when the owner exits. +On failure, timeout and `stop/1` it exits with reason `:normal`, so the link +from `start_link/1` does not stop the owner. The owner must be a local process. +The Moshi server limits above also apply: one connection at a time, and model +state continues across connections. + +`mix test test/duplex_test.exs` (with `AUDIOFLOW_MEDIA=1`) checks simultaneous +input and output, frame sizes, the handshake gate, the input and owner bounds, +timeouts and connection cleanup against a local fixture. With +`AUDIOFLOW_HTTP_MODEL_TESTS=1` and `AUDIOFLOW_MOSHI_PCM`, it also streams the +question and then silence in real time to a running server. + +### Continuous OpenAI Realtime conversation + +`AudioFlow.Duplex.OpenAIRealtime` keeps one authenticated OpenAI Realtime GA +WebSocket open for a whole conversation. It needs no media build. + +```elixir +{:ok, duplex} = + AudioFlow.Duplex.start( + owner: self(), + adapter: + {AudioFlow.Duplex.OpenAIRealtime, + model: System.fetch_env!("OPENAI_REALTIME_MODEL"), + api_key: fn -> System.fetch_env!("OPENAI_API_KEY") end, + voice: "marin"}) + +# After {AudioFlow.Duplex, ^duplex, :ready}, push 24 kHz PCM continuously, +# silence included: +:ok = AudioFlow.Duplex.push(duplex, %AudioFlow.Audio{data: pcm, sample_rate: 24_000}) +``` + +The adapter sends `session.update` (type `realtime`, `output_modalities` +`["audio"]`, PCM 24 kHz in and out, the voice, input transcription and +`server_vad` with `create_response` and `interrupt_response`) after +`session.created`, and emits `:ready` after `session.updated`. Each push is one +`input_audio_buffer.append`. The adapter never commits input and never sends +`response.create`: OpenAI detects each utterance, replies to it and cancels the +reply when new speech starts. All utterances of one connection share the +provider conversation; a new connection starts a new one. The API key function +runs only to connect, so the key is not kept in the session state. Options: +`:model`, `:api_key`, `:voice` (`"marin"`), `:instructions` (`""`), +`:transcription_model` (`"gpt-4o-mini-transcribe"`) and `:endpoint`. + +The owner also receives: + +| Event | Meaning | +| --- | --- | +| `{:speech_started, item}` | User speech started. Flush queued reply audio; keep the microphone open. Late audio and text of the interrupted reply are dropped. | +| `{:transcript, item, text \| :failed}` | Final transcript of the user utterance `item`. | +| `{:response, id, status}` | Reply `id` was `:created`, or ended `:completed`, `:cancelled`, `:incomplete` or `:failed`. | +| `{:output, item}` | The next `{:audio, _}` events belong to reply audio `item`. | + +After a flush, report the played part of the cut reply with +`AudioFlow.Duplex.control(duplex, {:played, item, ms})`. If `ms` is less than +the audio received for `item`, the adapter sends `conversation.item.truncate` +(`audio_end_ms` capped to the received audio), so the provider history keeps +only the played audio and its transcript. Only the last interrupted reply is +accepted, once; other reports return `{:error, :stale}` and leave the call +open. A rejected truncation also leaves the call open. The played time is +client playback time: it does not prove acoustic delivery. Without a report, +the provider history keeps the full reply. + +Provider `error` events fail the session with `{:remote_error, code}` (only +the code or type, never the message). Tool calls fail it with +`:unsupported_tool_call`, because no tools are configured. All +`AudioFlow.Duplex` bounds apply; `:max_response_bytes` (64 MiB) is about 17 +minutes of base64 reply audio per session. +The chat example sets this bound to 256 MiB for OpenAI calls, to allow the +30-minute call limit to apply before the response byte limit in ordinary use. + +`mix test test/duplex_openai_test.exs` checks the handshake order, server VAD +configuration, several utterances on one socket, continuous silence, +interruption drops, truncation bounds, provider errors and cleanup against a +local WebSocket peer, not OpenAI. + ## Bounds, cancellation and errors All providers accept `:endpoint` overrides for proxies and local tests. Use @@ -215,9 +350,14 @@ samples fail. Limits and timeout options must be positive integers. ## Protocol references and verification -Wire shapes were checked against official documentation on 2026-11-03: +Wire shapes were checked against official documentation on 2026-11-03 +(OpenAI Realtime events again on 2026-11-06): - [OpenAI Realtime conversations](https://developers.openai.com/api/docs/guides/realtime-conversations) +- [OpenAI Realtime WebSocket](https://developers.openai.com/api/docs/guides/voice-websockets), + [voice activity detection](https://developers.openai.com/api/docs/guides/realtime-vad), + [client events](https://developers.openai.com/api/reference/resources/realtime/client-events) and + [server events](https://developers.openai.com/api/reference/resources/realtime/server-events) - [Gemini Live WebSocket reference](https://ai.google.dev/api/live) - [Deepgram pre-recorded utterances](https://developers.deepgram.com/docs/utterances) - [Cartesia bytes TTS](https://docs.cartesia.ai/api-reference/tts/bytes) diff --git a/examples/chat/README.md b/examples/chat/README.md index a53da75..fb98d5e 100644 --- a/examples/chat/README.md +++ b/examples/chat/README.md @@ -4,8 +4,16 @@ A local LiveView chat over one AudioFlow session per browser tab. Type a message, or record one with the microphone. While you record, the user message shows a live transcript. The reply text streams into the conversation, the reply audio plays as it arrives, and each reply keeps an audio player for -replay. The UI uses [live_shadcn](https://live-shadcn-storybook.fly.dev/) and -its AI Elements components. +replay. Two always-on modes keep the microphone open from **Start +conversation** to **Stop**: **OpenAI live conversation** (OpenAI Realtime) and +**Local Moshi full duplex**. The UI uses +[live_shadcn](https://live-shadcn-storybook.fly.dev/) and its AI Elements +components. + +The page shows only the provider, its voice, the conversation controls, a short +status and the conversation. Setup, limits and privacy details are in this +README. Turn-based modes keep transcript saving and playback diagnostics in +collapsed **Settings** and **Diagnostics** sections. The native profile runs models on Apple Silicon through MLX (macOS 26.2+). Linux defaults to a credential-free synthetic demo. Remote providers work in @@ -27,6 +35,128 @@ Demo STT returns a fixed “Hello”, replies echo the input and output PCM is s It tests session wiring, not recognition or synthesis. No EMLX, EXLA, Bumblebee or model downloads are needed. Use the same profile for all Mix commands. +## Always-on OpenAI live conversation + +This mode uses `AudioFlow.Duplex` with `AudioFlow.Duplex.OpenAIRealtime` over +one server-side WebSocket to OpenAI Realtime. It needs no media build and no +model download. + +```sh +cd examples/chat +export CHAT_PROFILE=demo CHAT_MODE=openai +export OPENAI_API_KEY=... OPENAI_REALTIME_MODEL=gpt-realtime +mix setup +mix phx.server +``` + +Open , select the voice, click **Start conversation** +once and allow the microphone. Talk normally. The microphone stays open until +you click **Stop**: + +- The browser streams 80 ms chunks of 24 kHz PCM all the time, also silence and + also while the reply plays. +- OpenAI server VAD detects each utterance and starts the spoken reply. The + client never commits input or requests a reply. +- When you start to speak during a reply, OpenAI cancels the reply, and the + browser stops the queued reply audio at once. The microphone stays open. + The browser reports how much of the reply it played (audio clock minus the + output latency), and the server truncates the reply in the OpenAI history to + that part (`conversation.item.truncate`), capped to the audio it received. +- All utterances of one call share one OpenAI conversation. A new call starts + a new conversation. **Clear text** clears the page only. +- Your speech shows as a transcript message (`gpt-4o-mini-transcribe`), and + each reply as one assistant message. + +The key stays on the server: the adapter reads it only to connect, and the +browser never sends or receives it. `OPENAI_REALTIME_ENDPOINT` (optional, +`ws://` or `wss://` without user information) replaces the OpenAI endpoint, +for example for a proxy. + +Limits (in addition to the shared limits below): the browser queues at most +60 s of reply audio; if a reply is longer, the rest of that reply is dropped. +Provider errors stop the call and show the provider error code only. Tool +calls are not supported and stop the call. The truncation uses browser +playback time, not acoustic delivery: it does not prove that you heard the +audio, and the transcript text of a truncated reply on the page is not cut. +Use headphones; the browser requests echo cancellation, and without it the +model can hear its own voice. + +## Full duplex conversation with local Moshi + +This mode has no turns. The microphone stays open, and Moshi audio plays at +the same time. You can speak while Moshi speaks; your speech does not stop the +playback. It uses `AudioFlow.Duplex` with `AudioFlow.Duplex.Moshi`. It needs +`AUDIOFLOW_MEDIA=1` (Ogg Opus through Membrane) and no Whisper, Qwen or Kokoro +download. The demo profile starts no native model. + +1. Start the Moshi server in a separate terminal. The model + `kyutai/moshika-mlx-q4` loads from the Hugging Face cache + (`~/.cache/huggingface/hub/models--kyutai--moshika-mlx-q4`). If the cache is + empty, the first start downloads approximately 5 GB. `HF_HUB_OFFLINE=1` + prevents network access when the model is in the cache. + + ```sh + HF_HUB_OFFLINE=1 uvx --python 3.12 --from moshi_mlx python -m moshi_mlx.local_web \ + -q 4 --hf-repo kyutai/moshika-mlx-q4 --no-browser --port 8998 + ``` + +2. Start the chat in full duplex mode: + + ```sh + cd examples/chat + export CHAT_PROFILE=demo AUDIOFLOW_MEDIA=1 CHAT_MODE=moshi + mix setup + mix phx.server + ``` + +3. Open , click **Start conversation** and allow the + microphone. Click **Stop** to end the conversation. + +Use the same three variables for all Mix commands of this profile. The build +goes to `_build/demo_media`, so it does not reuse modules from another profile +(`_build` native, `_build/demo` demo, `_build/native_media` native with media). +Without `CHAT_MODE=moshi`, select **Local Moshi full duplex** in the Provider +list and click **Apply**. + +The server reads the model endpoint only from `AUDIOFLOW_MOSHI_ENDPOINT` +(default `ws://127.0.0.1:8998/api/chat`). The value must be a `ws://` or +`wss://` URL without user information. Browser events never select the +endpoint. + +Status and errors show next to the controls: **Connecting…**, **Live**, +**Conversation ended** or **Stopped by an error** with the reason (for +example `connect_failed` when the Moshi server does not run, or the microphone +error). The text input, the record button, the pause controls and the +recordings control are not available in this mode. Moshi does not transcribe +you, so only the model text shows. A pause of 1.5 s in the model text starts a +new message. + +Limits: + +| Item | Limit | +| --- | --- | +| Input chunk | exactly 3,840 bytes: 80 ms of 24 kHz mono s16le PCM. Other sizes are refused. | +| Resampling | continuous box filter from the capture rate to 24 kHz. Capture below 24 kHz fails. | +| Input before the model handshake | dropped | +| Input that waits for a server acknowledgement | 4 chunks (320 ms) | +| Input that waits to be sent | 12 chunks (960 ms); the oldest chunk is dropped first | +| Input lead (`AudioFlow.Duplex` `:max_input_lead_ms`) | 2 s. Moshi: input that the model has not answered. OpenAI: input ahead of the wall clock since the call started, so silence never fills it. More is refused with `overloaded` and dropped. | +| Queued model audio in the browser | Moshi 1 s, OpenAI 60 s ahead of the playback clock; later chunks are dropped | +| Time | 15 s to the model handshake; 30 s without accepted input ends the conversation; 30 min in total | +| Conversation messages | the latest 200, 4,000 bytes each | + +**Diagnostics** (collapsed) shows the sent and dropped input chunks, the +queued playback, the dropped model audio and the interruptions. These limits +apply to both always-on modes. Each conversation has a generation number; the +browser and the server ignore events of an earlier generation. Stop, an +error, a microphone failure or disconnection, a LiveView disconnect and a +server stop release the microphone, the queued playback and the model +connection. The Moshi server serves one connection at a time. + +Use headphones. The browser requests echo cancellation, but AudioFlow does not +verify it. Without headphones, Moshi can hear its own voice. Microphone access +requires `localhost` or HTTPS. + ## Run native models on Apple Silicon The repository `mise.toml` pins Erlang, Elixir, Node.js, and @@ -137,7 +267,7 @@ pinned to the commit in live_shadcn's `registry/UPSTREAM.json`. ## Remote providers and per-tab controls -The pipeline form applies settings by starting a **new chat**; it never silently +The provider form applies settings by starting a **new chat**; it never silently replays or discards history during a turn. Stop recording/generation first. Native model selections remain shared across tabs, as before. Remote pipeline settings are per tab. Browser events contain selection IDs and PCM, never keys. @@ -148,15 +278,15 @@ Export credentials in the server shell before `mix phx.server`: | Remote chain | `DEEPGRAM_API_KEY`, `CHAT_HTTP_ENDPOINT` (full chat-completions URL), `CHAT_HTTP_MODEL` | `DEEPGRAM_MODEL` (default nova-3), `CHAT_HTTP_API_KEY`; language en/es/fr/de/ro applies to STT and TTS | | ElevenLabs TTS in chain | `ELEVENLABS_API_KEY`, `ELEVENLABS_VOICE_ID` | `ELEVENLABS_MODEL` (default eleven_multilingual_v2) | | Cartesia TTS in chain | `CARTESIA_API_KEY`, `CARTESIA_VOICE_ID` | `CARTESIA_MODEL` (default sonic-3.6); API version 2026-08-14 | -| OpenAI speech-to-speech | `OPENAI_API_KEY`, `OPENAI_REALTIME_MODEL` | Page voice marin/cedar; input/output 24 kHz | -| Gemini speech-to-speech | `GEMINI_API_KEY`, `GEMINI_LIVE_MODEL` (include models/ prefix) | Provider default voice/language; input 16 kHz, output 24 kHz | +| OpenAI live conversation (always on) | `OPENAI_API_KEY`, `OPENAI_REALTIME_MODEL` | `OPENAI_REALTIME_ENDPOINT`; page voice marin/cedar; input/output 24 kHz | +| Gemini speech-to-speech (turn-based) | `GEMINI_API_KEY`, `GEMINI_LIVE_MODEL` (include models/ prefix) | Provider default voice/language; input 16 kHz, output 24 kHz | Missing variables produce a visible error and keep the existing chat active. Provider account/model/voice availability must be checked with your account. See [provider contracts](../../docs/providers.md). The chained pipeline supports -text and microphone messages with text history. Speech-to-speech accepts only -committed microphone utterances, opens a fresh provider connection each turn, -and has **no history replay**. The language control applies only to the remote +text and microphone messages with text history. Gemini speech-to-speech accepts +only committed microphone utterances, opens a fresh provider connection each +turn, and has **no history replay**. OpenAI live conversation is described above. The language control applies only to the remote chain; the OpenAI voice control only to OpenAI. Local voices use Kokoro's control. The browser actually converts microphone samples to the selected rate using a box filter; it rejects capture below that rate. This is basic speech conversion, @@ -172,13 +302,14 @@ and on flush. Suspended contexts do not advance; queued buffers are not counted. A token rejects acknowledgements from earlier turns. Stop/new input flushes playback even after generation has finished. Cancellation conservatively keeps only complete aligned chained speech chunks covered by acknowledgements; -it can undercount by one reporting interval. Speech-to-speech deltas have no -proven text/audio alignment; no heard-text history or native provider truncation -is claimed. Replay players do not modify conversation history. First-text, +it can undercount by one reporting interval. Gemini speech-to-speech deltas have +no proven text/audio alignment; no heard-text history or native provider +truncation is claimed. Replay players do not modify conversation history. First-text, first-audio, total generation time and acknowledged playback are separate values; they do not measure acoustic latency. -Recording is off by default. Enable between turns to persist bounded JSON event +Recording is off by default and not available in the always-on modes. In +**Settings**, click **Save redacted transcripts** between turns to persist bounded JSON event metadata with **all text replaced by `[REDACTED]`** and no audio. It deliberately does not attempt selective PII detection. Controls list, download and delete the current tab's artifacts. Disable deletes that tab's store. Bounds: 1,024 events, @@ -200,8 +331,7 @@ server command, npm setup and client connection. Use [`telephony-loopback.exs`](../telephony-loopback.exs) for the credential-free paced telephony/Telnyx reordering exercise (`MIX_ENV=test mix run examples/telephony-loopback.exs` from the repository root). These transports are separate runnable examples, -not modes of this microphone chat. They arrive on the parent integration branch -via PR #35. Navigation in the chat links to that branch's source/setup. +not modes of this microphone chat, and the chat page does not link to them. The [standalone network publisher](../network/README.md) runs actual encoded PCMU/VP8 two-peer negotiation with `AUDIOFLOW_WEBRTC=1 mix run @@ -226,11 +356,16 @@ Chat validation commands: ```sh cd examples/chat CHAT_PROFILE=demo mix test -node --test assets/test/audio.test.js +CHAT_PROFILE=demo AUDIOFLOW_MEDIA=1 mix test +node --test assets/test/ CHAT_PROFILE=demo mix assets.build ``` -The JS test uses a simulated AudioContext clock, not a browser speaker. +The JS tests use a simulated AudioContext clock and microphone, not a browser +speaker. The OpenAI LiveView tests use a local WebSocket peer with the OpenAI +Realtime event format, not OpenAI. With `AUDIOFLOW_MEDIA=1`, the Moshi LiveView +tests use a local WebSocket peer with the Moshi wire format, not the Moshi +model. Implementation validation on Linux (synthetic/local fixtures only): 7 chat ExUnit tests, 1 simulated AudioContext test, and 51 relevant core tests passed; @@ -252,9 +387,9 @@ no breaking dependency upgrades were made as part of this feature. ### Provisional interruption / real browser pause -The chat's **Pause / test interruption (10 s)** control requests a provisional -interruption. **Resume false interruption** continues the same turn, worker, -queued speech and speech checkpoints. **Confirm / Stop**, the 10-second candidate +In the collapsed **Diagnostics** section of the turn-based modes, **Pause +playback** requests a provisional interruption (10 s). **Resume** continues the +same turn, worker, queued speech and speech checkpoints. **Confirm stop**, the 10-second candidate deadline, the original turn timeout, or an endpoint failure cancels and flushes. Resume must be acknowledged before the candidate deadline too. This is an explicit manual test control, not an automatic microphone/VAD classifier. diff --git a/examples/chat/assets/js/app.js b/examples/chat/assets/js/app.js index d875912..d3395b4 100644 --- a/examples/chat/assets/js/app.js +++ b/examples/chat/assets/js/app.js @@ -8,12 +8,13 @@ import "live_ai_elements"; import { hooks as liveBase } from "phoenix-colocated/live_base"; import { hooks as liveAiElements } from "phoenix-colocated/live_ai_elements"; import { Player, Recorder } from "./audio"; +import { Duplex } from "./duplex"; const csrfToken = document.querySelector("meta[name='csrf-token']").getAttribute("content"); const liveSocket = new LiveSocket("/live", Socket, { params: { _csrf_token: csrfToken }, - hooks: { ...liveBase, ...liveAiElements, Player, Recorder }, + hooks: { ...liveBase, ...liveAiElements, Duplex, Player, Recorder }, }); liveSocket.connect(); diff --git a/examples/chat/assets/js/audio.js b/examples/chat/assets/js/audio.js index 0b0b79d..5c45b07 100644 --- a/examples/chat/assets/js/audio.js +++ b/examples/chat/assets/js/audio.js @@ -7,7 +7,7 @@ const INPUT_RATE = 16_000; const MAX_SECONDS = 30; -const CAPTURE_WORKLET = ` +export const CAPTURE_WORKLET = ` registerProcessor("capture", class extends AudioWorkletProcessor { process(inputs) { const channel = inputs[0]?.[0]; @@ -30,7 +30,7 @@ for (const type of ["pointerdown", "keydown"]) { document.addEventListener(type, () => playbackContext(), { capture: true }); } -const toBase64 = (bytes) => { +export const toBase64 = (bytes) => { let binary = ""; for (let i = 0; i < bytes.length; i += 0x8000) { binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000)); @@ -38,7 +38,7 @@ const toBase64 = (bytes) => { return btoa(binary); }; -const fromBase64 = (text) => Uint8Array.from(atob(text), (c) => c.charCodeAt(0)); +export const fromBase64 = (text) => Uint8Array.from(atob(text), (c) => c.charCodeAt(0)); // Box-filter downsampling is enough for speech recognition input. const toPcm16 = (chunks, rate, targetRate = INPUT_RATE) => { diff --git a/examples/chat/assets/js/duplex.js b/examples/chat/assets/js/duplex.js new file mode 100644 index 0000000..3e10540 --- /dev/null +++ b/examples/chat/assets/js/duplex.js @@ -0,0 +1,377 @@ +// Always-on conversation through AudioFlow.Duplex (local Moshi or OpenAI). +// +// The microphone stays open from Start to Stop. Its samples are resampled +// continuously to 24 kHz and sent as 80 ms s16le chunks. Model audio plays at +// the same time; microphone input never stops playback. +// +// When the server reports user speech ("call_flush"), queued model audio is +// stopped and the microphone stays open. The hook then reports how much of +// the cut reply audio the browser rendered ("call_played"), and drops later +// audio of that reply. +// +// Flow limits: +// - Before the server reports the model handshake, microphone input is dropped. +// - At most MAX_IN_FLIGHT chunks wait for a server acknowledgement. +// - At most MAX_PENDING chunks wait to be sent; the oldest is dropped first. +// - Model audio more than data-playback-ahead seconds (default +// MAX_PLAYBACK_AHEAD) ahead of the clock is dropped, and so is the rest of +// that reply, so the rendered time maps to a prefix of the reply. +// - Each conversation has a server generation. Events of another generation +// are ignored. + +import { CAPTURE_WORKLET, fromBase64, toBase64 } from "./audio.js"; + +export const CALL_RATE = 24_000; +export const CHUNK_SAMPLES = 1_920; +export const MAX_IN_FLIGHT = 4; +export const MAX_PENDING = 12; +export const MAX_PLAYBACK_AHEAD = 1; +const PLAYBACK_LEAD = 0.04; + +// Box-filter (area) resampler that keeps its phase between blocks, so the +// result does not depend on how the browser splits the input. +export class StreamResampler { + constructor(inputRate, outputRate) { + if (inputRate < outputRate) throw new Error(`Capture sample rate is below ${outputRate} Hz`); + this.ratio = inputRate / outputRate; + this.sum = 0; + this.filled = 0; + } + + push(samples) { + const out = new Float32Array(Math.ceil((samples.length + this.filled) / this.ratio) + 1); + let count = 0; + for (const sample of samples) { + let left = 1; + while (left > 0) { + const take = Math.min(left, this.ratio - this.filled); + this.sum += sample * take; + this.filled += take; + left -= take; + if (this.filled >= this.ratio - 1e-9) { + out[count++] = this.sum / this.ratio; + this.sum = 0; + this.filled = 0; + } + } + } + return out.subarray(0, count); + } +} + +// Collects float samples into fixed s16le chunks. +export class Chunker { + constructor(size) { + this.buffer = new Int16Array(size); + this.length = 0; + } + + push(samples) { + const chunks = []; + for (const sample of samples) { + const value = Math.max(-1, Math.min(1, sample)); + this.buffer[this.length++] = value < 0 ? value * 0x8000 : value * 0x7fff; + if (this.length === this.buffer.length) { + chunks.push(new Uint8Array(this.buffer.slice().buffer)); + this.length = 0; + } + } + return chunks; + } +} + +export const Duplex = { + mounted() { + this.call = null; + this.readyGeneration = null; + this.controls = this.el.parentElement; + this.onClick = (event) => { + const button = event.target.closest("[data-call]"); + if (!button || button.disabled) return; + if (button.dataset.call === "start") this.start(); + else this.stop(); + }; + this.controls.addEventListener("click", this.onClick); + + this.handleEvent("call_ready", ({ generation }) => { + this.readyGeneration = generation; + const call = this.current(generation); + if (call) { + call.ready = true; + clearTimeout(call.startupTimer); + } + }); + this.handleEvent("call_play", ({ generation, output, pcm, rate }) => { + const call = this.current(generation); + if (call) this.play(call, pcm, rate, output ?? null); + }); + this.handleEvent("call_flush", ({ generation }) => { + const call = this.current(generation); + if (call) this.flush(call); + }); + this.handleEvent("call_stopped", ({ generation }) => { + const call = this.current(generation); + if (call) this.release(call); + }); + }, + + destroyed() { + this.controls.removeEventListener("click", this.onClick); + this.release(this.call); + }, + + // The server stops the conversation when the LiveView process ends. + disconnected() { + this.release(this.call); + }, + + current(generation) { + return this.call && this.call.generation === generation ? this.call : null; + }, + + async start() { + if (this.call) return; + const call = { + generation: null, + ready: false, + context: null, + stream: null, + node: null, + pending: [], + inFlight: 0, + sent: 0, + dropped: 0, + sources: new Set(), + next: 0, + late: 0, + flushed: 0, + // Read at start: the server sets it per provider. + ahead: Number(this.el.dataset?.playbackAhead) || MAX_PLAYBACK_AHEAD, + output: null, + cut: null, + released: false, + }; + this.call = call; + this.draw("Requesting microphone…"); + call.startupTimer = setTimeout(() => { + this.fail(call, new Error( + call.generation === null + ? "Microphone or audio setup did not finish. Allow microphone access and try again." + : "The model connection did not become ready. Try again.", + )); + }, 20_000); + + try { + // Created during the click, so the browser allows playback. + call.context = new AudioContext(); + const resampler = new StreamResampler(call.context.sampleRate, CALL_RATE); + const url = URL.createObjectURL(new Blob([CAPTURE_WORKLET], { type: "text/javascript" })); + // A stream that arrives after a stop or a failure is stopped at once. + const media = navigator.mediaDevices + .getUserMedia({ + audio: { channelCount: 1, echoCancellation: true, noiseSuppression: true }, + }) + .then((stream) => { + call.stream = stream; + if (call.released) this.release(call); + return stream; + }); + const [stream] = await Promise.all([ + media, + call.context.audioWorklet.addModule(url).finally(() => URL.revokeObjectURL(url)), + ]); + if (this.call !== call) return; + + const chunker = new Chunker(CHUNK_SAMPLES); + call.node = new AudioWorkletNode(call.context, "capture"); + call.node.port.onmessage = ({ data }) => { + if (this.call !== call || !call.ready) return; + for (const chunk of chunker.push(resampler.push(data))) this.enqueue(call, chunk); + }; + call.context.createMediaStreamSource(stream).connect(call.node); + for (const track of stream.getTracks()) { + track.onended = () => this.fail(call, new Error("Microphone disconnected")); + } + + this.draw("Connecting…"); + this.pushEvent("call_start", {}, (reply) => { + if (this.call !== call) { + // Stopped while the server started it. + if (reply?.ok) this.pushEvent("call_stop", { generation: reply.generation }); + return; + } + if (!reply?.ok) return this.release(call); + call.generation = reply.generation; + call.ready = this.readyGeneration === reply.generation; + if (call.ready) clearTimeout(call.startupTimer); + this.ticker = setInterval(() => this.draw(), 500); + this.draw(); + }); + } catch (error) { + this.fail(call, error); + } + }, + + stop() { + const call = this.call; + if (!call) return; + if (call.generation !== null) this.pushEvent("call_stop", { generation: call.generation }); + this.release(call); + }, + + fail(call, error) { + if (this.call !== call) return this.release(call); + this.release(call); + this.pushEvent("call_failed", { message: error.message }); + }, + + enqueue(call, chunk) { + call.pending.push(chunk); + while (call.pending.length > MAX_PENDING) { + call.pending.shift(); + call.dropped++; + } + this.pump(call); + }, + + pump(call) { + while (call.inFlight < MAX_IN_FLIGHT && call.pending.length > 0) { + const pcm = toBase64(call.pending.shift()); + call.inFlight++; + this.pushEvent("call_audio", { generation: call.generation, pcm }, (reply) => { + if (this.call !== call) return; + call.inFlight--; + if (reply?.ok) call.sent++; + else call.dropped++; + this.pump(call); + }); + } + }, + + play(call, pcm, rate, output) { + if (output !== null && output === call.cut) return; + const bytes = fromBase64(pcm); + const samples = new Int16Array(bytes.buffer, 0, bytes.length >> 1); + if (samples.length === 0) return; + + if (output !== null && call.output?.id !== output) { + call.output = { id: output, spans: [], rendered: 0, rate, dropping: false }; + } + const reply = output === null ? null : call.output; + const context = call.context; + const now = context.currentTime; + const start = Math.max(call.next, now + PLAYBACK_LEAD); + if (reply?.dropping || start - now > call.ahead) { + call.late++; + if (reply) reply.dropping = true; + return; + } + + const buffer = context.createBuffer(1, samples.length, rate); + const channel = buffer.getChannelData(0); + for (let i = 0; i < samples.length; i++) channel[i] = samples[i] / 0x8000; + + const source = context.createBufferSource(); + source.buffer = buffer; + source.connect(context.destination); + source.onended = () => call.sources.delete(source); + source.start(start); + call.sources.add(source); + call.next = start + buffer.duration; + if (reply) { + this.fold(call, reply); + reply.spans.push([start, call.next, samples.length]); + } + }, + + // Audio-clock time that the listener has heard: output latency is + // subtracted, so progress never counts audio still in the output buffer. + heard(call) { + const context = call.context; + return context.currentTime - (context.outputLatency || context.baseLatency || 0); + }, + + // Moves fully heard spans into a sum, so the span list stays short. + fold(call, reply) { + const heard = this.heard(call); + reply.spans = reply.spans.filter(([_start, end, samples]) => { + if (end > heard) return true; + reply.rendered += samples; + return false; + }); + }, + + // Count exact scheduled samples and round only the partially rendered span. + renderedSamples(call, reply) { + const heard = this.heard(call); + let sum = reply.rendered; + for (const [start, end, samples] of reply.spans) { + sum += Math.min(samples, Math.max(0, Math.round((Math.min(heard, end) - start) * reply.rate))); + } + return sum; + }, + + // User speech: stop queued model audio, keep the microphone, report progress. + flush(call) { + const reply = call.output; + if (reply) this.fold(call, reply); + const ms = reply ? Math.floor(this.renderedSamples(call, reply) * 1000 / reply.rate) : 0; + const complete = reply && reply.spans.length === 0 && !reply.dropping; + for (const source of call.sources) { + source.onended = null; + source.stop(); + } + call.sources.clear(); + call.next = 0; + call.flushed++; + if (!reply) return; + call.cut = reply.id; + call.output = null; + if (!complete) this.pushEvent("call_played", { generation: call.generation, output: reply.id, ms }); + }, + + release(call) { + if (!call) return; + clearTimeout(call.startupTimer); + call.released = true; + if (this.call === call) { + this.call = null; + clearInterval(this.ticker); + this.draw(""); + } + if (call.node) { + call.node.port.onmessage = null; + call.node.disconnect(); + } + for (const track of call.stream?.getTracks() ?? []) { + track.onended = null; + track.stop(); + } + for (const source of call.sources) { + source.onended = null; + source.stop(); + } + call.sources.clear(); + call.pending.length = 0; + if (call.context?.state !== "closed") call.context?.close(); + }, + + draw(text) { + const start = this.controls.querySelector('[data-call="start"]'); + const stop = this.controls.querySelector('[data-call="stop"]'); + if (start) start.disabled = Boolean(this.call); + if (stop) stop.disabled = !this.call; + const stats = this.controls.querySelector("#duplex-stats"); + if (!stats) return; + const call = this.call; + if (text !== undefined || !call) { + stats.textContent = text ?? ""; + return; + } + const queued = Math.max(0, call.next - call.context.currentTime); + stats.textContent = + `Sent ${call.sent} · dropped ${call.dropped} input chunks · ` + + `${Math.round(queued * 1000)} ms queued playback · ${call.late} late output chunks · ` + + `${call.flushed} interruptions`; + }, +}; diff --git a/examples/chat/assets/test/duplex.test.js b/examples/chat/assets/test/duplex.test.js new file mode 100644 index 0000000..2436d01 --- /dev/null +++ b/examples/chat/assets/test/duplex.test.js @@ -0,0 +1,361 @@ +import { afterEach, test } from "node:test"; +import assert from "node:assert/strict"; + +// Browser fakes: a 48 kHz AudioContext with a settable clock, a microphone +// stream whose tracks record stop(), and a worklet port the test drives. +let contexts = []; +let microphone; +globalThis.document = { addEventListener() {} }; +globalThis.window = { addEventListener() {}, removeEventListener() {} }; +globalThis.AudioContext = class { + constructor() { + this.sampleRate = 48_000; + this.currentTime = 0; + this.state = "running"; + this.sources = []; + this.audioWorklet = { addModule: async () => {} }; + contexts.push(this); + } + close() { + this.state = "closed"; + } + createMediaStreamSource() { + return { connect() {} }; + } + createBuffer(_, samples, rate) { + return { duration: samples / rate, getChannelData: () => new Float32Array(samples) }; + } + createBufferSource() { + const source = { + connect() {}, + start(at) { + source.at = at; + }, + stop() { + source.stopped = true; + }, + }; + this.sources.push(source); + return source; + } +}; +globalThis.AudioWorkletNode = class { + constructor() { + this.port = {}; + microphone.node = this; + } + disconnect() { + this.disconnected = true; + } +}; +Object.defineProperty(globalThis, "navigator", { + configurable: true, + value: { mediaDevices: { getUserMedia: () => microphone.grant() } }, +}); + +const { + Duplex, + StreamResampler, + CHUNK_SAMPLES, + MAX_IN_FLIGHT, + MAX_PENDING, + MAX_PLAYBACK_AHEAD, +} = await import("../js/duplex.js"); + +// A failed assertion must not leave a call (and its status timer) running. +const mounted = []; +afterEach(() => mounted.splice(0).forEach((hook) => hook.destroyed())); + +const tick = () => new Promise((resolve) => setImmediate(resolve)); + +function grantMicrophone() { + const track = { + stop() { + track.stopped = true; + }, + }; + microphone = { track, grant: async () => ({ getTracks: () => [track] }) }; + return microphone; +} + +function mount(dataset = {}) { + const handlers = {}; + const pushes = []; + const listeners = {}; + const stats = { textContent: "" }; + const buttons = { + start: { disabled: false, dataset: { call: "start" } }, + stop: { disabled: true, dataset: { call: "stop" } }, + }; + const el = { + addEventListener(type, fn) { + listeners[type] = fn; + }, + removeEventListener() {}, + querySelector: (selector) => selector.includes('"start"') ? buttons.start : + selector.includes('"stop"') ? buttons.stop : stats, + }; + const hook = { + ...Duplex, + el: { parentElement: el, dataset }, + handleEvent(name, fn) { + handlers[name] = fn; + }, + pushEvent(name, payload, reply) { + pushes.push({ name, payload, reply }); + }, + }; + hook.mounted(); + mounted.push(hook); + const click = (action) => + listeners.click({ target: { closest: () => buttons[action] } }); + const sent = (name) => pushes.filter((push) => push.name === name); + return { hook, handlers, pushes, click, sent, stats, buttons }; +} + +// Starts a conversation: click, microphone grant, server reply, model handshake. +async function connect(generation = 1, dataset = {}) { + const view = mount(dataset); + grantMicrophone(); + view.click("start"); + await tick(); + view.sent("call_start")[0].reply({ ok: true, generation }); + view.handlers.call_ready({ generation }); + return view; +} + +// 80 ms of capture at 48 kHz, in 128-sample worklet blocks. +function speak(blocks = 30, value = 0.5) { + for (let i = 0; i < blocks; i++) { + microphone.node.port.onmessage({ data: new Float32Array(128).fill(value) }); + } +} + +const pcm = (samples) => Buffer.alloc(samples * 2).toString("base64"); + +test("resampler output does not depend on block boundaries", () => { + const input = Float32Array.from({ length: 4_410 }, (_, i) => Math.sin(i / 7)); + const whole = new StreamResampler(44_100, 24_000).push(input); + const split = new StreamResampler(44_100, 24_000); + const parts = []; + for (let i = 0; i < input.length; i += 128) parts.push(...split.push(input.subarray(i, i + 128))); + assert.equal(whole.length, 2_400); + assert.equal(parts.length, whole.length); + parts.forEach((value, i) => assert.ok(Math.abs(value - whole[i]) < 1e-5)); + assert.throws(() => new StreamResampler(16_000, 24_000), /below 24000 Hz/); +}); + +test("capture sends 80 ms 24 kHz chunks only after the model handshake", async () => { + const view = mount(); + grantMicrophone(); + view.click("start"); + await tick(); + speak(60); + assert.equal(view.sent("call_audio").length, 0); + view.sent("call_start")[0].reply({ ok: true, generation: 7 }); + speak(60); + assert.equal(view.sent("call_audio").length, 0); + view.handlers.call_ready({ generation: 7 }); + speak(30); + const [chunk] = view.sent("call_audio"); + assert.equal(chunk.payload.generation, 7); + const bytes = Buffer.from(chunk.payload.pcm, "base64"); + assert.equal(bytes.length, CHUNK_SAMPLES * 2); + assert.equal(bytes.readInt16LE(0), Math.round(0.5 * 0x7fff - 0.5)); +}); + +test("input waits for acknowledgements and drops the oldest chunks past the queue limit", async () => { + const view = await connect(); + speak(30 * (MAX_IN_FLIGHT + MAX_PENDING + 3)); + const audio = () => view.sent("call_audio"); + assert.equal(audio().length, MAX_IN_FLIGHT); + audio()[0].reply({ ok: true }); + assert.equal(audio().length, MAX_IN_FLIGHT + 1); + audio()[1].reply({ ok: false, error: "overloaded" }); + assert.equal(audio().length, MAX_IN_FLIGHT + 2); + view.hook.draw(); + assert.match(view.stats.textContent, /Sent 1 · dropped 4 input chunks/); +}); + +test("capture starts when the model handshake arrives before the start reply", async () => { + const view = mount(); + grantMicrophone(); + view.click("start"); + await tick(); + view.handlers.call_ready({ generation: 9 }); + view.sent("call_start")[0].reply({ ok: true, generation: 9 }); + speak(30); + assert.equal(view.sent("call_audio").length, 1); + assert.equal(view.sent("call_audio")[0].payload.generation, 9); +}); + +test("model audio plays while the microphone keeps sending", async () => { + const view = await connect(); + const [context] = contexts.slice(-1); + view.handlers.call_play({ generation: 1, pcm: pcm(1_920), rate: 24_000 }); + view.handlers.call_play({ generation: 1, pcm: pcm(1_920), rate: 24_000 }); + speak(30); + view.sent("call_audio")[0].reply({ ok: true }); + speak(30); + view.handlers.call_play({ generation: 1, pcm: pcm(1_920), rate: 24_000 }); + assert.equal(view.sent("call_audio").length, 2); + assert.deepEqual( + context.sources.map((source) => [Number(source.at.toFixed(2)), Boolean(source.stopped)]), + [ + [0.04, false], + [0.12, false], + [0.2, false], + ], + ); +}); + +test("playback drops audio beyond the queue limit and audio of another generation", async () => { + const view = await connect(2); + const [context] = contexts.slice(-1); + for (let i = 0; i < 20; i++) { + view.handlers.call_play({ generation: 2, pcm: pcm(1_920), rate: 24_000 }); + } + const accepted = context.sources.length; + assert.ok(accepted > 1 && accepted < 20); + assert.ok(context.sources.every((source) => source.at <= MAX_PLAYBACK_AHEAD)); + view.handlers.call_play({ generation: 1, pcm: pcm(1_920), rate: 24_000 }); + assert.equal(context.sources.length, accepted); + context.currentTime = 0.5; + view.handlers.call_play({ generation: 2, pcm: pcm(1_920), rate: 24_000 }); + assert.equal(context.sources.length, accepted + 1); +}); + +test("stop releases the microphone, playback and context and ignores later events", async () => { + const view = await connect(3); + const [context] = contexts.slice(-1); + view.handlers.call_play({ generation: 3, pcm: pcm(1_920), rate: 24_000 }); + view.click("stop"); + assert.deepEqual(view.sent("call_stop").at(-1).payload, { generation: 3 }); + assert.ok(microphone.track.stopped); + assert.ok(microphone.node.disconnected); + assert.ok(context.sources.every((source) => source.stopped)); + assert.equal(context.state, "closed"); + view.handlers.call_play({ generation: 3, pcm: pcm(1_920), rate: 24_000 }); + assert.equal(context.sources.length, 1); +}); + +test("server stop, disconnect and a stop during startup all release the call", async () => { + const stopped = await connect(4); + stopped.handlers.call_stopped({ generation: 3 }); + assert.ok(!microphone.track.stopped); + stopped.handlers.call_stopped({ generation: 4 }); + assert.ok(microphone.track.stopped); + + const view = await connect(6); + view.hook.disconnected(); + assert.ok(microphone.track.stopped); + + const early = mount(); + grantMicrophone(); + early.click("start"); + assert.equal(early.buttons.stop.disabled, false); + await tick(); + early.click("stop"); + assert.equal(early.buttons.start.disabled, false); + assert.ok(microphone.track.stopped); + early.sent("call_start")[0].reply({ ok: true, generation: 8 }); + assert.deepEqual(early.sent("call_stop").at(-1).payload, { generation: 8 }); +}); + +test("microphone denial and device loss report a failure and release capture", async () => { + const denied = mount(); + microphone = { + grant: async () => { + throw new Error("Permission denied"); + }, + }; + denied.click("start"); + await tick(); + assert.deepEqual(denied.sent("call_failed").at(-1).payload, { message: "Permission denied" }); + assert.equal(contexts.at(-1).state, "closed"); + assert.equal(denied.sent("call_start").length, 0); + + const lost = await connect(9); + microphone.track.onended(); + assert.deepEqual(lost.sent("call_failed").at(-1).payload, { message: "Microphone disconnected" }); + assert.ok(microphone.track.stopped); +}); + +test("a microphone request that does not finish times out and releases a late grant", async (t) => { + t.mock.timers.enable({ apis: ["setTimeout"] }); + const view = mount(); + const mic = grantMicrophone(); + let grant; + mic.grant = () => new Promise((resolve) => { grant = resolve; }); + view.click("start"); + t.mock.timers.tick(20_000); + assert.equal(view.hook.call, null); + assert.match(view.sent("call_failed").at(-1).payload.message, /microphone/i); + grant({ getTracks: () => [mic.track] }); + await tick(); + assert.ok(mic.track.stopped); + assert.equal(view.sent("call_start").length, 0); +}); + +test("user speech flushes queued reply audio, reports heard time and keeps the microphone", async () => { + const view = await connect(5, { playbackAhead: "60" }); + const [context] = contexts.slice(-1); + context.outputLatency = 0.02; + for (let i = 0; i < 3; i++) { + view.handlers.call_play({ generation: 5, output: "item_1", pcm: pcm(1_920), rate: 24_000 }); + } + // Chunks at 0.04, 0.12 and 0.2 s. At 0.1 s minus 20 ms latency, 40 ms were heard. + context.currentTime = 0.1; + view.handlers.call_flush({ generation: 4 }); + assert.equal(view.sent("call_played").length, 0); + view.handlers.call_flush({ generation: 5 }); + + assert.ok(context.sources.every((source) => source.stopped)); + assert.deepEqual(view.sent("call_played").at(-1).payload, { + generation: 5, + output: "item_1", + ms: 40, + }); + assert.ok(!microphone.track.stopped); + assert.ok(!microphone.node.disconnected); + speak(30); + assert.equal(view.sent("call_audio").length, 1); + + // Late audio of the cut reply is dropped; the next reply plays at once. + view.handlers.call_play({ generation: 5, output: "item_1", pcm: pcm(1_920), rate: 24_000 }); + assert.equal(context.sources.length, 3); + view.handlers.call_play({ generation: 5, output: "item_2", pcm: pcm(1_920), rate: 24_000 }); + assert.equal(context.sources.length, 4); + assert.equal(Number(context.sources[3].at.toFixed(2)), 0.14); +}); + +test("reply audio past the playback limit drops the rest of that reply", async () => { + const view = await connect(6, { playbackAhead: "0.2" }); + const [context] = contexts.slice(-1); + for (let i = 0; i < 4; i++) { + view.handlers.call_play({ generation: 6, output: "item_1", pcm: pcm(1_920), rate: 24_000 }); + } + // Chunks start at 0.04, 0.12 and 0.2 s; the fourth would start past 0.2 s. + assert.equal(context.sources.length, 3); + // Room is free again, but the reply has a gap; its heard time must stay a prefix. + context.currentTime = 0.5; + view.handlers.call_play({ generation: 6, output: "item_1", pcm: pcm(1_920), rate: 24_000 }); + assert.equal(context.sources.length, 3); + view.handlers.call_flush({ generation: 6 }); + assert.equal(view.sent("call_played").at(-1).payload.ms, 240); + view.handlers.call_play({ generation: 6, output: "item_2", pcm: pcm(1_920), rate: 24_000 }); + assert.equal(context.sources.length, 4); +}); + +test("a fully played reply at a large clock time keeps its provider history", async () => { + const view = await connect(7, { playbackAhead: "60" }); + const context = contexts.at(-1); + context.currentTime = 123.46; + for (let i = 0; i < 50; i++) { + view.handlers.call_play({ generation: 7, output: "complete", pcm: pcm(2_400), rate: 24_000 }); + } + context.currentTime = 130; + view.handlers.call_flush({ generation: 7 }); + assert.equal(view.sent("call_played").length, 0); + assert.equal(microphone.track.stopped, undefined); +}); diff --git a/examples/chat/lib/chat/setup.ex b/examples/chat/lib/chat/setup.ex index d740a7e..f53f077 100644 --- a/examples/chat/lib/chat/setup.ex +++ b/examples/chat/lib/chat/setup.ex @@ -6,8 +6,9 @@ defmodule Chat.Setup do {"demo", "Synthetic demo"}, {"local", "Local Apple MLX"}, {"remote", "Deepgram → Chat HTTP → TTS"}, - {"openai", "OpenAI speech-to-speech"}, - {"gemini", "Gemini speech-to-speech"} + {"openai", "OpenAI live conversation"}, + {"gemini", "Gemini speech-to-speech"}, + {"moshi", "Local Moshi full duplex"} ] @languages ~w(en es fr de ro) @voices ~w(marin cedar) @@ -18,21 +19,38 @@ defmodule Chat.Setup do def voices, do: @voices def tts_providers, do: @tts_providers - def defaults, - do: %{ - "mode" => if(Chat.Engine.native?(), do: "local", else: "demo"), + @moshi_endpoint "ws://127.0.0.1:8998/api/chat" + + @doc "Startup settings. `CHAT_MODE` selects the startup mode." + def defaults(env \\ &System.get_env/1) do + mode = env.("CHAT_MODE") + + %{ + "mode" => + if(Enum.any?(@modes, &(elem(&1, 0) == mode)), + do: mode, + else: if(Chat.Engine.native?(), do: "local", else: "demo") + ), "language" => "en", "voice" => "marin", "tts" => "elevenlabs" } + end def requirements("remote"), do: ["DEEPGRAM_API_KEY", "CHAT_HTTP_ENDPOINT", "CHAT_HTTP_MODEL"] def requirements("openai"), do: ["OPENAI_API_KEY", "OPENAI_REALTIME_MODEL"] def requirements("gemini"), do: ["GEMINI_API_KEY", "GEMINI_LIVE_MODEL"] def requirements(_), do: [] - def rate(%{"mode" => "openai"}), do: 24_000 + def rate(%{"mode" => mode}) when mode in ["openai", "moshi"], do: 24_000 def rate(_), do: 16_000 - def speech?(settings), do: settings["mode"] in ["openai", "gemini"] + @doc "Turn-based speech-to-speech: one recorded utterance per turn." + def speech?(settings), do: settings["mode"] == "gemini" + + @doc """ + Always-on modes use `AudioFlow.Duplex` instead of a turn-based session: the + microphone stays open from Start to Stop. + """ + def duplex?(settings), do: settings["mode"] in ["moshi", "openai"] def options(s, env \\ &System.get_env/1) do mode = s["mode"] @@ -45,12 +63,18 @@ defmodule Chat.Setup do not supported?(s) -> {:error, "Unsupported language, voice or TTS"} - mode == "local" and not Chat.Engine.native?() -> - {:error, "Restart with CHAT_PROFILE=native on Apple Silicon"} + unavailable = unavailable(mode) -> + {:error, unavailable} missing != [] -> {:error, "Missing server environment: " <> Enum.join(missing, ", ")} + mode == "moshi" -> + moshi(env.("AUDIOFLOW_MOSHI_ENDPOINT")) + + mode == "openai" -> + openai(s, env) + true -> {:ok, build(s, env) ++ [timeout_ms: 120_000, max_events: 4096, max_input_bytes: 1_440_000]} @@ -70,6 +94,57 @@ defmodule Chat.Setup do s["tts"] in @tts_providers end + defp unavailable("local"), + do: unless(Chat.Engine.native?(), do: "Restart with CHAT_PROFILE=native on Apple Silicon") + + defp unavailable("moshi"), + do: + unless(Code.ensure_loaded?(AudioFlow.Duplex.Moshi), + do: "Restart with AUDIOFLOW_MEDIA=1 for full duplex Moshi" + ) + + defp unavailable(_mode), do: nil + + # The endpoint comes only from the server environment, never from the browser. + defp moshi(endpoint) when endpoint in [nil, ""], do: moshi(@moshi_endpoint) + + defp moshi(endpoint) do + if websocket?(endpoint), + do: {:ok, [duplex: {AudioFlow.Duplex.Moshi, [endpoint: endpoint]}]}, + else: + {:error, + "AUDIOFLOW_MOSHI_ENDPOINT must be a ws:// or wss:// URL without user information"} + end + + # The optional endpoint (a proxy, for example) comes only from the server environment. + defp openai(s, env) do + options = [ + model: env.("OPENAI_REALTIME_MODEL"), + api_key: key(env, "OPENAI_API_KEY"), + voice: s["voice"] + ] + + case env.("OPENAI_REALTIME_ENDPOINT") do + endpoint when endpoint in [nil, ""] -> + {:ok, [duplex: {AudioFlow.Duplex.OpenAIRealtime, options}]} + + endpoint -> + if websocket?(endpoint), + do: {:ok, [duplex: {AudioFlow.Duplex.OpenAIRealtime, options ++ [endpoint: endpoint]}]}, + else: + {:error, + "OPENAI_REALTIME_ENDPOINT must be a ws:// or wss:// URL without user information"} + end + end + + defp websocket?(endpoint) do + match?( + %URI{scheme: scheme, host: host, userinfo: nil} + when scheme in ["ws", "wss"] and host not in [nil, ""], + URI.parse(endpoint) + ) + end + defp key(env, name), do: fn -> env.(name) end defp build(%{"mode" => "demo"}, _), do: Adapters.Demo.options() ++ [history: true] defp build(%{"mode" => "local"}, _), do: Chat.Stage.session_options() @@ -117,17 +192,6 @@ defmodule Chat.Setup do ] end - defp build(%{"mode" => "openai"} = s, env), - do: [ - speech_to_speech: - {Adapters.OpenAIRealtime, - [ - model: env.("OPENAI_REALTIME_MODEL"), - api_key: key(env, "OPENAI_API_KEY"), - voice: s["voice"] - ]} - ] - defp build(%{"mode" => "gemini"}, env), do: [ speech_to_speech: diff --git a/examples/chat/lib/chat_web/live/chat_live.ex b/examples/chat/lib/chat_web/live/chat_live.ex index f6dcdf3..99ea642 100644 --- a/examples/chat/lib/chat_web/live/chat_live.ex +++ b/examples/chat/lib/chat_web/live/chat_live.ex @@ -8,10 +8,20 @@ defmodule ChatWeb.ChatLive do message shows that partial text. When recording stops, the complete audio is one session turn. Reply audio is pushed to the browser as it arrives, and the complete reply is kept as a WAV file for replay. + + The always-on modes (local Moshi and OpenAI live conversation) use + `AudioFlow.Duplex`. From Start to Stop the browser sends 80 ms chunks of + 24 kHz PCM continuously, and the model audio and text come back at the same + time. Moshi has no turns. OpenAI detects speech itself: when the user starts + to speak, the browser flushes queued reply audio (the microphone stays open) + and reports how much of the reply played, so the provider history keeps only + that part. Each conversation has a generation number; events from an earlier + generation are ignored. """ use Phoenix.LiveView alias AudioFlow.Audio + alias AudioFlow.Duplex alias AudioFlow.Recording.Store alias AudioFlow.Text alias Chat.Catalog @@ -28,27 +38,39 @@ defmodule ChatWeb.ChatLive do # Start a partial transcription after this much new audio (0.5 s). @partial_bytes 16_000 + # One duplex input chunk: 80 ms of 24 kHz mono s16le PCM. + @call_chunk_bytes 3_840 + # Model text after this much silence starts a new message. + @call_segment_ms 1_500 + @call_max_messages 200 + @call_max_message_bytes 4_000 + # User utterances that wait for their transcript. + @call_max_pending 16 + # Seconds of model audio that the browser queues ahead of playback. + @playback_ahead %{"moshi" => 1, "openai" => 60} @impl true def mount(_params, _session, socket) do - session = + settings = Setup.defaults() + + {session, setup_error} = if connected?(socket) do Phoenix.PubSub.subscribe(Chat.PubSub, Chat.Engine.topic()) Process.send_after(self(), :retention, 60_000) - - {:ok, session} = - AudioFlow.start_session( - elem(Setup.options(Setup.defaults()), 1) ++ [output: {Chat.Output, self()}] - ) - - session + open_session(settings) + else + {nil, nil} end {:ok, assign(socket, session: session, - settings: Setup.defaults(), - setup_error: nil, + settings: settings, + setup_error: setup_error, + call: nil, + call_status: "idle", + call_error: nil, + generation: 0, capture: nil, artifacts: [], playback_turn: nil, @@ -71,7 +93,9 @@ defmodule ChatWeb.ChatLive do @impl true def handle_event("send", %{"text" => text}, socket) do - case if(Setup.speech?(socket.assigns.settings), do: "", else: String.trim(text)) do + settings = socket.assigns.settings + + case if(Setup.speech?(settings) or Setup.duplex?(settings), do: "", else: String.trim(text)) do "" -> {:reply, %{ok: false}, socket} @@ -81,6 +105,10 @@ defmodule ChatWeb.ChatLive do end end + def handle_event(event, _params, %{assigns: %{session: nil}} = socket) + when event in ["recording", "pause", "resume", "capture"], + do: {:noreply, assign(socket, setup_error: "Not available without a turn-based session.")} + def handle_event("recording", _params, socket) do socket = cancel(socket) |> add_message("user", "", pending: true, live: true) id = List.last(socket.assigns.messages).id @@ -157,9 +185,73 @@ defmodule ChatWeb.ChatLive do def handle_event("new_chat", _params, socket) do socket = cancel(socket) if socket.assigns.session, do: AudioFlow.clear_history(socket.assigns.session) - {:noreply, assign(socket, messages: [])} + call = socket.assigns.call && %{socket.assigns.call | reply_id: nil} + {:noreply, assign(socket, messages: [], call: call)} + end + + def handle_event("call_start", _params, socket) do + cond do + not Setup.duplex?(socket.assigns.settings) -> + {:reply, %{ok: false, error: "Select the full duplex pipeline first."}, socket} + + socket.assigns.call -> + {:reply, %{ok: false, error: "A conversation is already active."}, socket} + + true -> + # The adapter and endpoint come from the server settings, not from params. + case Setup.options(socket.assigns.settings) do + {:ok, [duplex: adapter]} -> + start_call(socket, adapter, socket.assigns.settings["mode"] == "openai") + + {:error, message} -> + {:reply, %{ok: false, error: message}, call_error(socket, message)} + end + end + end + + def handle_event( + "call_audio", + %{"generation" => generation, "pcm" => pcm}, + %{assigns: %{call: %{generation: generation, ready: true} = call}} = socket + ) + when is_binary(pcm) do + with true <- byte_size(pcm) <= div(@call_chunk_bytes * 4, 3) + 4, + {:ok, <<_::binary-size(@call_chunk_bytes)>> = data} <- Base.decode64(pcm), + :ok <- Duplex.push(call.pid, %Audio{data: data, sample_rate: 24_000}) do + {:reply, %{ok: true}, socket} + else + {:error, reason} -> {:reply, %{ok: false, error: describe(reason)}, socket} + _ -> {:reply, %{ok: false, error: "invalid_chunk"}, socket} + end end + def handle_event("call_audio", _params, socket), + do: {:reply, %{ok: false, error: "stale"}, socket} + + def handle_event("call_stop", %{"generation" => generation}, socket) do + case socket.assigns.call do + %{generation: ^generation} -> {:noreply, stop_call(socket, "idle")} + _ -> {:noreply, socket} + end + end + + # Playback progress of the reply audio that a flush cut. The adapter caps it + # to the received audio and ignores reports for any other reply. + def handle_event( + "call_played", + %{"generation" => generation, "output" => output, "ms" => ms}, + %{assigns: %{call: %{generation: generation, ready: true} = call}} = socket + ) + when is_binary(output) and byte_size(output) <= 256 and is_integer(ms) and ms >= 0 do + _ = Duplex.control(call.pid, {:played, output, ms}) + {:noreply, socket} + end + + def handle_event("call_played", _params, socket), do: {:noreply, socket} + + def handle_event("call_failed", %{"message" => message}, socket) when is_binary(message), + do: {:noreply, call_error(socket, "Microphone error: " <> String.slice(message, 0, 200))} + def handle_event("select_model", %{"_target" => [field]} = params, socket) when field in ["stt", "llm", "voice"] do result = Chat.Engine.select(String.to_existing_atom(field), params[field]) @@ -176,17 +268,18 @@ defmodule ChatWeb.ChatLive do {:error, message} -> {:noreply, assign(socket, setup_error: message)} - {:ok, options} -> - if socket.assigns.recording || socket.assigns.turn do + {:ok, _options} -> + if socket.assigns.recording || socket.assigns.turn || socket.assigns.call do {:noreply, assign(socket, - setup_error: "Stop the current turn/recording before changing settings." + setup_error: + "Stop the current turn, recording or conversation before changing settings." )} else socket = cancel(socket) - AudioFlow.stop_session(socket.assigns.session) + if socket.assigns.session, do: AudioFlow.stop_session(socket.assigns.session) Chat.Capture.close(socket.assigns.capture) - {:ok, session} = AudioFlow.start_session(options ++ [output: {Chat.Output, self()}]) + {session, setup_error} = open_session(settings) {:noreply, assign(socket, @@ -195,7 +288,9 @@ defmodule ChatWeb.ChatLive do messages: [], capture: nil, artifacts: [], - setup_error: nil + setup_error: setup_error, + call_status: "idle", + call_error: nil )} end end @@ -270,8 +365,250 @@ defmodule ChatWeb.ChatLive do end end + defp open_session(settings) do + case Setup.options(settings) do + {:ok, [duplex: _]} -> + {nil, nil} + + {:ok, options} -> + {:ok, session} = AudioFlow.start_session(options ++ [output: {Chat.Output, self()}]) + {session, nil} + + {:error, message} -> + {nil, message} + end + end + + # `turns`: the model marks user speech and replies (OpenAI). Without turns + # (Moshi), a pause in the model text starts a new message. + defp start_call(socket, adapter, turns) do + generation = socket.assigns.generation + 1 + socket = assign(socket, generation: generation) + + case start_duplex(adapter) do + {:ok, pid} -> + call = %{ + pid: pid, + monitor: Process.monitor(pid), + generation: generation, + ready: false, + turns: turns, + reply_id: nil, + reply_response: nil, + text_at: nil, + output: nil, + users: [] + } + + {:reply, %{ok: true, generation: generation}, + assign(socket, call: call, call_status: "connecting", call_error: nil)} + + {:error, reason} -> + message = "Cannot start the conversation: " <> describe(reason) + {:reply, %{ok: false, error: message}, call_error(socket, message)} + end + end + + # A model failure must not stop the LiveView. Duplex monitors this owner. + defp start_duplex(adapter) do + limits = + if elem(adapter, 0) == Duplex.OpenAIRealtime, + do: [max_response_bytes: 256 * 1024 * 1024], + else: [] + + Duplex.start([owner: self(), adapter: adapter] ++ limits) + rescue + error in ArgumentError -> {:error, Exception.message(error)} + end + + defp call_event(%{assigns: %{call: %{turns: true} = call}} = socket, :ready) do + socket + |> assign(call: %{call | ready: true}, call_status: "live") + |> push_event("call_ready", %{generation: call.generation}) + end + + defp call_event(socket, :ready) do + %{call: call} = socket.assigns + socket = add_message(socket, "assistant", "", pending: true, live: true) + + socket + |> assign( + call: %{call | ready: true, reply_id: List.last(socket.assigns.messages).id}, + call_status: "live" + ) + |> push_event("call_ready", %{generation: call.generation}) + end + + defp call_event(socket, {:audio, %Audio{data: data, sample_rate: rate}}) do + %{call: call} = socket.assigns + + push_event(socket, "call_play", %{ + generation: call.generation, + output: call.output, + pcm: Base.encode64(data), + rate: rate + }) + end + + defp call_event(socket, {:text, text}), do: call_text(socket, text) + + # The user starts to speak: queued reply audio is obsolete. The browser + # flushes it and keeps the microphone open. + defp call_event(socket, {:speech_started, item}) do + %{call: call} = socket.assigns + socket = add_message(socket, "user", "", pending: true, live: true) + + pending = call.users ++ [{item, List.last(socket.assigns.messages).id}] + {removed, users} = Enum.split(pending, max(length(pending) - @call_max_pending, 0)) + socket = Enum.reduce(removed, socket, fn {_, id}, socket -> settle(socket, id) end) + + socket + |> assign(call: %{call | output: nil, users: users}) + |> push_event("call_flush", %{generation: call.generation}) + |> trim_messages() + end + + defp call_event(socket, {:transcript, item, text}) do + %{call: call} = socket.assigns + + case List.keytake(call.users, item, 0) do + {{_, id}, users} -> socket |> assign(call: %{call | users: users}) |> transcript(id, text) + nil -> socket + end + end + + defp call_event(socket, {:response, id, :created}) do + %{call: call} = socket.assigns + socket = if call.reply_id, do: settle(socket, call.reply_id), else: socket + socket = add_message(socket, "assistant", "", pending: true) + + assign(socket, + call: %{call | reply_id: List.last(socket.assigns.messages).id, reply_response: id} + ) + |> trim_messages() + end + + defp call_event( + %{assigns: %{call: %{reply_response: id} = call}} = socket, + {:response, id, status} + ) do + socket + |> update_message(call.reply_id, &%{&1 | note: reply_note(status, &1.text)}) + |> settle(call.reply_id) + |> assign(call: %{call | reply_id: nil, reply_response: nil}) + end + + defp call_event(socket, {:response, _id, _status}), do: socket + + defp call_event(socket, {:output, item}), + do: assign(socket, call: %{socket.assigns.call | output: item}) + + defp call_event(socket, {:error, reason}), + do: call_error(socket, "Conversation error: " <> describe(reason)) + + defp call_event(socket, :closed), do: stop_call(socket, "closed") + defp call_event(socket, _event), do: socket + + defp transcript(socket, id, :failed), + do: update_message(socket, id, &%{&1 | pending: false, live: false, note: "Not transcribed."}) + + defp transcript(socket, id, text) do + case String.trim(text) do + "" -> remove_message(socket, id) + text -> update_message(socket, id, &%{&1 | text: text, pending: false, live: false}) + end + end + + # A reply cancelled before any text gets no note, so `settle/2` removes it. + defp reply_note(:cancelled, ""), do: nil + defp reply_note(:cancelled, _text), do: "Interrupted." + defp reply_note(:incomplete, _text), do: "Reply incomplete." + defp reply_note(:failed, _text), do: "Reply failed." + defp reply_note(:completed, _text), do: nil + + defp call_text(%{assigns: %{call: %{turns: true, reply_id: id}}} = socket, text) + when id != nil, + do: update_message(socket, id, &%{&1 | text: &1.text <> text, pending: false}) + + defp call_text(%{assigns: %{call: %{turns: true}}} = socket, _text), do: socket + + # Moshi does not mark turns. A pause in the model text starts a new message, + # and the conversation keeps only the latest messages. + defp call_text(socket, text) do + %{call: call, messages: messages} = socket.assigns + now = System.monotonic_time(:millisecond) + current = call.reply_id && Enum.find(messages, &(&1.id == call.reply_id)) + + socket = + if current == nil or (call.text_at != nil and now - call.text_at >= @call_segment_ms) or + byte_size(current.text) >= @call_max_message_bytes do + socket = if current, do: settle(socket, current.id), else: socket + socket = add_message(socket, "assistant", "") + assign(socket, call: %{call | reply_id: List.last(socket.assigns.messages).id}) + else + socket + end + + %{call: call} = socket.assigns + + socket + |> update_message(call.reply_id, fn message -> + text = if message.text == "", do: String.trim_leading(text), else: text + %{message | text: message.text <> text, pending: false, live: false} + end) + |> trim_messages() + |> assign(call: %{call | text_at: now}) + end + + defp trim_messages(socket), + do: assign(socket, messages: Enum.take(socket.assigns.messages, -@call_max_messages)) + + # A message without text or note is removed; otherwise it stops waiting. + defp settle(socket, id) do + case Enum.find(socket.assigns.messages, &(&1.id == id)) do + %{text: "", note: nil} -> remove_message(socket, id) + %{} -> update_message(socket, id, &%{&1 | pending: false, live: false}) + nil -> socket + end + end + + defp call_error(socket, message), do: stop_call(socket, "error", message) + + # Stops the conversation process and tells the browser to release the + # microphone and the queued playback of this generation. + defp stop_call(socket, status, error \\ nil) do + socket = + case socket.assigns.call do + nil -> + socket + + call -> + Process.demonitor(call.monitor, [:flush]) + + try do + Duplex.stop(call.pid) + catch + :exit, _ -> :ok + end + + call.users + |> Enum.reduce(settle(socket, call.reply_id), fn {_, id}, socket -> + settle(socket, id) + end) + |> push_event("call_stopped", %{generation: call.generation}) + end + + assign(socket, call: nil, call_status: status, call_error: error) + end + + defp describe({:remote_error, code}) when is_binary(code), do: "provider error " <> code + defp describe(reason) when is_binary(reason), do: reason + defp describe(reason) when is_atom(reason), do: Atom.to_string(reason) + defp describe(reason), do: inspect(reason) + @impl true def terminate(_, socket) do + stop_call(socket, "closed") Chat.Capture.close(socket.assigns.capture) if socket.assigns.session, do: AudioFlow.stop_session(socket.assigns.session) :ok @@ -332,6 +669,18 @@ defmodule ChatWeb.ChatLive do do: {:noreply, capture_event(socket, event)} def handle_info({AudioFlow, _, _, _}, socket), do: {:noreply, socket} + + def handle_info({Duplex, pid, event}, %{assigns: %{call: %{pid: pid}}} = socket), + do: {:noreply, call_event(socket, event)} + + def handle_info({Duplex, _, _}, socket), do: {:noreply, socket} + + def handle_info( + {:DOWN, ref, :process, _, reason}, + %{assigns: %{call: %{monitor: ref}}} = socket + ), + do: {:noreply, call_error(socket, "Conversation stopped: " <> describe(reason))} + def handle_info({:models, models}, socket), do: {:noreply, assign(socket, models: models)} def handle_info({ref, result}, %{assigns: %{recording: %{task: ref} = recording}} = socket) do @@ -409,16 +758,9 @@ defmodule ChatWeb.ChatLive do ) } - note = - if metrics.first_text_us, - do: "First text #{ms(metrics.first_text_us)}, first audio #{ms(metrics.first_audio_us)}", - else: "No speech was recognized." - finish(socket, audio: audio, - note: - note <> - " · Transcript #{ms(metrics[:first_transcript_us])} · Total #{ms(metrics[:duration_us])} · #{metrics[:events]} events · played #{socket.assigns.played_ms} ms" + note: if(metrics.first_text_us, do: nil, else: "No speech was recognized.") ) end @@ -501,8 +843,7 @@ defmodule ChatWeb.ChatLive do socket = if socket.assigns.turn, - do: - finish(socket, note: "Stopped; history keeps only acknowledged complete speech chunks."), + do: finish(socket, note: "Stopped."), else: socket socket |> assign(candidate: nil, control: nil, paused: false) |> push_event("flush", %{}) @@ -554,9 +895,6 @@ defmodule ChatWeb.ChatLive do end end - defp ms(nil), do: "none" - defp ms(us), do: "#{div(us, 1000)} ms" - defp system_memory_gb do case System.cmd("sysctl", ["-n", "hw.memsize"], stderr_to_stdout: true) do {bytes, 0} -> String.to_integer(String.trim(bytes)) / 1_073_741_824 @@ -579,6 +917,16 @@ defmodule ChatWeb.ChatLive do else: "The largest combinations may not fit in memory." end + defp call_label("connecting"), do: "Connecting…" + defp call_label("live"), do: "Live · microphone on" + defp call_label("closed"), do: "Conversation ended" + defp call_label("error"), do: "Stopped by an error" + defp call_label(_), do: "Not connected" + + defp call_variant("live"), do: "default" + defp call_variant("error"), do: "destructive" + defp call_variant(_), do: "secondary" + defp gb(value), do: :erlang.float_to_binary(value * 1.0, decimals: 1) @impl true @@ -587,91 +935,74 @@ defmodule ChatWeb.ChatLive do assign(assigns, stt_models: Catalog.stt(), llm_models: Catalog.llm(), - voices: Catalog.voices() + voices: Catalog.voices(), + duplex: Setup.duplex?(assigns.settings), + playback_ahead: @playback_ahead ) ~H"""
-
-

AudioFlow chat

-

- Type a message, or record one with the microphone. -

-
- New chat +

AudioFlow

+ + {if @duplex, do: "Clear text", else: "New chat"} +
-
-
- - - - - -
-

{@setup_error}

-

- Active: {@settings["mode"]} · Input PCM {Chat.Setup.rate(@settings)} Hz mono · Playback acknowledged: {@played_ms} ms -

-

- Synthetic demo: fixed transcript, echoed text, silent PCM. No inference. -

-

- Microphone only; fresh provider connection each turn, no history replay. No text/audio alignment or native history truncation is claimed. Language and Gemini voice use provider defaults. -

-

- Remote chain requires DEEPGRAM_API_KEY, CHAT_HTTP_ENDPOINT, CHAT_HTTP_MODEL and ELEVENLABS_API_KEY / ELEVENLABS_VOICE_ID or CARTESIA_API_KEY / CARTESIA_VOICE_ID. Optional CHAT_HTTP_API_KEY. Speech-to-speech requires OPENAI_API_KEY / OPENAI_REALTIME_MODEL or GEMINI_API_KEY / GEMINI_LIVE_MODEL. Configure these on the server. -

- -

- Opt-in text-only JSON: all content replaced with [REDACTED], no PCM. Limit 20 turns, 1 hour, 128 KB buffered per turn. Deleted on disconnect; retention checked every minute and on access. -

-
- {id} - -
-
- +
+ + + + + + Apply + +
+
-

- - ≈ {gb(@models.memory_gb)} GB of model weights{if @system_memory_gb, - do: " · #{gb(@system_memory_gb)} GB memory"} - - {fit_text(@system_memory_gb)} -

+
+
+
+ + Start conversation + + + Stop + +
+ + {call_label(@call_status)} +
+ +
+ Diagnostics + +
+
+
+ Settings +
+

+ ≈ {gb(@models.memory_gb)} GB of model weights{if @system_memory_gb, + do: " · #{gb(@system_memory_gb)} GB memory"}. {fit_text(@system_memory_gb)} +

+
+ + {if @capture, do: "Delete saved transcripts", else: "Save redacted transcripts"} + + + Text only, with all words replaced by [REDACTED]. Deleted when you leave. + +
+
+ {id} + + Download + + + Delete + +
+
+

No messages yet. @@ -752,13 +1132,20 @@ defmodule ChatWeb.ChatLive do -

- - - - {if @paused, do: "Web Audio suspended", else: "Playback running or awaiting endpoint"} -
- +
+ Diagnostics +
+ + Pause playback + + + Resume + + Confirm stop + Playback acknowledged: {@played_ms} ms +
+
+ "_build" + {true, true} -> "_build/native_media" + {false, true} -> "_build/demo_media" + {false, false} -> "_build/demo" + end) # Set LIVE_SHADCN_PATH to a live_shadcn checkout to use local packages. @live_shadcn "3ddada48f623d72260360acf115e5d9b5eacd1cf" @@ -17,6 +27,7 @@ defmodule Chat.MixProject do app: :chat, version: "0.1.0", elixir: "~> 1.18", + build_path: @build_path, listeners: [Phoenix.CodeReloader], elixirc_paths: ["lib"] ++ if(@native_profile, do: ["native"], else: []), deps: deps(), diff --git a/examples/chat/mix.lock b/examples/chat/mix.lock index 13e0ca1..ed1039f 100644 --- a/examples/chat/mix.lock +++ b/examples/chat/mix.lock @@ -2,15 +2,22 @@ "abnf_parsec": {:hex, :abnf_parsec, "2.1.0", "c4e88d5d089f1698297c0daced12be1fb404e6e577ecf261313ebba5477941f9", [:mix], [{:nimble_parsec, "~> 1.4", [hex: :nimble_parsec, repo: "hexpm", optional: false]}], "hexpm", "e0ed6290c7cc7e5020c006d1003520390c9bdd20f7c3f776bd49bfe3c5cd362a"}, "axon": {:hex, :axon, "0.9.0", "882be41d4d5c8f6d9b09682147ddac186324b927beb3aa5c17536f6684a76753", [:mix], [{:kino, "~> 0.19", [hex: :kino, repo: "hexpm", optional: true]}, {:kino_vega_lite, "~> 0.1.7", [hex: :kino_vega_lite, repo: "hexpm", optional: true]}, {:nx, "~> 1.0", [hex: :nx, repo: "hexpm", optional: false]}, {:polaris, "~> 0.2", [hex: :polaris, repo: "hexpm", optional: false]}, {:table_rex, "~> 3.1 or ~> 4.1", [hex: :table_rex, repo: "hexpm", optional: true]}], "hexpm", "243611436749007a5ec5ec0f5ebe0eb2261d8999217a5fad068c46a51a0d649f"}, "bandit": {:hex, :bandit, "1.14.1", "5fb450e2360faf03d9b9fb45cfe52e14197f62d376c34781219bec0f9bc7ca06", [:mix], [{:hpax, "~> 1.1", [hex: :hpax, repo: "hexpm", optional: false]}, {:plug, "~> 1.18", [hex: :plug, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}, {:thousand_island, "~> 1.6", [hex: :thousand_island, repo: "hexpm", optional: false]}, {:websock, "~> 0.5", [hex: :websock, repo: "hexpm", optional: false]}], "hexpm", "87c7ee5e08fb5f22d4e072e681e1101266a21432889b08ef8d0cb0c1450f8bba"}, + "bimap": {:hex, :bimap, "1.3.0", "3ea4832e58dc83a9b5b407c6731e7bae87458aa618e6d11d8e12114a17afa4b3", [:mix], [], "hexpm", "bf5a2b078528465aa705f405a5c638becd63e41d280ada41e0f77e6d255a10b4"}, "bumblebee": {:hex, :bumblebee, "0.8.0", "24d44c902baf91cf91d7ac0eba1c0feb02590eca34892fc859022a3b6b604732", [:mix], [{:axon, "~> 0.9.0", [hex: :axon, repo: "hexpm", optional: false]}, {:jason, "~> 1.4.0", [hex: :jason, repo: "hexpm", optional: false]}, {:nx, "~> 1.0", [hex: :nx, repo: "hexpm", optional: false]}, {:nx_image, "~> 0.2.0", [hex: :nx_image, repo: "hexpm", optional: false]}, {:nx_signal, "~> 0.4.0", [hex: :nx_signal, repo: "hexpm", optional: false]}, {:safetensors, "~> 0.2.0", [hex: :safetensors, repo: "hexpm", optional: false]}, {:tokenizers, "~> 0.4", [hex: :tokenizers, repo: "hexpm", optional: false]}, {:unpickler, "~> 0.1.0", [hex: :unpickler, repo: "hexpm", optional: false]}, {:unzip, "~> 0.12.0 or ~> 0.13.0", [hex: :unzip, repo: "hexpm", optional: false]}], "hexpm", "283272b12c24a8ec8d3fc31c3564a39babeeff09e51670039090ee17014d59a6"}, + "bunch": {:hex, :bunch, "1.6.4", "b23ecefdcbc1d8b9723044055daa2ad8573a0ebe6ef35c0ac4f3bad243273ba3", [:mix], [], "hexpm", "cacbe7437dd5299c9e665011d32127e0ce92b26ab4b9f64ebd2389f57cc7c141"}, + "bunch_native": {:hex, :bunch_native, "0.5.2", "706723acd1644fb6f8e7c8f3864172a7eee7664250e790696253825e3b65e18a", [:mix], [{:bundlex, "~> 1.0", [hex: :bundlex, repo: "hexpm", optional: false]}], "hexpm", "23f9e036c34510d8ace14fc47553fd7672e2330e769ab84fe4b54fac80095a4b"}, + "bundlex": {:hex, :bundlex, "1.5.9", "8f4c85e7a8ecea275f71970a917172e6beb7cd241963ef302391ded8f6e2b146", [:mix], [{:bunch, "~> 1.0", [hex: :bunch, repo: "hexpm", optional: false]}, {:elixir_uuid, "~> 1.2", [hex: :elixir_uuid, repo: "hexpm", optional: false]}, {:jason, "~> 1.4", [hex: :jason, repo: "hexpm", optional: false]}, {:qex, "~> 0.5", [hex: :qex, repo: "hexpm", optional: false]}, {:req, ">= 0.4.0", [hex: :req, repo: "hexpm", optional: false]}, {:zarex, "~> 1.0", [hex: :zarex, repo: "hexpm", optional: false]}], "hexpm", "ee2cd62e26a0470766f728a7903a74228059fcb54acd2e6d54a5e7b06ab1146d"}, "castore": {:hex, :castore, "1.0.22", "a01978e6a5d42fa3a34143630588f92036e7d90e2309ecdd466722d1279a2213", [:mix], [], "hexpm", "c2a4d42723b4affbc1c3e15d8f6df3f7d8f1f627c84de643383634cce58493d5"}, "cc_precompiler": {:hex, :cc_precompiler, "0.1.11", "8c844d0b9fb98a3edea067f94f616b3f6b29b959b6b3bf25fee94ffe34364768", [:mix], [{:elixir_make, "~> 0.7", [hex: :elixir_make, repo: "hexpm", optional: false]}], "hexpm", "3427232caf0835f94680e5bcf082408a70b48ad68a5f5c0b02a3bea9f3a075b9"}, + "coerce": {:hex, :coerce, "1.0.2", "5ef791040c92baaa5dd344887563faaeac6e6742573a167493294f8af3672bbe", [:mix], [], "hexpm", "0b3451c729571234fdac478636c298e71d1f2ce1243abed5fa43fa3181b980eb"}, "complex": {:hex, :complex, "1.0.0", "32075df521760e83d808652f52dd57f21712d47d5918a328709da78358387507", [:mix], [], "hexpm", "b4fd7ab305712472521043aa4322f7e4cdd85ca3ddf79c9c2c338d6663adc8d8"}, + "crc": {:hex, :crc, "0.11.0", "179cd2cb8d5f35d8b7d285eb12541da4680eefba253a5b97d4a949f7a30b56b4", [:mix, :rebar3], [], "hexpm", "b9e37d3e54c2d828611ad83dc2e0ea448c37cdb60a8b481355f9f68d69c9c3fc"}, "crontab": {:hex, :crontab, "1.2.1", "17991605725002e8dd949b95c1460b757b0702c048a7c9ea8b03183d08d3b9a9", [:mix], [{:ecto, "~> 1.0 or ~> 2.0 or ~> 3.0", [hex: :ecto, repo: "hexpm", optional: true]}], "hexpm", "ab550a005380d30c05038a1abff66989591e7703b2cc0d83f446a86fab258150"}, "db_connection": {:hex, :db_connection, "2.10.2", "ae391e803a5adff104da913c2fc1c0c14a37f8b10001dcef568796e1fb7bf95c", [:mix], [{:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "510b14482330f1af6490a2fa0efd8d4f1435d1529b165647df22ac0f2df0fa93"}, "decimal": {:hex, :decimal, "3.2.0", "f1235f05d841a211fda78a08fdb9777f2ff51a71f18455233fae186ff76187c6", [:mix], [], "hexpm", "190bca80580ce61aa69bb0eacadd7677710205c770225c2c2c07e32a5c31b234"}, "dotenvy": {:hex, :dotenvy, "1.2.1", "43b28d17c996d70ac09f6a6dfd2245378b346ed7290c36452b46cdca77cd96bc", [:mix], [], "hexpm", "20cf780119be89a7cae7808543ebc8b7e56f0993b6aa058260fab686afe9073d"}, "elixir_make": {:hex, :elixir_make, "0.10.1", "f5a44ab6b48421de1c4fd33c147e22cd2f82fd86e8a9a4d24809d466cad63c5e", [:mix], [], "hexpm", "ce1eaa234bc87f0279718e793fd6f8ad35b4e8ee8d412329e3879eee8d40adba"}, + "elixir_uuid": {:hex, :elixir_uuid, "1.2.1", "dce506597acb7e6b0daeaff52ff6a9043f5919a4c3315abb4143f0b00378c097", [:mix], [], "hexpm", "f7eba2ea6c3555cea09706492716b0d87397b88946e6380898c2889d68585752"}, "emlx": {:git, "https://github.com/elixir-nx/emlx.git", "5f5cd886fd2550b1e9452ddc3943fec5597b0cd5", [ref: "5f5cd886fd2550b1e9452ddc3943fec5597b0cd5", sparse: "emlx"]}, "emlx_axon": {:git, "https://github.com/elixir-nx/emlx.git", "5f5cd886fd2550b1e9452ddc3943fec5597b0cd5", [ref: "5f5cd886fd2550b1e9452ddc3943fec5597b0cd5", sparse: "emlx_axon"]}, "exla": {:hex, :exla, "1.0.0", "1c24b1e38416c954bf45851e7591e945876b76ac37e6ba992f01bb72ea615163", [:make, :mix], [{:elixir_make, "~> 0.6", [hex: :elixir_make, repo: "hexpm", optional: false]}, {:fine, "~> 0.1", [hex: :fine, repo: "hexpm", optional: false]}, {:nimble_pool, "~> 1.0", [hex: :nimble_pool, repo: "hexpm", optional: false]}, {:nx, "~> 1.0", [hex: :nx, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4.0 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}, {:xla, "~> 0.10.0", [hex: :xla, repo: "hexpm", optional: false]}], "hexpm", "f89b030d368372fe62aacecc773e2d096d812d1afe55acfed333ac9a43864ba7"}, @@ -18,6 +25,7 @@ "finch": {:hex, :finch, "0.24.0", "4022b6194e907b6d9b597c168001cac38e488a35fe36cef9d8297e3159782510", [:mix], [{:mime, "~> 1.0 or ~> 2.0", [hex: :mime, repo: "hexpm", optional: false]}, {:mint, "~> 1.8", [hex: :mint, repo: "hexpm", optional: false]}, {:nimble_options, "~> 0.4 or ~> 1.0", [hex: :nimble_options, repo: "hexpm", optional: false]}, {:nimble_pool, "~> 1.1", [hex: :nimble_pool, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "33ba40069c3587c2f99f9125b766e19dad87d6d54be3c6961db2304df04cef00"}, "fine": {:hex, :fine, "0.1.6", "4bf7151493443c454aac9f2fa2f34f5fefd0346a83fb5586a016c4a135c63247", [:mix], [], "hexpm", "5638eb4495488e885ebec167fa57973e5c35e1a50c344eb7666c90ec1c4e3b12"}, "fuse": {:hex, :fuse, "2.5.0", "71afa90be21da4e64f94abba9d36472faa2d799c67fedc3bd1752a88ea4c4753", [:rebar3], [], "hexpm", "7f52a1c84571731ad3c91d569e03131cc220ebaa7e2a11034405f0bac46a4fef"}, + "heap": {:hex, :heap, "2.0.2", "d98cb178286cfeb5edbcf17785e2d20af73ca57b5a2cf4af584118afbcf917eb", [:mix], [], "hexpm", "ba9ea2fe99eb4bcbd9a8a28eaf71cbcac449ca1d8e71731596aace9028c9d429"}, "hf_hub": {:hex, :hf_hub, "0.3.1", "c3285b8c94b8622b9df137330a8a889c4f0ce171d459f9bc53e5d758a4dfcbcf", [:mix], [{:explorer, "~> 0.10", [hex: :explorer, repo: "hexpm", optional: true]}, {:jason, "~> 1.4", [hex: :jason, repo: "hexpm", optional: false]}, {:req, "~> 0.5", [hex: :req, repo: "hexpm", optional: false]}, {:yaml_elixir, "~> 2.9", [hex: :yaml_elixir, repo: "hexpm", optional: false]}], "hexpm", "ad58acabb774fb89a34590b6995b0472f3343ffa27c3624a833f9374543169d1"}, "hpax": {:hex, :hpax, "1.1.0", "782931867cc23217c68fb5f68fe1a11f5e7544c7fda82c8a7019a5df5a4a1cdf", [:mix], [], "hexpm", "0b8d0f05832f55571d65ac720f79bf8994138ffbb133209dc4685eae0ad456a8"}, "idna": {:hex, :idna, "7.1.0", "1067a13043538129602d2f2ce6899d8713125c7d19734aa557ce2e3ea55bd4f1", [:rebar3], [], "hexpm", "6ae959a025bf36df61a8cab8508d9654891b5426a84c44d82deaffd6ddf8c71f"}, @@ -31,14 +39,39 @@ "live_base": {:git, "https://github.com/TudorAndrei/live_shadcn.git", "3ddada48f623d72260360acf115e5d9b5eacd1cf", [ref: "3ddada48f623d72260360acf115e5d9b5eacd1cf", sparse: "packages/live_base"]}, "live_shadcn": {:git, "https://github.com/TudorAndrei/live_shadcn.git", "3ddada48f623d72260360acf115e5d9b5eacd1cf", [ref: "3ddada48f623d72260360acf115e5d9b5eacd1cf", sparse: "packages/live_shadcn"]}, "llm_db": {:hex, :llm_db, "2026.10.7", "7a8a1ef710727a4b0314055c72cbfc7fa10de61ff8728a8189f1e896b410bd0e", [:mix], [{:dotenvy, "~> 1.1", [hex: :dotenvy, repo: "hexpm", optional: false]}, {:igniter, "~> 0.7", [hex: :igniter, repo: "hexpm", optional: true]}, {:jason, "~> 1.4", [hex: :jason, repo: "hexpm", optional: false]}, {:req, "~> 0.5", [hex: :req, repo: "hexpm", optional: false]}, {:toml, "~> 0.7", [hex: :toml, repo: "hexpm", optional: false]}, {:zoi, "~> 0.18.11", [hex: :zoi, repo: "hexpm", optional: false]}], "hexpm", "eb4aa0a64ce3c4d80bd49a2e87ba830f5d2b2bed46fe5e2fc0e4ee0eb17c04bb"}, + "logger_backends": {:hex, :logger_backends, "1.0.1", "08a9bd09eed271eac41ff35dd7603b6abf9e0f8b6ffe40359846cb0bfd37704f", [:mix], [], "hexpm", "d7903244fe8d84eeb3d3d42f8d7de080fd0409b613040df54c78b3591672d652"}, "lucide_icons": {:hex, :lucide_icons, "2.4.7", "124c3998924a626a16f10569473530bc1008aabbdc2f5a327c7f64ae20b5ec34", [:mix], [{:phoenix_html, "~> 4.3", [hex: :phoenix_html, repo: "hexpm", optional: false]}, {:phoenix_live_view, "~> 1.2", [hex: :phoenix_live_view, repo: "hexpm", optional: false]}], "hexpm", "0f6de8ab224304c1b61c77e699d574bdd05bc68cd8390c7d42000831ef245ec9"}, + "membrane_aac_format": {:hex, :membrane_aac_format, "0.8.1", "1084337ac856fb59ef484f8e52a286d036142c1d025728bb47a6dfc868b91ddc", [:mix], [{:bimap, "~> 1.1", [hex: :bimap, repo: "hexpm", optional: false]}], "hexpm", "7e8fbaae4895947394bfafaa4ec823d7eea035a3ccfbfe57a534b2872bf92862"}, + "membrane_av1_format": {:hex, :membrane_av1_format, "0.3.1", "d7d52d11ef359f723f443a12836624ab19235353732f18e8b0adf23b1d1a5062", [:mix], [{:bimap, "~> 1.3", [hex: :bimap, repo: "hexpm", optional: false]}, {:membrane_core, "~> 1.0", [hex: :membrane_core, repo: "hexpm", optional: false]}], "hexpm", "dcea3c1f255a28d188e85a68a8729b258a3fb1a151254266a872000254f85b90"}, + "membrane_cmaf_format": {:hex, :membrane_cmaf_format, "0.7.2", "fe1aeb7705d4422329eb19039d30ddb7973fe62c06ea03ea6669dbd94bf7f380", [:mix], [], "hexpm", "91f2c07bfbadee69b46de6a568a91ac80c1a4eada82aa82957f003bad07bdfab"}, + "membrane_common_c": {:hex, :membrane_common_c, "0.16.2", "76272743921844cfcad9e97aec6ae00e349c679919e87ff8ea2131939b4838e4", [:mix], [{:membrane_core, "~> 1.0", [hex: :membrane_core, repo: "hexpm", optional: false]}, {:shmex, "~> 0.5.0", [hex: :shmex, repo: "hexpm", optional: false]}, {:unifex, "~> 1.0", [hex: :unifex, repo: "hexpm", optional: false]}], "hexpm", "8416f95bdaeb147072be48418bbccab60e7f58bdbe24927be3a6903d96fea8be"}, + "membrane_core": {:hex, :membrane_core, "1.3.5", "10825d9359dcb440892a731528a11d8d7d704ee1607def41cc259c688f69a452", [:mix], [{:bunch, "~> 1.6", [hex: :bunch, repo: "hexpm", optional: false]}, {:qex, "~> 0.3", [hex: :qex, repo: "hexpm", optional: false]}, {:ratio, "~> 3.0 or ~> 4.0", [hex: :ratio, repo: "hexpm", optional: false]}, {:telemetry, "~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "cec2027446d7fcc860289907ea7259e0385b468e795c635334cb80d3c5f2a366"}, + "membrane_ffmpeg_swresample_plugin": {:hex, :membrane_ffmpeg_swresample_plugin, "0.21.0", "30f9dc3b6bee6d62f3d7d85603ad3f18ca14ea52adfad88771b009a645a10eea", [:mix], [{:bunch, "~> 1.6", [hex: :bunch, repo: "hexpm", optional: false]}, {:bundlex, "~> 1.2", [hex: :bundlex, repo: "hexpm", optional: false]}, {:membrane_common_c, "~> 0.16.0", [hex: :membrane_common_c, repo: "hexpm", optional: false]}, {:membrane_core, "~> 1.0", [hex: :membrane_core, repo: "hexpm", optional: false]}, {:membrane_precompiled_dependency_provider, "~> 0.2.1", [hex: :membrane_precompiled_dependency_provider, repo: "hexpm", optional: false]}, {:membrane_raw_audio_format, "~> 0.12.0", [hex: :membrane_raw_audio_format, repo: "hexpm", optional: false]}, {:mockery, "~> 2.1", [hex: :mockery, repo: "hexpm", optional: false]}, {:unifex, "~> 1.1", [hex: :unifex, repo: "hexpm", optional: false]}], "hexpm", "255177b22e39c7d20f1acceef8dda9fe7fd9094c5d906ffb0be4d6017f953501"}, + "membrane_ffmpeg_swscale_plugin": {:hex, :membrane_ffmpeg_swscale_plugin, "0.16.5", "0323608675db448e861b7f9b5d8f1ec3f89ad5683a953eb8b46456f0c2252fe4", [:mix], [{:bundlex, "~> 1.2", [hex: :bundlex, repo: "hexpm", optional: false]}, {:membrane_common_c, "~> 0.16.0", [hex: :membrane_common_c, repo: "hexpm", optional: false]}, {:membrane_core, "~> 1.1", [hex: :membrane_core, repo: "hexpm", optional: false]}, {:membrane_precompiled_dependency_provider, "~> 0.2.1", [hex: :membrane_precompiled_dependency_provider, repo: "hexpm", optional: false]}, {:membrane_raw_video_format, "~> 0.4.1", [hex: :membrane_raw_video_format, repo: "hexpm", optional: false]}], "hexpm", "c9b2f3328e441eb61127b74230295fee0097b8194c57f4118c09281b2a03cb9d"}, + "membrane_file_plugin": {:hex, :membrane_file_plugin, "0.17.5", "2e65607d68e7c25ce0a1b0dfadbca7b3d5b57859be5c700ed9e865edf7304580", [:mix], [{:logger_backends, "~> 1.0", [hex: :logger_backends, repo: "hexpm", optional: false]}, {:membrane_core, "~> 1.0", [hex: :membrane_core, repo: "hexpm", optional: false]}], "hexpm", "974c88cb0e7727a8a0a49bb019d7824d4d9092cce2ac666771fe4266d2ea4276"}, + "membrane_h264_ffmpeg_plugin": {:hex, :membrane_h264_ffmpeg_plugin, "0.32.8", "4361ea3852111b874ee37bdc37f6193d73ae3c192b418c7ae1a923b44f122cca", [:mix], [{:bunch, "~> 1.6", [hex: :bunch, repo: "hexpm", optional: false]}, {:bundlex, "~> 1.3", [hex: :bundlex, repo: "hexpm", optional: false]}, {:membrane_common_c, "~> 0.16.0", [hex: :membrane_common_c, repo: "hexpm", optional: false]}, {:membrane_core, "~> 1.0", [hex: :membrane_core, repo: "hexpm", optional: false]}, {:membrane_h264_format, "~> 0.6.1", [hex: :membrane_h264_format, repo: "hexpm", optional: false]}, {:membrane_precompiled_dependency_provider, "~> 0.2.1", [hex: :membrane_precompiled_dependency_provider, repo: "hexpm", optional: false]}, {:membrane_raw_video_format, "~> 0.4.1", [hex: :membrane_raw_video_format, repo: "hexpm", optional: false]}, {:unifex, "~> 1.1", [hex: :unifex, repo: "hexpm", optional: false]}], "hexpm", "ccbc84f610fefceb241eedb3ae5e3e955e9b63d0e6e879d28116de8c6b23fa5b"}, + "membrane_h264_format": {:hex, :membrane_h264_format, "0.6.1", "44836cd9de0abe989b146df1e114507787efc0cf0da2368f17a10c47b4e0738c", [:mix], [], "hexpm", "4b79be56465a876d2eac2c3af99e115374bbdc03eb1dea4f696ee9a8033cd4b0"}, + "membrane_h265_format": {:hex, :membrane_h265_format, "0.2.0", "1903c072cf7b0980c4d0c117ab61a2cd33e88782b696290de29570a7fab34819", [:mix], [], "hexpm", "6df418bdf242c0d9f7dbf2e5aea4c2d182e34ac9ad5a8b8cef2610c290002e83"}, + "membrane_h26x_plugin": {:hex, :membrane_h26x_plugin, "0.11.4", "958aaac3d6908521aac25e483c9caf74ad0448a4ae0d8fb3656733426583e195", [:mix], [{:bunch, "~> 1.4", [hex: :bunch, repo: "hexpm", optional: false]}, {:membrane_core, "~> 1.0", [hex: :membrane_core, repo: "hexpm", optional: false]}, {:membrane_h264_format, "~> 0.6.0", [hex: :membrane_h264_format, repo: "hexpm", optional: false]}, {:membrane_h265_format, "~> 0.2.0", [hex: :membrane_h265_format, repo: "hexpm", optional: false]}], "hexpm", "2284b609fdc6cf9f08d12be8e92cfd9e007c1332b16ec9beb7b4e9219b371f1c"}, + "membrane_mp4_format": {:hex, :membrane_mp4_format, "0.8.1", "ba0032af6527ca9b4bd9b9282436ca43dda206002fc0b27ad3f2cc87f419ee92", [:mix], [], "hexpm", "0e4ec53a50b26a18d6e969f4776606d321ea39bddf5a4571e94f9ccf44e7a53a"}, + "membrane_mp4_plugin": {:hex, :membrane_mp4_plugin, "0.36.11", "49f9bdaddb31a7fb0c7047cb93027058ff0de39c11b9ced28f15b1119983966b", [:mix], [{:bunch, "~> 1.5", [hex: :bunch, repo: "hexpm", optional: false]}, {:membrane_aac_format, "~> 0.8.0", [hex: :membrane_aac_format, repo: "hexpm", optional: false]}, {:membrane_av1_format, "~> 0.3.1", [hex: :membrane_av1_format, repo: "hexpm", optional: false]}, {:membrane_cmaf_format, "~> 0.7.0", [hex: :membrane_cmaf_format, repo: "hexpm", optional: false]}, {:membrane_core, "~> 1.0", [hex: :membrane_core, repo: "hexpm", optional: false]}, {:membrane_file_plugin, "~> 0.17.0", [hex: :membrane_file_plugin, repo: "hexpm", optional: false]}, {:membrane_h264_format, "~> 0.6.1", [hex: :membrane_h264_format, repo: "hexpm", optional: false]}, {:membrane_h265_format, "~> 0.2.0", [hex: :membrane_h265_format, repo: "hexpm", optional: false]}, {:membrane_mp4_format, "~> 0.8.0", [hex: :membrane_mp4_format, repo: "hexpm", optional: false]}, {:membrane_opus_format, "~> 0.3.0", [hex: :membrane_opus_format, repo: "hexpm", optional: false]}, {:membrane_timestamp_queue, "~> 0.2.1", [hex: :membrane_timestamp_queue, repo: "hexpm", optional: false]}], "hexpm", "300d27dbd43632e2e6063ae99bbf42bc9f3495a5761f8bba5274703f3352ed95"}, + "membrane_ogg_plugin": {:hex, :membrane_ogg_plugin, "0.5.2", "32c99c04575b828c4986158a16b91f4d74958cd907e68ea4bdc1e1e1fefcda57", [:mix], [{:crc, "~> 0.10", [hex: :crc, repo: "hexpm", optional: false]}, {:membrane_core, "~> 1.0", [hex: :membrane_core, repo: "hexpm", optional: false]}, {:membrane_opus_format, "~> 0.3.0", [hex: :membrane_opus_format, repo: "hexpm", optional: false]}], "hexpm", "3a80a08c280f9f66ff01dd079a8783200d46aa9713cf4a698a6ef36e374ef187"}, + "membrane_opus_format": {:hex, :membrane_opus_format, "0.3.2", "7751374d26f5d94fe0aaf33cfc121618d1e156eb6c9eaef6c8bd23825179b123", [:mix], [], "hexpm", "5e12deaeca6502b82a6d0b56ae54fa128d27e11b5b573d08d39a55724c62a9bf"}, + "membrane_opus_plugin": {:hex, :membrane_opus_plugin, "0.21.0", "0fcacddfe88ec154f842cc2887e0c993ac99a7fde1b5e8595d22f9266a93a1c8", [:mix], [{:bunch, "~> 1.3", [hex: :bunch, repo: "hexpm", optional: false]}, {:bundlex, "~> 1.2", [hex: :bundlex, repo: "hexpm", optional: false]}, {:membrane_common_c, "~> 0.16.0", [hex: :membrane_common_c, repo: "hexpm", optional: false]}, {:membrane_core, "~> 1.0", [hex: :membrane_core, repo: "hexpm", optional: false]}, {:membrane_opus_format, "~> 0.3.0", [hex: :membrane_opus_format, repo: "hexpm", optional: false]}, {:membrane_precompiled_dependency_provider, "~> 0.2.0", [hex: :membrane_precompiled_dependency_provider, repo: "hexpm", optional: false]}, {:membrane_raw_audio_format, "~> 0.12.0", [hex: :membrane_raw_audio_format, repo: "hexpm", optional: false]}, {:unifex, "~> 1.0", [hex: :unifex, repo: "hexpm", optional: false]}], "hexpm", "663111f56f1feb3e6fc7d3605a653c43b050936f724e37fe27631cdbd52300a3"}, + "membrane_portaudio_plugin": {:hex, :membrane_portaudio_plugin, "0.19.6", "9ceec1405a2ef8b578a5443f7eb7708e864e167810e008e1c9ee8da25150360e", [:mix], [{:bunch, "~> 1.5", [hex: :bunch, repo: "hexpm", optional: false]}, {:membrane_common_c, "~> 0.16.0", [hex: :membrane_common_c, repo: "hexpm", optional: false]}, {:membrane_core, "~> 1.0", [hex: :membrane_core, repo: "hexpm", optional: false]}, {:membrane_precompiled_dependency_provider, "~> 0.2.1", [hex: :membrane_precompiled_dependency_provider, repo: "hexpm", optional: false]}, {:membrane_raw_audio_format, "~> 0.12.0", [hex: :membrane_raw_audio_format, repo: "hexpm", optional: false]}, {:mockery, "~> 2.1", [hex: :mockery, repo: "hexpm", optional: false]}, {:unifex, "~> 1.2", [hex: :unifex, repo: "hexpm", optional: false]}], "hexpm", "48ba05a9a445305972a6aa778caf15547cef0b2bf0ae89d74d9e6fa669c2240f"}, + "membrane_precompiled_dependency_provider": {:hex, :membrane_precompiled_dependency_provider, "0.2.4", "4aa7d91255d0f325d2350a8c655667d38a3995ba073eef4907d467c399f001e3", [:mix], [{:bundlex, "~> 1.4", [hex: :bundlex, repo: "hexpm", optional: false]}, {:req, "~> 0.5", [hex: :req, repo: "hexpm", optional: false]}], "hexpm", "81c12cbe2c8bc5f547c6a8a11a71e2f55995a312c202bbc9b3ddc60c39818b91"}, + "membrane_raw_audio_format": {:hex, :membrane_raw_audio_format, "0.12.3", "fbbc35e78a39eafdd59d04d931f3490f3104019dc3f3ea20baebbb758b858b44", [:mix], [{:bimap, "~> 1.1", [hex: :bimap, repo: "hexpm", optional: false]}, {:bunch, "~> 1.0", [hex: :bunch, repo: "hexpm", optional: false]}, {:membrane_core, "~> 1.0", [hex: :membrane_core, repo: "hexpm", optional: false]}], "hexpm", "8e50520ce2ab0405a3a0b2d78a001223bb2d76014aaa4c59398cc21d4187fe26"}, + "membrane_raw_video_format": {:hex, :membrane_raw_video_format, "0.4.5", "b06f509e9f40e05c81e4246461f704e169a592f2379f52fbd7f953e13e139d24", [:mix], [{:image, ">= 0.54.0", [hex: :image, repo: "hexpm", optional: true]}, {:plug, "~> 1.15", [hex: :plug, repo: "hexpm", optional: true]}], "hexpm", "c4f62b148ecc1643ac2e77e1fda8ee5bd9b595b4047941b02c514a5f310971f2"}, + "membrane_timestamp_queue": {:hex, :membrane_timestamp_queue, "0.2.3", "aa0fd07550bed4d4dc0d0a70ee5525532a9e5f55d2532cfe4be972c605eec203", [:mix], [{:heap, "~> 2.0", [hex: :heap, repo: "hexpm", optional: false]}, {:membrane_core, "~> 1.0", [hex: :membrane_core, repo: "hexpm", optional: false]}], "hexpm", "0600814cbad3b4df80633418abc9b79f171ec7c152282d9735e27772caf54f11"}, "mime": {:hex, :mime, "2.0.7", "b8d739037be7cd402aee1ba0306edfdef982687ee7e9859bee6198c1e7e2f128", [:mix], [], "hexpm", "6171188e399ee16023ffc5b76ce445eb6d9672e2e241d2df6050f3c771e80ccd"}, "mint": {:hex, :mint, "1.11.0", "a713551624815c0435237b93d90ea8b9b14254690c66f732d0ef8930f76ff1d9", [:mix], [{:castore, "~> 0.1.0 or ~> 1.0", [hex: :castore, repo: "hexpm", optional: true]}, {:hpax, "~> 1.1", [hex: :hpax, repo: "hexpm", optional: false]}], "hexpm", "c6279ba2d6aa3a383a1d4cfbe7b59f42e6efd400f58d8e2acfeac48a438693ab"}, "mint_web_socket": {:hex, :mint_web_socket, "1.0.6", "5ffcf350df5b90f2d7a04adf877165228804993714592512374218d4679e325a", [:mix], [{:mint, ">= 1.4.1 and < 2.0.0-0", [hex: :mint, repo: "hexpm", optional: false]}], "hexpm", "0c360e9012413f1c115a63532601eb5d63731aab7010949178769760686c1698"}, + "mockery": {:hex, :mockery, "2.5.0", "a87acd74fd733aa3b9cb5663d6f690178b056608f2652f18e4ec423ddd5496ed", [:mix], [], "hexpm", "52492b2eba61055df1c626e894663b624b5e6fdfaaaba1d9a8596236fbf4da69"}, "multigraph": {:hex, :multigraph, "0.16.1-mg.5", "5118665ea3e2eede7244104ccc716b7c517bba44e33c26fb84d7297d77872646", [:mix], [], "hexpm", "d7e3511f1d29e96ed7e7cd01b92bb52eea487b6c61da838f1e61a2ec6838799d"}, "nimble_options": {:hex, :nimble_options, "1.1.1", "e3a492d54d85fc3fd7c5baf411d9d2852922f66e69476317787a7b2bb000a61b", [:mix], [], "hexpm", "821b2470ca9442c4b6984882fe9bb0389371b8ddec4d45a9504f00a66f650b44"}, "nimble_parsec": {:hex, :nimble_parsec, "1.4.2", "8efba0122db06df95bfaa78f791344a89352ba04baedd3849593bfce4d0dc1c6", [:mix], [], "hexpm", "4b21398942dda052b403bbe1da991ccd03a053668d147d53fb8c4e0efe09c973"}, "nimble_pool": {:hex, :nimble_pool, "1.1.0", "bf9c29fbdcba3564a8b800d1eeb5a3c58f36e1e11d7b7fb2e084a643f645f06b", [:mix], [], "hexpm", "af2e4e6b34197db81f7aad230c1118eac993acc0dae6bc83bac0126d4ae0813a"}, + "numbers": {:hex, :numbers, "5.2.5", "47189ba1c0e634f851a76281a2bb7be1914c48498eb1289d16cd50b6c713b436", [:mix], [{:coerce, "~> 1.0.2", [hex: :coerce, repo: "hexpm", optional: false]}, {:decimal, "~> 3.0", [hex: :decimal, repo: "hexpm", optional: true]}], "hexpm", "724563c5b9ed1adccea08b2938215a026aa4344d7506e6b9c75f60d8e2fc9463"}, "nx": {:hex, :nx, "1.0.0", "83d586079cb37d11a4cf8c0edaf2eccafe88aa2369e35ebdb1c3d78c43c8eb33", [:mix], [{:complex, "~> 1.0", [hex: :complex, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4.0 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "e06c7587efff7a3dfc1e2c92705943e319db20070359e9850c3921aaf26d6998"}, "nx_image": {:hex, :nx_image, "0.2.0", "795780095fd77c4712a2af74b18b7dec9677e474af5c22ffc1d5818099e106be", [:mix], [{:nx, "~> 1.0", [hex: :nx, repo: "hexpm", optional: false]}], "hexpm", "37276f456e82fb21b8f8b25d64b1889ffac56a9a46171e359ed2d696c712b597"}, "nx_signal": {:hex, :nx_signal, "0.4.0", "a65b9e2f3ab37135fe0d38e0b05bf87820ade9e4b7dc582786256d9f14c9f733", [:mix], [{:nx, "~> 1.0", [hex: :nx, repo: "hexpm", optional: false]}], "hexpm", "123e90414c212e01dae462576fd44e58254754c01a76f51d0fd84893c51a4a2c"}, @@ -54,11 +87,14 @@ "poolboy": {:hex, :poolboy, "1.5.2", "392b007a1693a64540cead79830443abf5762f5d30cf50bc95cb2c1aaafa006b", [:rebar3], [], "hexpm", "dad79704ce5440f3d5a3681c8590b9dc25d1a561e8f5a9c995281012860901e3"}, "postgrex": {:hex, :postgrex, "0.22.4", "d271f595dfd25230b6398354e19d17bb5e2d20130fd2d9bdca7e15f125d43552", [:mix], [{:db_connection, "~> 2.9", [hex: :db_connection, repo: "hexpm", optional: false]}, {:decimal, "~> 1.5 or ~> 2.0 or ~> 3.0", [hex: :decimal, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: true]}, {:table, "~> 0.1.0", [hex: :table, repo: "hexpm", optional: true]}], "hexpm", "4aae45a2d60e35b04eea2602440be152fae332901f1fc7a60fc7cb7f0f9a9c5a"}, "protox": {:hex, :protox, "2.1.0", "af130f17349a34acb3c79a48f05cc2b07fddf7d9951944b92c217c5b439bfa6e", [:mix], [], "hexpm", "89efe4c45eacaa8e8e6347d4be0813b6d5c58d004920a5150d81ea655cbd8cb2"}, + "qex": {:hex, :qex, "0.5.2", "a0c861a2de2380314c23ef592349824ca9016c5845380667ff1d9a22a8796f9b", [:mix], [], "hexpm", "6fb81bf3ae354a9abb471b9561538ea3e8540125d803b00f45cbccff52f00496"}, + "ratio": {:hex, :ratio, "4.0.1", "3044166f2fc6890aa53d3aef0c336f84b2bebb889dc57d5f95cc540daa1912f8", [:mix], [{:decimal, "~> 1.6 or ~> 2.0", [hex: :decimal, repo: "hexpm", optional: true]}, {:numbers, "~> 5.2.0", [hex: :numbers, repo: "hexpm", optional: false]}], "hexpm", "c60cbb3ccdff9ffa56e7d6d1654b5c70d9f90f4d753ab3a43a6bf40855b881ce"}, "req": {:hex, :req, "0.7.5", "0c3293cbf7717aba20b1b1b3ea13fe8d3fdf6f1557490f390c3f1ef6dd9db955", [:mix], [{:brotli, "~> 0.3.1", [hex: :brotli, repo: "hexpm", optional: true]}, {:finch, "~> 0.21", [hex: :finch, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: false]}, {:mime, "~> 2.0.6 or ~> 2.1", [hex: :mime, repo: "hexpm", optional: false]}, {:nimble_csv, "~> 1.0", [hex: :nimble_csv, repo: "hexpm", optional: true]}, {:plug, "~> 1.0", [hex: :plug, repo: "hexpm", optional: true]}], "hexpm", "576853c4bf403faa3c1fa5d093e0759227083b78f8a6864c67d62c0a9c45514d"}, "req_llm": {:hex, :req_llm, "1.29.0", "4f0b2c4da1261fb83f4fe678c741ab45ae9baaa0ffe2779b48b771e58d54e4a2", [:mix], [{:dotenvy, "~> 1.1", [hex: :dotenvy, repo: "hexpm", optional: false]}, {:ex_aws_auth, "~> 1.5", [hex: :ex_aws_auth, repo: "hexpm", optional: true]}, {:finch, "~> 0.22", [hex: :finch, repo: "hexpm", optional: false]}, {:goth, "~> 1.4", [hex: :goth, repo: "hexpm", optional: true]}, {:igniter, "~> 0.7", [hex: :igniter, repo: "hexpm", optional: true]}, {:jason, "~> 1.4", [hex: :jason, repo: "hexpm", optional: false]}, {:jsv, "~> 0.11", [hex: :jsv, repo: "hexpm", optional: false]}, {:llm_db, "~> 2026.10.4", [hex: :llm_db, repo: "hexpm", optional: false]}, {:nimble_options, "~> 1.1", [hex: :nimble_options, repo: "hexpm", optional: false]}, {:req, "~> 0.6", [hex: :req, repo: "hexpm", optional: false]}, {:server_sent_events, "~> 1.1.0", [hex: :server_sent_events, repo: "hexpm", optional: false]}, {:splode, "~> 0.3.0", [hex: :splode, repo: "hexpm", optional: false]}, {:websockex, "~> 0.5.1", [hex: :websockex, repo: "hexpm", optional: false]}, {:zoi, "~> 0.18.11", [hex: :zoi, repo: "hexpm", optional: false]}], "hexpm", "0d632304e9acc6099fc743b18036559e08bcbd5335cab8347f2fa858c691a081"}, "rustler_precompiled": {:hex, :rustler_precompiled, "0.10.1", "2895d3a3239d612c13c18945c0a693e07de4e8f9bc2b6b2297cba3d6576f9eea", [:mix], [{:rustler, "~> 0.28", [hex: :rustler, repo: "hexpm", optional: true]}], "hexpm", "0efa66bc2a4206aec64a2c422ca0b1d69bdc411c7b359ec928feb889357b4abb"}, "safetensors": {:hex, :safetensors, "0.2.0", "d7d37cb91723c09a1bede338bbdd8f7e19f82b8cb41874a0fb7fb02f5f396783", [:mix], [{:jason, "~> 1.4", [hex: :jason, repo: "hexpm", optional: false]}, {:nx, "~> 1.0", [hex: :nx, repo: "hexpm", optional: false]}], "hexpm", "cc1c095a64256821240208f429acc8b3a8faf47ab08414afcbf13d81d7830ffe"}, "server_sent_events": {:hex, :server_sent_events, "1.1.0", "54606238b9182ba673a10ce90bd95f81a0939c1baa91cdf86b66acc04edd1832", [:mix], [], "hexpm", "8e164db8e295a2d869a8faafbf4a1eeaa749b62fe93f66271adff6394d93ce15"}, + "shmex": {:hex, :shmex, "0.5.2", "5e807c4ec0320fdd3b224d3f8052d501908217a066b67c0433f4cfa369a2b07c", [:mix], [{:bunch_native, "~> 0.5.0", [hex: :bunch_native, repo: "hexpm", optional: false]}, {:bundlex, "~> 1.0", [hex: :bundlex, repo: "hexpm", optional: false]}], "hexpm", "7325f40a7308fecaaab1b19790903034926e5fb202a48fcf51dfd2c4ba97f861"}, "splode": {:hex, :splode, "0.3.3", "420917ee2373c5db8462417ea6faa8cbeb8deec7b18ae5dd2fa07c67f883f25a", [:mix], [], "hexpm", "3f98c7799ec8960f816b4ccc5cc6a5d2b72a20ad3f8fff9199fb530194ad9f50"}, "telemetry": {:hex, :telemetry, "1.4.2", "a0cb522801dffb1c49fe6e30561badffc7b6d0e180db1300df759faa22062855", [:rebar3], [], "hexpm", "928f6495066506077862c0d1646609eed891a4326bee3126ba54b60af61febb1"}, "telemetry_metrics": {:hex, :telemetry_metrics, "1.2.0", "7632c19c01d88d8aaca5da1a0e8912f5af39b79e7c08a2c253aeb3c14c2c957e", [:mix], [{:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "71dde12fc29b58b9c77ec17ec319109e5ca848d010fc1965ed4463bba1837c07"}, @@ -68,6 +104,7 @@ "tokenizers": {:hex, :tokenizers, "0.5.2", "cd9d3a32c86889c0d16320e09ebf329b68c30ea40a4e4bba322eeb82a64323f1", [:mix], [{:castore, "~> 0.1 or ~> 1.0", [hex: :castore, repo: "hexpm", optional: false]}, {:rustler, ">= 0.0.0", [hex: :rustler, repo: "hexpm", optional: true]}, {:rustler_precompiled, "~> 0.6", [hex: :rustler_precompiled, repo: "hexpm", optional: false]}], "hexpm", "0503f9c94ddc0853254125254f84a0e9df8df9700aaf53ddc5a9b0fe78449477"}, "toml": {:hex, :toml, "0.7.0", "fbcd773caa937d0c7a02c301a1feea25612720ac3fa1ccb8bfd9d30d822911de", [:mix], [], "hexpm", "0690246a2478c1defd100b0c9b89b4ea280a22be9a7b313a8a058a2408a2fa70"}, "transmuter": {:git, "https://github.com/georgeguimaraes/transmuter.git", "231028d9ff6f53bd58fa15d9f24d632258369805", [ref: "231028d9ff6f53bd58fa15d9f24d632258369805"]}, + "unifex": {:hex, :unifex, "1.2.5", "b557f7f6c2bfd0c451369a9a29323854674bfca9c60c44d4bccc669c4a28477c", [:mix], [{:bunch, "~> 1.0", [hex: :bunch, repo: "hexpm", optional: false]}, {:bundlex, "~> 1.4", [hex: :bundlex, repo: "hexpm", optional: false]}, {:shmex, "~> 0.5.0", [hex: :shmex, repo: "hexpm", optional: false]}], "hexpm", "7c8d473f8e2b43556d792179d9f6d56ff047c252288dc29a554b5a1e1404e528"}, "unpickler": {:hex, :unpickler, "0.1.0", "c2262c0819e6985b761e7107546cef96a485f401816be5304a65fdd200d5bd6a", [:mix], [], "hexpm", "e2b3f61e62406187ac52afead8a63bfb4e49394028993f3c4c42712743cab79e"}, "unzip": {:hex, :unzip, "0.13.0", "bf5ec6ac6063c69e6ec54c8b4a3b8dcd7a2719d28d10d7025776ab107957cde9", [:mix], [], "hexpm", "4bcb9892ecbf2042606b43ab685a1bffe03c14003e6246f5453db2c829237fd9"}, "websock": {:hex, :websock, "0.5.3", "2f69a6ebe810328555b6fe5c831a851f485e303a7c8ce6c5f675abeb20ebdadc", [:mix], [], "hexpm", "6105453d7fac22c712ad66fab1d45abdf049868f253cf719b625151460b8b453"}, @@ -76,5 +113,6 @@ "xla": {:hex, :xla, "0.10.0", "41121e9f011456242d3a79b9289910ce43419be0b0e7ebe67cc1292c6b3f232f", [:make, :mix], [{:elixir_make, "~> 0.4", [hex: :elixir_make, repo: "hexpm", optional: false]}], "hexpm", "f57d91aea6e661b52bf12239316c598679e9170628122bbd941235f040122bc6"}, "yamerl": {:hex, :yamerl, "0.10.0", "4ff81fee2f1f6a46f1700c0d880b24d193ddb74bd14ef42cb0bcf46e81ef2f8e", [:rebar3], [], "hexpm", "346adb2963f1051dc837a2364e4acf6eb7d80097c0f53cbdc3046ec8ec4b4e6e"}, "yaml_elixir": {:hex, :yaml_elixir, "2.12.2", "9dd1330fb4cd9a36a7b0f502e5b12486eff632792ee4a5f0eba52a4d4ec32c9c", [:mix], [{:yamerl, "~> 0.10", [hex: :yamerl, repo: "hexpm", optional: false]}], "hexpm", "e7c1b10122f973e6558462d51c39026ba0e14afbc6745318e990ea82cfe9e159"}, + "zarex": {:hex, :zarex, "1.0.6", "f657ed1187e6e90472e24c92b1fd5bf3f846e74bd240bd77276c13f336a8d168", [:mix], [], "hexpm", "b628a9b0bc312f278af2c288078c31fd4757224b82d768e91bcf3bedbe3a50e7"}, "zoi": {:hex, :zoi, "0.18.11", "d278490068df1b453b1d23cfda3bd66dfe609013fb38ed624387c8bae13b485e", [:mix], [{:decimal, "~> 2.0 or ~> 3.0", [hex: :decimal, repo: "hexpm", optional: true]}, {:phoenix_html, "~> 2.14.2 or ~> 3.0 or ~> 4.1", [hex: :phoenix_html, repo: "hexpm", optional: true]}], "hexpm", "02786ed534335541b0f21aa3787875019dc91bb5f01e32aba72ce2b987c40640"}, } diff --git a/examples/chat/test/chat_test.exs b/examples/chat/test/chat_test.exs index d188e6c..2580907 100644 --- a/examples/chat/test/chat_test.exs +++ b/examples/chat/test/chat_test.exs @@ -36,24 +36,44 @@ defmodule ChatTest do assert :ok = AudioFlow.cancel(session) end - test "provider configuration validates missing environment and preserves speech contract" do + test "provider configuration validates missing environment and selects each speech contract" do settings = Map.put(Chat.Setup.defaults(), "mode", "remote") assert {:error, missing} = Chat.Setup.options(settings, fn _ -> nil end) assert missing =~ "DEEPGRAM_API_KEY" assert missing =~ "ELEVENLABS_VOICE_ID" - for {mode, rate, adapter} <- [ - {"openai", 24_000, AudioFlow.Adapters.OpenAIRealtime}, - {"gemini", 16_000, AudioFlow.Adapters.GeminiLive} + gemini = Map.put(settings, "mode", "gemini") + assert Chat.Setup.rate(gemini) == 16_000 + assert {:ok, opts} = Chat.Setup.options(gemini, fn _ -> "server-value" end) + assert {AudioFlow.Adapters.GeminiLive, provider} = opts[:speech_to_speech] + assert is_function(provider[:api_key], 0) + refute Keyword.has_key?(opts, :history) + refute Keyword.has_key?(opts, :stt) + + # OpenAI is an always-on conversation; the key stays a server-side function. + openai = %{settings | "mode" => "openai", "voice" => "cedar"} + assert Chat.Setup.rate(openai) == 24_000 + assert Chat.Setup.duplex?(openai) + env = &%{"OPENAI_API_KEY" => "server-key", "OPENAI_REALTIME_MODEL" => "gpt-realtime"}[&1] + + assert {:ok, [duplex: {AudioFlow.Duplex.OpenAIRealtime, provider}]} = + Chat.Setup.options(openai, env) + + assert provider[:model] == "gpt-realtime" and provider[:voice] == "cedar" + assert provider[:api_key].() == "server-key" + refute Keyword.has_key?(provider, :endpoint) + + for {endpoint, result} <- [ + {"ws://127.0.0.1:9000/v1/realtime", :ok}, + {"https://api.openai.com/v1/realtime", :error}, + {"wss://user:secret@proxy.test/v1/realtime", :error} ] do - s = Map.put(settings, "mode", mode) - assert Chat.Setup.rate(s) == rate - assert {:ok, opts} = Chat.Setup.options(s, fn _ -> "server-value" end) - assert {^adapter, provider} = opts[:speech_to_speech] - assert is_function(provider[:api_key], 0) - refute Keyword.has_key?(opts, :history) - refute Keyword.has_key?(opts, :stt) + env = &(%{"OPENAI_REALTIME_ENDPOINT" => endpoint}[&1] || env.(&1)) + assert elem(Chat.Setup.options(openai, env), 0) == result end + + assert {:error, missing} = Chat.Setup.options(openai, fn _ -> nil end) + assert missing =~ "OPENAI_API_KEY" end test "recording redacts split text, omits PCM and deletes the private directory" do @@ -91,12 +111,11 @@ defmodule ChatTest do test "actual LiveView controls submit, configure, record, download and delete" do {:ok, view, html} = live(build_conn(), "/") assert html =~ "Synthetic demo" - assert html =~ "No inference" view |> element("#configuration") |> render_submit(%{"mode" => "remote"}) assert render(view) =~ "Missing server environment" - assert render(view) =~ "Active: demo" + assert has_element?(view, "select[name=mode] option[value=demo][selected]") view |> element("button[phx-click=capture]") |> render_click() - assert render(view) =~ "Disable and delete recordings" + assert render(view) =~ "Delete saved transcripts" render_hook(view, "send", %{"text" => "private-message"}) assert eventually(fn -> diff --git a/examples/chat/test/duplex_test.exs b/examples/chat/test/duplex_test.exs new file mode 100644 index 0000000..59ee40e --- /dev/null +++ b/examples/chat/test/duplex_test.exs @@ -0,0 +1,314 @@ +defmodule Chat.DuplexSetupTest do + use ExUnit.Case, async: true + + test "CHAT_MODE selects the startup mode; an unknown mode keeps the profile default" do + assert Chat.Setup.defaults(&%{"CHAT_MODE" => "moshi"}[&1])["mode"] == "moshi" + assert Chat.Setup.defaults(&%{"CHAT_MODE" => "nope"}[&1])["mode"] == "demo" + assert Chat.Setup.rate(%{"mode" => "moshi"}) == 24_000 + end + + test "the Moshi endpoint comes only from AUDIOFLOW_MOSHI_ENDPOINT" do + settings = %{Chat.Setup.defaults(fn _ -> nil end) | "mode" => "moshi"} + + if Code.ensure_loaded?(AudioFlow.Duplex.Moshi) do + assert {:ok, [duplex: {AudioFlow.Duplex.Moshi, [endpoint: "ws://127.0.0.1:8998/api/chat"]}]} = + Chat.Setup.options(settings, fn _ -> nil end) + + env = &%{"AUDIOFLOW_MOSHI_ENDPOINT" => "ws://10.0.0.2:9000/api/chat"}[&1] + + assert {:ok, [duplex: {_, [endpoint: "ws://10.0.0.2:9000/api/chat"]}]} = + Chat.Setup.options(settings, env) + + for endpoint <- ["http://127.0.0.1:8998/api/chat", "ws://user:secret@127.0.0.1/api/chat"] do + assert {:error, message} = + Chat.Setup.options(settings, &%{"AUDIOFLOW_MOSHI_ENDPOINT" => endpoint}[&1]) + + assert message =~ "AUDIOFLOW_MOSHI_ENDPOINT" + end + else + assert {:error, "Restart with AUDIOFLOW_MEDIA=1" <> _} = + Chat.Setup.options(settings, fn _ -> nil end) + end + end +end + +if Code.ensure_loaded?(AudioFlow.Duplex.Moshi) do + defmodule Chat.DuplexTest do + use ExUnit.Case, async: false + import Phoenix.ConnTest + import Phoenix.LiveViewTest + + alias Membrane.Ogg.Opus, as: OggOpus + alias Membrane.Ogg.Page + alias Membrane.Ogg.Parser + alias Membrane.Opus.Decoder.Native, as: Decoder + alias Membrane.Opus.Encoder.Native, as: Encoder + + @endpoint ChatWeb.Endpoint + @chunk 3_840 + + # A local Moshi wire peer: handshake byte, then one 80 ms Ogg Opus page and + # the scripted text for each 80 ms frame that the client sends. With + # `answer: false` it reads input and sends no audio. + defmodule Moshi do + @behaviour WebSock + + def init({owner, script, answer}) do + head = + Page.create_first(1) + |> Page.append_packet!(OggOpus.create_id_header(1)) + |> Page.finalize(0) + + state = %{ + owner: owner, + script: script, + answer: answer, + buffer: <<>>, + continued: nil, + decoder: Decoder.create(24_000, 1), + encoder: Encoder.create(24_000, 1, 2049, -1000, 3001), + frames: 0 + } + + send(owner, {:moshi, :connected}) + {:push, [{:binary, <<0>>}, {:binary, <<1>> <> Page.serialize(head)}], state} + end + + def handle_in({<<1, data::binary>>, opcode: :binary}, state) do + {packets, continued, rest} = Parser.parse(state.buffer <> data, state.continued) + + pcm = + for %Parser.Packet{payload: packet} <- packets, + not String.starts_with?(packet, ["OpusHead", "OpusTags"]), + into: <<>>, + do: Decoder.decode_packet(state.decoder, packet) + + frames = div(byte_size(pcm), 3_840) + if frames > 0, do: send(state.owner, {:moshi, :input_frames, frames}) + + replies = + Enum.flat_map(state.frames..(state.frames + frames - 1)//1, fn index -> + [{:binary, <<1>> <> output(state, index)}] ++ + for text <- List.wrap(state.script[index]), do: {:binary, <<2>> <> text} + end) + + {:push, if(state.answer, do: replies, else: []), + %{state | buffer: rest, continued: continued, frames: state.frames + frames}} + end + + def handle_info(_message, state), do: {:ok, state} + + defp output(state, index) do + page = %Page{bos: false, bitstream_serial_number: 1, page_sequence_number: index + 1} + + for _ <- 1..4, reduce: page do + page -> + {:ok, packet} = Encoder.encode_packet(state.encoder, :binary.copy(<<0, 0>>, 480), 480) + Page.append_packet!(page, packet) + end + |> Page.finalize((index + 1) * 3_840) + |> Page.serialize() + end + end + + defmodule Server do + def init(options), do: options + + def call(conn, options), + do: conn |> WebSockAdapter.upgrade(Moshi, options, []) |> Plug.Conn.halt() + end + + setup do + for name <- ["CHAT_MODE", "AUDIOFLOW_MOSHI_ENDPOINT"] do + original = System.get_env(name) + + on_exit(fn -> + if original, do: System.put_env(name, original), else: System.delete_env(name) + end) + end + + System.put_env("CHAT_MODE", "moshi") + :ok + end + + defp moshi(script, answer \\ true) do + server = + start_supervised!( + Supervisor.child_spec( + {Bandit, + plug: {Server, {self(), script, answer}}, + port: 0, + ip: {127, 0, 0, 1}, + startup_log: false}, + id: make_ref() + ) + ) + + {:ok, {_, port}} = ThousandIsland.listener_info(server) + System.put_env("AUDIOFLOW_MOSHI_ENDPOINT", "ws://127.0.0.1:#{port}/api/chat") + end + + defp chunk(byte \\ 1), do: Base.encode64(:binary.copy(<>, div(@chunk, 2))) + defp call(view), do: :sys.get_state(view.pid).socket.assigns.call + + defp connect(view) do + # A browser-supplied endpoint is ignored; the server environment wins. + render_hook(view, "call_start", %{"endpoint" => "ws://127.0.0.1:1/api/chat"}) + assert_reply(view, %{ok: true, generation: generation}) + assert_receive {:moshi, :connected}, 2_000 + assert_push_event(view, "call_ready", %{generation: ^generation}, 2_000) + generation + end + + test "CHAT_MODE=moshi opens the duplex controls instead of turn-based input" do + {:ok, view, _} = live(build_conn(), "/") + html = render(view) + assert html =~ "Start conversation" + assert html =~ "Not connected" + refute has_element?(view, "#prompt") + refute has_element?(view, "#recorder") + assert has_element?(view, "button[data-call=stop][disabled]") + assert :sys.get_state(view.pid).socket.assigns.session == nil + end + + test "microphone input and model output flow at the same time until stop" do + moshi(%{0 => " Hi", 1 => " there."}) + {:ok, view, _} = live(build_conn(), "/") + generation = connect(view) + assert render(view) =~ "Live · microphone on" + assert has_element?(view, "button[data-call=start][disabled]") + + render_hook(view, "call_audio", %{"generation" => generation, "pcm" => chunk()}) + assert_reply(view, %{ok: true}) + assert_receive {:moshi, :input_frames, 1}, 2_000 + assert_push_event(view, "call_play", %{generation: ^generation, rate: 24_000, pcm: pcm}) + assert byte_size(Base.decode64!(pcm)) == @chunk + + # Model audio arrived; the next input is still accepted and answered. + render_hook(view, "call_audio", %{"generation" => generation, "pcm" => chunk()}) + assert_reply(view, %{ok: true}) + assert_receive {:moshi, :input_frames, 1}, 2_000 + assert_push_event(view, "call_play", %{generation: ^generation}) + assert eventually(fn -> render(view) =~ "Hi there." end) + + %{pid: duplex} = call(view) + monitor = Process.monitor(duplex) + render_hook(view, "call_stop", %{"generation" => generation}) + assert_receive {:DOWN, ^monitor, :process, ^duplex, :normal} + assert_push_event(view, "call_stopped", %{generation: ^generation}) + assert render(view) =~ "Not connected" + assert render(view) =~ "Hi there." + + render_hook(view, "call_audio", %{"generation" => generation, "pcm" => chunk()}) + assert_reply(view, %{ok: false, error: "stale"}) + end + + test "input chunks are bounded, generation-checked and rejected before the handshake" do + moshi(%{}) + {:ok, view, _} = live(build_conn(), "/") + + render_hook(view, "call_audio", %{"generation" => 1, "pcm" => chunk()}) + assert_reply(view, %{ok: false, error: "stale"}) + + generation = connect(view) + + for pcm <- [Base.encode64(<<0, 0>>), Base.encode64(:binary.copy(<<0>>, 4 * @chunk)), "%%"] do + render_hook(view, "call_audio", %{"generation" => generation, "pcm" => pcm}) + assert_reply(view, %{ok: false, error: "invalid_chunk"}) + end + + render_hook(view, "call_audio", %{"generation" => generation + 1, "pcm" => chunk()}) + assert_reply(view, %{ok: false, error: "stale"}) + assert call(view).generation == generation + end + + test "input that the model has not answered for 2 s is refused, and the call stays open" do + moshi(%{}, false) + {:ok, view, _} = live(build_conn(), "/") + generation = connect(view) + + for _ <- 1..25 do + render_hook(view, "call_audio", %{"generation" => generation, "pcm" => chunk()}) + assert_reply(view, %{ok: true}) + end + + render_hook(view, "call_audio", %{"generation" => generation, "pcm" => chunk()}) + assert_reply(view, %{ok: false, error: "overloaded"}) + assert render(view) =~ "Live · microphone on" + end + + test "settings and a second conversation are refused while one is active" do + moshi(%{}) + {:ok, view, _} = live(build_conn(), "/") + connect(view) + + render_hook(view, "call_start", %{}) + assert_reply(view, %{ok: false, error: "A conversation is already active."}) + view |> element("#configuration") |> render_submit(%{"mode" => "demo"}) + assert render(view) =~ "Stop the current turn, recording or conversation" + assert has_element?(view, "select[name=mode] option[value=moshi][selected]") + end + + test "microphone denial and an unreachable model stop the conversation with an error" do + moshi(%{}) + {:ok, view, _} = live(build_conn(), "/") + generation = connect(view) + %{pid: duplex} = call(view) + monitor = Process.monitor(duplex) + render_hook(view, "call_failed", %{"message" => "Permission denied"}) + assert_receive {:DOWN, ^monitor, :process, ^duplex, :normal} + assert_push_event(view, "call_stopped", %{generation: ^generation}) + assert has_element?(view, "[role=alert]", "Microphone error: Permission denied") + + {:ok, closed} = :gen_tcp.listen(0, ip: {127, 0, 0, 1}) + {:ok, port} = :inet.port(closed) + :gen_tcp.close(closed) + System.put_env("AUDIOFLOW_MOSHI_ENDPOINT", "ws://127.0.0.1:#{port}/api/chat") + render_hook(view, "call_start", %{}) + assert_reply(view, %{ok: true, generation: failed}) + assert_push_event(view, "call_stopped", %{generation: ^failed}, 2_000) + assert has_element?(view, "[role=alert]", "Conversation error: connect_failed") + assert render(view) =~ "Stopped by an error" + assert has_element?(view, "button[data-call=start]:not([disabled])") + end + + test "model text after a pause starts a new message" do + moshi(%{0 => " One.", 30 => " Two."}) + {:ok, view, _} = live(build_conn(), "/") + generation = connect(view) + + push = fn -> + render_hook(view, "call_audio", %{"generation" => generation, "pcm" => chunk()}) + end + + push.() + assert eventually(fn -> render(view) =~ "One." end) + Process.sleep(1_600) + + for _ <- 1..30 do + push.() + assert_receive {:moshi, :input_frames, 1}, 2_000 + end + + assert eventually(fn -> render(view) =~ "Two." end) + + texts = + for %{role: "assistant", text: text} <- :sys.get_state(view.pid).socket.assigns.messages, + do: text + + assert texts == ["One.", "Two."] + end + + defp eventually(fun, tries \\ 100) + defp eventually(_, 0), do: false + + defp eventually(fun, tries) do + if fun.() do + true + else + Process.sleep(20) + eventually(fun, tries - 1) + end + end + end +end diff --git a/examples/chat/test/openai_live_test.exs b/examples/chat/test/openai_live_test.exs new file mode 100644 index 0000000..259c326 --- /dev/null +++ b/examples/chat/test/openai_live_test.exs @@ -0,0 +1,308 @@ +defmodule Chat.OpenAILiveTest do + use ExUnit.Case, async: false + import Phoenix.ConnTest + import Phoenix.LiveViewTest + + @endpoint ChatWeb.Endpoint + @chunk 3_840 + + # A local peer with the OpenAI Realtime GA event framing. It reports each + # connection and client event to the test and pushes the events the test + # sends. It never acts on its own. + defmodule Peer do + @behaviour WebSock + + def init(owner) do + send(owner, {:peer, self()}) + {:ok, owner} + end + + def handle_in({data, opcode: :text}, owner) do + send(owner, {:client, JSON.decode!(data)}) + {:ok, owner} + end + + def handle_info({:events, events}, owner), + do: {:push, Enum.map(events, &{:text, JSON.encode!(&1)}), owner} + + def terminate(_reason, owner) do + send(owner, :peer_closed) + :ok + end + end + + defmodule Server do + def init(owner), do: owner + + def call(conn, owner) do + send(owner, {:upgrade, conn.query_string}) + conn |> WebSockAdapter.upgrade(Peer, owner, []) |> Plug.Conn.halt() + end + end + + setup do + names = ["CHAT_MODE", "OPENAI_API_KEY", "OPENAI_REALTIME_MODEL", "OPENAI_REALTIME_ENDPOINT"] + original = Map.new(names, &{&1, System.get_env(&1)}) + + on_exit(fn -> + for {name, value} <- original, + do: if(value, do: System.put_env(name, value), else: System.delete_env(name)) + end) + + System.put_env(%{ + "CHAT_MODE" => "openai", + "OPENAI_API_KEY" => "fixture-key", + "OPENAI_REALTIME_MODEL" => "fixture-model" + }) + + :ok + end + + # The server reads the provider endpoint only from its environment. + defp openai_peer do + server = + start_supervised!( + {Bandit, plug: {Server, self()}, port: 0, ip: {127, 0, 0, 1}, startup_log: false} + ) + + {:ok, {_, port}} = ThousandIsland.listener_info(server) + System.put_env("OPENAI_REALTIME_ENDPOINT", "ws://127.0.0.1:#{port}/v1/realtime") + end + + defp connect(view) do + render_hook(view, "call_start", %{"endpoint" => "ws://127.0.0.1:1/ignored"}) + assert_reply(view, %{ok: true, generation: generation}) + assert_receive {:upgrade, "model=fixture-model"}, 2_000 + assert_receive {:peer, peer} + send(peer, {:events, [%{type: "session.created", session: %{}}]}) + assert_receive {:client, %{"type" => "session.update", "session" => session}}, 2_000 + assert render(view) =~ "Connecting…" + send(peer, {:events, [%{type: "session.updated", session: session}]}) + assert_push_event(view, "call_ready", %{generation: ^generation}, 2_000) + {generation, peer, session} + end + + defp audio(view, generation) do + pcm = Base.encode64(:binary.copy(<<0>>, @chunk)) + render_hook(view, "call_audio", %{"generation" => generation, "pcm" => pcm}) + end + + defp utterance(peer, user, transcript, response, item, text) do + send( + peer, + {:events, + [ + %{type: "input_audio_buffer.speech_started", item_id: user, audio_start_ms: 0}, + %{type: "input_audio_buffer.speech_stopped", item_id: user, audio_end_ms: 800}, + %{type: "response.created", response: %{id: response}}, + %{ + type: "response.output_audio.delta", + response_id: response, + item_id: item, + content_index: 0, + delta: Base.encode64(:binary.copy(<<0>>, 4_800)) + }, + %{type: "response.output_audio_transcript.delta", response_id: response, delta: text}, + %{ + type: "conversation.item.input_audio_transcription.completed", + item_id: user, + transcript: transcript + } + ]} + ) + end + + defp messages(view) do + for %{role: role, text: text} <- :sys.get_state(view.pid).socket.assigns.messages, + do: {role, text} + end + + test "OpenAI mode opens the always-on controls with the voice choice" do + {:ok, view, html} = live(build_conn(), "/") + assert html =~ "OpenAI live conversation" + assert html =~ "Start conversation" + assert has_element?(view, "select[name=voice]") + assert has_element?(view, "button[data-call=stop][disabled]") + refute has_element?(view, "#prompt") + refute has_element?(view, "#recorder") + refute view |> element("#duplex") |> render() =~ "Moshi" + assert :sys.get_state(view.pid).socket.assigns.session == nil + end + + test "one connection hears several utterances while the microphone streams" do + openai_peer() + {:ok, view, _} = live(build_conn(), "/") + view |> element("#configuration") |> render_submit(%{"mode" => "openai", "voice" => "cedar"}) + {generation, peer, session} = connect(view) + assert session["audio"]["output"]["voice"] == "cedar" + assert render(view) =~ "Live · microphone on" + + for _ <- 1..10 do + audio(view, generation) + assert_reply(view, %{ok: true}) + assert_receive {:client, %{"type" => "input_audio_buffer.append"}} + end + + utterance(peer, "user_1", "Hello there", "resp_1", "item_1", "Hi! How can I help?") + assert_push_event(view, "call_flush", %{generation: ^generation}, 2_000) + + assert_push_event(view, "call_play", %{generation: ^generation, output: "item_1", pcm: pcm}) + assert byte_size(Base.decode64!(pcm)) == 4_800 + + # The microphone keeps streaming while reply audio plays. + audio(view, generation) + assert_reply(view, %{ok: true}) + + send( + peer, + {:events, + [%{type: "response.done", response: %{id: "resp_1", status: "completed", output: []}}]} + ) + + assert eventually(fn -> + messages(view) == [{"user", "Hello there"}, {"assistant", "Hi! How can I help?"}] + end) + + # The second utterance interrupts the reply; the browser reports what played. + utterance(peer, "user_2", "Stop, another question", "resp_2", "item_2", "Sure.") + assert_push_event(view, "call_flush", %{generation: ^generation}, 2_000) + + render_hook(view, "call_played", %{ + "generation" => generation, + "output" => "item_1", + "ms" => 40 + }) + + assert_receive {:client, + %{ + "type" => "conversation.item.truncate", + "item_id" => "item_1", + "audio_end_ms" => 40 + }}, + 2_000 + + assert eventually(fn -> + messages(view) == [ + {"user", "Hello there"}, + {"assistant", "Hi! How can I help?"}, + {"user", "Stop, another question"}, + {"assistant", "Sure."} + ] + end) + + # Both utterances used the same provider connection; none was committed by the client. + refute_received {:peer, _} + refute_received {:client, %{"type" => "input_audio_buffer.commit"}} + refute_received {:client, %{"type" => "response.create"}} + + render_hook(view, "call_stop", %{"generation" => generation}) + assert_push_event(view, "call_stopped", %{generation: ^generation}) + assert_receive :peer_closed, 2_000 + assert render(view) =~ "Not connected" + end + + test "a provider error stops the call with its code and a new call starts fresh" do + openai_peer() + {:ok, view, _} = live(build_conn(), "/") + {generation, peer, _} = connect(view) + + send( + peer, + {:events, + [ + %{ + type: "error", + error: %{type: "server_error", code: "boom", message: "provider-message-text"} + } + ]} + ) + + assert_push_event(view, "call_stopped", %{generation: ^generation}, 2_000) + assert has_element?(view, "[role=alert]", "Conversation error: provider error boom") + refute render(view) =~ "provider-message-text" + assert_receive :peer_closed, 2_000 + + {next, _peer, _} = connect(view) + assert next == generation + 1 + end + + test "old response completion cannot close the current reply and clearing text stays clear" do + openai_peer() + {:ok, view, _} = live(build_conn(), "/") + {_generation, peer, _} = connect(view) + + send( + peer, + {:events, + [ + %{type: "response.created", response: %{id: "old"}}, + %{ + type: "response.output_audio_transcript.delta", + response_id: "old", + delta: "Old reply" + }, + %{type: "response.created", response: %{id: "new"}}, + %{type: "response.output_audio_transcript.delta", response_id: "new", delta: "New"}, + %{type: "response.done", response: %{id: "old", status: "cancelled", output: []}}, + %{type: "response.output_audio_transcript.delta", response_id: "new", delta: " reply"} + ]} + ) + + assert eventually(fn -> + messages(view) == [{"assistant", "Old reply"}, {"assistant", "New reply"}] + end) + + render_hook(view, "new_chat", %{}) + + send( + peer, + {:events, + [ + %{ + type: "response.output_audio_transcript.delta", + response_id: "new", + delta: " after clearing" + }, + %{type: "response.done", response: %{id: "new", status: "completed", output: []}} + ]} + ) + + assert eventually(fn -> + :sys.get_state(view.pid).socket.assigns.call.reply_response == nil + end) + + assert messages(view) == [] + end + + test "pending transcript eviction removes waiting messages" do + openai_peer() + {:ok, view, _} = live(build_conn(), "/") + {_generation, peer, _} = connect(view) + + for n <- 1..20 do + send( + peer, + {:events, + [%{type: "input_audio_buffer.speech_started", item_id: "u#{n}", audio_start_ms: n * 100}]} + ) + end + + assert eventually(fn -> + state = :sys.get_state(view.pid).socket.assigns + Enum.count_until(state.call.users, 17) == 16 and + Enum.count_until(state.messages, 17) == 16 + end) + end + + defp eventually(fun, tries \\ 100) + defp eventually(_, 0), do: false + + defp eventually(fun, tries) do + if fun.() do + true + else + Process.sleep(20) + eventually(fun, tries - 1) + end + end +end diff --git a/lib/audio_flow/adapters/providers/socket.ex b/lib/audio_flow/adapters/providers/socket.ex index c12ae68..0ab23f1 100644 --- a/lib/audio_flow/adapters/providers/socket.ex +++ b/lib/audio_flow/adapters/providers/socket.ex @@ -7,36 +7,56 @@ defmodule AudioFlow.Adapters.Providers.Socket do # `decode` maps each `{:text | :binary, data}` frame to a handler event; the # default accepts JSON objects only. def run(url, headers, frames, state, handler, options, decode \\ &json_event/1) do - uri = URI.parse(url) - - unless (uri.scheme in ["ws", "wss"] and uri.host) && is_nil(uri.userinfo), - do: raise(ArgumentError, "expected ws/wss endpoint without user information") - + endpoint!(url) timeout = positive!(options, :timeout_ms, 30_000) limit = positive!(options, :max_response_bytes, 16_777_216) deadline = System.monotonic_time(:millisecond) + timeout - {scheme, port, path} = target(uri) - case Mint.HTTP.connect(scheme, uri.host, port, - mode: :passive, - protocols: [:http1], - transport_opts: [timeout: timeout] - ) do - {:ok, conn} -> + case open(url, headers, deadline, mode: :passive) do + {:ok, conn, ws, ref, pending} -> socket = %{ conn: conn, - ws: nil, - ref: nil, + ws: ws, + ref: ref, deadline: deadline, bytes: 0, limit: limit, decode: decode } - upgrade(socket, scheme, path, headers, {frames, state, handler}) + stream(socket, frames, pending, state, handler) - {:error, _} -> - {:error, :connect_failed} + {:error, _} = error -> + error + end + end + + def endpoint!(url) do + uri = URI.parse(url) + + unless (uri.scheme in ["ws", "wss"] and uri.host) && is_nil(uri.userinfo), + do: raise(ArgumentError, "expected ws/wss endpoint without user information") + + url + end + + # Connects and completes the WebSocket upgrade before `deadline` (monotonic + # milliseconds). The caller owns the connection. `pending` holds responses + # that arrived with the upgrade. Options: `:mode` for `Mint.WebSocket.new/5` + # and extra `:transport_opts`. + def open(url, headers, deadline, options) do + uri = URI.parse(url) + {scheme, port, path} = target(uri) + timeout = max(deadline - System.monotonic_time(:millisecond), 1) + transport = [timeout: timeout] ++ Keyword.get(options, :transport_opts, []) + + case Mint.HTTP.connect(scheme, uri.host, port, + mode: :passive, + protocols: [:http1], + transport_opts: transport + ) do + {:ok, conn} -> upgrade(conn, scheme, path, headers, deadline, options[:mode]) + {:error, _} -> {:error, :connect_failed} end end @@ -47,14 +67,21 @@ defmodule AudioFlow.Adapters.Providers.Socket do {scheme, port, path} end - defp upgrade(%{conn: conn} = socket, scheme, path, headers, {frames, state, handler}) do + defp upgrade(conn, scheme, path, headers, deadline, mode) do {:ok, conn, ref} = check(WS.upgrade(if(scheme == :https, do: :wss, else: :ws), conn, path, headers)) - {conn, status, headers, pending} = handshake(conn, ref, socket.deadline, nil, []) - {:ok, conn, ws} = check(WS.new(conn, ref, status, headers, mode: :passive)) + {conn, status, headers, pending} = handshake(conn, ref, deadline, nil, []) + {:ok, conn, ws} = check(WS.new(conn, ref, status, headers, mode: mode)) + {:ok, conn, ws, ref, pending} + catch + {:provider_socket, reason} -> + Mint.HTTP.close(conn) + {:error, reason} + end - socket = send_frames(%{socket | conn: conn, ws: ws, ref: ref}, frames) + defp stream(socket, frames, pending, state, handler) do + socket = send_frames(socket, frames) loop(socket, pending, state, handler) catch {:provider_socket, reason} -> {:error, reason} diff --git a/lib/audio_flow/duplex.ex b/lib/audio_flow/duplex.ex new file mode 100644 index 0000000..03c5e13 --- /dev/null +++ b/lib/audio_flow/duplex.ex @@ -0,0 +1,503 @@ +defmodule AudioFlow.Duplex do + @schema NimbleOptions.new!( + owner: [type: :pid, required: true, doc: "Receives the session messages."], + adapter: [ + type: {:tuple, [:atom, :keyword_list]}, + required: true, + doc: "`{module, options}` that implements `AudioFlow.Duplex.Adapter`." + ], + connect_timeout_ms: [ + type: :pos_integer, + default: 15_000, + doc: "Time from start to the model handshake." + ], + idle_timeout_ms: [ + type: :pos_integer, + default: 30_000, + doc: "Time after `:ready` or the last accepted push." + ], + max_session_ms: [type: :pos_integer, default: 1_800_000, doc: "Total session time."], + max_chunk_bytes: [type: :pos_integer, default: 48_000, doc: "Largest push."], + max_response_bytes: [ + type: :pos_integer, + default: 67_108_864, + doc: "Total incoming WebSocket bytes, including partial frames." + ], + max_input_lead_ms: [ + type: :pos_integer, + default: 2_000, + doc: + "Input lead. With adapter input flow `:answered`: pushed audio not yet answered by model audio. With `:realtime`: pushed audio ahead of the wall clock since `:ready`." + ], + max_owner_queue: [ + type: :pos_integer, + default: 250, + doc: "Owner mailbox length that fails the session." + ], + send_timeout_ms: [type: :pos_integer, default: 5_000, doc: "TCP send timeout."] + ) + + @moduledoc """ + One continuous full-duplex model connection. Input and output flow at the + same time. There are no turns: no end-of-turn detection, no silence gate and + no output drop while the user speaks. For committed turns, use + `AudioFlow.Session`. + + {:ok, duplex} = + AudioFlow.Duplex.start_link(owner: self(), adapter: {AudioFlow.Duplex.Moshi, []}) + + receive do + {AudioFlow.Duplex, ^duplex, :ready} -> :ok + end + + :ok = AudioFlow.Duplex.push(duplex, %AudioFlow.Audio{data: pcm, sample_rate: 24_000}) + + `start_link/1` returns before the connection opens. The owner then receives + `{AudioFlow.Duplex, pid, event}` messages: + + * `:ready` after the model handshake. `push/2` returns + `{:error, :not_ready}` before it. + * `{:audio, %AudioFlow.Audio{}}` and `{:text, text}` with model output, in + wire order. + * Adapters with model turn detection also send `{:speech_started, item}`, + `{:transcript, item, text | :failed}`, `{:response, id, status}` and + `{:output, item}`. See `AudioFlow.Duplex.Adapter`. + * `{:error, reason}` when the session fails. `:closed` follows. + * `:closed` once, when the session stops for any reason except owner exit. + + Failure reasons: `:connect_failed`, `:connect_timeout`, `{:http_status, status}`, + `:idle_timeout`, `:session_timeout`, `:connection_closed`, `:socket_error`, + `:invalid_frame`, `:invalid_event`, `:owner_overloaded`, `:send_failed` and + adapter reasons. + + The session stops when the owner exits. It stops with reason `:normal` on + failure, timeout and `stop/1`, so a link to it does not stop the owner. + + ## Bounds + + The adapter selects the input flow. With `:answered` (Moshi, one output + frame for each input frame), input that the model has not answered is at + most `:max_input_lead_ms`. With `:realtime` (OpenAI, output only when the + model speaks), pushed audio is at most `:max_input_lead_ms` ahead of the + wall clock since `:ready`, so continuous silence never overloads. A push + past the bound returns `{:error, :overloaded}` and the chunk is not + sent. Output is sent to the owner at once and is not buffered. If the owner + mailbox has `:max_owner_queue` messages or more, the session fails with + `:owner_overloaded`. The owner must be a local process. + + """ <> NimbleOptions.docs(@schema) + use GenServer + alias AudioFlow.Adapters.Providers.Socket + alias AudioFlow.Audio + alias Mint.WebSocket, as: WS + + @call_timeout 5_000 + + @doc "Starts a session. Raises `ArgumentError` for invalid options." + def start_link(options), do: start_session(options, :linked) + + @doc "Starts an unlinked session. The session still monitors its owner." + def start(options), do: start_session(options, :unlinked) + + defp start_session(options, link) do + options = NimbleOptions.validate!(options, @schema) + owner = options[:owner] + + unless node(owner) == node(), do: raise(ArgumentError, "owner must be a local process") + + {module, adapter_options} = options[:adapter] + Code.ensure_loaded!(module) + config = module.config(adapter_options) + Socket.endpoint!(config.url) + + unless Map.get(config, :input_flow, :answered) in [:answered, :realtime], + do: raise(ArgumentError, "input_flow must be :answered or :realtime") + + args = {options, module, config} + + if link == :linked, + do: GenServer.start_link(__MODULE__, args), + else: GenServer.start(__MODULE__, args) + end + + @doc """ + Sends one mono s16le chunk at the adapter sample rate. Returns `:ok` after + the frames are written to the socket. + + These errors leave the session open: `:not_ready`, `:invalid_audio`, + `:too_large`, `:overloaded` and `:timeout` (no answer in 5 s). `:closed` + means the session stopped. Other reasons fail the session. + """ + def push(pid, audio) when is_pid(pid) do + GenServer.call(pid, {:push, audio}, @call_timeout) + catch + :exit, {:timeout, _} -> {:error, :timeout} + :exit, _ -> {:error, :closed} + end + + @doc """ + Sends an adapter control command, for example playback progress. Returns + `:ok`, `{:error, :not_ready}`, `{:error, :unsupported}` (the adapter has no + controls), adapter errors such as `{:error, :stale}` (these leave the session + open), `{:error, :timeout}` or `{:error, :closed}`. + """ + def control(pid, command) when is_pid(pid) do + GenServer.call(pid, {:control, command}, @call_timeout) + catch + :exit, {:timeout, _} -> {:error, :timeout} + :exit, _ -> {:error, :closed} + end + + @doc "Stops the session and closes the connection. Returns `:ok` if it already stopped." + def stop(pid) when is_pid(pid) do + GenServer.stop(pid, :normal, @call_timeout) + catch + :exit, _ -> :ok + end + + @impl true + def init({options, module, config}) do + Process.flag(:trap_exit, true) + owner = options[:owner] + server = self() + lead = div(options[:max_input_lead_ms] * config.sample_rate, 1000) + + connector = + spawn_link(fn -> + send( + server, + {:connector, self(), + connect(server, config, options[:connect_timeout_ms], options[:send_timeout_ms])} + ) + end) + + {:ok, + %{ + owner: owner, + owner_ref: Process.monitor(owner), + owner_alive: true, + module: module, + adapter: module.init(config.options), + rate: config.sample_rate, + input_flow: Map.get(config, :input_flow, :answered), + ready_at: nil, + phase: :connecting, + connector: connector, + conn: nil, + ws: nil, + ref: nil, + pushed: 0, + received: 0, + response_bytes: 0, + max_response_bytes: options[:max_response_bytes], + max_lead: lead, + max_chunk: options[:max_chunk_bytes], + max_queue: options[:max_owner_queue], + idle_ms: options[:idle_timeout_ms], + connect_timer: :erlang.start_timer(options[:connect_timeout_ms], self(), :connect), + session_timer: :erlang.start_timer(options[:max_session_ms], self(), :session), + idle_timer: nil + }} + end + + @impl true + def handle_call({_kind, _value}, _from, %{phase: phase} = state) when phase != :ready, + do: {:reply, {:error, :not_ready}, state} + + def handle_call({:control, command}, _from, state) do + with true <- function_exported?(state.module, :handle_control, 2), + {:ok, frames, adapter} <- state.module.handle_control(command, state.adapter), + {:ok, state} <- send_frames(%{state | adapter: adapter}, frames) do + {:reply, :ok, state} + else + false -> {:reply, {:error, :unsupported}, state} + {:error, reason, state} -> fail({:error, reason}, state, reason) + {:error, reason} -> {:reply, {:error, reason}, state} + end + end + + def handle_call({:push, audio}, _from, state) do + with :ok <- check_audio(audio, state), + {:ok, frames, adapter} <- state.module.handle_audio(audio, state.adapter), + {:ok, state} <- send_frames(%{state | adapter: adapter}, frames) do + state = %{state | pushed: state.pushed + div(byte_size(audio.data), 2)} + {:reply, :ok, restart_idle(state)} + else + {:error, reason} when reason in [:invalid_audio, :too_large, :overloaded] -> + {:reply, {:error, reason}, state} + + {:error, reason, state} -> + fail({:error, reason}, state, reason) + + {:error, reason} -> + fail({:error, reason}, state, reason) + end + end + + defp check_audio(%Audio{} = audio, state) do + cond do + not Audio.valid?(audio) or audio.sample_rate != state.rate -> + {:error, :invalid_audio} + + byte_size(audio.data) > state.max_chunk -> + {:error, :too_large} + + state.pushed + div(byte_size(audio.data), 2) - allowance(state) > state.max_lead -> + {:error, :overloaded} + + true -> + :ok + end + end + + defp check_audio(_audio, _state), do: {:error, :invalid_audio} + + # Samples that the bound already counts as consumed. + defp allowance(%{input_flow: :answered} = state), do: state.received + + defp allowance(%{input_flow: :realtime} = state), + do: div((System.monotonic_time(:millisecond) - state.ready_at) * state.rate, 1000) + + defp fail(reply, state, reason) do + notify!(state, {:error, reason}) + {:stop, :normal, reply, state} + end + + @impl true + def handle_info({:DOWN, ref, :process, _, _}, %{owner_ref: ref} = state), + do: {:stop, :normal, %{state | owner_alive: false}} + + def handle_info({:EXIT, pid, reason}, %{connector: pid} = state) do + state = %{state | connector: nil} + if reason == :normal, do: {:noreply, state}, else: failed(state, :connect_failed) + end + + def handle_info({:EXIT, _pid, _reason}, state), do: {:noreply, state} + + def handle_info({:timeout, timer, kind}, state) do + case {kind, state} do + {:connect, %{connect_timer: ^timer}} -> failed(state, :connect_timeout) + {:session, %{session_timer: ^timer}} -> failed(state, :session_timeout) + {:idle, %{idle_timer: ^timer}} -> failed(state, :idle_timeout) + _stale -> {:noreply, state} + end + end + + def handle_info({:connector, pid, {:ok, conn, ws, ref, pending}}, %{connector: pid} = state) do + case Mint.HTTP.set_mode(conn, :active) do + {:ok, conn} -> + responses(%{state | conn: conn, ws: ws, ref: ref, phase: :open}, pending) + + {:error, _} -> + Mint.HTTP.close(conn) + failed(state, :socket_error) + end + end + + def handle_info({:connector, pid, {:error, reason}}, %{connector: pid} = state), + do: failed(state, reason) + + def handle_info(message, %{conn: conn} = state) when conn != nil do + case WS.stream(conn, message) do + {:ok, conn, responses} -> + responses(%{state | conn: conn}, responses) + + {:error, conn, %Mint.TransportError{reason: :closed}, _} -> + failed(%{state | conn: conn}, :connection_closed) + + {:error, conn, _, _} -> + failed(%{state | conn: conn}, :socket_error) + + :unknown -> + {:noreply, state} + end + end + + def handle_info(_message, state), do: {:noreply, state} + + @impl true + def terminate(_reason, state) do + if state.connector, do: Process.exit(state.connector, :kill) + + if state.conn do + _ = send_frames(state, [{:close, 1000, ""}]) + Mint.HTTP.close(state.conn) + end + + if state.owner_alive, do: send(state.owner, {__MODULE__, self(), :closed}) + :ok + end + + defp failed(state, reason) do + notify!(state, {:error, reason}) + {:stop, :normal, state} + end + + defp responses(state, []), do: {:noreply, state} + + defp responses(%{ref: ref} = state, [{:data, ref, data} | rest]) do + bytes = state.response_bytes + byte_size(data) + + if bytes > state.max_response_bytes do + failed(state, :response_too_large) + else + decode_response(%{state | response_bytes: bytes}, data, rest) + end + end + + defp responses(%{ref: ref} = state, [{:done, ref} | _]), do: failed(state, :connection_closed) + defp responses(state, [_ | rest]), do: responses(state, rest) + + defp decode_response(state, data, rest) do + case WS.decode(state.ws, data) do + {:ok, ws, frames} -> + case frames(%{state | ws: ws}, frames) do + {:ok, state} -> responses(state, rest) + {:error, reason, state} -> failed(state, reason) + end + + {:error, ws, _} -> + failed(%{state | ws: ws}, :invalid_frame) + end + end + + defp frames(state, []), do: {:ok, state} + + defp frames(state, [{:ping, data} | rest]) do + with {:ok, state} <- send_frames(state, [{:pong, data}]), do: frames(state, rest) + end + + defp frames(state, [{:pong, _} | rest]), do: frames(state, rest) + defp frames(state, [{:close, _, _} | _]), do: {:error, :connection_closed, state} + + defp frames(state, [{kind, _} = frame | rest]) when kind in [:text, :binary] do + with {:ok, events, outgoing, adapter} <- state.module.handle_frame(frame, state.adapter), + {:ok, state} <- send_frames(%{state | adapter: adapter}, outgoing), + {:ok, state} <- events(state, events) do + frames(state, rest) + else + {:error, reason, state} -> {:error, reason, state} + {:error, reason} -> {:error, reason, state} + end + end + + defp frames(state, _), do: {:error, :invalid_frame, state} + + defp events(state, []), do: {:ok, state} + + defp events(%{phase: :open} = state, [:ready | rest]) do + :erlang.cancel_timer(state.connect_timer) + + state = + restart_idle(%{ + state + | phase: :ready, + connect_timer: nil, + ready_at: System.monotonic_time(:millisecond) + }) + + with :ok <- notify(state, :ready), do: events(state, rest) + end + + defp events(state, [{:audio, %Audio{} = audio} = event | rest]) do + state = %{state | received: state.received + div(byte_size(audio.data), 2)} + with :ok <- notify(state, event), do: events(state, rest) + end + + defp events(state, [event | rest]) do + if valid_event?(event) do + with :ok <- notify(state, event), do: events(state, rest) + else + {:error, :invalid_event, state} + end + end + + @statuses [:created, :completed, :cancelled, :incomplete, :failed] + + defp valid_event?({:text, text}), do: is_binary(text) + defp valid_event?({:speech_started, item}), do: is_binary(item) + defp valid_event?({:output, item}), do: is_binary(item) + + defp valid_event?({:transcript, item, text}), + do: is_binary(item) and (is_binary(text) or text == :failed) + + defp valid_event?({:response, id, status}), do: is_binary(id) and status in @statuses + defp valid_event?(_event), do: false + + defp notify(state, event) do + case Process.info(state.owner, :message_queue_len) do + {:message_queue_len, length} when length >= state.max_queue -> + {:error, :owner_overloaded, state} + + _ -> + send(state.owner, {__MODULE__, self(), event}) + :ok + end + end + + defp notify!(state, event), do: send(state.owner, {__MODULE__, self(), event}) + + defp restart_idle(state) do + if state.idle_timer, do: :erlang.cancel_timer(state.idle_timer) + %{state | idle_timer: :erlang.start_timer(state.idle_ms, self(), :idle)} + end + + defp send_frames(state, frames) do + Enum.reduce_while(frames, {:ok, state}, fn frame, {:ok, state} -> + result = + case WS.encode(state.ws, frame) do + {:ok, ws, data} -> write(%{state | ws: ws}, data) + {:error, ws, _} -> {:error, :send_failed, %{state | ws: ws}} + end + + if match?({:ok, _}, result), do: {:cont, result}, else: {:halt, result} + end) + end + + defp write(state, data) do + case WS.stream_request_body(state.conn, state.ref, data) do + {:ok, conn} -> + {:ok, %{state | conn: conn}} + + {:error, conn, %Mint.TransportError{reason: reason}} + when reason in [:closed, :epipe, :econnreset] -> + {:error, :connection_closed, %{state | conn: conn}} + + {:error, conn, _} -> + {:error, :send_failed, %{state | conn: conn}} + end + end + + # Runs in a linked process, so the session answers calls while it connects. + # The socket moves to the session after the WebSocket upgrade. + defp connect(server, config, timeout, send_timeout) do + deadline = System.monotonic_time(:millisecond) + timeout + transport = [send_timeout: send_timeout, send_timeout_close: true] + # A header function keeps credentials out of the session state. + headers = if is_function(config.headers, 0), do: config.headers.(), else: config.headers + + case Socket.open(config.url, headers, deadline, + mode: :active, + transport_opts: transport + ) do + {:ok, conn, ws, ref, pending} -> + case Mint.HTTP.controlling_process(conn, server) do + {:ok, conn} -> + {:ok, conn, ws, ref, pending} + + {:error, _} -> + Mint.HTTP.close(conn) + {:error, :connect_failed} + end + + {:error, :timeout} -> + {:error, :connect_timeout} + + {:error, {:http_status, _}} = error -> + error + + {:error, _} -> + {:error, :connect_failed} + end + end +end diff --git a/lib/audio_flow/duplex/adapter.ex b/lib/audio_flow/duplex/adapter.ex new file mode 100644 index 0000000..1261133 --- /dev/null +++ b/lib/audio_flow/duplex/adapter.ex @@ -0,0 +1,79 @@ +defmodule AudioFlow.Duplex.Adapter do + @moduledoc """ + Wire protocol of one continuous `AudioFlow.Duplex` model connection. + + `AudioFlow.Duplex` owns the WebSocket, the timers, the bounds and the owner + messages. An adapter only maps audio to frames and frames to events. All + callbacks except `config/1` run in the session process. + + `handle_frame/2` returns events in wire order: + + * `:ready` once, after the model handshake. The session rejects audio + until then. + * `{:audio, %AudioFlow.Audio{}}` with model output at `:sample_rate`. + * `{:text, text}` with model text. + + Adapters for models with their own turn detection also return: + + * `{:speech_started, item}`: the model detected user speech. Audio of the + current reply is obsolete; the owner flushes queued playback. `item` is + the provider ID of the user input. + * `{:transcript, item, text}`: final transcript of the user input `item`, + or `{:transcript, item, :failed}`. + * `{:response, id, status}`: a model reply starts (`:created`) or ends + (`:completed`, `:cancelled`, `:incomplete` or `:failed`). + * `{:output, item}`: the next `{:audio, _}` events belong to the reply + audio `item`, until the next `{:output, _}` or `{:speech_started, _}`. + """ + alias AudioFlow.Audio + + @type frame :: {:text | :binary, binary()} + @type item :: String.t() + @type event :: + :ready + | {:audio, Audio.t()} + | {:text, String.t()} + | {:speech_started, item()} + | {:transcript, item(), String.t() | :failed} + | {:response, String.t(), :created | :completed | :cancelled | :incomplete | :failed} + | {:output, item()} + + @doc """ + Validates options in the caller of `AudioFlow.Duplex.start_link/1`. Raises + `ArgumentError` for invalid options. `:url` must be `ws` or `wss`. + + `:headers` can be a function that returns the headers. The session calls it + only to connect, so credentials do not stay in the session state. + + `:input_flow` (default `:answered`) selects the input bound. `:answered` + counts input that model audio has not answered; use it when the model sends + one output frame for each input frame. `:realtime` counts input ahead of the + wall clock; use it when the model is silent while the user speaks. + """ + @callback config(options :: keyword()) :: %{ + required(:url) => String.t(), + required(:headers) => [{String.t(), String.t()}] | (-> [{String.t(), String.t()}]), + required(:sample_rate) => pos_integer(), + required(:options) => term(), + optional(:input_flow) => :answered | :realtime + } + + @doc "Returns the initial protocol state from `config/1` `:options`." + @callback init(options :: term()) :: state :: term() + + @callback handle_frame(frame(), state :: term()) :: + {:ok, [event()], [frame()], state :: term()} | {:error, term()} + + @doc "Maps one accepted input chunk to frames. Partial model frames may stay buffered." + @callback handle_audio(Audio.t(), state :: term()) :: + {:ok, [frame()], state :: term()} | {:error, term()} + + @doc """ + Maps a command from `AudioFlow.Duplex.control/2` to frames. An error leaves + the session open. + """ + @callback handle_control(command :: term(), state :: term()) :: + {:ok, [frame()], state :: term()} | {:error, term()} + + @optional_callbacks handle_control: 2 +end diff --git a/lib/audio_flow/duplex/openai_realtime.ex b/lib/audio_flow/duplex/openai_realtime.ex new file mode 100644 index 0000000..f023324 --- /dev/null +++ b/lib/audio_flow/duplex/openai_realtime.ex @@ -0,0 +1,279 @@ +defmodule AudioFlow.Duplex.OpenAIRealtime do + @moduledoc """ + `AudioFlow.Duplex` adapter for one continuous OpenAI Realtime conversation + over the GA WebSocket protocol. Needs no media dependencies. + + The adapter sends `session.update` after `session.created` and emits `:ready` + after `session.updated`. Input is mono s16le PCM at 24 kHz; each push becomes + one `input_audio_buffer.append`. OpenAI server VAD detects speech, commits each + utterance and creates the reply (`create_response`). New speech cancels the + current reply (`interrupt_response`). The adapter never commits input or + creates replies itself. The provider conversation keeps every utterance of + one connection; a new connection starts a new conversation. + + Events: `{:speech_started, item}`, `{:transcript, item, text | :failed}`, + `{:response, id, status}`, `{:output, item}`, `{:audio, audio}` and + `{:text, delta}` (assistant audio transcript or text). After + `{:speech_started, _}`, late audio and text of the interrupted reply are + dropped. + + Control `{:played, item, ms}` reports how much audio of the interrupted reply + `item` played before the owner flushed it. If that is less than the audio + received for `item`, the adapter sends `conversation.item.truncate` with + `audio_end_ms` capped to the received audio, so the provider history keeps + only the played part. Only the last interrupted reply is accepted, once; + anything else returns `{:error, :stale}`. + + Fatal reasons: `{:remote_error, code}` (provider `error` event, except for a + rejected truncation), `:unsupported_tool_call` (no tools are configured), + `:invalid_audio` and `:invalid_event`. + + Options: `:model` (required), `:api_key` (required; a function is resolved + only to connect), `:voice` (`"marin"`), `:instructions` (`""`), + `:transcription_model` (`"gpt-4o-mini-transcribe"`) and `:endpoint` + (`"wss://api.openai.com/v1/realtime"`). + """ + @behaviour AudioFlow.Duplex.Adapter + alias AudioFlow.Adapters.Providers.Socket + alias AudioFlow.Audio + + @rate 24_000 + @truncate "audioflow_truncate_" + @statuses %{ + "completed" => :completed, + "cancelled" => :cancelled, + "incomplete" => :incomplete, + "failed" => :failed + } + + @impl true + def config(options) do + options = + Keyword.validate!(options, [ + :model, + :api_key, + voice: "marin", + instructions: "", + transcription_model: "gpt-4o-mini-transcribe", + endpoint: "wss://api.openai.com/v1/realtime" + ]) + + for key <- [:model, :voice, :transcription_model, :endpoint] do + unless is_binary(options[key]) and options[key] != "", + do: raise(ArgumentError, "#{key} must be a nonempty string") + end + + unless is_binary(options[:instructions]), + do: raise(ArgumentError, "instructions must be a string") + + api_key = options[:api_key] + + unless is_function(api_key, 0) or (is_binary(api_key) and api_key != ""), + do: raise(ArgumentError, "api_key must be a nonempty string or a function") + + %{ + url: Socket.url(options[:endpoint], %{"model" => options[:model]}), + headers: fn -> [{"authorization", "Bearer " <> Socket.key(api_key: api_key)}] end, + sample_rate: @rate, + input_flow: :realtime, + options: Keyword.take(options, [:model, :voice, :instructions, :transcription_model]) + } + end + + @impl true + def init(options) do + %{ + session: options, + phase: :connecting, + response: nil, + dropped: nil, + output: nil, + cut: nil, + truncates: 0 + } + end + + @impl true + def handle_frame({:text, data}, state) do + case JSON.decode(data) do + {:ok, %{"type" => type} = event} when is_binary(type) -> event(type, event, state) + _ -> {:error, :invalid_event} + end + end + + def handle_frame(_frame, _state), do: {:error, :invalid_event} + + @impl true + def handle_audio(%Audio{data: data}, state), + do: {:ok, [json(%{type: "input_audio_buffer.append", audio: Base.encode64(data)})], state} + + @impl true + def handle_control({:played, item, ms}, %{cut: %{item: item} = cut} = state) + when is_binary(item) and is_integer(ms) and ms >= 0 do + received = div(cut.samples * 1000, @rate) + state = %{state | cut: nil} + + if ms < received do + count = state.truncates + 1 + + truncate = %{ + type: "conversation.item.truncate", + event_id: @truncate <> Integer.to_string(count), + item_id: item, + content_index: cut.content_index, + audio_end_ms: ms + } + + {:ok, [json(truncate)], %{state | truncates: count}} + else + {:ok, [], state} + end + end + + def handle_control({:played, item, ms}, _state) + when is_binary(item) and is_integer(ms) and ms >= 0, + do: {:error, :stale} + + def handle_control(_command, _state), do: {:error, :invalid_command} + + defp event("session.created", _event, %{phase: :connecting} = state), + do: + {:ok, [], [json(%{type: "session.update", session: session(state.session)})], + %{state | phase: :updating}} + + defp event("session.updated", _event, %{phase: :updating} = state), + do: {:ok, [:ready], [], %{state | phase: :ready}} + + defp event("error", event, state) do + error = if is_map(event["error"]), do: event["error"], else: %{} + + # A rejected truncation only leaves the provider history longer. + if is_binary(error["event_id"]) and String.starts_with?(error["event_id"], @truncate), + do: {:ok, [], [], state}, + else: {:error, {:remote_error, code(error)}} + end + + defp event(_type, _event, %{phase: phase} = state) when phase != :ready, + do: {:ok, [], [], state} + + defp event("input_audio_buffer.speech_started", %{"item_id" => item}, state) + when is_binary(item) do + state = %{state | dropped: state.response, cut: state.output || state.cut, output: nil} + {:ok, [{:speech_started, item}], [], state} + end + + defp event( + "conversation.item.input_audio_transcription.completed", + %{"item_id" => item, "transcript" => text}, + state + ) + when is_binary(item) and is_binary(text), + do: {:ok, [{:transcript, item, text}], [], state} + + defp event("conversation.item.input_audio_transcription.failed", %{"item_id" => item}, state) + when is_binary(item), + do: {:ok, [{:transcript, item, :failed}], [], state} + + defp event("response.created", %{"response" => %{"id" => id}}, state) when is_binary(id), + do: {:ok, [{:response, id, :created}], [], %{state | response: id}} + + defp event("response.output_audio.delta", %{"response_id" => id}, %{dropped: id} = state), + do: {:ok, [], [], state} + + defp event( + "response.output_audio.delta", + %{"item_id" => item, "delta" => delta} = event, + state + ) + when is_binary(item) and is_binary(delta) do + case Base.decode64(delta) do + {:ok, pcm} when rem(byte_size(pcm), 2) == 0 -> audio(pcm, item, event, state) + _ -> {:error, :invalid_audio} + end + end + + defp event(type, %{"response_id" => id}, %{dropped: id} = state) + when type in ["response.output_audio_transcript.delta", "response.output_text.delta"], + do: {:ok, [], [], state} + + defp event(type, %{"delta" => text}, state) + when type in ["response.output_audio_transcript.delta", "response.output_text.delta"] and + is_binary(text), + do: {:ok, [{:text, text}], [], state} + + defp event("response.done", %{"response" => %{"id" => id} = response}, state) + when is_binary(id) do + output = if is_list(response["output"]), do: response["output"], else: [] + + cond do + Enum.any?(output, &(is_map(&1) and &1["type"] == "function_call")) -> + {:error, :unsupported_tool_call} + + status = @statuses[response["status"]] -> + state = %{ + state + | response: if(state.response == id, do: nil, else: state.response), + dropped: if(state.dropped == id, do: nil, else: state.dropped) + } + + {:ok, [{:response, id, status}], [], state} + + true -> + {:error, :invalid_event} + end + end + + defp event(type, _event, _state) + when type in [ + "input_audio_buffer.speech_started", + "response.created", + "response.output_audio.delta", + "response.output_audio_transcript.delta", + "response.output_text.delta", + "response.done", + "conversation.item.input_audio_transcription.completed", + "conversation.item.input_audio_transcription.failed" + ], + do: {:error, :invalid_event} + + defp event(_type, _event, state), do: {:ok, [], [], state} + + defp audio(pcm, item, event, state) do + {started, output} = + case state.output do + %{item: ^item} = output -> {[], output} + _ -> {[{:output, item}], %{item: item, content_index: index(event), samples: 0}} + end + + output = %{output | samples: output.samples + div(byte_size(pcm), 2)} + audio = {:audio, %Audio{data: pcm, sample_rate: @rate}} + {:ok, started ++ [audio], [], %{state | output: output}} + end + + defp session(options) do + %{ + type: "realtime", + model: options[:model], + output_modalities: ["audio"], + instructions: options[:instructions], + audio: %{ + input: %{ + format: %{type: "audio/pcm", rate: @rate}, + transcription: %{model: options[:transcription_model]}, + turn_detection: %{type: "server_vad", create_response: true, interrupt_response: true} + }, + output: %{format: %{type: "audio/pcm", rate: @rate}, voice: options[:voice]} + } + } + end + + defp index(%{"content_index" => index}) when is_integer(index) and index >= 0, do: index + defp index(_event), do: 0 + + # Only the short code or type: provider messages can quote request data. + defp code(%{"code" => code}) when is_binary(code), do: String.slice(code, 0, 64) + defp code(%{"type" => type}) when is_binary(type), do: String.slice(type, 0, 64) + defp code(_error), do: "unknown" + + defp json(value), do: {:text, JSON.encode!(value)} +end diff --git a/lib_media/audio_flow/adapters/moshi.ex b/lib_media/audio_flow/adapters/moshi.ex index 811176f..4b50f34 100644 --- a/lib_media/audio_flow/adapters/moshi.ex +++ b/lib_media/audio_flow/adapters/moshi.ex @@ -8,8 +8,10 @@ defmodule AudioFlow.Adapters.Moshi do Moshi does not transcribe the user, so there is no `:transcript` event. Use directly or in Session `:speech_to_speech`; see docs/providers.md. - Moshi is full duplex and has no end-of-turn signal. The adapter sends the - committed input, then silence, one 80 ms frame for each frame it receives. + Moshi is full duplex and has no end-of-turn signal. For continuous microphone + input with simultaneous output, use `AudioFlow.Duplex` with + `AudioFlow.Duplex.Moshi` instead. This adapter sends the committed input, + then silence, one 80 ms frame for each frame it receives. Output that belongs to the input period is dropped. The reply ends after `:end_silence_ms` of model output without text, or fails with `:no_reply` when `:max_reply_ms` passes without text. @@ -21,21 +23,12 @@ defmodule AudioFlow.Adapters.Moshi do @behaviour AudioFlow.Adapter alias AudioFlow.Adapters.Providers.Socket alias AudioFlow.Audio - alias Membrane.Ogg.Opus, as: OggOpus - alias Membrane.Ogg.Page - alias Membrane.Ogg.Parser - alias Membrane.Opus.Decoder.Native, as: Decoder - alias Membrane.Opus.Encoder.Native, as: Encoder + alias AudioFlow.Moshi.Codec @rate 24_000 - # Moshi steps every 80 ms; Opus packets are 20 ms. + # Moshi steps every 80 ms. @frame 1_920 - @packet 480 @lead @frame * 6 - # libopus OPUS_APPLICATION_AUDIO, OPUS_AUTO bitrate, OPUS_SIGNAL_VOICE. - @application 2049 - @bitrate -1000 - @signal 3001 def run(audio, options, emit) do Socket.audio!(audio, @rate) @@ -51,11 +44,7 @@ defmodule AudioFlow.Adapters.Moshi do received: 0, last_text: nil, ready: false, - encoder: Encoder.create(@rate, 1, @application, @bitrate, @signal), - decoder: Decoder.create(@rate, 1), - buffer: <<>>, - continued: nil, - page: nil, + codec: Codec.new(), emit: emit } @@ -66,7 +55,7 @@ defmodule AudioFlow.Adapters.Moshi do state, &event/2, Keyword.put_new(options, :timeout_ms, 60_000), - &decode/1 + &Codec.wire/1 ) end @@ -77,19 +66,10 @@ defmodule AudioFlow.Adapters.Moshi do end end - defp decode({:binary, <<0>>}), do: {:ok, :ready} - defp decode({:binary, <<1, data::binary>>}), do: {:ok, {:audio, data}} - - defp decode({:binary, <<2, text::binary>>}), - do: if(String.valid?(text), do: {:ok, {:text, text}}, else: :error) - - defp decode(_frame), do: :error - defp event(:ready, %{ready: false} = state) do - head = header(Page.create_first(:rand.uniform(0xFFFFFFFF) - 1), OggOpus.create_id_header(1)) - tags = header(Page.create_subsequent(head), OggOpus.create_comment_header()) - headers = {:binary, <<1>> <> Page.serialize(head) <> Page.serialize(tags)} - {state, frames} = top_up(%{state | ready: true, page: tags}, state.input_samples + @lead) + {codec, headers} = Codec.headers(state.codec) + state = %{state | ready: true, codec: codec} + {state, frames} = top_up(state, state.input_samples + @lead) {:cont, state, [headers | frames]} end @@ -106,14 +86,9 @@ defmodule AudioFlow.Adapters.Moshi do end defp event({:audio, data}, state) do - case parse(state.buffer <> data, state.continued) do - {:ok, packets, continued, rest} -> - pcm = - for %Parser.Packet{payload: packet} <- packets, not opus_header?(packet), into: <<>> do - Decoder.decode_packet(state.decoder, packet) - end - - state = %{state | buffer: rest, continued: continued} + case Codec.decode(state.codec, data) do + {:ok, codec, pcm} -> + state = %{state | codec: codec} :ok = emit_reply(pcm, state) received(%{state | received: state.received + div(byte_size(pcm), 2)}) @@ -122,20 +97,6 @@ defmodule AudioFlow.Adapters.Moshi do end end - # Parser.parse/2 keeps partial pages in `rest` and raises on a corrupt page. - defp parse(bytes, continued) do - {packets, continued, rest} = Parser.parse(bytes, continued) - {:ok, packets, continued, rest} - rescue - RuntimeError -> :error - end - - defp opus_header?(<<"OpusHead", _::binary>>), do: true - defp opus_header?(<<"OpusTags", _::binary>>), do: true - defp opus_header?(_packet), do: false - - defp header(page, packet), do: page |> Page.append_packet!(packet) |> Page.finalize(0) - defp emit_reply(pcm, state) do skip = max(state.input_samples - state.received, 0) * 2 @@ -181,22 +142,8 @@ defmodule AudioFlow.Adapters.Moshi do do: binary_part(state.input, state.sent * 2, @frame * 2), else: :binary.copy(<<0>>, @frame * 2) - packets = - for <> do - {:ok, packet} = Encoder.encode_packet(state.encoder, chunk, @packet) - packet - end - - sent = state.sent + @frame - - # One page per frame, so the server gets each frame at once. Ogg Opus - # granule positions count 48 kHz samples. - page = - packets - |> Enum.reduce(Page.create_subsequent(state.page), &Page.append_packet!(&2, &1)) - |> Page.finalize(sent * 2) - - state = %{state | sent: sent, page: page} - top_up(state, target, [{:binary, <<1>> <> Page.serialize(page)} | frames]) + {codec, frame} = Codec.encode(state.codec, pcm) + state = %{state | sent: state.sent + @frame, codec: codec} + top_up(state, target, [frame | frames]) end end diff --git a/lib_media/audio_flow/duplex/moshi.ex b/lib_media/audio_flow/duplex/moshi.ex new file mode 100644 index 0000000..7a857c0 --- /dev/null +++ b/lib_media/audio_flow/duplex/moshi.ex @@ -0,0 +1,80 @@ +defmodule AudioFlow.Duplex.Moshi do + @moduledoc """ + `AudioFlow.Duplex` adapter for a local Kyutai Moshi server + (`moshi_mlx.local_web` or the PyTorch `moshi.server`). Requires + `AUDIOFLOW_MEDIA=1` for Ogg Opus. + + Input is mono s16le PCM at 24 kHz. The adapter sends each complete 80 ms + frame (1,920 samples, 3,840 bytes) as one Ogg page of four 20 ms Opus + packets. A shorter remainder waits for the next push. Push 3,840-byte chunks + to send each frame at once. + + The session emits all decoded model audio and every text token as it + arrives, also while input continues. Moshi does not transcribe the user. + + Option: `:endpoint` (`"ws://127.0.0.1:8998/api/chat"`). + """ + @behaviour AudioFlow.Duplex.Adapter + alias AudioFlow.Audio + alias AudioFlow.Moshi.Codec + + @endpoint "ws://127.0.0.1:8998/api/chat" + + @impl true + def config(options) do + options = Keyword.validate!(options, endpoint: @endpoint) + endpoint = options[:endpoint] + + unless is_binary(endpoint), do: raise(ArgumentError, "endpoint must be a string") + + %{url: endpoint, headers: [], sample_rate: Codec.rate(), options: []} + end + + @impl true + def init([]), do: %{codec: Codec.new(), ready: false, pending: <<>>} + + @impl true + def handle_frame(frame, state) do + case {Codec.wire(frame), state.ready} do + {{:ok, :ready}, false} -> + {codec, headers} = Codec.headers(state.codec) + {:ok, [:ready], [headers], %{state | codec: codec, ready: true}} + + {{:ok, {:text, text}}, true} -> + {:ok, [{:text, text}], [], state} + + {{:ok, {:audio, data}}, true} -> + case Codec.decode(state.codec, data) do + {:ok, codec, <<>>} -> {:ok, [], [], %{state | codec: codec}} + {:ok, codec, pcm} -> {:ok, [audio(pcm)], [], %{state | codec: codec}} + :error -> {:error, :invalid_audio} + end + + _ -> + {:error, :invalid_event} + end + end + + @impl true + def handle_audio(%Audio{data: data}, state) do + size = Codec.frame_samples() * 2 + {frames, pending} = split(state.pending <> data, size, []) + + {codec, pages} = + Enum.reduce(frames, {state.codec, []}, fn pcm, {codec, pages} -> + {codec, page} = Codec.encode(codec, pcm) + {codec, [page | pages]} + end) + + {:ok, Enum.reverse(pages), %{state | codec: codec, pending: pending}} + end + + defp split(pcm, size, frames) when byte_size(pcm) < size, do: {Enum.reverse(frames), pcm} + + defp split(pcm, size, frames) do + <> = pcm + split(rest, size, [frame | frames]) + end + + defp audio(pcm), do: {:audio, %Audio{data: pcm, sample_rate: Codec.rate()}} +end diff --git a/lib_media/audio_flow/moshi/codec.ex b/lib_media/audio_flow/moshi/codec.ex new file mode 100644 index 0000000..9149871 --- /dev/null +++ b/lib_media/audio_flow/moshi/codec.ex @@ -0,0 +1,91 @@ +defmodule AudioFlow.Moshi.Codec do + @moduledoc false + # Moshi wire framing: binary WebSocket messages with a one-byte kind, `0` + # handshake, `1` Ogg Opus audio (24 kHz mono), `2` UTF-8 text. Client audio + # is one Ogg page per 80 ms frame, four 20 ms Opus packets per page, so the + # server gets each frame at once. + alias Membrane.Ogg.Opus, as: OggOpus + alias Membrane.Ogg.Page + alias Membrane.Ogg.Parser + alias Membrane.Opus.Decoder.Native, as: Decoder + alias Membrane.Opus.Encoder.Native, as: Encoder + + @rate 24_000 + @frame 1_920 + @packet 480 + # libopus OPUS_APPLICATION_AUDIO, OPUS_AUTO bitrate, OPUS_SIGNAL_VOICE. + @application 2049 + @bitrate -1000 + @signal 3001 + @max_pending_bytes 262_144 + + def rate, do: @rate + def frame_samples, do: @frame + + def new do + %{ + encoder: Encoder.create(@rate, 1, @application, @bitrate, @signal), + decoder: Decoder.create(@rate, 1), + buffer: <<>>, + continued: nil, + page: nil, + granule: 0 + } + end + + def wire({:binary, <<0>>}), do: {:ok, :ready} + def wire({:binary, <<1, data::binary>>}), do: {:ok, {:audio, data}} + + def wire({:binary, <<2, text::binary>>}), + do: if(String.valid?(text), do: {:ok, {:text, text}}, else: :error) + + def wire(_frame), do: :error + + def headers(codec) do + head = header(Page.create_first(:rand.uniform(0xFFFFFFFF) - 1), OggOpus.create_id_header(1)) + tags = header(Page.create_subsequent(head), OggOpus.create_comment_header()) + {%{codec | page: tags}, {:binary, <<1>> <> Page.serialize(head) <> Page.serialize(tags)}} + end + + defp header(page, packet), do: page |> Page.append_packet!(packet) |> Page.finalize(0) + + # `pcm` is exactly one 80 ms frame. Ogg Opus granule positions count 48 kHz + # samples. + def encode(codec, <>) do + granule = codec.granule + @frame * 2 + + page = + for <>, + reduce: Page.create_subsequent(codec.page) do + page -> + {:ok, packet} = Encoder.encode_packet(codec.encoder, chunk, @packet) + Page.append_packet!(page, packet) + end + |> Page.finalize(granule) + + {%{codec | page: page, granule: granule}, {:binary, <<1>> <> Page.serialize(page)}} + end + + # Returns the PCM of all complete Opus packets. Partial pages stay buffered. + def decode(codec, data) do + {packets, continued, rest} = Parser.parse(codec.buffer <> data, codec.continued) + + pcm = + for %Parser.Packet{payload: packet} <- packets, not opus_header?(packet), into: <<>> do + Decoder.decode_packet(codec.decoder, packet) + end + + if byte_size(rest) + byte_size(continued || <<>>) > @max_pending_bytes do + :error + else + {:ok, %{codec | buffer: rest, continued: continued}, pcm} + end + rescue + # Parser.parse/2 raises on a corrupt page. + _error in [RuntimeError, ErlangError] -> :error + end + + defp opus_header?(<<"OpusHead", _::binary>>), do: true + defp opus_header?(<<"OpusTags", _::binary>>), do: true + defp opus_header?(_packet), do: false +end diff --git a/test/duplex_openai_test.exs b/test/duplex_openai_test.exs new file mode 100644 index 0000000..f440e4e --- /dev/null +++ b/test/duplex_openai_test.exs @@ -0,0 +1,348 @@ +defmodule AudioFlow.DuplexOpenAITest do + use ExUnit.Case, async: true + alias AudioFlow.Audio + alias AudioFlow.Duplex + alias AudioFlow.Duplex.OpenAIRealtime + + # Local peer with the OpenAI Realtime GA event framing. It reports the + # upgrade request and every client event to the test, and pushes the events + # that the test sends to it. It never acts on its own. + defmodule Peer do + @behaviour WebSock + + def init(owner) do + send(owner, {:peer, self()}) + {:ok, owner} + end + + def handle_in({data, opcode: :text}, owner) do + send(owner, {:client, JSON.decode!(data)}) + {:ok, owner} + end + + def handle_info({:events, events}, owner), + do: {:push, Enum.map(events, &{:text, JSON.encode!(&1)}), owner} + + def handle_info(:close, owner), do: {:stop, :normal, owner} + + def terminate(_reason, owner) do + send(owner, :peer_closed) + :ok + end + end + + defmodule Endpoint do + def init(owner), do: owner + + def call(conn, owner) do + send(owner, {:upgrade, conn.query_string, conn.req_headers}) + conn |> WebSockAdapter.upgrade(Peer, owner, []) |> Plug.Conn.halt() + end + end + + # 80 ms of 24 kHz mono s16le. + @chunk 3_840 + + defp endpoint do + server = + start_supervised!( + {Bandit, plug: {Endpoint, self()}, port: 0, ip: {127, 0, 0, 1}, startup_log: false} + ) + + {:ok, {_, port}} = ThousandIsland.listener_info(server) + "ws://127.0.0.1:#{port}/v1/realtime" + end + + defp start(options \\ []) do + adapter = + {OpenAIRealtime, + endpoint: endpoint(), + model: "fixture-model", + api_key: fn -> "fixture-key" end, + voice: "cedar"} + + {:ok, duplex} = Duplex.start_link([owner: self(), adapter: adapter] ++ options) + assert_receive {:peer, peer} + {duplex, peer} + end + + defp ready(options \\ []) do + {duplex, peer} = start(options) + send(peer, {:events, [%{type: "session.created", session: %{}}]}) + assert_receive {:client, %{"type" => "session.update"}} + send(peer, {:events, [%{type: "session.updated", session: %{}}]}) + assert_receive {Duplex, ^duplex, :ready} + {duplex, peer} + end + + defp silence(bytes \\ @chunk), do: %Audio{data: :binary.copy(<<0>>, bytes), sample_rate: 24_000} + defp pcm(samples), do: Base.encode64(:binary.copy(<<1, 0>>, samples)) + + defp delta(response, item, samples) do + %{ + type: "response.output_audio.delta", + response_id: response, + item_id: item, + output_index: 0, + content_index: 0, + delta: pcm(samples) + } + end + + defp reply(peer, response, item, text, samples) do + send( + peer, + {:events, + [ + %{type: "response.created", response: %{id: response, status: "in_progress"}}, + delta(response, item, samples), + %{type: "response.output_audio_transcript.delta", response_id: response, delta: text} + ]} + ) + end + + defp done(peer, response, status, output \\ []), + do: + send( + peer, + {:events, + [%{type: "response.done", response: %{id: response, status: status, output: output}}]} + ) + + defp speech(peer, item, transcript) do + send( + peer, + {:events, + [ + %{type: "input_audio_buffer.speech_started", item_id: item, audio_start_ms: 0}, + %{type: "input_audio_buffer.speech_stopped", item_id: item, audio_end_ms: 900}, + %{type: "input_audio_buffer.committed", item_id: item}, + %{ + type: "conversation.item.input_audio_transcription.completed", + item_id: item, + content_index: 0, + transcript: transcript + } + ]} + ) + end + + test "configures server VAD replies, then is ready only after session.updated" do + {duplex, peer} = start() + + assert_received {:upgrade, "model=fixture-model", headers} + assert {"authorization", "Bearer fixture-key"} in headers + assert {:error, :not_ready} = Duplex.push(duplex, silence()) + + send(peer, {:events, [%{type: "session.created", session: %{}}]}) + assert_receive {:client, %{"type" => "session.update", "session" => session}} + + assert %{ + "type" => "realtime", + "model" => "fixture-model", + "output_modalities" => ["audio"], + "audio" => %{ + "input" => %{ + "format" => %{"type" => "audio/pcm", "rate" => 24_000}, + "transcription" => %{"model" => "gpt-4o-mini-transcribe"}, + "turn_detection" => %{ + "type" => "server_vad", + "create_response" => true, + "interrupt_response" => true + } + }, + "output" => %{ + "format" => %{"type" => "audio/pcm", "rate" => 24_000}, + "voice" => "cedar" + } + } + } = session + + refute_receive {Duplex, ^duplex, :ready}, 100 + assert {:error, :not_ready} = Duplex.push(duplex, silence()) + + send(peer, {:events, [%{type: "session.updated", session: session}]}) + assert_receive {Duplex, ^duplex, :ready} + assert :ok = Duplex.push(duplex, silence()) + assert_receive {:client, %{"type" => "input_audio_buffer.append", "audio" => audio}} + assert Base.decode64!(audio) == silence().data + end + + test "several utterances share one connection; input is only appended, never committed" do + {duplex, peer} = ready() + + for {user, response, item, text} <- [ + {"user_1", "resp_1", "item_1", "Hello."}, + {"user_2", "resp_2", "item_2", "Again."} + ] do + assert :ok = Duplex.push(duplex, silence()) + speech(peer, user, "Question #{user}") + reply(peer, response, item, text, 480) + done(peer, response, "completed") + + assert_receive {Duplex, ^duplex, {:speech_started, ^user}} + assert_receive {Duplex, ^duplex, {:transcript, ^user, "Question " <> ^user}} + assert_receive {Duplex, ^duplex, {:response, ^response, :created}} + assert_receive {Duplex, ^duplex, {:output, ^item}} + assert_receive {Duplex, ^duplex, {:audio, %Audio{data: data, sample_rate: 24_000}}} + assert byte_size(data) == 960 + assert_receive {Duplex, ^duplex, {:text, ^text}} + assert_receive {Duplex, ^duplex, {:response, ^response, :completed}} + end + + for _ <- 1..2, do: assert_receive({:client, %{"type" => "input_audio_buffer.append"}}) + refute_received {:client, _} + refute_received {:peer, _} + end + + test "continuous silence well past the input lead is accepted at the real-time rate" do + {duplex, _peer} = ready(max_input_lead_ms: 400) + + # 2.4 s of silence at the browser rate, with no model output at all. + for _ <- 1..30 do + assert :ok = Duplex.push(duplex, silence()) + Process.sleep(80) + end + + # A burst far ahead of the clock is refused, and the call stays open. + results = for _ <- 1..40, do: Duplex.push(duplex, silence()) + assert {:error, :overloaded} in results + assert Process.alive?(duplex) + refute_received {Duplex, ^duplex, {:error, _}} + end + + test "speech during a reply drops its late audio and text, and the next reply plays" do + {duplex, peer} = ready() + reply(peer, "resp_1", "item_1", "Long answer", 2_400) + assert_receive {Duplex, ^duplex, {:audio, _}} + assert_receive {Duplex, ^duplex, {:text, "Long answer"}} + + send( + peer, + {:events, + [ + %{type: "input_audio_buffer.speech_started", item_id: "user_2", audio_start_ms: 10}, + delta("resp_1", "item_1", 2_400), + %{type: "response.output_audio_transcript.delta", response_id: "resp_1", delta: " late"} + ]} + ) + + assert_receive {Duplex, ^duplex, {:speech_started, "user_2"}} + done(peer, "resp_1", "cancelled") + assert_receive {Duplex, ^duplex, {:response, "resp_1", :cancelled}} + refute_received {Duplex, ^duplex, {:audio, _}} + refute_received {Duplex, ^duplex, {:text, " late"}} + + # Input continues during and after the interruption. + assert :ok = Duplex.push(duplex, silence()) + reply(peer, "resp_2", "item_2", "Short", 480) + assert_receive {Duplex, ^duplex, {:output, "item_2"}} + assert_receive {Duplex, ^duplex, {:audio, _}} + assert_receive {Duplex, ^duplex, {:text, "Short"}} + end + + test "played audio of the interrupted reply truncates the provider item, capped and once" do + {duplex, peer} = ready() + # 200 ms of reply audio in two deltas. + reply(peer, "resp_1", "item_1", "Hi", 2_400) + send(peer, {:events, [delta("resp_1", "item_1", 2_400)]}) + for _ <- 1..2, do: assert_receive({Duplex, ^duplex, {:audio, _}}) + + assert {:error, :stale} = Duplex.control(duplex, {:played, "item_1", 50}) + + speech(peer, "user_2", "Wait") + assert_receive {Duplex, ^duplex, {:speech_started, "user_2"}} + + assert {:error, :stale} = Duplex.control(duplex, {:played, "other", 50}) + assert {:error, :invalid_command} = Duplex.control(duplex, {:played, "item_1", -1}) + assert :ok = Duplex.control(duplex, {:played, "item_1", 120}) + + assert_receive {:client, + %{ + "type" => "conversation.item.truncate", + "item_id" => "item_1", + "content_index" => 0, + "audio_end_ms" => 120, + "event_id" => event_id + }} + + assert {:error, :stale} = Duplex.control(duplex, {:played, "item_1", 100}) + + # A rejected truncation does not end the call. + send( + peer, + {:events, [%{type: "error", error: %{type: "invalid_request_error", event_id: event_id}}]} + ) + + assert :ok = Duplex.push(duplex, silence()) + + # A report at or past the received audio needs no truncation. + reply(peer, "resp_2", "item_2", "Ok", 2_400) + assert_receive {Duplex, ^duplex, {:output, "item_2"}} + speech(peer, "user_3", "More") + assert_receive {Duplex, ^duplex, {:speech_started, "user_3"}} + assert :ok = Duplex.control(duplex, {:played, "item_2", 5_000}) + refute_receive {:client, %{"type" => "conversation.item.truncate"}}, 100 + refute_received {Duplex, ^duplex, {:error, _}} + end + + test "provider errors, tool calls and invalid audio fail the call with a reason" do + for {events, reason} <- [ + {[%{type: "error", error: %{type: "server_error", code: "boom", message: "detail"}}], + {:remote_error, "boom"}}, + {[ + %{ + type: "response.done", + response: %{id: "r", status: "completed", output: [%{type: "function_call"}]} + } + ], :unsupported_tool_call}, + {[%{type: "response.output_audio.delta", response_id: "r", item_id: "i", delta: "%%"}], + :invalid_audio} + ] do + {duplex, peer} = ready() + ref = Process.monitor(duplex) + send(peer, {:events, events}) + assert_receive {Duplex, ^duplex, {:error, ^reason}} + assert_receive {Duplex, ^duplex, :closed} + assert_receive {:DOWN, ^ref, :process, ^duplex, :normal} + assert_receive :peer_closed + end + end + + test "an error before session.updated fails the start" do + {duplex, peer} = start() + + send( + peer, + {:events, [%{type: "error", error: %{type: "invalid_request_error", code: "bad_model"}}]} + ) + + assert_receive {Duplex, ^duplex, {:error, {:remote_error, "bad_model"}}} + assert_receive {Duplex, ^duplex, :closed} + refute_received {Duplex, ^duplex, :ready} + end + + test "stop closes the connection; a new call starts a new provider session" do + {duplex, _peer} = ready() + assert :ok = Duplex.stop(duplex) + assert_receive {Duplex, ^duplex, :closed} + assert_receive :peer_closed + assert {:error, :closed} = Duplex.control(duplex, {:played, "item", 0}) + + {second, _peer} = ready() + assert second != duplex + end + + test "rejects invalid options in the caller" do + for options <- [ + [api_key: "k"], + [model: "m"], + [model: "", api_key: "k"], + [model: "m", api_key: "k", endpoint: "https://api.openai.com/v1/realtime"] + ] do + assert_raise ArgumentError, fn -> + Duplex.start_link(owner: self(), adapter: {OpenAIRealtime, options}) + end + end + end +end diff --git a/test/duplex_test.exs b/test/duplex_test.exs new file mode 100644 index 0000000..1e8b046 --- /dev/null +++ b/test/duplex_test.exs @@ -0,0 +1,283 @@ +if System.get_env("AUDIOFLOW_MEDIA") == "1" do + defmodule AudioFlow.DuplexTest do + use ExUnit.Case, async: true + alias AudioFlow.Audio + alias AudioFlow.Duplex + alias AudioFlow.Test.MoshiServer + alias Membrane.Ogg.Page + + # One Moshi step: 80 ms of 24 kHz mono s16le. + @frame_bytes 3_840 + + defp tone(bytes) do + for i <- 0..(div(bytes, 2) - 1), + into: <<>>, + do: <> + end + + defp chunk(bytes \\ @frame_bytes), do: %Audio{data: tone(bytes), sample_rate: 24_000} + + defp start(server_options, options \\ []) do + endpoint = MoshiServer.endpoint(self(), server_options) + + {:ok, duplex} = + Duplex.start_link([owner: self(), adapter: {Duplex.Moshi, endpoint: endpoint}] ++ options) + + assert_receive {:moshi_server, server} + {duplex, server} + end + + defp ready(server_options \\ [], options \\ []) do + {duplex, server} = start(server_options, options) + assert_receive {Duplex, ^duplex, :ready} + # The Ogg Opus head and tags pages carry no PCM. + assert_receive {:client_pcm, <<>>} + {duplex, server} + end + + defp drain(duplex, events) do + receive do + {Duplex, ^duplex, event} -> drain(duplex, [event | events]) + after + 0 -> events + end + end + + test "model audio and text arrive while microphone input continues" do + {duplex, _server} = ready(script: %{1 => " Hi"}) + + for index <- 0..2 do + assert :ok = Duplex.push(duplex, chunk()) + assert_receive {:client_pcm, pcm} + assert byte_size(pcm) == @frame_bytes + assert pcm |> :binary.bin_to_list() |> Enum.any?(&(&1 != 0)) + + # Each input frame is answered before the next one is pushed: no + # end-of-turn gate holds output back while the user speaks. + assert_receive {Duplex, ^duplex, {:audio, %Audio{data: out, sample_rate: 24_000}}} + assert byte_size(out) == @frame_bytes + if index == 1, do: assert_receive({Duplex, ^duplex, {:text, " Hi"}}) + end + + refute_received {Duplex, ^duplex, {:error, _}} + end + + test "sends each complete 80 ms frame as its own message and keeps the remainder" do + {duplex, _server} = ready() + + assert :ok = Duplex.push(duplex, chunk(1_000)) + refute_receive {:client_pcm, _}, 100 + + assert :ok = Duplex.push(duplex, chunk(2 * @frame_bytes - 1_000)) + assert_receive {:client_pcm, first} + assert_receive {:client_pcm, second} + assert byte_size(first) == @frame_bytes and byte_size(second) == @frame_bytes + end + + test "emits ready only after the model handshake and rejects audio before it" do + {duplex, server} = start(handshake: :manual) + + assert {:error, :not_ready} = Duplex.push(duplex, chunk()) + refute_receive {Duplex, ^duplex, :ready}, 100 + + send(server, :handshake) + assert_receive {Duplex, ^duplex, :ready} + assert :ok = Duplex.push(duplex, chunk()) + end + + test "bounds unanswered input and rejects invalid chunks without closing" do + {duplex, server} = + ready([reply: :manual], max_input_lead_ms: 200, max_chunk_bytes: @frame_bytes) + + assert {:error, :invalid_audio} = + Duplex.push(duplex, %Audio{data: nil, sample_rate: 24_000}) + + assert {:error, :invalid_audio} = + Duplex.push(duplex, %Audio{data: tone(@frame_bytes), sample_rate: 16_000}) + + assert {:error, :invalid_audio} = + Duplex.push(duplex, %Audio{data: <<0>>, sample_rate: 24_000}) + + assert {:error, :too_large} = Duplex.push(duplex, chunk(2 * @frame_bytes)) + + # 200 ms bound: two 80 ms frames fit, a third does not. + assert :ok = Duplex.push(duplex, chunk()) + assert :ok = Duplex.push(duplex, chunk()) + assert {:error, :overloaded} = Duplex.push(duplex, chunk()) + assert_receive {:client_pcm, _} + assert_receive {:client_pcm, _} + refute_receive {:client_pcm, _}, 100 + + send(server, :reply) + assert_receive {Duplex, ^duplex, {:audio, _}} + assert_receive {Duplex, ^duplex, {:audio, _}} + assert :ok = Duplex.push(duplex, chunk()) + assert_receive {:client_pcm, _} + refute_received {Duplex, ^duplex, {:error, _}} + end + + test "stop closes the connection and later calls report it closed" do + {duplex, _server} = ready() + + assert :ok = Duplex.stop(duplex) + assert_receive {Duplex, ^duplex, :closed} + assert_receive :moshi_server_closed + refute_received {Duplex, ^duplex, {:error, _}} + assert {:error, :closed} = Duplex.push(duplex, chunk()) + assert :ok = Duplex.stop(duplex) + end + + test "corrupt Opus is reported as an error without crashing the owner" do + {duplex, server} = ready() + ref = Process.monitor(duplex) + + page = + Page.create_first(2) + |> Page.append_packet!(<<3>>) + |> Page.finalize(0) + |> Page.serialize() + + send(server, {:push, [{:binary, <<1>> <> page}]}) + assert_receive {Duplex, ^duplex, {:error, :invalid_audio}} + assert_receive {Duplex, ^duplex, :closed} + assert_receive {:DOWN, ^ref, :process, ^duplex, :normal} + end + + test "the incoming byte budget closes the connection" do + {duplex, _server} = start([], max_response_bytes: 1) + assert_receive {Duplex, ^duplex, {:error, :response_too_large}} + assert_receive {Duplex, ^duplex, :closed} + assert_receive :moshi_server_closed + end + + test "owner exit closes the connection" do + owner = spawn(fn -> Process.sleep(:infinity) end) + endpoint = MoshiServer.endpoint(self()) + + {:ok, duplex} = + Duplex.start_link(owner: owner, adapter: {Duplex.Moshi, endpoint: endpoint}) + + ref = Process.monitor(duplex) + assert_receive {:moshi_server, _server} + Process.exit(owner, :kill) + + assert_receive {:DOWN, ^ref, :process, ^duplex, :normal} + assert_receive :moshi_server_closed + end + + test "fails the session when the owner mailbox is full" do + test = self() + + owner = + spawn(fn -> + receive do + {Duplex, _, :ready} = message -> send(test, message) + end + + Process.sleep(:infinity) + end) + + endpoint = MoshiServer.endpoint(self()) + + {:ok, duplex} = + Duplex.start_link( + owner: owner, + adapter: {Duplex.Moshi, endpoint: endpoint}, + max_owner_queue: 1 + ) + + ref = Process.monitor(duplex) + assert_receive {Duplex, ^duplex, :ready} + assert :ok = Duplex.push(duplex, chunk(2 * @frame_bytes)) + + assert_receive {:DOWN, ^ref, :process, ^duplex, :normal} + assert_receive :moshi_server_closed + + assert {:messages, + [ + {Duplex, ^duplex, {:audio, _}}, + {Duplex, ^duplex, {:error, :owner_overloaded}}, + {Duplex, ^duplex, :closed} + ]} = Process.info(owner, :messages) + + Process.exit(owner, :kill) + end + + for {reason, server_options, options, action} <- [ + {:connect_timeout, [handshake: :manual], [connect_timeout_ms: 100], nil}, + {:idle_timeout, [], [idle_timeout_ms: 100], nil}, + {:session_timeout, [], [max_session_ms: 150], nil}, + {:connection_closed, [], [], :close} + ] do + test "reports #{reason}, then closed, and closes the connection" do + {duplex, server} = start(unquote(server_options), unquote(options)) + ref = Process.monitor(duplex) + if unquote(action), do: send(server, unquote(action)) + + assert_receive {Duplex, ^duplex, {:error, unquote(reason)}}, 1_000 + assert_receive {Duplex, ^duplex, :closed} + assert_receive :moshi_server_closed + assert_receive {:DOWN, ^ref, :process, ^duplex, :normal} + end + end + + test "reports connect_failed when no server listens" do + {:ok, socket} = :gen_tcp.listen(0, ip: {127, 0, 0, 1}) + {:ok, port} = :inet.port(socket) + :ok = :gen_tcp.close(socket) + + {:ok, duplex} = + Duplex.start_link( + owner: self(), + adapter: {Duplex.Moshi, endpoint: "ws://127.0.0.1:#{port}/api/chat"} + ) + + assert_receive {Duplex, ^duplex, {:error, :connect_failed}} + assert_receive {Duplex, ^duplex, :closed} + end + + test "rejects invalid options in the caller" do + adapter = {Duplex.Moshi, endpoint: "http://127.0.0.1:8998/api/chat"} + + assert_raise ArgumentError, fn -> Duplex.start_link(owner: self(), adapter: adapter) end + + assert_raise ArgumentError, fn -> + Duplex.start_link(owner: self(), adapter: {Duplex.Moshi, port: 8998}) + end + end + + @tag :http_model + test "a local Moshi server answers continuous input" do + endpoint = System.get_env("AUDIOFLOW_MOSHI_ENDPOINT", "ws://127.0.0.1:8998/api/chat") + question = System.fetch_env!("AUDIOFLOW_MOSHI_PCM") |> File.read!() + + {:ok, duplex} = + Duplex.start_link( + owner: self(), + adapter: {Duplex.Moshi, endpoint: endpoint}, + connect_timeout_ms: 60_000 + ) + + assert_receive {Duplex, ^duplex, :ready}, 60_000 + silence = :binary.copy(<<0>>, @frame_bytes * 75) + + events = + for < silence>>, reduce: [] do + events -> + # The first steps after server start are slow; those pushes overload. + assert Duplex.push(duplex, %Audio{data: frame, sample_rate: 24_000}) in [ + :ok, + {:error, :overloaded} + ] + + Process.sleep(80) + drain(duplex, events) + end + + assert Enum.any?(events, &match?({:audio, _}, &1)) + assert Enum.any?(events, &match?({:text, _}, &1)) + refute Enum.any?(events, &match?({:error, _}, &1)) + Duplex.stop(duplex) + end + end +end diff --git a/test/moshi_test.exs b/test/moshi_test.exs index db734c2..0097038 100644 --- a/test/moshi_test.exs +++ b/test/moshi_test.exs @@ -3,96 +3,10 @@ if System.get_env("AUDIOFLOW_MEDIA") == "1" do use ExUnit.Case, async: true alias AudioFlow.Adapters.Moshi alias AudioFlow.Audio - alias Membrane.Ogg.Opus, as: OggOpus - alias Membrane.Ogg.Page - alias Membrane.Ogg.Parser - alias Membrane.Opus.Decoder.Native, as: Decoder - alias Membrane.Opus.Encoder.Native, as: Encoder + alias AudioFlow.Test.MoshiServer @frame 1_920 - # Answers each client frame with one 80 ms output page, then the text - # scripted for that frame, like moshi_mlx.local_web. - defmodule Server do - @behaviour WebSock - - def init({owner, script}) do - state = %{ - owner: owner, - script: script, - buffer: <<>>, - continued: nil, - decoder: Decoder.create(24_000, 1), - encoder: Encoder.create(24_000, 1, 2049, -1000, 3001), - frames: 0 - } - - head = - Page.create_first(1) - |> Page.append_packet!(OggOpus.create_id_header(1)) - |> Page.finalize(0) - - {:push, [{:binary, <<0>>}, {:binary, <<1>> <> Page.serialize(head)}], state} - end - - def handle_in({<<1, data::binary>>, opcode: :binary}, state) do - {packets, continued, rest} = Parser.parse(state.buffer <> data, state.continued) - - pcm = - for %Parser.Packet{payload: packet} <- packets, - not String.starts_with?(packet, ["OpusHead", "OpusTags"]), - into: <<>>, - do: Decoder.decode_packet(state.decoder, packet) - - send(state.owner, {:client_pcm, pcm}) - frames = div(byte_size(pcm), 2 * 1_920) - - replies = - Enum.flat_map(state.frames..(state.frames + frames - 1)//1, fn index -> - [{:binary, <<1>> <> output(state, index)}] ++ - for text <- List.wrap(state.script[index]), do: {:binary, <<2>> <> text} - end) - - {:push, replies, - %{state | buffer: rest, continued: continued, frames: state.frames + frames}} - end - - def handle_info(_message, state), do: {:ok, state} - - defp output(state, index) do - packets = - for _ <- 1..4 do - {:ok, packet} = Encoder.encode_packet(state.encoder, :binary.copy(<<0, 0>>, 480), 480) - packet - end - - page = %Page{bos: false, bitstream_serial_number: 1, page_sequence_number: index + 1} - - packets - |> Enum.reduce(page, &Page.append_packet!(&2, &1)) - |> Page.finalize((index + 1) * 3_840) - |> Page.serialize() - end - end - - defmodule Endpoint do - def init(options), do: options - - def call(conn, options), - do: conn |> WebSockAdapter.upgrade(Server, options, []) |> Plug.Conn.halt() - end - - defp endpoint(script) do - server = - start_supervised!( - {Bandit, - plug: {Endpoint, {self(), script}}, port: 0, ip: {127, 0, 0, 1}, startup_log: false} - ) - - {:ok, {_, port}} = ThousandIsland.listener_info(server) - "ws://127.0.0.1:#{port}/api/chat" - end - defp run(script, options) do owner = self() @@ -102,7 +16,7 @@ if System.get_env("AUDIOFLOW_MEDIA") == "1" do do: <> input = %Audio{data: tone, sample_rate: 24_000} - options = [endpoint: endpoint(script)] ++ options + options = [endpoint: MoshiServer.endpoint(owner, script: script)] ++ options Moshi.run(input, options, fn event -> send(owner, {:output, event}) diff --git a/test/support/moshi_server.ex b/test/support/moshi_server.ex new file mode 100644 index 0000000..0ec5e44 --- /dev/null +++ b/test/support/moshi_server.ex @@ -0,0 +1,140 @@ +if Code.ensure_loaded?(Membrane.Ogg.Parser) do + defmodule AudioFlow.Test.MoshiServer do + @moduledoc """ + Local Moshi WebSocket fixture with the `moshi_mlx.local_web` framing. + + It sends `{:moshi_server, pid}` to the owner, then the handshake and the + Ogg Opus head page. For each client message it sends `{:client_pcm, pcm}` + with the decoded PCM, then answers each 80 ms frame with one 80 ms silent + output page and the `:script` text for that frame index. On exit it sends + `:moshi_server_closed`. + + Options: `:script` (map of frame index to text), `handshake: :manual` + (send `:handshake` to the pid), `reply: :manual` (send `:reply` to answer + the frames received so far). Send `:close` to close the connection. + """ + @behaviour WebSock + alias Membrane.Ogg.Opus, as: OggOpus + alias Membrane.Ogg.Page + alias Membrane.Ogg.Parser + alias Membrane.Opus.Decoder.Native, as: Decoder + alias Membrane.Opus.Encoder.Native, as: Encoder + + @frame 1_920 + + def endpoint(owner, options \\ []) do + server = + ExUnit.Callbacks.start_supervised!( + {Bandit, + plug: {__MODULE__.Endpoint, {owner, options}}, + port: 0, + ip: {127, 0, 0, 1}, + startup_log: false} + ) + + {:ok, {_, port}} = ThousandIsland.listener_info(server) + "ws://127.0.0.1:#{port}/api/chat" + end + + defmodule Endpoint do + @moduledoc false + def init(options), do: options + + def call(conn, options) do + conn + |> WebSockAdapter.upgrade(AudioFlow.Test.MoshiServer, options, []) + |> Plug.Conn.halt() + end + end + + @impl true + def init({owner, options}) do + send(owner, {:moshi_server, self()}) + + state = %{ + owner: owner, + script: Keyword.get(options, :script, %{}), + reply: Keyword.get(options, :reply, :auto), + buffer: <<>>, + continued: nil, + decoder: Decoder.create(24_000, 1), + encoder: Encoder.create(24_000, 1, 2049, -1000, 3001), + received: 0, + answered: 0 + } + + case Keyword.get(options, :handshake, :auto) do + :auto -> {:push, handshake(), state} + :manual -> {:ok, state} + end + end + + @impl true + def handle_in({<<1, data::binary>>, opcode: :binary}, state) do + {packets, continued, rest} = Parser.parse(state.buffer <> data, state.continued) + + pcm = + for %Parser.Packet{payload: packet} <- packets, + not String.starts_with?(packet, ["OpusHead", "OpusTags"]), + into: <<>>, + do: Decoder.decode_packet(state.decoder, packet) + + send(state.owner, {:client_pcm, pcm}) + + state = %{ + state + | buffer: rest, + continued: continued, + received: state.received + div(byte_size(pcm), 2 * @frame) + } + + if state.reply == :auto, do: answer(state), else: {:ok, state} + end + + @impl true + def handle_info(:handshake, state), do: {:push, handshake(), state} + def handle_info(:reply, state), do: answer(state) + def handle_info(:close, state), do: {:stop, :normal, state} + def handle_info({:push, frames}, state), do: {:push, frames, state} + + @impl true + def terminate(_reason, state) do + send(state.owner, :moshi_server_closed) + :ok + end + + defp handshake do + head = + Page.create_first(1) + |> Page.append_packet!(OggOpus.create_id_header(1)) + |> Page.finalize(0) + + [{:binary, <<0>>}, {:binary, <<1>> <> Page.serialize(head)}] + end + + defp answer(state) do + replies = + Enum.flat_map(state.answered..(state.received - 1)//1, fn index -> + [{:binary, <<1>> <> output(state, index)}] ++ + for text <- List.wrap(state.script[index]), do: {:binary, <<2>> <> text} + end) + + {:push, replies, %{state | answered: state.received}} + end + + defp output(state, index) do + packets = + for _ <- 1..4 do + {:ok, packet} = Encoder.encode_packet(state.encoder, :binary.copy(<<0, 0>>, 480), 480) + packet + end + + page = %Page{bos: false, bitstream_serial_number: 1, page_sequence_number: index + 1} + + packets + |> Enum.reduce(page, &Page.append_packet!(&2, &1)) + |> Page.finalize((index + 1) * 3_840) + |> Page.serialize() + end + end +end