From 077fe4f99531a3314fa8eace8a15ac0ea27e88a0 Mon Sep 17 00:00:00 2001 From: TudorAndrei Date: Sun, 15 Nov 2026 15:06:42 +0200 Subject: [PATCH] perf(audio): benchmark hot paths and use FFmpeg codecs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Replace custom resampling and μ-law codecs with FFmpeg-backed converters - Add CPU hot-path benchmarks and update telephony stream coverage --- README.md | 4 +- bench/hot_paths.exs | 295 ++++++++++++++++++ examples/telephony-loopback.exs | 8 +- lib/audio_flow/graph/nodes/audio.ex | 3 +- lib/audio_flow/resampler.ex | 111 ++----- lib/audio_flow/telephony/mulaw.ex | 44 ++- lib/audio_flow/telephony/packetizer.ex | 15 +- lib/audio_flow/telephony/rate_converter.ex | 45 +-- mix.exs | 10 +- mix.lock | 2 + .../content/docs/docs/features/transports.md | 11 +- test/graph_test.exs | 16 +- test/network_protocol_test.exs | 9 +- test/telephony_test.exs | 11 +- test/webrtc_session_test.exs | 41 +-- 15 files changed, 429 insertions(+), 196 deletions(-) create mode 100644 bench/hot_paths.exs diff --git a/README.md b/README.md index ed47212..e55a8d0 100644 --- a/README.md +++ b/README.md @@ -28,7 +28,9 @@ mix run examples/demo.exs mix audio_flow.bench --runs 20 --concurrency 4 ``` -The core needs no model downloads. Optional parts are enabled with environment +The core needs no model downloads. It resamples audio and codes G.711 with +FFmpeg through two Membrane plugins, so the first build needs a C compiler and +downloads prebuilt FFmpeg libraries. Optional parts are enabled with environment variables: | Variable | Adds | Source directory | diff --git a/bench/hot_paths.exs b/bench/hot_paths.exs new file mode 100644 index 0000000..d3f1299 --- /dev/null +++ b/bench/hot_paths.exs @@ -0,0 +1,295 @@ +# Micro-benchmarks for AudioFlow's CPU paths. No models, no network. +# +# mix run bench/hot_paths.exs +# +# Each row is the median and p99 wall time of one call, the reductions the +# calling process spent on it, and, for audio paths, the real-time factor +# (seconds of audio handled per CPU second, higher is better). +defmodule Bench.NullDetector do + @behaviour AudioFlow.VoiceDetector + @impl true + def init(options), do: {512, 16_000, Keyword.get(options, :probability, 0.0)} + @impl true + def predict(_audio, probability), do: {probability, probability} +end + +defmodule Bench do + alias AudioFlow.Audio + + def pcm(samples), do: :crypto.strong_rand_bytes(samples * 2) + def audio(ms, rate), do: %Audio{data: pcm(div(ms * rate, 1000)), sample_rate: rate} + + def run(name, fun, options \\ []) do + audio_ms = Keyword.get(options, :audio_ms) + budget_us = Keyword.get(options, :budget_ms, 1500) * 1000 + fun.() + {first, _} = :timer.tc(fun) + iterations = min(20_000, max(5, div(budget_us, max(first, 1)))) + + # Sessions send events to their owner, so the calls stay in this process. + times = Enum.sort(for _ <- 1..iterations, do: elem(:timer.tc(fun), 0)) + {:reductions, before} = Process.info(self(), :reductions) + fun.() + {:reductions, after_call} = Process.info(self(), :reductions) + median = Enum.at(times, div(iterations, 2)) + p99 = Enum.at(times, min(iterations - 1, trunc(iterations * 0.99))) + + factor = + if audio_ms && median > 0, + do: :erlang.float_to_binary(audio_ms * 1000 / median, decimals: 1) <> "x", + else: "-" + + IO.puts( + String.pad_trailing(name, 46) <> + String.pad_leading("#{median}", 10) <> + String.pad_leading("#{p99}", 10) <> + String.pad_leading("#{after_call - before}", 12) <> + String.pad_leading(factor, 12) <> String.pad_leading("#{iterations}", 8) + ) + end + + def header(title) do + IO.puts("\n== #{title}") + + IO.puts( + String.pad_trailing("case", 46) <> + String.pad_leading("p50 us", 10) <> + String.pad_leading("p99 us", 10) <> + String.pad_leading("reductions", 12) <> + String.pad_leading("realtime", 12) <> String.pad_leading("n", 8) + ) + end +end + +alias AudioFlow.Audio +alias AudioFlow.Telephony.MuLaw +alias AudioFlow.Telephony.Packetizer +alias AudioFlow.Telephony.RateConverter + +Bench.header("Telephony codec (20 ms packets)") +ulaw = :crypto.strong_rand_bytes(160) +pcm8 = Bench.pcm(160) +pcm16 = Bench.pcm(320) +{_, up} = RateConverter.up(pcm8, %RateConverter{}) +{_, down} = RateConverter.down(pcm16, %RateConverter{}) +Bench.run("MuLaw.decode 160 B", fn -> MuLaw.decode(ulaw) end, audio_ms: 20) +Bench.run("MuLaw.encode 160 samples", fn -> MuLaw.encode(pcm8) end, audio_ms: 20) + +Bench.run("RateConverter.up 8k->16k", fn -> RateConverter.up(pcm8, up) end, + audio_ms: 20 +) + +Bench.run("RateConverter.down 16k->8k", fn -> RateConverter.down(pcm16, down) end, + audio_ms: 20 +) + +second16 = Bench.audio(1000, 16_000) +second8 = Bench.audio(1000, 8000) + +Bench.run("Packetizer.push 1 s @16k", fn -> Packetizer.push(second16, %Packetizer{}) end, + audio_ms: 1000 +) + +Bench.run("Packetizer.push 1 s @8k", fn -> Packetizer.push(second8, %Packetizer{}) end, + audio_ms: 1000 +) + +Bench.header("Resampler (1 s of audio)") + +for {from, to} <- [ + {48_000, 16_000}, + {24_000, 16_000}, + {8000, 16_000}, + {16_000, 24_000}, + {44_100, 16_000} + ] do + audio = Bench.audio(1000, from) + + Bench.run("Resampler.convert #{from}->#{to}", fn -> AudioFlow.Resampler.convert(audio, to) end, + audio_ms: 1000 + ) +end + +Bench.header("VoiceInput (null detector, 512-sample frames)") +chunk20 = %Audio{data: Bench.pcm(320), sample_rate: 16_000} +silent = AudioFlow.VoiceInput.new({Bench.NullDetector, [probability: 0.0]}) +speech = AudioFlow.VoiceInput.new({Bench.NullDetector, [probability: 1.0]}) + +feed = fn state, count -> + Enum.reduce(1..count, state, fn _, state -> + elem(AudioFlow.VoiceInput.push(state, chunk20), 1) + end) +end + +Bench.run("push 1 s silence in 20 ms chunks", fn -> feed.(silent, 50) end, audio_ms: 1000) +Bench.run("push 1 s speech in 20 ms chunks", fn -> feed.(speech, 50) end, audio_ms: 1000) +Bench.run("push 10 s speech in 20 ms chunks", fn -> feed.(speech, 500) end, audio_ms: 10_000) +big = %Audio{data: Bench.pcm(16_000 * 10), sample_rate: 16_000} + +Bench.run("push 10 s speech as one chunk", fn -> AudioFlow.VoiceInput.push(speech, big) end, + audio_ms: 10_000 +) + +long = feed.(speech, 1400) +Bench.run("flush a 28 s utterance", fn -> AudioFlow.VoiceInput.flush(long) end) + +Bench.header("Text") + +tokens = + for i <- 1..400, + do: + Enum.at( + ["The ", "quick ", "fox. ", "Dr. ", "Smith ", "said: ", "\"yes!\" ", "and "], + rem(i, 8) + ) + +stream = fn -> + Enum.reduce(tokens, "", fn token, pending -> + elem(AudioFlow.TextChunks.push(pending, token), 1) + end) +end + +Bench.run("TextChunks.push 400 tokens", stream) +no_break = for _ <- 1..400, do: "word " + +Bench.run("TextChunks.push 400 tokens, no sentence end", fn -> + Enum.reduce(no_break, "", fn token, pending -> + elem(AudioFlow.TextChunks.push(pending, token), 1) + end) +end) + +history = + Enum.reduce(1..8, AudioFlow.History.new(true), fn i, history -> + {:ok, _, context} = + AudioFlow.History.prompt(history, "question #{i} " <> String.duplicate("x", 200)) + + {:ok, context} = AudioFlow.History.append(context, String.duplicate("y", 600)) + AudioFlow.History.commit(context) + end) + +Bench.run("History.prompt with 8 turns", fn -> + AudioFlow.History.prompt(history, "next question") +end) + +Bench.header("Session (in-process adapters)") +owner_options = fn options -> Keyword.put(options, :owner, self()) end + +drain = fn session, turn -> + receive_loop = fn loop -> + receive do + {AudioFlow, ^session, ^turn, {:done, _}} -> :ok + {AudioFlow, ^session, ^turn, {:error, reason, _}} -> raise inspect(reason) + {AudioFlow, ^session, ^turn, _} -> loop.(loop) + end + end + + receive_loop.(receive_loop) +end + +input = %Audio{data: <<0, 0>>, sample_rate: 16_000} + +Bench.run("start_session + stop_session", fn -> + {:ok, session} = AudioFlow.start_session(owner_options.(AudioFlow.Adapters.Demo.options())) + AudioFlow.stop_session(session) +end) + +{:ok, demo} = AudioFlow.start_session(AudioFlow.Adapters.Demo.options()) + +Bench.run("demo turn on a warm session", fn -> + {:ok, turn} = AudioFlow.submit(demo, input) + drain.(demo, turn) +end) + +function = fn run -> {AudioFlow.Adapters.Function, [run: run]} end +frame = %Audio{data: Bench.pcm(480), sample_rate: 24_000} + +streaming = fn chunks, sentences -> + [ + stt: function.(fn _, emit -> emit.("hello") end), + llm: function.(fn _, emit -> Enum.each(1..sentences, fn _ -> emit.("A sentence. ") end) end), + tts: function.(fn _, emit -> Enum.each(1..chunks, fn _ -> emit.(frame) end) end), + max_events: 100_000 + ] +end + +for {sentences, chunks} <- [{1, 50}, {10, 50}, {10, 100}] do + {:ok, session} = AudioFlow.start_session(streaming.(chunks, sentences)) + + Bench.run( + "turn: #{sentences} sentences x #{chunks} audio frames (20 ms)", + fn -> + {:ok, turn} = AudioFlow.submit(session, input) + drain.(session, turn) + end, + audio_ms: sentences * chunks * 20 + ) +end + +{:ok, with_history} = + AudioFlow.start_session(Keyword.put(streaming.(50, 10), :history, true)) + +Bench.run( + "turn: 10 x 50 frames, history on", + fn -> + {:ok, turn} = AudioFlow.submit(with_history, input) + drain.(with_history, turn) + end, + audio_ms: 10_000 +) + +Bench.header("Telephony WebSocket endpoint (Twilio, inbound 20 ms frames)") + +{:ok, socket} = + AudioFlow.Telephony.WebSocket.init( + provider: :twilio, + session: AudioFlow.Adapters.Demo.options(), + vad: {Bench.NullDetector, [probability: 0.0]} + ) + +start = + JSON.encode!(%{ + event: "start", + streamSid: "MZ1", + start: %{ + streamSid: "MZ1", + mediaFormat: %{encoding: "audio/x-mulaw", sampleRate: 8000, channels: 1} + } + }) + +{:ok, socket} = AudioFlow.Telephony.WebSocket.handle_in({start, opcode: :text}, socket) + +media = fn chunk -> + JSON.encode!(%{ + event: "media", + streamSid: "MZ1", + media: %{track: "inbound", chunk: chunk, payload: Base.encode64(ulaw)} + }) +end + +frames = for chunk <- 1..50, do: {media.(chunk), opcode: :text} + +Bench.run( + "handle_in 1 s of inbound media (50 frames)", + fn -> + Enum.reduce(frames, %{socket | last_chunk: nil}, fn message, state -> + {:ok, state} = AudioFlow.Telephony.WebSocket.handle_in(message, state) + state + end) + end, + audio_ms: 1000 +) + +Bench.header("Recording") +store_root = Path.join(System.tmp_dir!(), "audioflow-bench-#{System.unique_integer([:positive])}") +{:ok, store} = AudioFlow.Recording.Store.new(store_root) +recorder = AudioFlow.Recording.new(self(), store, redactor: &{:ok, &1}, audio: true) +turn = make_ref() +second = Bench.audio(1000, 24_000) + +Bench.run( + "consume 1 s audio event (base64)", + fn -> + AudioFlow.Recording.consume(recorder, {AudioFlow, self(), turn, {:audio, second}}) + end, audio_ms: 1000) + +File.rm_rf!(store_root) diff --git a/examples/telephony-loopback.exs b/examples/telephony-loopback.exs index 8c16b24..099cba6 100644 --- a/examples/telephony-loopback.exs +++ b/examples/telephony-loopback.exs @@ -69,8 +69,8 @@ for provider <- [:twilio, :telnyx] do media: %{ track: "inbound", chunk: Integer.to_string(chunk), - timestamp: Integer.to_string((chunk - 1) * 48), - payload: Base.encode64(:binary.copy(<<255>>, 384)) + timestamp: Integer.to_string((chunk - 1) * 50), + payload: Base.encode64(:binary.copy(<<255>>, 400)) } }, key, @@ -79,7 +79,7 @@ for provider <- [:twilio, :telnyx] do ) end - for _ <- 1..6 do + for _ <- 1..5 do {:json, %{"event" => "media", "media" => %{"payload" => payload}}} = Client.recv(socket) 160 = byte_size(Base.decode64!(payload)) end @@ -88,5 +88,5 @@ for provider <- [:twilio, :telnyx] do {:close, _} = Client.recv(socket) Client.close(socket) GenServer.stop(server) - IO.puts("#{provider}: start/media/stop passed; received six paced PCMU packets") + IO.puts("#{provider}: start/media/stop passed; received five paced PCMU packets") end diff --git a/lib/audio_flow/graph/nodes/audio.ex b/lib/audio_flow/graph/nodes/audio.ex index 1942817..5b93576 100644 --- a/lib/audio_flow/graph/nodes/audio.ex +++ b/lib/audio_flow/graph/nodes/audio.ex @@ -29,6 +29,5 @@ defmodule AudioFlow.Graph.Nodes.Audio do def adapter("audio.resample", %{sample_rate: rate}), do: {AudioFlow.Adapters.Function, [run: fn audio, emit -> emit.(resample(audio, rate)) end]} - @doc "Linear interpolation of mono signed 16-bit PCM." - defdelegate resample(audio, rate), to: AudioFlow.Resampler, as: :linear + defdelegate resample(audio, rate), to: AudioFlow.Resampler, as: :convert end diff --git a/lib/audio_flow/resampler.ex b/lib/audio_flow/resampler.ex index 9d39073..7c457dc 100644 --- a/lib/audio_flow/resampler.ex +++ b/lib/audio_flow/resampler.ex @@ -1,99 +1,50 @@ defmodule AudioFlow.Resampler do @moduledoc """ - Converts complete mono s16le PCM to another sample rate. + Converts mono s16le PCM to another sample rate with FFmpeg's libswresample, + through `Membrane.FFmpeg.SWResample.Converter.Native`. - It uses a polyphase windowed-sinc filter with 8 zero crossings on each side. - The cut-off is 0.9 of the lower Nyquist frequency, so downsampling removes - content that would alias. The conversion is not stateful: convert a complete - utterance, not separate stream chunks. It runs in Elixir. On an Apple M-series - CPU, one minute of 48 kHz input takes about 1.8 seconds, and one minute of - 8 kHz input about 0.9 seconds. + `convert/2` converts complete audio. For a stream, keep the state from + `new/2`, call `push/2` for each chunk and `flush/1` at the end. The converter + holds a few milliseconds of audio until the flush, so the chunks of a stream + join to the same samples as one conversion of the whole input. + + The state is a native handle. Use it from one process, and do not push to it + after a flush. """ alias AudioFlow.Audio + alias Membrane.FFmpeg.SWResample.Converter.Native - @zero_crossings 8 + @format Membrane.RawAudio.SampleFormat.serialize(:s16le) def convert(%Audio{sample_rate: rate} = audio, rate), do: audio def convert(%Audio{} = audio, rate) when is_integer(rate) and rate > 0 do unless Audio.valid?(audio), do: raise(ArgumentError, "expected mono s16le PCM") - divisor = Integer.gcd(audio.sample_rate, rate) - up = div(rate, divisor) - down = div(audio.sample_rate, divisor) - - count = div(byte_size(audio.data), 2) - output_count = div(count * up, down) - {table, half} = table(up, down) - padding = :binary.copy(<<0, 0>>, half) - input = padding <> audio.data <> padding - width = 4 * half - - data = - for k <- 0..(output_count - 1)//1, into: <<>> do - position = k * down - start = div(position, up) + 1 - window = binary_part(input, 2 * start, width) - value = dot(window, elem(table, rem(position, up)), 0.0) - < round() |> max(-32_768) |> min(32_767)::little-signed-16>> - end - - %Audio{data: data, sample_rate: rate} - end - - defp dot(<>, [weight | weights], acc), - do: dot(rest, weights, acc + weight * sample) - - defp dot(<<>>, [], acc), do: acc - - # One weight list for each output phase. Weight j of phase p applies to input - # sample center - half + 1 + j, at distance (j + 1 - half - p / up) samples. - defp table(up, down) do - cutoff = 0.9 * min(1.0, up / down) - half = ceil(@zero_crossings / cutoff) - - phases = - for phase <- 0..(up - 1) do - offset = phase / up - - weights = - for j <- 0..(2 * half - 1) do - distance = j + 1 - half - offset - kernel(distance, cutoff, half) - end - - sum = Enum.sum(weights) - Enum.map(weights, &(&1 / sum)) - end - - {List.to_tuple(phases), half} + state = new(audio.sample_rate, rate) + data = push(state, audio.data) <> flush(state) + # The flush can round the length up by one sample. + size = div(div(byte_size(audio.data), 2) * rate, audio.sample_rate) * 2 + %Audio{data: binary_part(data, 0, min(size, byte_size(data))), sample_rate: rate} end - defp kernel(distance, cutoff, half) do - window = 0.5 + 0.5 * :math.cos(:math.pi() * distance / half) - x = :math.pi() * cutoff * distance - sinc = if abs(x) < 1.0e-9, do: 1.0, else: :math.sin(x) / x - if abs(distance) >= half, do: 0.0, else: cutoff * sinc * window + @doc "Starts a stream conversion between two sample rates." + def new(from, to) when is_integer(from) and from > 0 and is_integer(to) and to > 0 do + {:ok, state} = Native.create(@format, from, 1, @format, to, 1) + state end - @doc "Linear interpolation of mono signed 16-bit PCM." - def linear(%Audio{sample_rate: rate} = audio, rate), do: audio - - def linear(%Audio{data: data, sample_rate: from}, to) do - samples = for <>, do: sample - input = List.to_tuple(samples) - count = tuple_size(input) - length = if count == 0, do: 0, else: max(1, div(count * to, from)) + @doc "Converts the next chunk. The output can be shorter than the input duration." + # The native converter reads an empty chunk as a flush. + def push(_state, <<>>), do: <<>> - pcm = - for index <- 0..(length - 1)//1, into: <<>> do - position = index * from / to - left = min(trunc(position), count - 1) - right = min(left + 1, count - 1) - weight = position - left - sample = round(elem(input, left) * (1 - weight) + elem(input, right) * weight) - <> - end + def push(state, data) when rem(byte_size(data), 2) == 0 do + {:ok, output} = Native.convert(data, state) + output + end - %Audio{data: pcm, sample_rate: to} + @doc "Returns the audio that the converter still holds." + def flush(state) do + {:ok, output} = Native.convert(<<>>, state) + output end end diff --git a/lib/audio_flow/telephony/mulaw.ex b/lib/audio_flow/telephony/mulaw.ex index f2f955c..6a83bf9 100644 --- a/lib/audio_flow/telephony/mulaw.ex +++ b/lib/audio_flow/telephony/mulaw.ex @@ -1,23 +1,37 @@ defmodule AudioFlow.Telephony.MuLaw do - @moduledoc "G.711 μ-law codec. PCM values are signed 16-bit little-endian." - import Bitwise + @moduledoc """ + G.711 μ-law codec on FFmpeg, through `membrane_g711_ffmpeg_plugin`. PCM + values are signed 16-bit little-endian. + """ + alias Membrane.G711.FFmpeg.Decoder + alias Membrane.G711.FFmpeg.Encoder - def decode(data) do - for <>, into: <<>> do - value = bxor(byte, 255) - magnitude = (((value &&& 15) <<< 3) + 132) <<< (value >>> 4 &&& 7) - sample = if (value &&& 128) == 0, do: magnitude - 132, else: 132 - magnitude - <> - end + def decode(<<>>), do: <<>> + + def decode(data) when is_binary(data) do + {:ok, frames} = Decoder.Native.decode(data, codec(:decoder)) + IO.iodata_to_binary(frames) end + def encode(<<>>), do: <<>> + def encode(data) when rem(byte_size(data), 2) == 0 do - for <>, into: <<>> do - mask = if sample < 0, do: 127, else: 255 - value = min(abs(sample), 32_635) + 132 - exponent = Enum.find(7..0//-1, 0, fn e -> value >= 128 <<< e end) - mantissa = value >>> (exponent + 3) &&& 15 - <> + {:ok, frames} = Encoder.Native.encode(data, codec(:encoder)) + IO.iodata_to_binary(frames) + end + + # An FFmpeg codec context is not safe to share, so each process keeps its own. + defp codec(kind) do + key = {__MODULE__, kind} + + with nil <- Process.get(key) do + {:ok, codec} = + if kind == :decoder, + do: Decoder.Native.create(:PCMU), + else: Encoder.Native.create(:s16le, :PCMU) + + Process.put(key, codec) + codec end end end diff --git a/lib/audio_flow/telephony/packetizer.ex b/lib/audio_flow/telephony/packetizer.ex index d36b7a3..682fc07 100644 --- a/lib/audio_flow/telephony/packetizer.ex +++ b/lib/audio_flow/telephony/packetizer.ex @@ -4,7 +4,7 @@ defmodule AudioFlow.Telephony.Packetizer do alias AudioFlow.Telephony.MuLaw alias AudioFlow.Telephony.RateConverter - defstruct rate: nil, converter: %RateConverter{}, pending: <<>>, active?: false + defstruct rate: nil, converter: %RateConverter{}, pending: <<>> def format(state, rate), do: %{state | rate: rate, converter: %RateConverter{}} @@ -14,20 +14,11 @@ defmodule AudioFlow.Telephony.Packetizer do do: RateConverter.down(data, state.converter), else: {data, state.converter} - split(state.pending <> MuLaw.encode(data), %{ - state - | rate: rate, - converter: converter, - active?: true - }) + split(state.pending <> MuLaw.encode(data), %{state | rate: rate, converter: converter}) end def finish(state) do - {tail, _} = - if state.active? and state.rate == 16_000, - do: RateConverter.finish_down(state.converter), - else: {<<>>, state.converter} - + {tail, _} = RateConverter.finish(state.converter) data = state.pending <> MuLaw.encode(tail) padding = rem(160 - rem(byte_size(data), 160), 160) split(data <> :binary.copy(<<255>>, padding), %__MODULE__{rate: state.rate}) diff --git a/lib/audio_flow/telephony/rate_converter.ex b/lib/audio_flow/telephony/rate_converter.ex index 8f3ee44..a2f5d82 100644 --- a/lib/audio_flow/telephony/rate_converter.ex +++ b/lib/audio_flow/telephony/rate_converter.ex @@ -1,41 +1,22 @@ defmodule AudioFlow.Telephony.RateConverter do @moduledoc """ - Stateful 8/16 kHz conversion for narrowband telephony. Upsampling uses linear - interpolation; downsampling uses a 31-tap windowed-sinc low-pass FIR at 3.4 kHz. - Filter delay is 15 input samples. This is not wideband audio restoration. + Stateful 8/16 kHz conversion for narrowband telephony, on `AudioFlow.Resampler`. + A converter works in the direction of its first call. It holds about 2 ms of + audio, which `finish/1` returns. """ - @half_width 15 - @history_size @half_width * 2 - @taps (for n <- -@half_width..@half_width do - sinc = - if n == 0, do: 0.425, else: :math.sin(2 * :math.pi() * 0.2125 * n) / (:math.pi() * n) + alias AudioFlow.Resampler - sinc * (0.54 + 0.46 * :math.cos(:math.pi() * n / @half_width)) - end) - @gain Enum.sum(@taps) - defstruct previous: 0, history: List.duplicate(0, @history_size), phase: 0 + defstruct [:resampler] - def up(data, state) when rem(byte_size(data), 2) == 0 do - {samples, previous} = - Enum.map_reduce(for(<>, do: s), state.previous, fn s, p -> - {<>, s} - end) + def up(data, state), do: convert(data, state, 8000, 16_000) + def down(data, state), do: convert(data, state, 16_000, 8000) - {IO.iodata_to_binary(samples), %{state | previous: previous}} - end - - def finish_down(state), do: down(:binary.copy(<<0, 0>>, @history_size), state) - - def down(data, state) when rem(byte_size(data), 2) == 0 do - {samples, state} = - Enum.map_reduce(for(<>, do: s), state, fn s, state -> - history = [s | state.history] - value = Enum.zip_with(history, @taps, &(&1 * &2)) |> Enum.sum() - value = (value / @gain) |> round() |> max(-32_768) |> min(32_767) - output = if state.phase == 1, do: <>, else: <<>> - {output, %{state | history: Enum.take(history, @history_size), phase: 1 - state.phase}} - end) + @doc "Returns the held audio and a new converter." + def finish(%__MODULE__{resampler: nil} = state), do: {<<>>, state} + def finish(%__MODULE__{resampler: resampler}), do: {Resampler.flush(resampler), %__MODULE__{}} - {IO.iodata_to_binary(samples), state} + defp convert(data, state, from, to) when rem(byte_size(data), 2) == 0 do + resampler = state.resampler || Resampler.new(from, to) + {Resampler.push(resampler, data), %{state | resampler: resampler}} end end diff --git a/mix.exs b/mix.exs index 3ab2f3c..8571747 100644 --- a/mix.exs +++ b/mix.exs @@ -60,6 +60,12 @@ defmodule AudioFlow.MixProject do {:zoi, "~> 0.18.11"}, {:telemetry, "~> 1.3"}, {:websock, "~> 0.5.3"}, + # FFmpeg resampling and G.711. Ratio 4.0.1 (via membrane_core) has an + # optional constraint that predates Decimal 3. Postgrex and Numbers share + # Decimal 3; media arithmetic compatibility is tested. + {:decimal, "~> 3.2", override: true}, + {:membrane_ffmpeg_swresample_plugin, "~> 0.21.0"}, + {:membrane_g711_ffmpeg_plugin, "~> 0.1.6"}, {:bandit, "~> 1.5", only: [:dev, :test]}, {:websock_adapter, "~> 0.5", only: [:dev, :test]}, {:credo, "~> 1.7", only: [:dev, :test], runtime: false}, @@ -74,12 +80,8 @@ defmodule AudioFlow.MixProject do if(enabled?("AUDIOFLOW_WEBRTC"), do: [{:ex_webrtc, "~> 0.18.0"}], else: []) ++ if(enabled?("AUDIOFLOW_MEDIA"), do: [ - # Ratio 4.0.1's optional constraint predates Decimal 3. Postgrex and - # Numbers share Decimal 3; media arithmetic compatibility is tested. - {:decimal, "~> 3.2", override: true}, {:membrane_core, "~> 1.3"}, {:membrane_raw_audio_format, "~> 0.12"}, - {:membrane_ffmpeg_swresample_plugin, "~> 0.21.0"}, {:membrane_portaudio_plugin, "~> 0.19.4"}, {:membrane_file_plugin, "~> 0.17.5"}, {:membrane_mp4_plugin, "~> 0.36.11"}, diff --git a/mix.lock b/mix.lock index c25b90b..ce185c7 100644 --- a/mix.lock +++ b/mix.lock @@ -57,6 +57,8 @@ "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_g711_ffmpeg_plugin": {:hex, :membrane_g711_ffmpeg_plugin, "0.1.6", "a05e986d4b9311a445d42eba84ec5341e726f84e31d629785a1e07fdb3aeccf0", [:mix], [{:bundlex, "~> 1.4", [hex: :bundlex, repo: "hexpm", optional: false]}, {:membrane_core, "~> 1.0", [hex: :membrane_core, repo: "hexpm", optional: false]}, {:membrane_g711_format, "~> 0.1.0", [hex: :membrane_g711_format, 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]}, {:unifex, "~> 1.1", [hex: :unifex, repo: "hexpm", optional: false]}], "hexpm", "c5c26ee46c9015322d8069d700dee42f1fd214c86d8fede1a5b3a6cddb741833"}, + "membrane_g711_format": {:hex, :membrane_g711_format, "0.1.1", "d0e001969c372280b7a1b89467540040baa72428a048b6aba9db645aedb8e713", [:mix], [], "hexpm", "e679bcf97019b3da1bf1e1a48a50ebcbfb8dfb4be4c89b74e6ae396762b0f02d"}, "membrane_h264_ffmpeg_plugin": {:hex, :membrane_h264_ffmpeg_plugin, "0.32.7", "643783cd4b0cb227ec39be0e7ffadf5b19e75afe675892ad832bb4d6c55057ec", [: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", "29e1089c9ea740672a27af94608f00d648fe6d9201b94f9e68e10f46db51b5c8"}, "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"}, diff --git a/site/src/content/docs/docs/features/transports.md b/site/src/content/docs/docs/features/transports.md index 22913cd..ce04dec 100644 --- a/site/src/content/docs/docs/features/transports.md +++ b/site/src/content/docs/docs/features/transports.md @@ -42,13 +42,14 @@ in the Answer/Dial/streaming_start request. The handler accepts mono PCMU at `media` and `clear` envelopes, without a Twilio SID. MP3 playback mode and other codecs are unsupported. See [Telnyx's streaming guide](https://developers.telnyx.com/docs/voice/programmable-voice/media-streaming). -Both paths decode Base64 headerless μ-law, interpolate to 16 kHz PCM, and feed +Both paths decode Base64 headerless μ-law, resample to 16 kHz PCM, and feed the configured VAD. Endpoint detection submits an utterance; confirmed speech cancels an active reply and clears remote playback. TTS must emit 8 or 16 kHz mono s16le PCM. Other rates fail the turn and close the stream with code 1011; -configure TTS output or an upstream resampler explicitly. Downsampling uses a -stateful 31-tap FIR, with 15 input samples of delay. On completion the filter -tail is drained and the last 20 ms packet is padded with μ-law silence. No +configure TTS output or an upstream resampler explicitly. G.711 and both rate +conversions use FFmpeg (libswresample), which holds about 2 ms of audio. On +completion that audio is drained and the last 20 ms packet is padded with μ-law +silence. No wideband recovery or production acoustic-quality claim is made. Input messages are capped at 100 KB and decoded media at 16 KB. Inbound media @@ -138,7 +139,7 @@ npm --prefix examples/rtvi-client run typecheck npm --prefix examples/rtvi-client test ``` -Core tests require no native media/ML libraries or provider credentials. Tests +Core tests require no model downloads or provider credentials. Tests exercise G.711 codewords, resampling chunk continuity and stop-band attenuation, real loopback WebSocket upgrades for both provider envelopes, PCM session input/output, barge-in clear, malformed input and stream lifecycle, plus the diff --git a/test/graph_test.exs b/test/graph_test.exs index 42d3bd9..0619add 100644 --- a/test/graph_test.exs +++ b/test/graph_test.exs @@ -295,22 +295,12 @@ defmodule AudioFlow.GraphTest do end end - test "resampling keeps the duration and interpolates between samples" do - pcm = for sample <- [0, 300, 600, 900], into: <<>>, do: <> + test "resampling keeps the duration" do + pcm = for i <- 0..799, into: <<>>, do: <> audio = %Audio{data: pcm, sample_rate: 8_000} assert %Audio{data: data, sample_rate: 16_000} = Graph.Nodes.Audio.resample(audio, 16_000) - - assert for(<>, do: sample) == [ - 0, - 150, - 300, - 450, - 600, - 750, - 900, - 900 - ] + assert byte_size(data) == 2 * byte_size(pcm) assert Graph.Nodes.Audio.resample(audio, 8_000) == audio end diff --git a/test/network_protocol_test.exs b/test/network_protocol_test.exs index 7d6e5d4..b635158 100644 --- a/test/network_protocol_test.exs +++ b/test/network_protocol_test.exs @@ -72,14 +72,15 @@ defmodule AudioFlow.NetworkProtocolTest do media = %{ event: "media", - media: %{track: "inbound", chunk: "1", payload: Base.encode64(:binary.copy(<<255>>, 768))} + media: %{track: "inbound", chunk: "1", payload: Base.encode64(:binary.copy(<<255>>, 800))} } Client.send_json(socket, Map.put(media, stream_key(@provider), "stream-1")) assert_receive {:input, %AudioFlow.Audio{sample_rate: 16_000, data: data}} assert byte_size(data) == 3072 - for _ <- 1..6 do + # The demo reply is 100 ms: five 20 ms packets. + for _ <- 1..5 do assert {:json, %{"event" => "media", "media" => %{"payload" => payload}} = frame} = Client.recv(socket) @@ -199,7 +200,7 @@ defmodule AudioFlow.NetworkProtocolTest do {AudioFlow.Adapters.Function, [ run: fn _, emit -> - emit.(%AudioFlow.Audio{sample_rate: 16_000, data: :binary.copy(<<0>>, 1280)}) + emit.(%AudioFlow.Audio{sample_rate: 16_000, data: :binary.copy(<<0>>, 1600)}) send(owner, {:speaking, self()}) Process.sleep(:infinity) end @@ -218,7 +219,7 @@ defmodule AudioFlow.NetworkProtocolTest do media = %{ event: "media", streamSid: "stream-1", - media: %{chunk: "1", payload: Base.encode64(:binary.copy(<<255>>, 768))} + media: %{chunk: "1", payload: Base.encode64(:binary.copy(<<255>>, 800))} } Client.send_json(socket, media) diff --git a/test/telephony_test.exs b/test/telephony_test.exs index 512ad8e..774f2fd 100644 --- a/test/telephony_test.exs +++ b/test/telephony_test.exs @@ -17,12 +17,15 @@ defmodule AudioFlow.TelephonyTest do pcm = for i <- 1..801, into: <<>>, do: <> for direction <- [:up, :down] do - {whole, _} = apply(RateConverter, direction, [pcm, %RateConverter{}]) + {whole, state} = apply(RateConverter, direction, [pcm, %RateConverter{}]) + {whole_tail, _} = RateConverter.finish(state) <> = pcm {a, state} = apply(RateConverter, direction, [first, %RateConverter{}]) - {b, _} = apply(RateConverter, direction, [rest, state]) - assert a <> b == whole - assert byte_size(whole) == if(direction == :up, do: 3204, else: 800) + {b, state} = apply(RateConverter, direction, [rest, state]) + {tail, _} = RateConverter.finish(state) + assert a <> b <> tail == whole <> whole_tail + # The flush can round the duration up by one sample. + assert byte_size(whole <> whole_tail) == if(direction == :up, do: 3204, else: 802) end end diff --git a/test/webrtc_session_test.exs b/test/webrtc_session_test.exs index b8f2db8..b780b3a 100644 --- a/test/webrtc_session_test.exs +++ b/test/webrtc_session_test.exs @@ -89,6 +89,8 @@ if System.get_env("AUDIOFLOW_WEBRTC") == "1" do :ok = WebRTC.publish(peer, key, :audio, :binary.copy(<<255>>, 160), pts + 20_000) :ok = WebRTC.publish(peer, key, :audio, :binary.copy(<<255>>, 160), pts + 40_000) + # The resampler holds 2 ms, so one more packet completes the silent frame. + :ok = WebRTC.publish(peer, key, :audio, :binary.copy(<<255>>, 160), pts + 60_000) end defp packet(peer) do @@ -179,27 +181,31 @@ if System.get_env("AUDIOFLOW_WEBRTC") == "1" do assert_receive {Session, ^bridge, {:utterance, :silence}}, 1000 assert_receive {:input, %Audio{data: input, sample_rate: 16_000}}, 1000 - {expected, up} = - RateConverter.up( - MuLaw.decode(MuLaw.encode(:binary.copy(<<0x10, 0x27>>, 160))), - %RateConverter{} + speech = MuLaw.decode(MuLaw.encode(:binary.copy(<<0x10, 0x27>>, 160))) + silence = MuLaw.decode(:binary.copy(<<255>>, 160)) + + {expected, _} = + Enum.map_reduce( + [speech, silence, silence, silence], + %RateConverter{}, + &RateConverter.up/2 ) - {silence, _} = RateConverter.up(MuLaw.decode(:binary.copy(<<255>>, 160)), up) - assert input == expected <> silence <> :binary.copy(<<0>>, 640) + assert byte_size(input) >= 1280 + assert input == binary_part(IO.iodata_to_binary(expected), 0, byte_size(input)) assert_receive {Session, ^bridge, {:session, turn, {:transcript, "actual utterance"}}} assert_receive {Session, ^bridge, {:session, ^turn, {:text, "reply text"}}} assert_receive {Session, ^bridge, {:session, ^turn, {:audio, %Audio{sample_rate: 16_000}}}} assert_receive {Session, ^bridge, {:session, ^turn, {:done, _}}} {pcm, down} = RateConverter.down(:binary.copy(<<0x10, 0x27>>, 1600), %RateConverter{}) - {tail, _} = RateConverter.down(:binary.copy(<<0>>, 60), down) + {tail, _} = RateConverter.finish(down) expected = MuLaw.encode(pcm <> tail) expected = expected <> :binary.copy(<<255>>, rem(160 - rem(byte_size(expected), 160), 160)) started = System.monotonic_time(:millisecond) - packets = for _ <- 1..6, do: packet(peer) - assert System.monotonic_time(:millisecond) - started >= 70 + packets = for _ <- 1..5, do: packet(peer) + assert System.monotonic_time(:millisecond) - started >= 50 assert Enum.map_join(packets, & &1.payload) == expected - assert Enum.map(packets, & &1.timestamp) == Enum.to_list(0..800//160) + assert Enum.map(packets, & &1.timestamp) == Enum.to_list(0..640//160) assert Enum.all?(packets, &(&1.payload_type == 0)) state = :sys.get_state(bridge) assert :sys.get_state(state.session).playback_history.playout.played == 0 @@ -265,17 +271,12 @@ if System.get_env("AUDIOFLOW_WEBRTC") == "1" do turn = make_ref() :ok = WebRTC.start_turn(peer, turn) - :ok = - WebRTC.publish( - peer, - turn, - :audio, - MuLaw.encode(:binary.copy(<<0x10, 0x27>>, 160)), - 60_000 - ) + speech = MuLaw.encode(:binary.copy(<<0x10, 0x27>>, 160)) + :ok = WebRTC.publish(peer, turn, :audio, speech, 80_000) + :ok = WebRTC.publish(peer, turn, :audio, speech, 100_000) - # Synchronize on the ingress state having consumed the third packet. - await(fn -> :sys.get_state(bridge).expected == 4 end) + # Synchronize on the ingress state having consumed both speech packets. + await(fn -> :sys.get_state(bridge).expected == 6 end) assert :sys.get_state(s.transport).key == nil assert :queue.is_empty(:sys.get_state(s.transport).queue)