Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,9 @@ AudioFlow.cancel(session)
AudioFlow.stop_session(session)
```

For OpenAI Realtime or Gemini Live without chained stages, use the explicit
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.

Expand Down
59 changes: 59 additions & 0 deletions docs/providers.md
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,65 @@ as an existing STT/LLM/TTS node would misrepresent its contract. Use the explici
Session mode or direct API today. There is no continuous duplex input, tool
execution, automatic reconnect, resampling or WebRTC in this mode.

## Local Moshi speech-to-speech

`AudioFlow.Adapters.Moshi` runs one committed turn against a local
[Kyutai Moshi](https://github.com/kyutai-labs/moshi) server. Moshi is a 7B
full-duplex model. The 4-bit MLX build needs approximately 5 GB of weights and
runs on an Apple Silicon laptop. The adapter needs `AUDIOFLOW_MEDIA=1`, because
it uses `membrane_opus_plugin` for Opus and `membrane_ogg_plugin` for Ogg pages.

Start the server (Python 3.12, approximately 5 GB download on first start):

```sh
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
```

Use the adapter with 24 kHz input:

```elixir
{:ok, session} = AudioFlow.start_session(
speech_to_speech: {AudioFlow.Adapters.Moshi, [endpoint: "ws://127.0.0.1:8998/api/chat"]},
timeout_ms: 60_000)
```

The wire protocol is binary WebSocket messages with a one-byte kind: `0`
handshake, `1` Ogg Opus audio (24 kHz mono), `2` UTF-8 text tokens. The adapter
sends the input as 80 ms Ogg pages of four 20 ms Opus packets, then silence. It
sends one silent frame for each output frame, so the model sets the pace, not
the wall clock. Output for the input period is dropped.

Moshi has no end-of-turn signal. The reply ends after `:end_silence_ms` (1,600)
of model output without a text token. The turn fails with `:no_reply` if
`:max_reply_ms` (20,000) passes without text. The default `:timeout_ms` is
60,000. Moshi does not transcribe the user, so there is no `:transcript` event.

Limits:

- The server serves one connection at a time. A second turn waits for the lock.
- Model state continues across connections. The server does not reset context
between turns, and the adapter cannot clear it.
- The first turn after server start is slow (approximately 13 s on an M5) while
MLX warms up. Later turns gave the first reply audio approximately 2 s after
submit for a 3.2 s question.
- Moshi speaks English only.
- The adapter calls the Opus `Native` modules and the Ogg `Page`, `Parser` and
`Opus` modules directly, not through Membrane pipeline elements. The
`Membrane.Ogg.Muxer` element holds packets until a page has 255 segments
(approximately 5 s), which is too slow for a duplex model. These modules are
internal to the plugins, so the dependencies are pinned to `~> 0.21.0` and
`~> 0.5.2`.

To check a running server, convert a question to raw 24 kHz PCM and run:

```sh
AUDIOFLOW_MEDIA=1 AUDIOFLOW_HTTP_MODEL_TESTS=1 \
AUDIOFLOW_MOSHI_PCM=question.s16le mix test test/moshi_test.exs
```

`AUDIOFLOW_MOSHI_ENDPOINT` overrides the default endpoint.

## Bounds, cancellation and errors

All providers accept `:endpoint` overrides for proxies and local tests. Use
Expand Down
28 changes: 23 additions & 5 deletions lib/audio_flow/adapters/providers/socket.ex
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ defmodule AudioFlow.Adapters.Providers.Socket do

# Synchronous, caller-owned socket: terminating the turn closes the connection.
# The byte budget also bounds fragmented messages before WebSocket decoding.
def run(url, headers, frames, state, handler, options) 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),
Expand All @@ -21,7 +23,16 @@ defmodule AudioFlow.Adapters.Providers.Socket do
transport_opts: [timeout: timeout]
) do
{:ok, conn} ->
socket = %{conn: conn, ws: nil, ref: nil, deadline: deadline, bytes: 0, limit: limit}
socket = %{
conn: conn,
ws: nil,
ref: nil,
deadline: deadline,
bytes: 0,
limit: limit,
decode: decode
}

upgrade(socket, scheme, path, headers, {frames, state, handler})

{:error, _} ->
Expand Down Expand Up @@ -128,21 +139,28 @@ defmodule AudioFlow.Adapters.Providers.Socket do
defp frames(_socket, [{:close, _, _} | _], _state, _handler), do: {:error, :incomplete_stream}

defp frames(socket, [{kind, data} | rest], state, handler) when kind in [:text, :binary] do
case JSON.decode(data) do
{:ok, event} when is_map(event) ->
case socket.decode.({kind, data}) do
{:ok, event} ->
case handler.(event, state) do
{:cont, state, outgoing} -> frames(send_frames(socket, outgoing), rest, state, handler)
:done -> :ok
{:error, _} = error -> error
end

_ ->
:error ->
{:error, :invalid_event}
end
end

defp frames(_, _, _, _), do: {:error, :invalid_frame}

defp json_event({_kind, data}) do
case JSON.decode(data) do
{:ok, event} when is_map(event) -> {:ok, event}
_ -> :error
end
end

def json(value), do: {:text, JSON.encode!(value)}

def key(options) do
Expand Down
203 changes: 203 additions & 0 deletions lib_media/audio_flow/adapters/moshi.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,203 @@
defmodule AudioFlow.Adapters.Moshi do
@moduledoc """
One committed audio turn with a local Kyutai Moshi server (`moshi_mlx.local_web`
or the PyTorch `moshi.server`). Requires `AUDIOFLOW_MEDIA=1`: Ogg Opus framing and
coding come from `membrane_ogg_plugin` and `membrane_opus_plugin`.

`run/3` emits `{:text, delta}` and `{:audio, Audio}` like `OpenAIRealtime`.
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.
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.

Options: `:endpoint` (`"ws://127.0.0.1:8998/api/chat"`), `:max_reply_ms`
(20,000), `:end_silence_ms` (1,600), `:timeout_ms` (60,000) and
`:max_response_bytes` (16,777,216).
"""
@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

@rate 24_000
# Moshi steps every 80 ms; Opus packets are 20 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)
samples = fn key, default -> Socket.positive!(options, key, default) * div(@rate, 1000) end
input = pad(audio.data)

state = %{
input: input,
input_samples: div(byte_size(input), 2),
max_reply: samples.(:max_reply_ms, 20_000),
end_silence: samples.(:end_silence_ms, 1_600),
sent: 0,
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,
emit: emit
}

Socket.run(
Keyword.get(options, :endpoint, "ws://127.0.0.1:8998/api/chat"),
[],
[],
state,
&event/2,
Keyword.put_new(options, :timeout_ms, 60_000),
&decode/1
)
end

defp pad(pcm) do
case rem(byte_size(pcm), @frame * 2) do
0 -> pcm
rest -> pcm <> :binary.copy(<<0>>, @frame * 2 - rest)
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)
{:cont, state, [headers | frames]}
end

defp event(_event, %{ready: false}), do: {:error, :invalid_event}
defp event(:ready, _state), do: {:error, :invalid_event}

defp event({:text, text}, state) do
if state.received >= state.input_samples do
:ok = state.emit.({:text, text})
{:cont, %{state | last_text: state.received}, []}
else
{:cont, state, []}
end
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}
:ok = emit_reply(pcm, state)
received(%{state | received: state.received + div(byte_size(pcm), 2)})

:error ->
{:error, :invalid_audio}
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

case pcm do
<<_::binary-size(^skip), reply::binary>> when reply != <<>> ->
state.emit.({:audio, %Audio{data: reply, sample_rate: @rate}})

_ ->
:ok
end
end

defp received(%{received: received, last_text: last} = state) do
reply = received - state.input_samples

cond do
last != nil and received - last >= state.end_silence ->
:done

reply >= state.max_reply and last != nil ->
:done

reply >= state.max_reply ->
{:error, :no_reply}

true ->
{state, frames} = top_up(state, received + @lead)
{:cont, state, frames}
end
end

# Sends input, then silence, until `target` samples or the reply bound.
defp top_up(state, target) do
target = min(target, state.input_samples + state.max_reply + @lead)
top_up(state, target, [])
end

defp top_up(%{sent: sent} = state, target, frames) when sent >= target,
do: {state, Enum.reverse(frames)}

defp top_up(state, target, frames) do
pcm =
if state.sent < state.input_samples,
do: binary_part(state.input, state.sent * 2, @frame * 2),
else: :binary.copy(<<0>>, @frame * 2)

packets =
for <<chunk::binary-size(@packet * 2) <- pcm>> 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])
end
end
4 changes: 3 additions & 1 deletion mix.exs
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,9 @@ defmodule AudioFlow.MixProject do
{:membrane_h26x_plugin, "~> 0.11.4"},
{:membrane_h264_ffmpeg_plugin, "~> 0.32.7"},
{:membrane_ffmpeg_swscale_plugin, "~> 0.16.5"},
{:membrane_raw_video_format, "~> 0.4.5"}
{:membrane_raw_video_format, "~> 0.4.5"},
{:membrane_opus_plugin, "~> 0.21.0"},
{:membrane_ogg_plugin, "~> 0.5.2"}
],
else: []
)
Expand Down
2 changes: 2 additions & 0 deletions mix.lock
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,9 @@
"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"},
Expand Down
Loading
Loading