[Bugfix] Report sample rate and channels for streamed speech PCM (#8567)
Signed-off-by: Yueqian Lin <linyueqian@outlook.com>
This commit is contained in:
1 parent
c32a26a845
commit
1c71a2c03a
8 files changed
+577
-93
No files matched your search
@@ -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:
|
||||
|
||||
Reference in new issue
Block a user