From 91b68bc12c060eeff0c4f7e141cef0abef90c374 Mon Sep 17 00:00:00 2001 From: Harold Date: Fri, 12 Dec 2025 01:15:27 +0800 Subject: [PATCH] feat: vad streaming --- main/xiaozhi-server/core/connection.py | 39 +- .../core/handle/receiveAudioHandle.py | 65 +-- .../xiaozhi-server/core/providers/asr/base.py | 235 +++++++- .../core/providers/asr/dto/__init__.py | 7 + .../core/providers/asr/dto/dto.py | 58 +- .../core/providers/asr/openai.py | 1 + .../xiaozhi-server/core/providers/vad/base.py | 330 ++++++++++- .../core/providers/vad/dto/__init__.py | 4 + .../core/providers/vad/dto/dto.py | 47 ++ .../xiaozhi-server/core/providers/vad/fsmn.py | 243 ++++++++ .../core/providers/vad/silero.py | 354 +++++++----- main/xiaozhi-server/core/websocket_server.py | 2 +- main/xiaozhi-server/custom_config.yaml | 13 +- .../test/vad/test_silero_vad_stream.py | 524 ++++++++++++++++++ 14 files changed, 1724 insertions(+), 198 deletions(-) create mode 100644 main/xiaozhi-server/core/providers/asr/dto/__init__.py create mode 100644 main/xiaozhi-server/core/providers/vad/dto/__init__.py create mode 100644 main/xiaozhi-server/core/providers/vad/dto/dto.py create mode 100644 main/xiaozhi-server/core/providers/vad/fsmn.py create mode 100644 main/xiaozhi-server/test/vad/test_silero_vad_stream.py diff --git a/main/xiaozhi-server/core/connection.py b/main/xiaozhi-server/core/connection.py index 4322b2983..af842b2bd 100644 --- a/main/xiaozhi-server/core/connection.py +++ b/main/xiaozhi-server/core/connection.py @@ -31,6 +31,7 @@ from core.utils.dialogue import Message, Dialogue from core.providers.asr.dto.dto import InterfaceType from core.providers.tts.dto.dto import MessageTag from core.providers.llm.base import LLMProviderBase +from core.providers.vad.base import VADStream, VADProviderBase from core.handle.textHandle import handleTextMessage from core.providers.tools.unified_tool_handler import UnifiedToolHandler from plugins_func.loadplugins import auto_import_modules @@ -104,7 +105,7 @@ class ConnectionHandler: self.report_tts_enable = self._report_enabled # 依赖的组件 - self.vad = None + self.vad: VADProviderBase = None self.asr = None self.tts = None self._asr = _asr @@ -123,12 +124,18 @@ class ConnectionHandler: self.last_activity_time = 0.0 # 统一的活动时间戳(毫秒) self.client_voice_stop = False self.last_is_voice = False + self._vad_states = {} # asr相关变量 # 因为实际部署时可能会用到公共的本地ASR,不能把变量暴露给公共ASR # 所以涉及到ASR的变量,需要在这里定义,属于connection的私有变量 self.asr_audio = [] self.asr_audio_queue = queue.Queue() + + # VAD stream instance (created per connection) + self.vad_stream: VADStream = None + # VAD event processor task + self._vad_event_task = None # llm相关变量 self.llm_finish_task = True @@ -429,6 +436,9 @@ class ConnectionHandler: if self.asr is None: self.asr = self._initialize_asr() + # Initialize VAD stream for this connection + self._initialize_vad_stream() + # 初始化声纹识别 self._initialize_voiceprint() @@ -649,6 +659,22 @@ class ConnectionHandler: return asr + def _initialize_vad_stream(self): + """Initialize VAD stream instance for this connection + + Only creates the VAD stream instance here (sync context). + The stream's task and event processor are started later in + open_audio_channels() which runs in async context. + """ + try: + # Create VAD stream for this connection + # Note: stream() only creates the instance, task is started via start() + self.vad_stream = self.vad.stream() + self.logger.bind(tag=TAG).info("VAD stream instance created") + except Exception as e: + self.logger.bind(tag=TAG).error(f"Failed to create VAD stream: {e}") + self.vad_stream = None + def _initialize_voiceprint(self): """为当前连接初始化声纹识别""" try: @@ -883,7 +909,7 @@ class ConnectionHandler: False, ) - init_vad = True + init_vad = False init_asr = True try: @@ -1255,6 +1281,14 @@ class ConnectionHandler: if hasattr(self, "audio_buffer"): self.audio_buffer.clear() + # Close VAD stream + if self.vad_stream: + try: + await self.vad_stream.close() + self.vad_stream = None + except Exception as e: + self.logger.bind(tag=TAG).error(f"Error closing VAD stream: {e}") + # 取消超时任务 if self.timeout_task and not self.timeout_task.done(): self.timeout_task.cancel() @@ -1375,6 +1409,7 @@ class ConnectionHandler: self.client_audio_buffer = bytearray() self.client_have_voice = False self.client_voice_stop = False + self._vad_states= {} # reset VAD exponential filter # if self.vad: # self.vad.reset_filter() diff --git a/main/xiaozhi-server/core/handle/receiveAudioHandle.py b/main/xiaozhi-server/core/handle/receiveAudioHandle.py index 8bbe8e22d..487e3a06f 100644 --- a/main/xiaozhi-server/core/handle/receiveAudioHandle.py +++ b/main/xiaozhi-server/core/handle/receiveAudioHandle.py @@ -473,52 +473,29 @@ async def _quick_asr_and_check(conn, audio_chunks): async def handleAudioMessage(conn, audio): - # 当前片段是否有人说话 - have_voice = conn.vad.is_vad(conn, audio) - # 如果设备刚刚被唤醒,短暂忽略VAD检测 - if hasattr(conn, "just_woken_up") and conn.just_woken_up: - have_voice = False - # 设置一个短暂延迟后恢复VAD检测 - conn.asr_audio.clear() - if not hasattr(conn, "vad_resume_task") or conn.vad_resume_task.done(): - conn.vad_resume_task = asyncio.create_task(resume_vad_detection(conn)) - return + """Handle incoming audio message from WebSocket + + New architecture: + 1. Push audio to VAD stream (async processing) + 2. VAD stream emits events → process_events() → asr_input_queue + 3. ASR processes audio from asr_input_queue + + Connection state (client_have_voice, client_voice_stop) is updated + by VAD stream's process_events() method. + """ - # 当音频 buffer 累积到 ~500ms 时,用部分 ASR 结果预取 Memory - await _trigger_pseudo_streaming_prefetch(conn, audio, have_voice) + # Push audio to VAD stream for processing + # VAD stream will: + # 1. Detect speech start/end + # 2. Update conn.client_have_voice and conn.client_voice_stop + # 3. Send audio to asr_input_queue + # 4. Trigger interrupt if needed (via callback) + if conn.vad_stream: + conn.vad_stream.push_audio(audio) - # 只有 TTS 正在播放且非手动监听模式时才检测打断 - # if conn.client_is_speaking and conn.client_listen_mode != "manual": - # # 初始化打断检测状态 - # _init_interrupt_state(conn) - - # if have_voice: - # # 检测到语音,增加连续语音帧计数 - # conn._continuous_voice_count += 1 - - # # 当连续语音帧达到阈值时,触发打断 - # # 这样可以过滤短暂噪音、回声、咳嗽等误触发 - # if conn._continuous_voice_count >= CONTINUOUS_VOICE_THRESHOLD: - # logger.bind(tag=TAG).info( - # f"持续语音检测触发打断: 连续 {conn._continuous_voice_count} 帧 " - # f"(阈值 {CONTINUOUS_VOICE_THRESHOLD} 帧, 约 {CONTINUOUS_VOICE_THRESHOLD * 60}ms)" - # ) - # # 重置计数器 - # conn._continuous_voice_count = 0 - # # 触发打断 - # await handleAbortMessage(conn) - # else: - # # 没有检测到语音,重置连续语音帧计数 - # conn._continuous_voice_count = 0 - if have_voice: - if conn.client_is_speaking and conn.client_listen_mode != "manual": - logger.bind(tag=TAG).info("检测到语音,触发打断") - await handleAbortMessage(conn) - - # 设备长时间空闲检测,用于say goodbye - await no_voice_close_connect(conn, have_voice) - # 接收音频 - await conn.asr.receive_audio(conn, audio, have_voice) + # Update activity time based on VAD state (for idle detection) + # Note: client_have_voice is updated by VAD stream's process_events() + await no_voice_close_connect(conn, conn.client_have_voice) async def resume_vad_detection(conn): diff --git a/main/xiaozhi-server/core/providers/asr/base.py b/main/xiaozhi-server/core/providers/asr/base.py index 9055484e7..662409f4a 100644 --- a/main/xiaozhi-server/core/providers/asr/base.py +++ b/main/xiaozhi-server/core/providers/asr/base.py @@ -4,7 +4,6 @@ import wave import uuid import json import time -import queue import asyncio import traceback import threading @@ -13,28 +12,76 @@ import concurrent.futures from abc import ABC, abstractmethod from config.logger import setup_logging from typing import Optional, Tuple, List -from core.handle.receiveAudioHandle import startToChat from core.handle.reportHandle import enqueue_asr_report from core.utils.util import remove_punctuation_and_length -from core.handle.receiveAudioHandle import handleAudioMessage +from .dto import ASRMessageType, ASRInputMessage +from queue import Queue, Empty TAG = __name__ logger = setup_logging() class ASRProviderBase(ABC): + def __init__(self): - pass + self.asr_input_queue = Queue[ASRInputMessage]() + self.asr_input_audio_format = "pcm" # 打开音频通道 async def open_audio_channels(self, conn): + # Thread for processing raw audio from WebSocket conn.asr_priority_thread = threading.Thread( - target=self.asr_text_priority_thread, args=(conn,), daemon=True + target=self._asr_audio_queue_thread, + args=(conn,), + daemon=True ) conn.asr_priority_thread.start() + + # Start VAD stream and event processor (must be in async context) + await self._start_vad_stream(conn) + + # Thread for processing ASR input messages from VAD stream + conn.asr_input_thread = threading.Thread( + target=self._asr_input_queue_thread, + args=(conn,), + daemon=True + ) + conn.asr_input_thread.start() + logger.bind(tag=TAG).info("ASR input queue thread started") - # 有序处理ASR音频 - def asr_text_priority_thread(self, conn): + async def _start_vad_stream(self, conn): + """Start VAD stream task and event processor + + This must be called from async context (running event loop). + """ + from core.handle.abortHandle import handleAbortMessage + + if conn.vad_stream is None: + logger.bind(tag=TAG).warning("VAD stream not initialized, skipping start") + return + + try: + # Start the VAD processing task + await conn.vad_stream.start() + + # Start the event processor task + conn._vad_event_task = asyncio.create_task( + conn.vad_stream.process_events( + conn=conn, + asr_input_queue=self.asr_input_queue, + interrupt_callback=handleAbortMessage, + ) + ) + logger.bind(tag=TAG).info("VAD stream and event processor started") + + except Exception as e: + logger.bind(tag=TAG).error(f"Failed to start VAD stream: {e}") + + def _asr_audio_queue_thread(self, conn): + """Thread for processing raw audio from WebSocket""" + # Import inside thread to avoid circular imports + from core.handle.receiveAudioHandle import handleAudioMessage + while not conn.stop_event.is_set(): try: message = conn.asr_audio_queue.get(timeout=1) @@ -43,14 +90,181 @@ class ASRProviderBase(ABC): conn.loop, ) future.result() - except queue.Empty: + except Empty: continue except Exception as e: logger.bind(tag=TAG).error( - f"处理ASR文本失败: {str(e)}, 类型: {type(e).__name__}, 堆栈: {traceback.format_exc()}" + f"处理ASR音频失败: {str(e)}, 类型: {type(e).__name__}, 堆栈: {traceback.format_exc()}" ) continue + def _asr_input_queue_thread(self, conn): + """Thread for processing ASRInputMessage from VAD stream + + This thread receives audio chunks from VAD stream's process_events() + and processes them when a LAST message is received (contains complete audio). + """ + while not conn.stop_event.is_set(): + try: + # Get message from async queue in sync context + message: ASRInputMessage = self.asr_input_queue.get(timeout=0.5) + + # Process ASRInputMessage + if message.message_type == ASRMessageType.FIRST: + # Start of new speech segment - just log, LAST contains complete audio + logger.bind(tag=TAG).debug( + f"ASR: Speech started, audio={message.audio_duration_ms:.0f}ms" + ) + + elif message.message_type == ASRMessageType.MIDDLE: + # For streaming ASR: would process incremental audio here + # Currently skipped by VAD event processor + pass + + elif message.message_type == ASRMessageType.LAST: + # End of speech segment - LAST contains complete audio from VAD + # No need to accumulate with FIRST (would cause duplication) + total_audio_ms = message.audio_duration_ms + logger.bind(tag=TAG).info( + f"ASR: Speech ended, total_audio={total_audio_ms:.0f}ms, " + f"speech_duration={message.speech_duration:.2f}s" + ) + + # Process the complete speech segment (LAST audio only) + asyncio.run_coroutine_threadsafe( + self._process_speech_segment(conn, [message.audio_data]), + conn.loop, + ) + + except asyncio.TimeoutError: + continue + except Empty: + continue + except Exception as e: + logger.bind(tag=TAG).error( + f"ASR input queue error: {str(e)}, type: {type(e).__name__}" + ) + continue + + logger.bind(tag=TAG).info("ASR input queue thread stopped") + + async def _process_speech_segment( + self, + conn, + pcm_audio_chunks: list[bytes] + ): + """Process a complete speech segment (PCM audio from VAD) + + Args: + conn: Connection handler + pcm_audio_chunks: List of PCM audio chunks (already decoded) + """ + # Import here to avoid circular imports + from core.handle.receiveAudioHandle import startToChat + + try: + total_start_time = time.monotonic() + + # Combine PCM chunks + combined_pcm = b"".join(pcm_audio_chunks) + + # Prepare WAV data for voiceprint if needed + wav_data = None + if conn.voiceprint_provider and combined_pcm: + wav_data = self._pcm_to_wav(combined_pcm) + + # Run ASR (audio is already PCM, not opus) + def run_asr(): + start_time = time.monotonic() + try: + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) + try: + # Pass PCM data directly + result = loop.run_until_complete( + self.speech_to_text(pcm_audio_chunks, conn.session_id, self.asr_input_audio_format) + ) + end_time = time.monotonic() + asr_elapsed_ms = (end_time - start_time) * 1000 + + # Calculate E2E latency + e2e_asr_delay = 0 + if hasattr(conn, '_latency_voice_end_time'): + e2e_asr_delay = time.time() * 1000 - conn._latency_voice_end_time + + logger.bind(tag=TAG).info( + f"🎙️ [Latency] ASR completed: {asr_elapsed_ms:.0f}ms | " + f"Voice end → ASR: {e2e_asr_delay:.0f}ms" + ) + return result + finally: + loop.close() + except Exception as e: + logger.bind(tag=TAG).error(f"ASR failed: {e}") + return ("", None) + + # Run voiceprint recognition + def run_voiceprint(): + if not wav_data: + return None + try: + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) + try: + result = loop.run_until_complete( + conn.voiceprint_provider.identify_speaker(wav_data, conn.session_id) + ) + return result + finally: + loop.close() + except Exception as e: + logger.bind(tag=TAG).error(f"Voiceprint failed: {e}") + return None + + # Run tasks in parallel + with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor: + asr_future = executor.submit(run_asr) + + if conn.voiceprint_provider and wav_data: + voiceprint_future = executor.submit(run_voiceprint) + asr_result = asr_future.result(timeout=15) + voiceprint_result = voiceprint_future.result(timeout=15) + results = {"asr": asr_result, "voiceprint": voiceprint_result} + else: + asr_result = asr_future.result(timeout=15) + results = {"asr": asr_result, "voiceprint": None} + + # Process results + raw_text, _ = results.get("asr", ("", None)) + speaker_name = results.get("voiceprint", None) + + if raw_text: + logger.bind(tag=TAG).info(f"Recognized text: {raw_text}") + if speaker_name: + logger.bind(tag=TAG).info(f"Recognized speaker: {speaker_name}") + + # Performance monitoring + total_time = time.monotonic() - total_start_time + logger.bind(tag=TAG).info(f"Total processing time: {total_time:.3f}s") + + # Check text length + text_len, _ = remove_punctuation_and_length(raw_text) + self.stop_ws_connection() + + if text_len > 0: + enhanced_text = self._build_enhanced_text(raw_text, speaker_name) + asr_report_time = int(time.time()) + + await startToChat(conn, enhanced_text) + # Note: For report, we need to convert PCM back to opus or use PCM directly + # For now, pass empty list as audio data for report + enqueue_asr_report(conn, enhanced_text, [], report_time=asr_report_time) + + except Exception as e: + logger.bind(tag=TAG).error(f"Process speech segment failed: {e}") + import traceback + logger.bind(tag=TAG).debug(f"Exception details: {traceback.format_exc()}") + # 接收音频 async def receive_audio(self, conn, audio, audio_have_voice): if conn.client_listen_mode == "auto" or conn.client_listen_mode == "realtime": @@ -74,6 +288,9 @@ class ASRProviderBase(ABC): # 处理语音停止 async def handle_voice_stop(self, conn, asr_audio_task: List[bytes]): """并行处理ASR和声纹识别""" + # Import here to avoid circular imports + from core.handle.receiveAudioHandle import startToChat + try: total_start_time = time.monotonic() diff --git a/main/xiaozhi-server/core/providers/asr/dto/__init__.py b/main/xiaozhi-server/core/providers/asr/dto/__init__.py new file mode 100644 index 000000000..174a3022a --- /dev/null +++ b/main/xiaozhi-server/core/providers/asr/dto/__init__.py @@ -0,0 +1,7 @@ +from .dto import InterfaceType, ASRMessageType, ASRInputMessage + +__all__ = [ + "InterfaceType", + "ASRMessageType", + "ASRInputMessage", +] diff --git a/main/xiaozhi-server/core/providers/asr/dto/dto.py b/main/xiaozhi-server/core/providers/asr/dto/dto.py index 85b2d7b21..55083c6c8 100644 --- a/main/xiaozhi-server/core/providers/asr/dto/dto.py +++ b/main/xiaozhi-server/core/providers/asr/dto/dto.py @@ -1,9 +1,59 @@ +from dataclasses import dataclass, field from enum import Enum from typing import Union, Optional class InterfaceType(Enum): - # 接口类型 - STREAM = "STREAM" # 流式接口 - NON_STREAM = "NON_STREAM" # 非流式接口 - LOCAL = "LOCAL" # 本地服务 + """ASR interface types""" + STREAM = "STREAM" # Streaming interface + NON_STREAM = "NON_STREAM" # Non-streaming interface + LOCAL = "LOCAL" # Local service + + +class ASRMessageType(Enum): + """ASR input message types + + Defines the position of audio chunk in a speech segment: + - FIRST: First chunk of a speech segment (speech start detected) + - MIDDLE: Middle chunk of a speech segment (during speaking) + - LAST: Last chunk of a speech segment (speech end detected) + """ + FIRST = "FIRST" # Speech started + MIDDLE = "MIDDLE" # During speech + LAST = "LAST" # Speech ended + + +@dataclass +class ASRInputMessage: + """ASR input message data structure + + Represents an audio chunk sent to ASR service for transcription. + + Attributes: + message_type: Position of this chunk in the speech segment + audio_data: PCM audio data (16-bit, 16kHz, mono) + speech_duration: Accumulated speech duration in seconds (from VAD) + probability: Speech probability for this chunk (0.0-1.0) + timestamp_ms: Timestamp when this message was created + """ + message_type: ASRMessageType + audio_data: bytes = field(default_factory=bytes) + speech_duration: float = 0.0 + probability: float = 0.0 + timestamp_ms: float = 0.0 + + @property + def is_first(self) -> bool: + """Check if this is the first message of a speech segment""" + return self.message_type == ASRMessageType.FIRST + + @property + def is_last(self) -> bool: + """Check if this is the last message of a speech segment""" + return self.message_type == ASRMessageType.LAST + + @property + def audio_duration_ms(self) -> float: + """Calculate audio duration in milliseconds""" + # 16kHz, 16-bit mono = 32 bytes per ms + return len(self.audio_data) / 32 if self.audio_data else 0.0 diff --git a/main/xiaozhi-server/core/providers/asr/openai.py b/main/xiaozhi-server/core/providers/asr/openai.py index d789911e2..5823f2ec3 100644 --- a/main/xiaozhi-server/core/providers/asr/openai.py +++ b/main/xiaozhi-server/core/providers/asr/openai.py @@ -14,6 +14,7 @@ logger = setup_logging() class ASRProvider(ASRProviderBase): def __init__(self, config: dict, delete_audio_file: bool): + super().__init__() self.interface_type = InterfaceType.NON_STREAM self.api_key = config.get("api_key") self.base_url = config.get("base_url") diff --git a/main/xiaozhi-server/core/providers/vad/base.py b/main/xiaozhi-server/core/providers/vad/base.py index 1d8d4c8dd..ada90ec13 100644 --- a/main/xiaozhi-server/core/providers/vad/base.py +++ b/main/xiaozhi-server/core/providers/vad/base.py @@ -1,9 +1,333 @@ +from __future__ import annotations + from abc import ABC, abstractmethod -from typing import Optional +from dataclasses import dataclass +import queue +from typing import TYPE_CHECKING, AsyncIterator, Callable, Optional, Union +from queue import Queue, Empty +import asyncio +import numpy as np +import time +import opuslib_next + +from config.logger import setup_logging +from .dto import VADEvent, VADEventType +from core.providers.asr.dto import ASRMessageType, ASRInputMessage + +if TYPE_CHECKING: + from core.connection import ConnectionHandler + +TAG = __name__ +logger = setup_logging() + +# Audio constants +SAMPLE_RATE = 16000 +CHANNELS = 1 +OPUS_FRAME_SAMPLES = 960 # 60ms at 16kHz + + +class ExpFilter: + """Exponential filter for smoothing probability values + + Smooths noisy VAD probability outputs to reduce false triggers. + Formula: smoothed = alpha * current + (1-alpha) * previous + + Args: + alpha: Smoothing factor (0-1). Higher = faster response, less smoothing. + """ + def __init__(self, alpha: float = 0.35): + self._alpha = alpha + self._filtered_value: Optional[float] = None + + def apply(self, sample: float) -> float: + if self._filtered_value is None: + self._filtered_value = sample + else: + self._filtered_value = self._alpha * sample + (1 - self._alpha) * self._filtered_value + return self._filtered_value + + def reset(self): + self._filtered_value = None class VADProviderBase(ABC): + """Base class for VAD providers + + VAD provider loads the model once and creates VADStream instances + for each connection. + """ + + def __init__(self): + super().__init__() + @abstractmethod - def is_vad(self, conn, data) -> bool: - """检测音频数据中的语音活动""" + def stream(self) -> VADStream: ... + + +class VADStream(ABC): + """Base class for VAD stream processing + + Each connection should have its own VADStream instance. + The stream maintains internal state and outputs VADEvent objects. + """ + + class _FlushSentinel: pass + + def __init__(self, vad: VADProviderBase): + self._vad = vad + self._last_activity_time = time.perf_counter() + self._is_closed = False + self._input_queue = asyncio.Queue[Union[bytes, VADStream._FlushSentinel]]() + self._output_queue = asyncio.Queue[VADEvent]() + + # Each stream has its own decoder to maintain independent state + self._decoder = opuslib_next.Decoder(SAMPLE_RATE, CHANNELS) + + # This allows VADStream to be instantiated outside of async context + self._task = None + # Event callback + self._event_callback: Optional[Callable[[VADEvent], None]] = None + + async def start(self) -> None: + """Start the VAD processing task + + Must be called in an async context (running event loop). + This is separated from __init__ to allow instantiation in sync context. + """ + if self._task is not None: + logger.bind(tag=TAG).warning("VAD stream already started") + return + + self._task = asyncio.create_task(self._run_task()) + logger.bind(tag=TAG).info("VAD stream task started") + + @abstractmethod + async def _run_task(self) -> None: + """Main processing loop - processes PCM data from input queue + + Subclass should implement this to: + 1. await self._input_queue.get() to receive PCM data + 2. Process the PCM data + 3. Call self._emit_event() to output VADEvent + """ + ... + + def push_audio(self, opus_data: bytes) -> None: + """Push opus audio packet for processing + + Decodes opus to PCM and queues for processing. + + Args: + opus_data: Opus encoded audio packet + """ + if self._is_closed: + return + + try: + # Decode opus to PCM in base class + pcm_data = self._decoder.decode(opus_data, OPUS_FRAME_SAMPLES) + self._input_queue.put_nowait(pcm_data) + except opuslib_next.OpusError as e: + logger.bind(tag=TAG).error(f"Opus decode error: {e}") + + async def close(self) -> None: + """Close the VAD stream and cancel running task""" + if self._task is not None: + self._task.cancel() + try: + await self._task + except asyncio.CancelledError: + logger.bind(tag=TAG).info("VAD stream task cancelled") + except Exception as e: + logger.bind(tag=TAG).error(f"VAD stream task failed: {e}") + + self._task = None + self._is_closed = True + self._input_queue = None + self._output_queue = None + + async def process_events( + self, + conn: "ConnectionHandler", + asr_input_queue: Queue[ASRInputMessage], + interrupt_callback: Optional[Callable[["ConnectionHandler"], asyncio.coroutine]] = None, + ) -> None: + """Process VAD events from output_queue and send to ASR input queue + + This method continuously reads VAD events from output_queue and: + 1. START_OF_SPEECH: Update conn state, send FIRST message, trigger interrupt if needed + 2. INFERENCE_DONE: Send MIDDLE message if speaking + 3. END_OF_SPEECH: Send LAST message, update conn state + + Args: + conn: Connection handler with client state + asr_input_queue: Queue to send ASR input messages + interrupt_callback: Optional async callback for interrupt handling + """ + logger.bind(tag=TAG).info("VAD event processor started") + + while not self._is_closed: + try: + # Wait for VAD event (sync queue with timeout) + event = await self._output_queue.get() + + current_time_ms = time.time() * 1000 + + if event.type == VADEventType.START_OF_SPEECH: + await self._handle_speech_start( + conn, event, asr_input_queue, + current_time_ms, interrupt_callback + ) + + elif event.type == VADEventType.INFERENCE_DONE: + # Skip MIDDLE messages for non-streaming ASR + # LAST message already contains complete audio segment + # TODO: For streaming ASR, implement incremental audio handling + pass + + elif event.type == VADEventType.END_OF_SPEECH: + await self._handle_speech_end( + conn, event, asr_input_queue, current_time_ms + ) + + except asyncio.CancelledError: + logger.bind(tag=TAG).info("VAD event processor cancelled") + break + except Exception as e: + logger.bind(tag=TAG).error(f"Error processing VAD event: {e}") + continue + + logger.bind(tag=TAG).info("VAD event processor stopped") + + async def _handle_speech_start( + self, + conn: "ConnectionHandler", + event: VADEvent, + asr_input_queue: Queue[ASRInputMessage], + current_time_ms: float, + interrupt_callback: Optional[Callable[["ConnectionHandler"], asyncio.coroutine]] = None, + ) -> None: + """Handle START_OF_SPEECH event + + 1. Update conn state (client_have_voice = True) + 2. Send FIRST message to ASR queue + 3. Check if interrupt is needed (client_is_speaking) + """ + logger.bind(tag=TAG).debug( + f"Speech start detected: prob={event.probability:.2f}, " + f"duration={event.speech_duration:.2f}s" + ) + + # Update connection state - voice started + conn.client_have_voice = True + + # Record latency tracking timestamp + conn._latency_voice_start_time = current_time_ms + + # Send FIRST message to ASR queue + asr_message = ASRInputMessage( + message_type=ASRMessageType.FIRST, + audio_data=event.audio_data, + speech_duration=event.speech_duration, + probability=event.probability, + timestamp_ms=current_time_ms, + ) + asr_input_queue.put_nowait(asr_message) + + logger.bind(tag=TAG).info( + f"ASR FIRST message sent: audio={asr_message.audio_duration_ms:.0f}ms" + ) + + # Check if interrupt is needed + # When TTS is speaking and user starts talking, trigger interrupt + if conn.client_is_speaking and conn.client_listen_mode != "manual": + logger.bind(tag=TAG).info( + "User started speaking while Agent is speaking, triggering interrupt" + ) + if interrupt_callback: + try: + await interrupt_callback(conn) + except Exception as e: + logger.bind(tag=TAG).error(f"Interrupt callback failed: {e}") + + async def _handle_inference_done( + self, + conn: "ConnectionHandler", + event: VADEvent, + asr_input_queue: Queue[ASRInputMessage], + current_time_ms: float, + ) -> None: + """Handle INFERENCE_DONE event + + Only send MIDDLE message if speech is ongoing (conn.client_have_voice) + """ + # Only send audio if client is speaking + if not conn.client_have_voice or not event.speaking: + return + + # Send MIDDLE message to ASR queue + asr_message = ASRInputMessage( + message_type=ASRMessageType.MIDDLE, + audio_data=event.audio_data, + speech_duration=event.speech_duration, + probability=event.probability, + timestamp_ms=current_time_ms, + ) + asr_input_queue.put_nowait(asr_message) + + logger.bind(tag=TAG).debug( + f"ASR MIDDLE message sent: prob={event.probability:.2f}, " + f"speech={event.speech_duration:.2f}s" + ) + + async def _handle_speech_end( + self, + conn: "ConnectionHandler", + event: VADEvent, + asr_input_queue: Queue[ASRInputMessage], + current_time_ms: float, + ) -> None: + """Handle END_OF_SPEECH event + + 1. Send LAST message to ASR queue + 2. Update conn state (client_voice_stop = True) + """ + logger.bind(tag=TAG).debug( + f"Speech end detected: duration={event.speech_duration:.2f}s, " + f"silence={event.silence_duration:.2f}s" + ) + + # Record latency tracking timestamp for voice end + conn._latency_voice_end_time = current_time_ms + + # Calculate voice duration for latency tracking + if hasattr(conn, '_latency_voice_start_time'): + voice_duration_ms = current_time_ms - conn._latency_voice_start_time + logger.bind(tag=TAG).info( + f"🎤 [Latency] Voice segment: {voice_duration_ms:.0f}ms" + ) + + # Send LAST message to ASR queue + asr_message = ASRInputMessage( + message_type=ASRMessageType.LAST, + audio_data=event.audio_data, + speech_duration=event.speech_duration, + probability=event.probability, + timestamp_ms=current_time_ms, + ) + asr_input_queue.put_nowait(asr_message) + + logger.bind(tag=TAG).info( + f"ASR LAST message sent: total_speech={event.speech_duration:.2f}s, " + f"audio={asr_message.audio_duration_ms:.0f}ms" + ) + + # Update connection state - voice stopped + conn.client_voice_stop = True + conn.client_have_voice = False + + + + + diff --git a/main/xiaozhi-server/core/providers/vad/dto/__init__.py b/main/xiaozhi-server/core/providers/vad/dto/__init__.py new file mode 100644 index 000000000..650402215 --- /dev/null +++ b/main/xiaozhi-server/core/providers/vad/dto/__init__.py @@ -0,0 +1,4 @@ +from .dto import VADEventType, VADEvent + +__all__ = ["VADEventType", "VADEvent"] + diff --git a/main/xiaozhi-server/core/providers/vad/dto/dto.py b/main/xiaozhi-server/core/providers/vad/dto/dto.py new file mode 100644 index 000000000..7c06b53c7 --- /dev/null +++ b/main/xiaozhi-server/core/providers/vad/dto/dto.py @@ -0,0 +1,47 @@ +from dataclasses import dataclass, field +from enum import Enum +from typing import Optional + + +class VADEventType(Enum): + """VAD event types""" + START_OF_SPEECH = "start_of_speech" # Speech started (after min_speech_duration) + INFERENCE_DONE = "inference_done" # Inference completed (every frame) + END_OF_SPEECH = "end_of_speech" # Speech ended (after min_silence_duration) + + +@dataclass +class VADEvent: + """VAD event data structure + + Attributes: + type: Event type (START_OF_SPEECH, INFERENCE_DONE, END_OF_SPEECH) + probability: Speech probability for current frame (0.0-1.0) + speech_duration: Accumulated speech duration in seconds + silence_duration: Accumulated silence duration in seconds + speaking: Whether currently speaking + audio_data: Audio data associated with this event (bytes, PCM 16-bit) + - START_OF_SPEECH: prefix padding + speech start + - INFERENCE_DONE: current inference window + - END_OF_SPEECH: complete speech segment with padding + inference_duration: Time taken for inference in seconds + """ + type: VADEventType + probability: float = 0.0 # speech probability (0.0-1.0) + speech_duration: float = 0.0 # accumulated speech duration (seconds) + silence_duration: float = 0.0 # accumulated silence duration (seconds) + speaking: bool = False # currently speaking + audio_data: bytes = field(default_factory=bytes) # PCM audio data + inference_duration: float = 0.0 # inference time (seconds) + + def __repr__(self) -> str: + audio_len_ms = len(self.audio_data) / 32 if self.audio_data else 0 # 16kHz, 16-bit = 32 bytes/ms + return ( + f"VADEvent(type={self.type.value}, " + f"speaking={self.speaking}, " + f"prob={self.probability:.2f}, " + f"speech={self.speech_duration:.2f}s, " + f"silence={self.silence_duration:.2f}s, " + f"audio={audio_len_ms:.0f}ms)" + ) + diff --git a/main/xiaozhi-server/core/providers/vad/fsmn.py b/main/xiaozhi-server/core/providers/vad/fsmn.py new file mode 100644 index 000000000..4e1eb6f98 --- /dev/null +++ b/main/xiaozhi-server/core/providers/vad/fsmn.py @@ -0,0 +1,243 @@ +import asyncio +import time +import numpy as np +from dataclasses import dataclass +from funasr import AutoModel + +from config.logger import setup_logging +from .base import VADProviderBase, VADStream +from .dto import VADEvent, VADEventType + + +TAG = __name__ +logger = setup_logging() + + +@dataclass +class FsmnVADOptions: + """FSMN VAD specific options""" + prefix_padding_duration: float = 0.3 # 300ms prefix padding + sample_rate: int = 16000 # 16kHz + chunk_size_ms: int = 100 # FSMN chunk size + + +class VADProvider(VADProviderBase): + """FSMN VAD provider using FunASR""" + + def __init__(self, config: dict): + super().__init__() + + model_name = config.get("model", "fsmn-vad") + model_revision = config.get("model_revision", "v2.0.4") + + self._model = AutoModel(model=model_name, model_revision=model_revision) + + # Parse config + chunk_size_ms = int(config.get("chunk_size_ms", "100")) + self._opts = FsmnVADOptions( + prefix_padding_duration=float(config.get("prefix_padding_duration", "0.3")), + sample_rate=16000, + chunk_size_ms=chunk_size_ms, + ) + + + + def stream(self) -> VADStream: + """Create a new VAD stream""" + return FsmnVADStream(self, self._model, self._opts) + + +class FsmnVADStream(VADStream): + """FSMN VAD stream implementation using FunASR + + FSMN VAD outputs events: + - [start, -1] -> speech start + - [-1, end] -> speech end + - [start, end] -> complete short segment (ignored) + - [] -> no event, keep current state + """ + + def __init__(self, vad: VADProvider, model, opts: FsmnVADOptions): + super().__init__(vad) + self._model = model + self._opts = opts + + # FSMN chunk size + self._chunk_samples = int(opts.chunk_size_ms * opts.sample_rate / 1000) + self._chunk_bytes = self._chunk_samples * 2 # int16 + self._chunk_duration = opts.chunk_size_ms / 1000 # seconds + + # Speech buffer for prefix padding (in bytes, not samples) + self._prefix_padding_bytes = int(opts.prefix_padding_duration * opts.sample_rate) * 2 + # Pre-allocate max speech buffer (60s + prefix padding) + max_speech_bytes = 60 * opts.sample_rate * 2 + self._prefix_padding_bytes + self._speech_buffer = bytearray(max_speech_bytes) + self._speech_buffer_max_reached = False + + def _get_speech_audio(self, end_index: int) -> bytes: + """Get the accumulated speech audio data""" + return bytes(self._speech_buffer[:end_index]) + + async def _run_task(self) -> None: + """Main processing loop - receives PCM data from base class""" + + # Local state variables + speech_buffer_index: int = 0 + speaking = False + speech_duration = 0.0 + silence_duration = 0.0 + speech_start_ms = 0 + + # Two buffers: one for inference, one for copying to speech buffer + input_audios: bytearray = bytearray() + inference_audios: bytearray = bytearray() + + # FSMN cache for streaming (reset on speech end) + fsmn_cache = {} + + while not self._is_closed: + try: + pcm_data = await self._input_queue.get() + if isinstance(pcm_data, VADStream._FlushSentinel): + continue + + # Accumulate PCM data to both buffers + input_audios.extend(pcm_data) + inference_audios.extend(pcm_data) + + # Process complete chunks + while len(inference_audios) >= self._chunk_bytes: + inference_start = time.perf_counter() + + # Extract chunk, convert int16 to float32 + chunk_int16 = np.frombuffer( + inference_audios[:self._chunk_bytes], dtype=np.int16 + ) + chunk_float32 = chunk_int16.astype(np.float32) / 32768.0 + + # Run FSMN inference + res = self._model.generate( + input=chunk_float32, + cache=fsmn_cache, + is_final=False, + chunk_size=self._opts.chunk_size_ms + ) + + inference_duration = time.perf_counter() - inference_start + + # Copy chunk to speech buffer + available_space = len(self._speech_buffer) - speech_buffer_index + to_copy = min(available_space, self._chunk_bytes) + + if to_copy > 0: + self._speech_buffer[speech_buffer_index:speech_buffer_index + to_copy] = input_audios[:to_copy] + speech_buffer_index += to_copy + elif not self._speech_buffer_max_reached: + self._speech_buffer_max_reached = True + logger.bind(tag=TAG).warning("Speech buffer max reached, dropping further audio") + + def _reset_write_cursor() -> None: + nonlocal speech_buffer_index + if speech_buffer_index <= self._prefix_padding_bytes: + return + + # Keep last prefix_padding worth of audio + padding_data = self._speech_buffer[ + speech_buffer_index - self._prefix_padding_bytes : speech_buffer_index + ] + + self._speech_buffer_max_reached = False + self._speech_buffer[: self._prefix_padding_bytes] = padding_data + speech_buffer_index = self._prefix_padding_bytes + + def _copy_speech_buffer() -> bytes: + return bytes(self._speech_buffer[:speech_buffer_index]) + + # Parse FSMN result + # res format: [{"key": "xxx", "value": [[start_ms, end_ms], ...]}] + if res and len(res) > 0 and res[0].get("value"): + seg = res[0]["value"][0] # Take first segment + seg_start, seg_end = seg[0], seg[1] + + if seg_start > 0 and seg_end == -1: + # Speech start event + if not speaking: + speaking = True + speech_start_ms = seg_start + silence_duration = 0.0 + + # Emit START_OF_SPEECH + self._output_queue.put_nowait(VADEvent( + type=VADEventType.START_OF_SPEECH, + speech_duration=0.0, + silence_duration=0.0, + speaking=True, + audio_data=_copy_speech_buffer(), + inference_duration=inference_duration, + )) + logger.bind(tag=TAG).info( + f"🎤 FSMN VAD START_OF_SPEECH @{seg_start}ms" + ) + + elif seg_start == -1 and seg_end > 0: + # Speech end event + if speaking: + speaking = False + speech_duration_ms = seg_end - speech_start_ms + speech_duration = speech_duration_ms / 1000 + + # Emit END_OF_SPEECH + self._output_queue.put_nowait(VADEvent( + type=VADEventType.END_OF_SPEECH, + speech_duration=speech_duration, + silence_duration=silence_duration, + speaking=False, + audio_data=_copy_speech_buffer(), + inference_duration=inference_duration, + )) + logger.bind(tag=TAG).info( + f"🔇 FSMN VAD END_OF_SPEECH @{seg_end}ms | " + f"duration={speech_duration:.2f}s" + ) + + # Reset for next utterance + speech_duration = 0.0 + fsmn_cache = {} + _reset_write_cursor() + + elif seg_start > 0 and seg_end > 0: + # Complete short segment - ignore + logger.bind(tag=TAG).debug( + f"FSMN: short segment [{seg_start}, {seg_end}]ms (ignored)" + ) + + # Update durations based on current state + if speaking: + speech_duration += self._chunk_duration + else: + silence_duration += self._chunk_duration + _reset_write_cursor() + + # Always emit INFERENCE_DONE + self._output_queue.put_nowait(VADEvent( + type=VADEventType.INFERENCE_DONE, + speech_duration=speech_duration, + silence_duration=silence_duration, + speaking=speaking, + audio_data=_copy_speech_buffer(), + inference_duration=inference_duration, + )) + + # Remove processed data from buffers + del inference_audios[:self._chunk_bytes] + del input_audios[:to_copy] + + except asyncio.CancelledError: + break + except Exception as e: + logger.bind(tag=TAG).error(f"Error in VAD task: {e}") + + def reset(self): + """Reset stream state for new utterance""" + # Note: Local variables in _run_task are reset by restarting the task + self._speech_buffer_max_reached = False diff --git a/main/xiaozhi-server/core/providers/vad/silero.py b/main/xiaozhi-server/core/providers/vad/silero.py index 3292d8882..d10b9134e 100644 --- a/main/xiaozhi-server/core/providers/vad/silero.py +++ b/main/xiaozhi-server/core/providers/vad/silero.py @@ -1,154 +1,240 @@ +import asyncio import time +from numba import byte import numpy as np import torch -import opuslib_next +from dataclasses import dataclass + from config.logger import setup_logging -from core.providers.vad.base import VADProviderBase +from .base import VADProviderBase, VADStream, ExpFilter +from .dto import VADEvent, VADEventType + + +@dataclass +class SileroVADOptions: + """Silero VAD specific options""" + min_speech_duration: float = 0.05 # 50ms to confirm speech start + min_silence_duration: float = 0.40 # 400ms to confirm speech end + prefix_padding_duration: float = 0.3 # 300ms prefix padding + activation_threshold: float = 0.5 # probability threshold + sample_rate: int = 16000 # 16kHz + TAG = __name__ logger = setup_logging() -class ExpFilter: - """Exponential filter for smoothing probability values (from LiveKit) - - Smooths noisy VAD probability outputs to reduce false triggers. - Formula: smoothed = α × current + (1-α) × previous - - Args: - alpha: Smoothing factor (0-1). Higher = faster response, less smoothing. - LiveKit default is 0.35. - """ - def __init__(self, alpha: float = 0.35): - self._alpha = alpha - self._filtered_value: float | None = None - - def apply(self, sample: float) -> float: - if self._filtered_value is None: - self._filtered_value = sample - else: - self._filtered_value = self._alpha * sample + (1 - self._alpha) * self._filtered_value - return self._filtered_value - - def reset(self): - self._filtered_value = None - - class VADProvider(VADProviderBase): - def __init__(self, config): - logger.bind(tag=TAG).info("SileroVAD", config) - self.model, _ = torch.hub.load( - repo_or_dir=config["model_dir"], + """Silero VAD provider""" + + def __init__(self, config: dict): + super().__init__() + # Load Silero model + self._model, _ = torch.hub.load( + repo_or_dir=config.get("model_dir", "models/snakers4_silero-vad"), source="local", model="silero_vad", force_reload=False, ) - - self.decoder = opuslib_next.Decoder(16000, 1) - - # VAD parameters - threshold = config.get("threshold", "0.6") - threshold_low = config.get("threshold_low", "0.3") - min_silence_duration_ms = config.get("min_silence_duration_ms", "200") - - self.vad_threshold = float(threshold) if threshold else 0.5 - self.vad_threshold_low = float(threshold_low) if threshold_low else 0.3 - self.silence_threshold_ms = ( - int(min_silence_duration_ms) if min_silence_duration_ms else 200 + + # Parse config + self._opts = SileroVADOptions( + min_speech_duration=float(config.get("min_speech_duration", "0.05")), + min_silence_duration=float(config.get("min_silence_duration", "0.40")), + prefix_padding_duration=float(config.get("prefix_padding_duration", "0.3")), + activation_threshold=float(config.get("threshold", "0.5")), + sample_rate=16000, ) + + def stream(self) -> VADStream: + """Create a new VAD stream""" + return SileroVADStream(self, self._model, self._opts) - # sliding window threshold - frame_window_threshold = config.get("frame_window_threshold", "3") - self.frame_window_threshold = int(frame_window_threshold) if frame_window_threshold else 3 - def is_vad(self, conn, opus_packet): - try: - now_ms = time.time() * 1000 - conn._vad_frame_count = getattr(conn, '_vad_frame_count', 0) + 1 - - pcm_frame = self.decoder.decode(opus_packet, 960) - conn.client_audio_buffer.extend(pcm_frame) +class SileroVADStream(VADStream): + """Silero VAD stream implementation""" + + # Silero requires 512 samples per inference (32ms at 16kHz) + WINDOW_SIZE_SAMPLES = 512 + WINDOW_SIZE_BYTES = WINDOW_SIZE_SAMPLES * 2 # int16 + WINDOW_DURATION = WINDOW_SIZE_SAMPLES / 16000 # seconds + SLOW_INFERENCE_THRESHOLD = 0.2 # seconds + + def __init__(self, vad: VADProvider, model, opts: SileroVADOptions): + super().__init__(vad) + self._model = model + self._opts = opts + self._exp_filter = ExpFilter(alpha=0.35) + + # Speech buffer for prefix padding (in bytes, not samples) + self._prefix_padding_bytes = int(opts.prefix_padding_duration * opts.sample_rate) * 2 + # Pre-allocate max speech buffer (60s + prefix padding) + max_speech_bytes = 60 * opts.sample_rate * 2 + self._prefix_padding_bytes + self._speech_buffer = bytearray(max_speech_bytes) + self._speech_buffer_max_reached = False + + async def _run_task(self) -> None: + """Main processing loop - receives PCM data from base class""" + + inference_data = np.empty(self.WINDOW_SIZE_SAMPLES, dtype=np.float32) + speech_buffer_index: int = 0 + + pub_speaking = False + pub_speech_duration = 0.0 + pub_silence_duration = 0.0 + + speech_threshold_duration = 0.0 + silence_threshold_duration = 0.0 - # process complete frames in buffer (512 samples per frame) - client_have_voice = False - while len(conn.client_audio_buffer) >= 512 * 2: - # extract first 512 samples (1024 bytes) - chunk = conn.client_audio_buffer[: 512 * 2] - conn.client_audio_buffer = conn.client_audio_buffer[512 * 2 :] - - # convert to tensor format for model - audio_int16 = np.frombuffer(chunk, dtype=np.int16) - audio_float32 = audio_int16.astype(np.float32) / 32768.0 - audio_tensor = torch.from_numpy(audio_float32) - - # run VAD inference - with torch.no_grad(): - speech_prob = self.model(audio_tensor, 16000).item() - - # dual threshold judgment (hysteresis) - if speech_prob >= self.vad_threshold: - is_voice = True - elif speech_prob <= self.vad_threshold_low: - is_voice = False - else: - is_voice = conn.last_is_voice - - conn.last_is_voice = is_voice - - # record first voice frame time (when is_voice becomes True) - if is_voice and not hasattr(conn, '_vad_first_voice_time'): - conn._vad_first_voice_time = now_ms - - # update sliding window - conn.client_voice_window.append(is_voice) - client_have_voice = ( - conn.client_voice_window.count(True) >= self.frame_window_threshold - ) - - # 检测语音开始(边缘检测) - if not conn.client_have_voice and client_have_voice: - conn._latency_voice_start_time = time.time() * 1000 - # calculate delay from first voice frame to VAD confirmation - first_voice_time = getattr(conn, '_vad_first_voice_time', None) - if first_voice_time: - voice_to_confirm = conn._latency_voice_start_time - first_voice_time - logger.bind(tag=TAG).info( - f"🎤 [延迟追踪] VAD检测到开始说话 | " - f"首个声音帧到确认: {voice_to_confirm:.0f}ms" - ) - else: - logger.bind(tag=TAG).info(f"🎤 [延迟追踪] VAD检测到开始说话") + extra_inference_time = 0.0 + + input_audios: bytearray = bytearray() + inference_audios: bytearray = bytearray() + + while not self._is_closed: + try: + pcm_data = await self._input_queue.get() + if isinstance(pcm_data, VADStream._FlushSentinel): + continue + + input_audios.extend(pcm_data) + inference_audios.extend(pcm_data) - # 检测语音结束(需要确保开始时间已设置) - if conn.client_have_voice and not client_have_voice: - stop_duration = time.time() * 1000 - conn.last_activity_time - if stop_duration >= self.silence_threshold_ms: - if conn.client_listen_mode != "manual": - conn.client_voice_stop = True - # 记录用户说完的时间(端到端延迟的起点) - conn._latency_voice_end_time = time.time() * 1000 - - # 安全检查:确保时间戳已设置 - start_time = getattr(conn, '_latency_voice_start_time', None) - - if start_time: - voice_duration = conn._latency_voice_end_time - start_time - logger.bind(tag=TAG).info( - f"🎤 [延迟追踪] VAD检测到说话结束 | " - f"语音时长: {voice_duration:.0f}ms" - ) - - # reset for next utterance - conn._latency_voice_start_time = None - if hasattr(conn, '_vad_first_voice_time'): - del conn._vad_first_voice_time - - if client_have_voice: - conn.client_have_voice = True - conn.last_activity_time = time.time() * 1000 + # Process complete windows + while len(inference_audios) >= self.WINDOW_SIZE_BYTES: + inference_start = time.perf_counter() + + # Extract window, convert int16 to float32 + window_int16 = np.frombuffer( + inference_audios[:self.WINDOW_SIZE_BYTES], dtype=np.int16 + ) + np.divide(window_int16, 32768.0, out=inference_data) + + # Convert to tensor and run inference + audio_tensor = torch.from_numpy(inference_data) + with torch.no_grad(): + prob = self._model(audio_tensor, self._opts.sample_rate).item() + + # Apply exponential smoothing + prob = self._exp_filter.apply(prob) + + # Copy inference window to speech buffer + available_space = len(self._speech_buffer) - speech_buffer_index + to_copy = min(available_space, self.WINDOW_SIZE_BYTES) + + if to_copy > 0: + self._speech_buffer[speech_buffer_index:speech_buffer_index + to_copy] = input_audios[:to_copy] + speech_buffer_index += to_copy + elif not self._speech_buffer_max_reached: + self._speech_buffer_max_reached = True + logger.bind(tag=TAG).warning("Speech buffer max reached, dropping further audio") + + # inference time + inference_duration = time.perf_counter() - inference_start + extra_inference_time = max( + 0.0, + extra_inference_time + inference_duration - self.WINDOW_DURATION, + ) - return client_have_voice - except opuslib_next.OpusError as e: - logger.bind(tag=TAG).info(f"解码错误: {e}") - except Exception as e: - logger.bind(tag=TAG).error(f"Error processing audio packet: {e}") + if inference_duration > self.SLOW_INFERENCE_THRESHOLD: + logger.bind(tag=TAG).warning( + "inference is slower than realtime", + extra={"delay": extra_inference_time}, + ) + + def _reset_write_cursor() -> None: + nonlocal speech_buffer_index + assert self._speech_buffer is not None + if speech_buffer_index <= self._prefix_padding_bytes: + return + + # Keep last prefix_padding worth of audio + padding_data = self._speech_buffer[ + speech_buffer_index - self._prefix_padding_bytes : speech_buffer_index + ] + + self._speech_buffer_max_reached = False + self._speech_buffer[: self._prefix_padding_bytes] = padding_data + speech_buffer_index = self._prefix_padding_bytes + + # copy the data from speech_buffer + def _copy_speech_buffer() -> bytes: + # copy the data from speech_buffer + assert self._speech_buffer is not None + return bytes(self._speech_buffer[:speech_buffer_index]) + + # Update durations + if pub_speaking: + pub_speech_duration += self.WINDOW_DURATION + else: + pub_silence_duration += self.WINDOW_DURATION + + # Emit INFERENCE_DONE + self._output_queue.put_nowait(VADEvent( + type=VADEventType.INFERENCE_DONE, + probability=prob, + speech_duration=pub_speech_duration, + silence_duration=pub_silence_duration, + speaking=pub_speaking, + audio_data=_copy_speech_buffer(), + inference_duration=inference_duration, + )) + + # State machine logic + if prob >= self._opts.activation_threshold: + speech_threshold_duration += self.WINDOW_DURATION + silence_threshold_duration = 0.0 + + if not pub_speaking: + if speech_threshold_duration >= self._opts.min_speech_duration: + pub_speaking = True + pub_silence_duration = 0.0 + pub_speech_duration = speech_threshold_duration + + # Emit START_OF_SPEECH + self._output_queue.put_nowait(VADEvent( + type=VADEventType.START_OF_SPEECH, + probability=prob, + speech_duration=pub_speech_duration, + silence_duration=0.0, + speaking=True, + audio_data=_copy_speech_buffer(), + inference_duration=inference_duration, + )) + else: + silence_threshold_duration += self.WINDOW_DURATION + speech_threshold_duration = 0.0 + + if not pub_speaking: + _reset_write_cursor() + + if pub_speaking and silence_threshold_duration >= self._opts.min_silence_duration: + pub_speaking = False + pub_silence_duration = silence_threshold_duration + + # Emit END_OF_SPEECH + self._output_queue.put_nowait(VADEvent( + type=VADEventType.END_OF_SPEECH, + probability=prob, + speech_duration=pub_speech_duration, + silence_duration=pub_silence_duration, + speaking=False, + audio_data=_copy_speech_buffer(), + inference_duration=inference_duration, + )) + + pub_speech_duration = 0.0 + _reset_write_cursor() + + # Remove processed data from buffers + del inference_audios[:self.WINDOW_SIZE_BYTES] + del input_audios[:to_copy] + + except asyncio.CancelledError: + break + except Exception as e: + logger.bind(tag=TAG).error(f"Error in VAD task: {e}") + + def reset(self): + """Reset stream state for new utterance""" + self._exp_filter.reset() diff --git a/main/xiaozhi-server/core/websocket_server.py b/main/xiaozhi-server/core/websocket_server.py index 215e30364..a1d0788bc 100644 --- a/main/xiaozhi-server/core/websocket_server.py +++ b/main/xiaozhi-server/core/websocket_server.py @@ -20,7 +20,7 @@ class WebSocketServer: modules = initialize_modules( self.logger, self.config, - False, + True, False, False, False, diff --git a/main/xiaozhi-server/custom_config.yaml b/main/xiaozhi-server/custom_config.yaml index bcf34a877..556f9414a 100644 --- a/main/xiaozhi-server/custom_config.yaml +++ b/main/xiaozhi-server/custom_config.yaml @@ -470,7 +470,18 @@ VAD: type: silero model_dir: models/snakers4_silero-vad threshold: 0.5 # high threshold to confirm voice - threshold_low: 0.35 # low threshold to confirm silence + min_silence_duration: 0.40 # silence detection duration (s) + min_speech_duration: 0.05 # speech detection duration (s) + prefix_padding_duration: 0.3 # prefix padding duration (s) + activation_threshold: 0.5 # activation threshold + sample_rate: 16000 # sample rate + # FSMN VAD from FunASR, optimized for Chinese + # Reference: https://huggingface.co/funasr/fsmn-vad + FsmnVAD: + type: fsmn + model: fsmn-vad + model_revision: v2.0.4 + chunk_size_ms: 100 # streaming chunk size in ms min_silence_duration_ms: 400 # silence detection duration (ms) frame_window_threshold: 3 # sliding window threshold diff --git a/main/xiaozhi-server/test/vad/test_silero_vad_stream.py b/main/xiaozhi-server/test/vad/test_silero_vad_stream.py new file mode 100644 index 000000000..db1642b5a --- /dev/null +++ b/main/xiaozhi-server/test/vad/test_silero_vad_stream.py @@ -0,0 +1,524 @@ +""" +Silero VAD Stream Unit Tests + +This test suite demonstrates how the VAD stream works: + +1. VAD Stream Architecture: + ┌──────────────┐ ┌───────────────┐ ┌──────────────┐ + │ push_audio() │ --> │ _input_queue │ --> │ _run_task() │ + │ (opus data) │ │ (PCM bytes) │ │ (inference) │ + └──────────────┘ └───────────────┘ └──────┬───────┘ + │ + v + ┌───────────────┐ + │ _output_queue │ + │ (VADEvent) │ + └───────────────┘ + +2. State Machine: + - IDLE state: Accumulate silence, reset buffer (keep prefix padding) + - When prob >= threshold for min_speech_duration → emit START_OF_SPEECH + - SPEAKING state: Accumulate speech audio + - When prob < threshold for min_silence_duration → emit END_OF_SPEECH + +3. Buffer Management: + - speech_buffer: Pre-allocated 60s + prefix_padding (for complete utterance) + - prefix_padding: 300ms audio kept before speech start + - _reset_write_cursor(): Slides buffer to keep only last 300ms +""" + +import asyncio +import pytest +import numpy as np +from unittest.mock import Mock, patch, MagicMock +from dataclasses import dataclass, field +from enum import Enum +from typing import Optional +import sys +import os + + +# ============================================================================ +# Local copies of VAD types to avoid importing opuslib-dependent modules +# ============================================================================ + +class VADEventType(Enum): + """VAD event types""" + START_OF_SPEECH = "start_of_speech" + INFERENCE_DONE = "inference_done" + END_OF_SPEECH = "end_of_speech" + + +@dataclass +class VADEvent: + """VAD event data structure""" + type: VADEventType + probability: float = 0.0 + speech_duration: float = 0.0 + silence_duration: float = 0.0 + speaking: bool = False + audio_data: bytes = field(default_factory=bytes) + inference_duration: float = 0.0 + + def __repr__(self) -> str: + audio_len_ms = len(self.audio_data) / 32 if self.audio_data else 0 + return ( + f"VADEvent(type={self.type.value}, " + f"speaking={self.speaking}, " + f"prob={self.probability:.2f}, " + f"speech={self.speech_duration:.2f}s, " + f"silence={self.silence_duration:.2f}s, " + f"audio={audio_len_ms:.0f}ms)" + ) + + +class ExpFilter: + """Exponential filter for smoothing probability values + + Smooths noisy VAD probability outputs to reduce false triggers. + Formula: smoothed = alpha * current + (1-alpha) * previous + """ + def __init__(self, alpha: float = 0.35): + self._alpha = alpha + self._filtered_value: Optional[float] = None + + def apply(self, sample: float) -> float: + if self._filtered_value is None: + self._filtered_value = sample + else: + self._filtered_value = self._alpha * sample + (1 - self._alpha) * self._filtered_value + return self._filtered_value + + def reset(self): + self._filtered_value = None + + +# Mock the Silero model for testing +class MockSileroModel: + """Mock Silero VAD model that returns predefined probabilities""" + + def __init__(self, probabilities: list[float]): + """ + Args: + probabilities: List of probability values to return sequentially + """ + self._probabilities = probabilities + self._call_index = 0 + + def __call__(self, audio_tensor, sample_rate): + """Return next probability in sequence""" + if self._call_index < len(self._probabilities): + prob = self._probabilities[self._call_index] + self._call_index += 1 + else: + prob = 0.0 # default to silence after sequence + + # Return a mock tensor with .item() method + result = Mock() + result.item.return_value = prob + return result + + def reset_states(self): + """Reset model states""" + pass + + +@dataclass +class SileroVADOptions: + """Copy of options for testing""" + min_speech_duration: float = 0.05 # 50ms to confirm speech start + min_silence_duration: float = 0.40 # 400ms to confirm speech end + prefix_padding_duration: float = 0.3 # 300ms prefix padding + activation_threshold: float = 0.5 # probability threshold + sample_rate: int = 16000 # 16kHz + + +class TestSileroVADStream: + """Test cases demonstrating VAD stream behavior""" + + # Silero processes 512 samples per inference (32ms at 16kHz) + WINDOW_SIZE_SAMPLES = 512 + WINDOW_SIZE_BYTES = 512 * 2 # int16 = 2 bytes per sample + WINDOW_DURATION = 512 / 16000 # 0.032 seconds + + def generate_pcm_silence(self, duration_ms: int) -> bytes: + """Generate silent PCM audio (zeros)""" + num_samples = int(duration_ms * 16) # 16kHz = 16 samples/ms + return np.zeros(num_samples, dtype=np.int16).tobytes() + + def generate_pcm_speech(self, duration_ms: int, amplitude: int = 10000) -> bytes: + """Generate simulated speech PCM audio (sine wave)""" + num_samples = int(duration_ms * 16) + t = np.linspace(0, duration_ms / 1000, num_samples) + # 440Hz sine wave + audio = (amplitude * np.sin(2 * np.pi * 440 * t)).astype(np.int16) + return audio.tobytes() + + @pytest.mark.asyncio + async def test_vad_stream_basic_flow(self): + """ + Test basic VAD stream flow: + 1. Push silence → no START_OF_SPEECH + 2. Push speech → START_OF_SPEECH after min_speech_duration + 3. Push silence → END_OF_SPEECH after min_silence_duration + """ + opts = SileroVADOptions() + + # Calculate how many windows needed + # min_speech_duration = 50ms, window = 32ms → need 2 windows above threshold + # min_silence_duration = 400ms, window = 32ms → need 13 windows below threshold + windows_for_speech_start = int(opts.min_speech_duration / self.WINDOW_DURATION) + 1 # 2 + windows_for_speech_end = int(opts.min_silence_duration / self.WINDOW_DURATION) + 1 # 13 + + # Build probability sequence: + # - 5 windows of silence (prob=0.1) + # - 3 windows of speech (prob=0.9) → triggers START_OF_SPEECH after 2nd + # - 15 windows of silence (prob=0.1) → triggers END_OF_SPEECH after 13th + probs = ( + [0.1] * 5 + # Initial silence + [0.9] * 3 + # Speech detected + [0.1] * 15 # Silence after speech + ) + + print(f"\n{'='*60}") + print(f"Test: Basic VAD Flow") + print(f"{'='*60}") + print(f"Window duration: {self.WINDOW_DURATION*1000:.1f}ms") + print(f"Windows for speech start: {windows_for_speech_start} " + f"({opts.min_speech_duration*1000:.0f}ms threshold)") + print(f"Windows for speech end: {windows_for_speech_end} " + f"({opts.min_silence_duration*1000:.0f}ms threshold)") + print(f"Probability sequence: {probs}") + print() + + # Simulate the state machine + events = await self._simulate_vad_state_machine(probs, opts) + + # Print events + print(f"\nGenerated Events:") + print(f"-" * 40) + for i, event in enumerate(events): + print(f" [{i}] {event}") + + # Verify events + start_events = [e for e in events if e.type == VADEventType.START_OF_SPEECH] + end_events = [e for e in events if e.type == VADEventType.END_OF_SPEECH] + inference_events = [e for e in events if e.type == VADEventType.INFERENCE_DONE] + + print(f"\nSummary:") + print(f" INFERENCE_DONE: {len(inference_events)}") + print(f" START_OF_SPEECH: {len(start_events)}") + print(f" END_OF_SPEECH: {len(end_events)}") + + assert len(start_events) == 1, "Should have exactly 1 START_OF_SPEECH" + assert len(end_events) == 1, "Should have exactly 1 END_OF_SPEECH" + assert start_events[0].speaking == True + assert end_events[0].speaking == False + + @pytest.mark.asyncio + async def test_vad_prefix_padding(self): + """ + Test that prefix_padding audio is included in START_OF_SPEECH event. + + When speech starts, we want to include 300ms of audio BEFORE the speech + detection point to capture the beginning of the utterance. + """ + opts = SileroVADOptions(prefix_padding_duration=0.3) # 300ms + + # Windows before speech starts that should be included as prefix + prefix_windows = int(opts.prefix_padding_duration / self.WINDOW_DURATION) # ~10 windows + + print(f"\n{'='*60}") + print(f"Test: Prefix Padding") + print(f"{'='*60}") + print(f"Prefix padding: {opts.prefix_padding_duration*1000:.0f}ms " + f"(~{prefix_windows} windows)") + + # Sequence: silence → speech + probs = [0.1] * 15 + [0.9] * 5 # Long silence then speech + + events = await self._simulate_vad_state_machine(probs, opts) + + start_events = [e for e in events if e.type == VADEventType.START_OF_SPEECH] + assert len(start_events) == 1 + + # Audio in START_OF_SPEECH should include prefix padding + audio_duration_ms = len(start_events[0].audio_data) / 32 # 16kHz, 16-bit + expected_min_duration = opts.prefix_padding_duration * 1000 # at least prefix + + print(f"Audio in START_OF_SPEECH: {audio_duration_ms:.0f}ms") + print(f"Expected minimum: {expected_min_duration:.0f}ms (prefix padding)") + + assert audio_duration_ms >= expected_min_duration, \ + f"Audio should include prefix padding: {audio_duration_ms:.0f}ms < {expected_min_duration:.0f}ms" + + @pytest.mark.asyncio + async def test_vad_short_speech_ignored(self): + """ + Test that very short speech bursts (< min_speech_duration) are ignored. + + This prevents false triggers from brief noise. + """ + opts = SileroVADOptions(min_speech_duration=0.05) # 50ms + + # Only 1 window of "speech" (32ms < 50ms threshold) + probs = [0.1] * 5 + [0.9] * 1 + [0.1] * 5 + + print(f"\n{'='*60}") + print(f"Test: Short Speech Ignored") + print(f"{'='*60}") + print(f"Single speech window: {self.WINDOW_DURATION*1000:.0f}ms") + print(f"Threshold: {opts.min_speech_duration*1000:.0f}ms") + print(f"Sequence: {probs}") + + events = await self._simulate_vad_state_machine(probs, opts) + + start_events = [e for e in events if e.type == VADEventType.START_OF_SPEECH] + + print(f"START_OF_SPEECH events: {len(start_events)}") + + assert len(start_events) == 0, "Short speech should not trigger START_OF_SPEECH" + + @pytest.mark.asyncio + async def test_vad_continuous_speech(self): + """ + Test continuous speech detection without false end triggers. + + Brief silence during speech (< min_silence_duration) should NOT + trigger END_OF_SPEECH. + """ + opts = SileroVADOptions( + min_speech_duration=0.05, + min_silence_duration=0.40 + ) + + # Speech → brief silence (3 windows = 96ms) → speech again + brief_silence_windows = 3 # 96ms < 400ms threshold + + probs = ( + [0.1] * 3 + # Initial silence + [0.9] * 5 + # Speech starts + [0.1] * brief_silence_windows + # Brief pause (should NOT end speech) + [0.9] * 5 + # Speech continues + [0.1] * 15 # Final silence (should end speech) + ) + + print(f"\n{'='*60}") + print(f"Test: Continuous Speech with Brief Pause") + print(f"{'='*60}") + print(f"Brief pause: {brief_silence_windows * self.WINDOW_DURATION * 1000:.0f}ms") + print(f"min_silence_duration: {opts.min_silence_duration*1000:.0f}ms") + + events = await self._simulate_vad_state_machine(probs, opts) + + end_events = [e for e in events if e.type == VADEventType.END_OF_SPEECH] + + print(f"END_OF_SPEECH events: {len(end_events)}") + + # Should only have ONE end event (at the final silence) + assert len(end_events) == 1, \ + "Brief pause should not trigger END_OF_SPEECH" + + @pytest.mark.asyncio + async def test_vad_exp_filter_smoothing(self): + """ + Test exponential filter smoothing effect. + + The ExpFilter smooths probability values to reduce false triggers: + smoothed = alpha * current + (1-alpha) * previous + """ + print(f"\n{'='*60}") + print(f"Test: Exponential Filter Smoothing") + print(f"{'='*60}") + + exp_filter = ExpFilter(alpha=0.35) + + # Simulate noisy probability sequence + raw_probs = [0.1, 0.9, 0.2, 0.8, 0.3, 0.7, 0.1, 0.1, 0.1] + smoothed_probs = [] + + print(f"Alpha: {exp_filter._alpha}") + print(f"{'Raw':<8} {'Smoothed':<10}") + print(f"-" * 20) + + for prob in raw_probs: + smoothed = exp_filter.apply(prob) + smoothed_probs.append(smoothed) + print(f"{prob:<8.2f} {smoothed:<10.3f}") + + # Smoothed values should be less volatile + raw_variance = np.var(raw_probs) + smoothed_variance = np.var(smoothed_probs) + + print(f"\nVariance - Raw: {raw_variance:.3f}, Smoothed: {smoothed_variance:.3f}") + + assert smoothed_variance < raw_variance, \ + "Smoothed signal should have lower variance" + + async def _simulate_vad_state_machine( + self, + probabilities: list[float], + opts: SileroVADOptions + ) -> list[VADEvent]: + """ + Simulate the Silero VAD state machine logic. + + This replicates the core logic from SileroVADStream._run_task() + without needing the actual model or audio processing. + """ + events = [] + exp_filter = ExpFilter(alpha=0.35) + + # State variables + pub_speaking = False + pub_speech_duration = 0.0 + pub_silence_duration = 0.0 + speech_threshold_duration = 0.0 + silence_threshold_duration = 0.0 + + # Speech buffer simulation + speech_buffer_index = 0 + prefix_padding_bytes = int(opts.prefix_padding_duration * opts.sample_rate) * 2 + + for prob in probabilities: + # Apply exponential smoothing + smoothed_prob = exp_filter.apply(prob) + + # Simulate writing audio to buffer + speech_buffer_index += self.WINDOW_SIZE_BYTES + + # Update durations + if pub_speaking: + pub_speech_duration += self.WINDOW_DURATION + else: + pub_silence_duration += self.WINDOW_DURATION + + # Generate fake audio data based on buffer index + audio_data = bytes(speech_buffer_index) + + # Emit INFERENCE_DONE + events.append(VADEvent( + type=VADEventType.INFERENCE_DONE, + probability=smoothed_prob, + speech_duration=pub_speech_duration, + silence_duration=pub_silence_duration, + speaking=pub_speaking, + audio_data=audio_data, + inference_duration=0.001, + )) + + # State machine logic + if smoothed_prob >= opts.activation_threshold: + speech_threshold_duration += self.WINDOW_DURATION + silence_threshold_duration = 0.0 + + if not pub_speaking: + if speech_threshold_duration >= opts.min_speech_duration: + pub_speaking = True + pub_silence_duration = 0.0 + pub_speech_duration = speech_threshold_duration + + # Emit START_OF_SPEECH + events.append(VADEvent( + type=VADEventType.START_OF_SPEECH, + probability=smoothed_prob, + speech_duration=pub_speech_duration, + silence_duration=0.0, + speaking=True, + audio_data=audio_data, + inference_duration=0.001, + )) + else: + silence_threshold_duration += self.WINDOW_DURATION + speech_threshold_duration = 0.0 + + if not pub_speaking: + # Reset buffer (keep prefix padding) + if speech_buffer_index > prefix_padding_bytes: + speech_buffer_index = prefix_padding_bytes + + if pub_speaking and silence_threshold_duration >= opts.min_silence_duration: + pub_speaking = False + pub_silence_duration = silence_threshold_duration + + # Emit END_OF_SPEECH + events.append(VADEvent( + type=VADEventType.END_OF_SPEECH, + probability=smoothed_prob, + speech_duration=pub_speech_duration, + silence_duration=pub_silence_duration, + speaking=False, + audio_data=audio_data, + inference_duration=0.001, + )) + + pub_speech_duration = 0.0 + speech_buffer_index = prefix_padding_bytes + + return events + + +class TestVADBufferManagement: + """Test cases for buffer management logic""" + + @pytest.mark.asyncio + async def test_buffer_reset_keeps_prefix(self): + """ + Test that _reset_write_cursor keeps the last prefix_padding bytes. + + This is crucial for capturing the beginning of speech: + + Before reset: [old audio][prefix padding][new audio] + After reset: [prefix padding] + """ + print(f"\n{'='*60}") + print(f"Test: Buffer Reset Keeps Prefix") + print(f"{'='*60}") + + prefix_duration = 0.3 # 300ms + sample_rate = 16000 + prefix_padding_bytes = int(prefix_duration * sample_rate) * 2 + + # Simulate buffer + max_speech_bytes = 60 * sample_rate * 2 + prefix_padding_bytes + speech_buffer = bytearray(max_speech_bytes) + + # Fill buffer with identifiable data + # [AAAA][BBBB][CCCC] where BBBB is the last prefix_padding worth + total_fill = prefix_padding_bytes * 3 + for i in range(total_fill): + if i < prefix_padding_bytes: + speech_buffer[i] = ord('A') + elif i < prefix_padding_bytes * 2: + speech_buffer[i] = ord('B') + else: + speech_buffer[i] = ord('C') + + speech_buffer_index = total_fill + + print(f"Buffer before reset:") + print(f" Index: {speech_buffer_index}") + print(f" Content pattern: [AAA...][BBB...][CCC...]") + + # Simulate _reset_write_cursor + if speech_buffer_index > prefix_padding_bytes: + padding_data = speech_buffer[ + speech_buffer_index - prefix_padding_bytes : speech_buffer_index + ] + speech_buffer[: prefix_padding_bytes] = padding_data + speech_buffer_index = prefix_padding_bytes + + print(f"\nBuffer after reset:") + print(f" Index: {speech_buffer_index}") + print(f" First byte: {chr(speech_buffer[0])}") + + # Verify the last chunk (CCCC) is now at the beginning + assert speech_buffer_index == prefix_padding_bytes + assert speech_buffer[0] == ord('C'), \ + "Reset should keep last prefix_padding bytes (CCCC)" + + +if __name__ == "__main__": + # Run tests with verbose output + pytest.main([__file__, "-v", "-s"]) +