[Bugfix] Report sample rate and channels for streamed speech PCM (#8567)

Signed-off-by: Yueqian Lin <linyueqian@outlook.com>
This commit is contained in:
Yueqian Lin authored and GitHub committed 2026-10-07 17:07:49 -07:00
1 parent c32a26a845
commit 1c71a2c03a
8 files changed
+577 -93

No files matched your search

+99 -4
View File
@@ -79,6 +79,10 @@ _SPEECH_USAGE_OUTPUT_TOKENS_HEADER = "X-VLLM-OMNI-OUTPUT-TOKENS"
_SPEECH_USAGE_TOTAL_TOKENS_HEADER = "X-VLLM-OMNI-TOTAL-TOKENS"
_SPEECH_USAGE_INPUT_TEXT_TOKENS_HEADER = "X-VLLM-OMNI-INPUT-TEXT-TOKENS"
_SPEECH_USAGE_INPUT_AUDIO_TOKENS_HEADER = "X-VLLM-OMNI-INPUT-AUDIO-TOKENS"
# Raw ``pcm`` bodies carry no format header and the rate/channel count is
# model-native, so responses state the s16le layout explicitly.
SPEECH_AUDIO_SAMPLE_RATE_HEADER = "X-Audio-Sample-Rate"
SPEECH_AUDIO_CHANNELS_HEADER = "X-Audio-Channels"
def _stage_speech_metadata(stage: Any) -> tuple[str | None, str | None, str | None]:
@@ -176,6 +180,64 @@ def _infer_audio_num_channels(audio: np.ndarray) -> int:
return 1
def _audio_format_headers(audio_format: dict[str, int] | None) -> dict[str, str]:
"""Response headers describing the emitted audio's rate and channel count."""
if not audio_format:
return {}
return {
SPEECH_AUDIO_SAMPLE_RATE_HEADER: str(int(audio_format["sample_rate"])),
SPEECH_AUDIO_CHANNELS_HEADER: str(int(audio_format["channels"])),
# Without this, CORS hides both headers from cross-origin browser clients.
"Access-Control-Expose-Headers": f"{SPEECH_AUDIO_SAMPLE_RATE_HEADER}, {SPEECH_AUDIO_CHANNELS_HEADER}",
}
class _PrimedAudioStream:
"""Async iterator over an audio stream whose first chunk was already pulled.
Raw audio streams pull the first chunk before the HTTP response starts so
its headers can state the real sample rate and channel count.
"""
def __init__(self, chunks: Any, first: Any, has_first: bool) -> None:
self._chunks = chunks
self._first = first
self._has_first = has_first
@classmethod
async def start(cls, chunks: Any) -> "_PrimedAudioStream":
try:
first = await anext(chunks)
except StopAsyncIteration:
return cls(chunks, None, False)
except BaseException:
with anyio.CancelScope(shield=True):
await chunks.aclose()
raise
return cls(chunks, first, True)
def __aiter__(self) -> "_PrimedAudioStream":
return self
async def __anext__(self) -> Any:
if self._has_first:
first, self._first, self._has_first = self._first, None, False
return first
return await anext(self._chunks)
async def aclose(self) -> None:
self._first, self._has_first = None, False
await self._chunks.aclose()
def _encoded_audio_format(audio_response: Any, sample_rate: int, audio: np.ndarray) -> dict[str, int]:
"""Rate and channel count of an encoded chunk, preferring encoder metadata."""
metadata = getattr(audio_response, "audio_metadata", None)
if metadata is not None:
return {"sample_rate": int(metadata.sample_rate_hz), "channels": int(metadata.channels)}
return {"sample_rate": int(sample_rate), "channels": _infer_audio_num_channels(np.asarray(audio))}
def _sanitize_filename(filename: str) -> str:
"""Sanitize filename to prevent path traversal attacks.
@@ -1568,6 +1630,7 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
collect: dict | None = None,
target_sample_rate: int | None = None,
cumulative_audio: bool = False,
audio_format: dict[str, int] | None = None,
):
"""Generate audio chunks for streaming response.
@@ -1581,6 +1644,9 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
generator: Async generator from the engine
request_id: Request identifier for logging
response_format: Audio format (pcm or wav)
audio_format: Optional out-parameter. Before the first audio
chunk is yielded it receives that chunk's ``sample_rate`` and
``channels``, so callers can describe a raw PCM stream.
Yields:
Raw audio bytes for each chunk (with WAV header for first chunk if wav format)
@@ -1722,8 +1788,11 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
speed=1.0,
base64_encode=False,
)
audio_bytes = cast(bytes, self.create_audio(audio_obj).audio_data)
audio_response = self.create_audio(audio_obj)
audio_bytes = cast(bytes, audio_response.audio_data)
record_audio_chunk(audio_bytes, chunk_np, res)
if audio_format is not None and not audio_format and audio_bytes:
audio_format.update(_encoded_audio_format(audio_response, output_sample_rate, chunk_np))
if wav_header is not None:
yield wav_header
if include_sample_rate:
@@ -1750,8 +1819,11 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
speed=1.0,
base64_encode=False,
)
audio_bytes = cast(bytes, self.create_audio(audio_obj).audio_data)
audio_response = self.create_audio(audio_obj)
audio_bytes = cast(bytes, audio_response.audio_data)
record_audio_chunk(audio_bytes, final_chunk, last_audio_result)
if audio_format is not None and not audio_format and audio_bytes:
audio_format.update(_encoded_audio_format(audio_response, output_sample_rate, final_chunk))
if wav_header is not None:
yield wav_header
if include_sample_rate:
@@ -1880,6 +1952,7 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
"""
usage_acc = SpeechOutputTokenCounter()
emitted_audio = False
audio_format: dict[str, int] = {}
try:
async with aclosing(
self._generate_audio_chunks(
@@ -1892,6 +1965,7 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
usage_acc=usage_acc,
tts_params=tts_params,
target_sample_rate=request.sample_rate if request is not None else None,
audio_format=audio_format,
)
) as chunks:
async for chunk in chunks:
@@ -1900,6 +1974,11 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
"audio": base64.b64encode(chunk).decode("ascii"),
"response_format": response_format,
}
if audio_format:
# Additive to the OpenAI schema: pcm deltas are
# model-native s16le, not always 24 kHz mono.
payload["sample_rate"] = audio_format["sample_rate"]
payload["channels"] = audio_format["channels"]
data = json.dumps(payload, separators=(",", ":"))
emitted_audio = True
yield f"event: speech.audio.delta\ndata: {data}\n\n"
@@ -2134,6 +2213,7 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
collect: dict | None = None,
target_sample_rate: int | None = None,
cumulative_audio: bool = False,
audio_format: dict[str, int] | None = None,
):
"""Yield raw PCM byte chunks from the engine generator.
@@ -2154,6 +2234,7 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
collect=collect,
target_sample_rate=target_sample_rate,
cumulative_audio=cumulative_audio,
audio_format=audio_format,
)
) as chunks:
async for chunk in chunks:
@@ -2355,6 +2436,10 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
base64_encode=base64_encode,
)
audio_response: AudioResponse = self.create_audio(audio_obj)
if collect is not None:
collect["audio_format"] = _encoded_audio_format(
audio_response, request.sample_rate or sample_rate, audio_tensor
)
self._mark_ref_audio_artifact_ready_for_request(request_id)
artifact_ready = True
if usage_out is not None:
@@ -2634,7 +2719,11 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
request_id=request_id,
arrival_time=request_arrival_ts,
)
return _SpeechStreamingResponse(
audio_format: dict[str, int] = {}
# Pull the first chunk before sending headers: the body has no
# self-describing format for pcm and the rate/channel count is
# model-native (not always 24 kHz mono), so the headers state it.
body = await _PrimedAudioStream.start(
self._generate_audio_chunks(
generator,
request_id,
@@ -2644,8 +2733,13 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
request_arrival_ts=request_arrival_ts,
tts_params=raw_tts_params,
target_sample_rate=request.sample_rate,
),
audio_format=audio_format,
)
)
return _SpeechStreamingResponse(
body,
media_type=media_type,
headers=_audio_format_headers(audio_format),
)
if request.is_sse_stream():
@@ -2735,6 +2829,7 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
)
if collect.get("audio_truncated") is not None:
headers["X-Audio-Truncated"] = "true" if collect["audio_truncated"] else "false"
headers.update(_audio_format_headers(collect.get("audio_format")))
return Response(content=audio_bytes, media_type=media_type, headers=headers)
except asyncio.CancelledError:
@@ -30,6 +30,9 @@ Protocol:
Server -> Client (default, word_timestamps=false):
{"type": "audio.start", "utterance_index": 0, "sentence_index": 0,
"sentence_text": "...", "format": "wav"}
# With stream_audio=true, audio.start is sent with the first audio
# chunk; for format "pcm" it also carries that audio's "sample_rate"
# and "channels" (s16le, interleaved, model-native).
<binary frame: audio bytes>
...
{"type": "audio.done", "utterance_index": 0, "sentence_index": 0}
@@ -56,6 +59,7 @@ import asyncio
import base64
import json
import time
from collections.abc import Awaitable, Callable
from contextlib import aclosing
from fastapi import WebSocket, WebSocketDisconnect
@@ -75,7 +79,7 @@ logger = init_logger(__name__)
_DEFAULT_IDLE_TIMEOUT = 30.0 # seconds
_DEFAULT_CONFIG_TIMEOUT = 10.0 # seconds
_PCM_SAMPLE_RATE = 24000
_BYTES_PER_SAMPLE = 2 # 16-bit mono PCM
_BYTES_PER_SAMPLE = 2 # 16-bit PCM, per channel
_MAX_CONFIG_MESSAGE_SIZE = 4 * 1024 * 1024 # allow large ref_audio payloads
_MAX_INPUT_TEXT_MESSAGE_SIZE = 128 * 1024
@@ -336,13 +340,28 @@ class OmniStreamingSpeechHandler:
"sentence_text": sentence_text,
"format": response_format,
}
if config.stream_audio and response_format == "pcm":
# Nominal stream rate; each audio.chunk carries the authoritative
# per-chunk sample_rate.
start_payload["sample_rate"] = _PCM_SAMPLE_RATE
if config.word_timestamps:
start_payload["word_timestamps"] = True
await websocket.send_json(start_payload)
# Streamed pcm is model-native s16le. Its rate and channel count are
# known once the first chunk is encoded, so for pcm audio.start is
# deferred to that point and states them; it is sent bare if no audio
# arrives. Non-streamed responses still send it before generation.
describe_pcm = config.stream_audio and response_format == "pcm"
audio_format: dict[str, int] = {}
start_sent = False
async def send_start() -> None:
nonlocal start_sent
if start_sent:
return
start_sent = True
if describe_pcm and audio_format:
start_payload["sample_rate"] = audio_format["sample_rate"]
start_payload["channels"] = audio_format["channels"]
await websocket.send_json(start_payload)
if not describe_pcm:
await send_start()
total_bytes = 0
generation_failed = False
@@ -365,6 +384,8 @@ class OmniStreamingSpeechHandler:
request_start_s=request_start_s,
request_arrival_ts=request_arrival_ts,
tts_params=tts_params,
audio_format=audio_format,
send_start=send_start,
)
else:
async with aclosing(
@@ -374,9 +395,11 @@ class OmniStreamingSpeechHandler:
request_start_s=request_start_s,
request_arrival_ts=request_arrival_ts,
tts_params=tts_params,
audio_format=audio_format,
)
) as stream:
async for chunk in stream:
await send_start()
total_bytes += len(chunk)
await websocket.send_bytes(chunk)
else:
@@ -401,6 +424,10 @@ class OmniStreamingSpeechHandler:
sentence_index,
e,
)
try:
await send_start()
except Exception:
logger.debug("Failed to send audio.start for sentence %d", sentence_index, exc_info=True)
await self._send_error(
websocket,
f"Generation failed for utterance {utterance_index}, sentence {sentence_index}: {e}",
@@ -408,6 +435,9 @@ class OmniStreamingSpeechHandler:
)
finally:
try:
if not start_sent:
# Keep audio.start/audio.done paired when no audio was produced.
await send_start()
await websocket.send_json(
{
"type": "audio.done",
@@ -433,6 +463,8 @@ class OmniStreamingSpeechHandler:
request_arrival_ts: float,
language: str | None = None,
tts_params: dict | None = None,
audio_format: dict[str, int] | None = None,
send_start: Callable[[], Awaitable[None]] | None = None,
) -> int:
"""Stream PCM as JSON ``audio.chunk`` frames, aligned per sentence.
@@ -450,6 +482,10 @@ class OmniStreamingSpeechHandler:
chunk_id = 0
# Receives the aligner stage's pooling output from the generator.
collect: dict = {}
audio_format = audio_format if audio_format is not None else {}
def frame_bytes() -> int:
return _BYTES_PER_SAMPLE * int(audio_format.get("channels", 1))
async def send_chunk(
chunk: bytes,
@@ -459,6 +495,8 @@ class OmniStreamingSpeechHandler:
chunk_end_ms: int,
) -> None:
nonlocal chunk_id
if send_start is not None:
await send_start()
await websocket.send_json(
{
"type": "audio.chunk",
@@ -468,6 +506,7 @@ class OmniStreamingSpeechHandler:
"chunk_start_ms": chunk_start_ms,
"chunk_end_ms": chunk_end_ms,
"sample_rate": chunk_sample_rate,
"channels": int(audio_format.get("channels", 1)),
"audio_b64": base64.b64encode(chunk).decode("ascii"),
"timestamps": timestamps_payload,
}
@@ -484,13 +523,14 @@ class OmniStreamingSpeechHandler:
tts_params=tts_params,
collect=collect,
cumulative_audio=True,
audio_format=audio_format,
)
) as stream:
async for chunk, chunk_sample_rate in stream:
sample_rate = chunk_sample_rate
chunk_start_ms = int(round((audio_bytes_seen / _BYTES_PER_SAMPLE / sample_rate) * 1000.0))
chunk_start_ms = int(round((audio_bytes_seen / frame_bytes() / sample_rate) * 1000.0))
audio_bytes_seen += len(chunk)
chunk_end_ms = int(round((audio_bytes_seen / _BYTES_PER_SAMPLE / sample_rate) * 1000.0))
chunk_end_ms = int(round((audio_bytes_seen / frame_bytes() / sample_rate) * 1000.0))
total_bytes += len(chunk)
# Audio first, timestamps after the whole sentence is aligned.
await send_chunk(chunk, chunk_sample_rate, None, chunk_start_ms, chunk_end_ms)
@@ -502,7 +542,7 @@ class OmniStreamingSpeechHandler:
timestamps_payload = (
extract_word_timestamps(aligner_res, sentence_text, language) if aligner_res is not None else None
)
sentence_end_ms = int(round((audio_bytes_seen / _BYTES_PER_SAMPLE / sample_rate) * 1000.0))
sentence_end_ms = int(round((audio_bytes_seen / frame_bytes() / sample_rate) * 1000.0))
await send_chunk(b"", sample_rate, timestamps_payload, 0, sentence_end_ms)
return total_bytes