From 1bda00eb2f38033da36c28c1ce7282ddf3b94986 Mon Sep 17 00:00:00 2001 From: TudorAndrei Date: Fri, 6 Nov 2026 15:35:26 +0200 Subject: [PATCH 1/3] feat(providers): accept a custom frame decoder in the provider socket Socket.run/7 takes a decoder that maps each text or binary frame to a handler event. The default still accepts JSON objects only, so the OpenAI Realtime and Gemini Live adapters do not change. --- lib/audio_flow/adapters/providers/socket.ex | 28 +++++++++++++++++---- 1 file changed, 23 insertions(+), 5 deletions(-) diff --git a/lib/audio_flow/adapters/providers/socket.ex b/lib/audio_flow/adapters/providers/socket.ex index 41cd811..c12ae68 100644 --- a/lib/audio_flow/adapters/providers/socket.ex +++ b/lib/audio_flow/adapters/providers/socket.ex @@ -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), @@ -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, _} -> @@ -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 From 34e52803dcd4d6f1f98a21ae4bbdf4d18a466c78 Mon Sep 17 00:00:00 2001 From: TudorAndrei Date: Fri, 6 Nov 2026 15:35:29 +0200 Subject: [PATCH 2/3] feat(moshi): add local Moshi speech-to-speech adapter AudioFlow.Adapters.Moshi runs one committed 24 kHz turn against a local Kyutai Moshi server (moshi_mlx.local_web) for Session speech_to_speech. Ogg Opus framing and coding use membrane_ogg_plugin and membrane_opus_plugin. The adapter sends one Ogg page per 80 ms frame, paces silence by received output, drops output for the input period and ends the reply after a silence without text tokens. --- lib_media/audio_flow/adapters/moshi.ex | 203 +++++++++++++++++++++++++ mix.exs | 4 +- mix.lock | 2 + test/moshi_test.exs | 170 +++++++++++++++++++++ 4 files changed, 378 insertions(+), 1 deletion(-) create mode 100644 lib_media/audio_flow/adapters/moshi.ex create mode 100644 test/moshi_test.exs diff --git a/lib_media/audio_flow/adapters/moshi.ex b/lib_media/audio_flow/adapters/moshi.ex new file mode 100644 index 0000000..f1faca9 --- /dev/null +++ b/lib_media/audio_flow/adapters/moshi.ex @@ -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 <> 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 diff --git a/mix.exs b/mix.exs index 702ca3e..3ab2f3c 100644 --- a/mix.exs +++ b/mix.exs @@ -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: [] ) diff --git a/mix.lock b/mix.lock index 434adae..c25b90b 100644 --- a/mix.lock +++ b/mix.lock @@ -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"}, diff --git a/test/moshi_test.exs b/test/moshi_test.exs new file mode 100644 index 0000000..db734c2 --- /dev/null +++ b/test/moshi_test.exs @@ -0,0 +1,170 @@ +if System.get_env("AUDIOFLOW_MEDIA") == "1" do + defmodule AudioFlow.MoshiTest 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 + + @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() + + tone = + for i <- 0..(2 * @frame - 1), + into: <<>>, + do: <> + + input = %Audio{data: tone, sample_rate: 24_000} + options = [endpoint: endpoint(script)] ++ options + + Moshi.run(input, options, fn event -> + send(owner, {:output, event}) + :ok + end) + end + + defp outputs do + receive do + {:output, event} -> [event | outputs()] + after + 0 -> [] + end + end + + test "sends Ogg Opus input then silence, drops input-period output, ends after silent text" do + script = %{0 => "early", 3 => " Hi", 4 => " there."} + assert :ok = run(script, end_silence_ms: 160) + + events = outputs() + assert for({:text, text} <- events, do: text) == [" Hi", " there."] + # Frames 0-1 answer the input. The reply is frames 2-6: after the last + # text at frame 4, two silent frames reach the 160 ms end bound. + assert byte_size(for({:audio, audio} <- events, into: <<>>, do: audio.data)) == + 5 * @frame * 2 + + assert_received {:client_pcm, <<>>} + assert_received {:client_pcm, first} + assert byte_size(first) == @frame * 2 + assert first |> :binary.bin_to_list() |> Enum.any?(&(&1 != 0)) + end + + test "fails with no_reply when the model stays silent for max_reply_ms" do + assert {:error, :no_reply} = run(%{0 => "early"}, max_reply_ms: 160) + assert outputs() |> Enum.filter(&match?({:text, _}, &1)) == [] + end + + test "rejects audio at another rate" do + assert_raise ArgumentError, fn -> + Moshi.run(%Audio{data: <<0, 0>>, sample_rate: 16_000}, [], fn _ -> :ok end) + end + end + + @tag :http_model + test "a local Moshi server answers a spoken question" 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!() + owner = self() + + assert :ok = + Moshi.run( + %Audio{data: question, sample_rate: 24_000}, + [endpoint: endpoint], + fn event -> + send(owner, {:output, event}) + :ok + end + ) + + events = outputs() + assert Enum.any?(events, &match?({:text, _}, &1)) + assert events |> Enum.filter(&match?({:audio, _}, &1)) |> length() > 0 + end + end +end From 9533691942db98e2427ecd4af505653dae20b90f Mon Sep 17 00:00:00 2001 From: TudorAndrei Date: Fri, 6 Nov 2026 15:35:32 +0200 Subject: [PATCH 3/3] docs(providers): document the local Moshi adapter --- README.md | 4 +++- docs/providers.md | 59 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 62 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 1361860..e321b81 100644 --- a/README.md +++ b/README.md @@ -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. diff --git a/docs/providers.md b/docs/providers.md index fc0e8bb..2a6eaff 100644 --- a/docs/providers.md +++ b/docs/providers.md @@ -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