diff --git a/main/xiaozhi-server/core/connection.py b/main/xiaozhi-server/core/connection.py index f79cebf8e..dceecdb1e 100644 --- a/main/xiaozhi-server/core/connection.py +++ b/main/xiaozhi-server/core/connection.py @@ -914,6 +914,10 @@ class ConnectionHandler: """ self.logger.bind(tag=TAG).info(f"大模型收到用户消息: {query}") + # 记录 LLM 开始处理时间 + llm_start_time = time.time() * 1000 + llm_first_token_time = None + # 检查 TTS 是否已初始化 if self.tts is None: self.logger.bind(tag=TAG).error("TTS 未初始化,无法处理聊天请求") @@ -950,11 +954,14 @@ class ConnectionHandler: try: # use dialogue with memory (use text for memory query) memory_str = None - if self.memory is not None: - future = asyncio.run_coroutine_threadsafe( - self.memory.query_memory(query_text), self.loop - ) - memory_str = future.result() + # if self.memory is not None: + # memory_start_time = time.time() * 1000 + # future = asyncio.run_coroutine_threadsafe( + # self.memory.query_memory(query_text), self.loop + # ) + # memory_str = future.result() + # memory_duration = (time.time() * 1000 - memory_start_time) / 1000 + # self.logger.bind(tag=TAG).info(f"[Latency] Memory查询完成, 耗时: {memory_duration:.3f}s") # 获取对话历史 dialogue_history = self.dialogue.get_llm_dialogue_with_memory( @@ -1013,6 +1020,21 @@ class ConnectionHandler: else: content = response + # 记录首个 token 时间(首字延迟) + if llm_first_token_time is None and content is not None and len(content) > 0: + llm_first_token_time = time.time() * 1000 + first_token_delay = llm_first_token_time - llm_start_time + + # 计算从用户说完到首 token 的延迟 + e2e_first_token = 0 + if hasattr(self, '_latency_voice_end_time'): + e2e_first_token = llm_first_token_time - self._latency_voice_end_time + + self.logger.bind(tag=TAG).info( + f"🤖 [延迟追踪] LLM首token: {first_token_delay:.0f}ms | " + f"用户说完→首token: {e2e_first_token:.0f}ms" + ) + # 在llm回复中获取情绪表情,一轮对话只在开头获取一次 # if emotion_flag and content is not None and content.strip(): # asyncio.run_coroutine_threadsafe( @@ -1080,6 +1102,20 @@ class ConnectionHandler: ).result() self._handle_function_result(result, function_call_data, depth=depth) + # 记录 LLM 完成时间 + llm_end_time = time.time() * 1000 + llm_total_delay = llm_end_time - llm_start_time + + # 计算从用户说完到 LLM 完成的延迟 + e2e_llm_complete = 0 + if hasattr(self, '_latency_voice_end_time'): + e2e_llm_complete = llm_end_time - self._latency_voice_end_time + + self.logger.bind(tag=TAG).info( + f"🤖 [延迟追踪] LLM完成: {llm_total_delay:.0f}ms | " + f"用户说完→LLM完成: {e2e_llm_complete:.0f}ms" + ) + # 存储对话内容 if len(response_message) > 0: text_buff = "".join(response_message) diff --git a/main/xiaozhi-server/core/handle/receiveAudioHandle.py b/main/xiaozhi-server/core/handle/receiveAudioHandle.py index 51a771c72..8bbe8e22d 100644 --- a/main/xiaozhi-server/core/handle/receiveAudioHandle.py +++ b/main/xiaozhi-server/core/handle/receiveAudioHandle.py @@ -488,28 +488,32 @@ async def handleAudioMessage(conn, audio): await _trigger_pseudo_streaming_prefetch(conn, audio, have_voice) # 只有 TTS 正在播放且非手动监听模式时才检测打断 - if conn.client_is_speaking and conn.client_listen_mode != "manual": - # 初始化打断检测状态 - _init_interrupt_state(conn) + # if conn.client_is_speaking and conn.client_listen_mode != "manual": + # # 初始化打断检测状态 + # _init_interrupt_state(conn) - if have_voice: - # 检测到语音,增加连续语音帧计数 - conn._continuous_voice_count += 1 + # 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 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) diff --git a/main/xiaozhi-server/core/handle/sendAudioHandle.py b/main/xiaozhi-server/core/handle/sendAudioHandle.py index a820ee46a..b8c9814d8 100644 --- a/main/xiaozhi-server/core/handle/sendAudioHandle.py +++ b/main/xiaozhi-server/core/handle/sendAudioHandle.py @@ -10,9 +10,28 @@ TAG = __name__ async def sendAudioMessage(conn, sentenceType, audios, text): if conn.tts.tts_audio_first_sentence: - conn.logger.bind(tag=TAG).info(f"发送第一段语音: {text}") conn.tts.tts_audio_first_sentence = False await send_tts_message(conn, "start", None) + + # 记录首句 TTS 播放时间(端到端延迟的终点) + first_audio_time = time.time() * 1000 + + # 计算 TTS 首包延迟(输入到输出) + tts_first_package_delay = 0 + if hasattr(conn, '_latency_tts_first_text_time') and conn._latency_tts_first_text_time: + tts_first_package_delay = first_audio_time - conn._latency_tts_first_text_time + + # 计算端到端延迟 + e2e_total_delay = 0 + if hasattr(conn, '_latency_voice_end_time'): + e2e_total_delay = first_audio_time - conn._latency_voice_end_time + + conn.logger.bind(tag=TAG).info( + f"🔊 [延迟追踪] 首句TTS开始播放 | " + f"TTS首包延迟: {tts_first_package_delay:.0f}ms | " + f"⏱️ 端到端总延迟: {e2e_total_delay:.0f}ms (用户说完→首句播放) | " + f"文本: {text if text else '(无文本)'}" + ) if sentenceType == SentenceType.FIRST: await send_tts_message(conn, "sentence_start", text) diff --git a/main/xiaozhi-server/core/providers/asr/base.py b/main/xiaozhi-server/core/providers/asr/base.py index 2562f5895..f4d731588 100644 --- a/main/xiaozhi-server/core/providers/asr/base.py +++ b/main/xiaozhi-server/core/providers/asr/base.py @@ -101,7 +101,17 @@ class ASRProviderBase(ABC): self.speech_to_text(asr_audio_task, conn.session_id, conn.audio_format) ) end_time = time.monotonic() - logger.bind(tag=TAG).info(f"ASR耗时: {end_time - start_time:.3f}s") + asr_elapsed_ms = (end_time - start_time) * 1000 + + # 计算从用户说完到 ASR 完成的延迟 + 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"🎙️ [延迟追踪] ASR完成: {asr_elapsed_ms:.0f}ms | " + f"用户说完→ASR完成: {e2e_asr_delay:.0f}ms" + ) return result finally: loop.close() diff --git a/main/xiaozhi-server/core/providers/llm/openai/openai.py b/main/xiaozhi-server/core/providers/llm/openai/openai.py index adfe8fd7b..cdddcc7f0 100644 --- a/main/xiaozhi-server/core/providers/llm/openai/openai.py +++ b/main/xiaozhi-server/core/providers/llm/openai/openai.py @@ -13,6 +13,7 @@ from config.logger import setup_logging from core.utils.util import check_model_key from core.providers.llm.base import LLMProviderBase from types import SimpleNamespace +import time TAG = __name__ diff --git a/main/xiaozhi-server/core/providers/tts/base.py b/main/xiaozhi-server/core/providers/tts/base.py index b7c025400..c4f2b3e2f 100644 --- a/main/xiaozhi-server/core/providers/tts/base.py +++ b/main/xiaozhi-server/core/providers/tts/base.py @@ -54,6 +54,8 @@ class TTSProviderBase(ABC): ";", ";", ":", + ".", + "!" ) self.first_sentence_punctuations = ( ",", # 启用逗号,让首段更快播放 @@ -286,10 +288,16 @@ class TTSProviderBase(ABC): self.tts_text_buff = [] self.is_first_sentence = True self.tts_audio_first_sentence = True + self.conn._latency_tts_first_text_time = None # Reset TTS input time elif ContentType.TEXT == message.content_type: self.tts_text_buff.append(message.content_detail) segment_text = self._get_segment_text() if segment_text: + # Record TTS first text input time (for latency tracking) + if not hasattr(self.conn, '_latency_tts_first_text_time') or self.conn._latency_tts_first_text_time is None: + import time + self.conn._latency_tts_first_text_time = time.time() * 1000 + logger.bind(tag=TAG).debug("📝 [延迟追踪] TTS首次接收文本") self.to_tts_stream(segment_text, opus_handler=self.handle_opus) elif ContentType.FILE == message.content_type: self._process_remaining_text_stream(opus_handler=self.handle_opus) @@ -407,8 +415,8 @@ class TTSProviderBase(ABC): segment_text_raw = current_text[: last_punct_pos + 1] # 首句长度检查:如果太短,等待更多文本 - if self.is_first_sentence and len(segment_text_raw) < MIN_FIRST_SEGMENT_CHARS: - return None # 继续等待更多文本 + # if self.is_first_sentence and len(segment_text_raw) < MIN_FIRST_SEGMENT_CHARS: + # return None # 继续等待更多文本 segment_text = textUtils.get_string_no_punctuation_or_emoji( segment_text_raw diff --git a/main/xiaozhi-server/core/providers/tts/fish_dual_stream.py b/main/xiaozhi-server/core/providers/tts/fish_dual_stream.py index 8e17fb5c9..7d24e0ab4 100644 --- a/main/xiaozhi-server/core/providers/tts/fish_dual_stream.py +++ b/main/xiaozhi-server/core/providers/tts/fish_dual_stream.py @@ -95,38 +95,58 @@ class TTSProvider(TTSProviderBase): self._ws_connected = False raise - async def _ensure_connection(self): - """Ensure WebSocket connection is established""" + async def _ensure_connection(self, max_retries: int = 2): + """Ensure WebSocket connection is established with retry logic""" if self.ws and self._ws_connected: logger.bind(tag=TAG).debug("Using existing WebSocket connection") return - logger.bind(tag=TAG).info("Establishing new WebSocket connection...") - headers = { "Authorization": f"Bearer {self.api_key}", "model": self.model, } - self.ws = await websockets.connect( - FISH_WS_URL, - additional_headers=headers, - max_size=10 * 1024 * 1024, # 10MB max message size - ) - self._ws_connected = True + last_error = None + for attempt in range(max_retries + 1): + try: + logger.bind(tag=TAG).info(f"Establishing WebSocket connection (attempt {attempt + 1}/{max_retries + 1})...") + + self.ws = await websockets.connect( + FISH_WS_URL, + additional_headers=headers, + max_size=10 * 1024 * 1024, # 10MB max message size + open_timeout=10, # 10s connection timeout + close_timeout=5, # 5s close timeout + ) + self._ws_connected = True + + # Start response monitor task + if self._monitor_task is None or self._monitor_task.done(): + logger.bind(tag=TAG).info("Starting WebSocket monitor task...") + self._monitor_task = asyncio.create_task(self._monitor_ws_response()) + + return # Success + + except Exception as e: + last_error = e + logger.bind(tag=TAG).warning(f"WebSocket connection attempt {attempt + 1} failed: {e}") + if attempt < max_retries: + await asyncio.sleep(0.5) # Brief delay before retry - # Start response monitor task - if self._monitor_task is None or self._monitor_task.done(): - logger.bind(tag=TAG).info("Starting WebSocket monitor task...") - self._monitor_task = asyncio.create_task(self._monitor_ws_response()) + # All retries failed + raise last_error def tts_text_priority_thread(self): """ Override: dual stream TTS text processing thread - Manages session lifecycle based on FIRST/LAST signals, - similar to Huoshan's implementation. + Manages session lifecycle based on FIRST/LAST signals. + + Key insights from Fish Audio WebSocket API: + 1. stop_event triggers WebSocket close, so only use it for interruptions + 2. For normal LAST, send flush event to force remaining text generation + 3. Fish has no multi-context management, interruption requires reconnection """ while not self.conn.stop_event.is_set(): try: @@ -138,19 +158,24 @@ class TTSProvider(TTSProviderBase): if message.sentence_type == SentenceType.FIRST: # ========== New dialogue round starts ========== self.conn.client_abort = False + self.tts_audio_first_sentence = True + self._first_sent = False + self._session_text_buffer = [] + self.conn._latency_tts_first_text_time = None # Reset TTS input time elif self.conn.client_abort: # ========== Interruption ========== - logger.bind(tag=TAG).info("Received interruption, canceling session") + # Only send stop event on interruption (this will close the connection) + logger.bind(tag=TAG).info("Received interruption, sending stop event") try: future = asyncio.run_coroutine_threadsafe( - self._finish_session(self.conn.sentence_id), + self._abort_session(), self.conn.loop ) future.result() except Exception as e: - logger.bind(tag=TAG).error(f"Failed to cancel session: {e}") - continue + logger.bind(tag=TAG).error(f"Failed to abort session: {e}") + continue # when user doesn't trigger interruption, start new TTS session if message.sentence_type == SentenceType.FIRST: @@ -168,9 +193,15 @@ class TTSProvider(TTSProviderBase): elif ContentType.TEXT == message.content_type: # ========== Text content ========== if message.content_detail: - # 累积文本用于上报(支持 voice_opening/closing 和 LLM 生成内容) + # Accumulate text for reporting (supports voice_opening/closing and LLM content) self._session_text_buffer.append(message.content_detail) + # Record TTS first text input time (for latency tracking) + if not hasattr(self.conn, '_latency_tts_first_text_time') or self.conn._latency_tts_first_text_time is None: + import time + self.conn._latency_tts_first_text_time = time.time() * 1000 + logger.bind(tag=TAG).debug("📝 [延迟追踪] TTS首次接收文本") + try: logger.bind(tag=TAG).debug( f"Sending TTS text: {message.content_detail}" @@ -195,15 +226,17 @@ class TTSProvider(TTSProviderBase): self._process_audio_file_stream(message.content_file, callback=lambda audio_data: self.handle_audio_file(audio_data, message.content_detail)) if message.sentence_type == SentenceType.LAST: - # ========== Dialogue round ends ========== + # ========== Dialogue round ends (normal) ========== + # DO NOT send stop event here! Just send flush to force remaining text. + # The finish event from Fish will trigger LAST in audio queue. try: future = asyncio.run_coroutine_threadsafe( - self._finish_session(self.conn.sentence_id), + self._flush_session(), loop=self.conn.loop, ) future.result() except Exception as e: - logger.bind(tag=TAG).error(f"Failed to finish session: {e}") + logger.bind(tag=TAG).error(f"Failed to flush session: {e}") continue except queue.Empty: @@ -213,7 +246,6 @@ class TTSProvider(TTSProviderBase): f"TTS text processing failed: {str(e)}, type: {type(e).__name__}, " f"stack: {traceback.format_exc()}" ) - continue async def close(self): """Clean up WebSocket resources""" @@ -271,6 +303,7 @@ class TTSProvider(TTSProviderBase): ) elif event_type == "finish": + logger.bind(tag=TAG).info(f"TTS session finished") # Session completed reason = response.get("reason", "unknown") if reason == "error": @@ -334,18 +367,6 @@ class TTSProvider(TTSProviderBase): """ Start a new TTS session """ - - # Wait for previous session to finish - # Avoid the latency of the finish event of the previous session - if self._session_active: - for _ in range(3): - if not self._session_active: - break - logger.bind(tag=TAG).debug("Waiting for previous session to finish...") - await asyncio.sleep(0.1) - else: - logger.bind(tag=TAG).debug("Previous session timeout, clearing connection state...") - await self.close() # Reset state for new session self.opus_encoder.reset_state() self._session_text_buffer = [] @@ -376,28 +397,52 @@ class TTSProvider(TTSProviderBase): await self._send_event(start_event) self._session_active = True - logger.bind(tag=TAG).info(f"TTS session started, sentence_id: {self.conn.sentence_id}") except Exception as e: logger.bind(tag=TAG).error(f"Failed to start session: {e}") raise - async def _finish_session(self, session_id: str = None): + async def _flush_session(self): """ - Finish current TTS session gracefully + Flush current TTS session - force generation of remaining text + + Send flush event to force Fish Audio to generate audio for any buffered text. + This does NOT close the connection - the finish event from Fish will do that. """ - logger.bind(tag=TAG).info(f"Finishing TTS session: {session_id}") + logger.bind(tag=TAG).debug("Flushing TTS session...") + + try: + if self.ws and self._session_active: + # Send flush event to force remaining text generation + flush_event = {"event": "flush"} + await self._send_event(flush_event) + logger.bind(tag=TAG).debug("TTS flush event sent") + except Exception as e: + logger.bind(tag=TAG).error(f"Failed to flush session: {e}") + + async def _abort_session(self): + """ + Abort current TTS session due to interruption + + Send stop event which will close the WebSocket connection. + This is only used when user interrupts the conversation. + """ + logger.bind(tag=TAG).info("Aborting TTS session due to interruption...") try: if self.ws and self._session_active: stop_event = {"event": "stop"} await self._send_event(stop_event) - logger.bind(tag=TAG).info("TTS session stop sent") + logger.bind(tag=TAG).info("TTS session stop sent (abort)") except Exception as e: - logger.bind(tag=TAG).error(f"Failed to finish session: {e}") + logger.bind(tag=TAG).error(f"Failed to abort session: {e}") finally: + # Clean up state self._session_active = False - self.conn.sentence_id = None + self._session_text_buffer = [] + self._first_sent = False + # Connection will be closed by Fish Audio after stop event + async def text_to_speak(self, text, output_file): """ diff --git a/main/xiaozhi-server/core/providers/tts/fishspeech.py b/main/xiaozhi-server/core/providers/tts/fishspeech.py index c7fabb9a7..bf88b1c79 100644 --- a/main/xiaozhi-server/core/providers/tts/fishspeech.py +++ b/main/xiaozhi-server/core/providers/tts/fishspeech.py @@ -1,46 +1,31 @@ +import os +import queue +import asyncio +import traceback +import time from pathlib import Path -from core.utils.util import parse_string_to_list -from core.providers.tts.base import TTSProviderBase from config.logger import setup_logging +from core.utils.tts import MarkdownCleaner +from core.providers.tts.base import TTSProviderBase +from core.utils import opus_encoder_utils, textUtils +from core.providers.tts.dto.dto import SentenceType, ContentType, InterfaceType from fishaudio import FishAudio, TTSConfig TAG = __name__ logger = setup_logging() - -def audio_to_bytes(file_path): - if not file_path or not Path(file_path).exists(): - return None - with open(file_path, "rb") as wav_file: - wav = wav_file.read() - return wav - - -def read_ref_text(ref_text): - path = Path(ref_text) - if path.exists() and path.is_file(): - with path.open("r", encoding="utf-8") as file: - return file.read() - return ref_text - - class TTSProvider(TTSProviderBase): def __init__(self, config, delete_audio_file): super().__init__(config, delete_audio_file) + + # Mark as streaming interface + self.interface_type = InterfaceType.SINGLE_STREAM self.model = config.get("model", "s1") - if config.get("reference_id"): - self.reference_id = config.get("reference_id") - else: - self.reference_id = None - self.reference_audio = parse_string_to_list( - config.get('ref_audio')if config.get('ref_audio') else config.get("reference_audio") - ) - self.reference_text = parse_string_to_list( - config.get('ref_text')if config.get('ref_text') else config.get("reference_text") - ) + self.reference_id = config.get("reference_id") + self.format = config.get("response_format", "pcm") self.sample_rate = config.get("sample_rate", 16000) self.audio_file_type = config.get("response_format", "pcm") @@ -55,7 +40,7 @@ class TTSProvider(TTSProviderBase): "yes", ) - # 处理空字符串的情况 + # Handle empty string cases channels = config.get("channels", "1") rate = config.get("rate", "44100") max_new_tokens = config.get("max_new_tokens", "1024") @@ -66,7 +51,7 @@ class TTSProvider(TTSProviderBase): self.max_new_tokens = int(max_new_tokens) if max_new_tokens else 1024 self.chunk_length = int(chunk_length) if chunk_length else 200 - # 处理空字符串的情况 + # Handle empty string cases top_p = config.get("top_p", "0.7") temperature = config.get("temperature", "0.7") repetition_penalty = config.get("repetition_penalty", "1.2") @@ -85,10 +70,188 @@ class TTSProvider(TTSProviderBase): self.use_memory_cache = config.get("use_memory_cache", "on") self.seed = int(config.get("seed")) if config.get("seed") else None - async def text_to_speak(self, text, output_file): - logger.bind(tag=TAG).info(f"fish speech synthesize text: {text}") + # Initialize Opus encoder (sample_rate should match FishSpeech output) + self.opus_encoder = opus_encoder_utils.OpusEncoderUtils( + sample_rate=self.sample_rate, channels=1, frame_size_ms=60 + ) - audio_stream = self._client.tts.stream( + # PCM buffer for accumulating data before encoding + self.pcm_buffer = bytearray() + + def tts_text_priority_thread(self): + """Streaming text processing thread""" + while not self.conn.stop_event.is_set(): + try: + message = self.tts_text_queue.get(timeout=1) + if message.sentence_type == SentenceType.FIRST: + self.conn.client_abort = False + if self.conn.client_abort: + logger.bind(tag=TAG).info("Received abort signal, stopping TTS text processing") + continue + if message.sentence_type == SentenceType.FIRST: + # Initialize parameters + self.tts_stop_request = False + self.processed_chars = 0 + self.tts_text_buff = [] + self.is_first_sentence = True + self.tts_audio_first_sentence = True + self._first_chunk_logged = False + self.before_stop_play_files.clear() + self.conn._latency_tts_first_text_time = None # Reset TTS input time + elif ContentType.TEXT == message.content_type: + self.tts_text_buff.append(message.content_detail) + segment_text = self._get_segment_text() + if segment_text: + # Record TTS first text input time (for latency tracking) + if not hasattr(self.conn, '_latency_tts_first_text_time') or self.conn._latency_tts_first_text_time is None: + import time + self.conn._latency_tts_first_text_time = time.time() * 1000 + logger.bind(tag=TAG).debug("📝 [延迟追踪] TTS首次接收文本") + self.to_tts_single_stream(segment_text) + + elif ContentType.FILE == message.content_type: + logger.bind(tag=TAG).info( + f"Adding audio file to play list: {message.content_file}" + ) + if message.content_file and os.path.exists(message.content_file): + self._process_audio_file_stream( + message.content_file, + callback=lambda audio_data: self.handle_audio_file(audio_data, message.content_detail) + ) + if message.sentence_type == SentenceType.LAST: + # Process remaining text + self._process_remaining_text_stream(True) + self._first_chunk_logged = False + + except queue.Empty: + continue + except Exception as e: + logger.bind(tag=TAG).error( + f"TTS text processing failed: {str(e)}, type: {type(e).__name__}, stack: {traceback.format_exc()}" + ) + + def _process_remaining_text_stream(self, is_last=False): + """Process remaining text and generate speech + Returns: + bool: Whether text was successfully processed + """ + full_text = "".join(self.tts_text_buff) + remaining_text = full_text[self.processed_chars:] + if remaining_text: + segment_text = textUtils.get_string_no_punctuation_or_emoji(remaining_text) + if segment_text: + self.to_tts_single_stream(segment_text, is_last) + self.processed_chars += len(full_text) + else: + self._process_before_stop_play_files() + else: + self._process_before_stop_play_files() + + def to_tts_single_stream(self, text, is_last=False): + try: + max_repeat_time = 5 + text = MarkdownCleaner.clean_markdown(text) + try: + asyncio.run(self.text_to_speak(text, is_last)) + except Exception as e: + logger.bind(tag=TAG).warning( + f"TTS generation failed {5 - max_repeat_time + 1} times: {text}, error: {e}" + ) + max_repeat_time -= 1 + + if max_repeat_time > 0: + logger.bind(tag=TAG).info( + f"TTS generation success: {text}, retries: {5 - max_repeat_time}" + ) + else: + logger.bind(tag=TAG).error( + f"TTS generation failed: {text}, please check network or service" + ) + except Exception as e: + logger.bind(tag=TAG).error(f"Failed to generate TTS: {e}") + finally: + return None + + async def text_to_speak(self, text, is_last): + """Stream TTS audio processing - encode and send each chunk immediately""" + logger.bind(tag=TAG).info(f"FishSpeech streaming synthesize: {text}") + start_time = time.time() * 1000 + + # Calculate bytes per frame for Opus encoding + frame_bytes = int( + self.opus_encoder.sample_rate + * self.opus_encoder.channels + * self.opus_encoder.frame_size_ms + / 1000 + * 2 # 16-bit = 2 bytes per sample + ) + + try: + # Get audio stream from FishSpeech + audio_stream = self._client.tts.stream( + text=text, + reference_id=self.reference_id, + model=self.model, + config=TTSConfig( + format=self.format, + sample_rate=self.sample_rate, + normalize=self.normalize, + latency="balanced", + ), + ) + + self.pcm_buffer.clear() + # Notify that a new sentence is starting + self.tts_audio_queue.put((SentenceType.FIRST, [], text)) + + first_chunk_logged = False + + # Process audio stream - encode and send each chunk immediately + for chunk in audio_stream: + # Log first chunk from TTS API + if not first_chunk_logged: + first_chunk_logged = True + first_chunk_time = time.time() * 1000 + self.conn.tts_first_chunk_time = first_chunk_time + api_latency = (first_chunk_time - start_time) / 1000 + logger.bind(tag=TAG).info(f"[Latency] TTS API首个chunk, 耗时: {api_latency:.3f}s") + + # Add chunk to PCM buffer + self.pcm_buffer.extend(chunk) + + # Encode and send complete frames immediately + while len(self.pcm_buffer) >= frame_bytes: + frame = bytes(self.pcm_buffer[:frame_bytes]) + del self.pcm_buffer[:frame_bytes] + + self.opus_encoder.encode_pcm_to_opus_stream( + frame, end_of_stream=False, callback=self.handle_opus + ) + + # Flush remaining data that's less than one frame + if self.pcm_buffer: + self.opus_encoder.encode_pcm_to_opus_stream( + bytes(self.pcm_buffer), + end_of_stream=True, + callback=self.handle_opus, + ) + self.pcm_buffer.clear() + + # If this is the last segment, process any pending files and signal completion + if is_last: + self._process_before_stop_play_files() + + except Exception as e: + logger.bind(tag=TAG).error(f"FishSpeech streaming error: {e}") + self.tts_audio_queue.put((SentenceType.LAST, [], None)) + + def to_tts(self, text): + """Non-streaming TTS for compatibility - falls back to accumulating all chunks""" + logger.bind(tag=TAG).info(f"FishSpeech synthesize text: {text}") + start_time = time.time() + text = MarkdownCleaner.clean_markdown(text) + + audio_bytes = self._client.tts.convert( text=text, reference_id=self.reference_id, model=self.model, @@ -97,17 +260,14 @@ class TTSProvider(TTSProviderBase): sample_rate=self.sample_rate, normalize=self.normalize, latency="balanced", - ), + ) ) + + logger.bind(tag=TAG).info(f"TTS non-streaming duration: {time.time() - start_time} seconds") + return audio_bytes - audio_bytes = b'' - - for chunk in audio_stream: - if chunk: - audio_bytes += chunk - - if output_file: - with open(output_file, "wb") as audio_file: - audio_file.write(audio_bytes) - else: - return audio_bytes + async def close(self): + """Resource cleanup""" + await super().close() + if hasattr(self, "opus_encoder"): + self.opus_encoder.close() diff --git a/main/xiaozhi-server/core/providers/vad/silero.py b/main/xiaozhi-server/core/providers/vad/silero.py index 9270e4bef..74abc212c 100644 --- a/main/xiaozhi-server/core/providers/vad/silero.py +++ b/main/xiaozhi-server/core/providers/vad/silero.py @@ -22,19 +22,19 @@ class VADProvider(VADProviderBase): self.decoder = opuslib_next.Decoder(16000, 1) # 处理空字符串的情况 - threshold = config.get("threshold", "0.5") - threshold_low = config.get("threshold_low", "0.2") - min_silence_duration_ms = config.get("min_silence_duration_ms", "1000") + 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.2 + 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 1000 + int(min_silence_duration_ms) if min_silence_duration_ms else 200 ) # 至少要多少帧才算有语音 - self.frame_window_threshold = 3 + self.frame_window_threshold = 5 def is_vad(self, conn, opus_packet): try: @@ -74,12 +74,23 @@ class VADProvider(VADProviderBase): 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 + logger.bind(tag=TAG).info(f"🎤 [延迟追踪] 用户开始说话") + # 如果之前有声音,但本次没有声音,且与上次有声音的时间差已经超过了静默阈值,则认为已经说完一句话 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 + voice_duration = conn._latency_voice_end_time - conn._latency_voice_start_time + logger.bind(tag=TAG).info( + f"🎤 [延迟追踪] 用户说完,语音时长: {voice_duration:.0f}ms" + ) if client_have_voice: conn.client_have_voice = True conn.last_activity_time = time.time() * 1000 diff --git a/main/xiaozhi-server/custom_config.yaml b/main/xiaozhi-server/custom_config.yaml index c8724acb9..94053b62b 100644 --- a/main/xiaozhi-server/custom_config.yaml +++ b/main/xiaozhi-server/custom_config.yaml @@ -68,8 +68,8 @@ log: # 使用完声音文件后删除文件(Delete the sound file when you are done using it) delete_audio: true -# 没有语音输入多久后断开连接(秒),默认2分钟,即120秒 -close_connection_no_voice_time: 120 +# 没有语音输入多久后断开连接(秒),默认15分钟,即900秒 +close_connection_no_voice_time: 900 # TTS请求超时时间(秒) tts_timeout: 10 # 开启唤醒词加速 @@ -476,7 +476,7 @@ ASR: VAD: SileroVAD: type: silero - threshold: 0.5 + threshold: 0.6 threshold_low: 0.3 model_dir: models/snakers4_silero-vad min_silence_duration_ms: 200 # 如果说话停顿比较长,可以把这个值设置大一些 @@ -535,12 +535,12 @@ LLM: api_key: 你的chat-glm web key GroqLLM: type: openai - model_name: openai/gpt-oss-20b + model_name: meta-llama/llama-4-scout-17b-16e-instruct base_url: https://api.groq.com/openai/v1 - api_key: your groq api key + api_key: ${GROQ_API_KEY} OpenaiLLM: type: openai - model_name: gpt-4o + model_name: gpt-4o-mini base_url: https://api.openai.com/v1 api_key: ${OPENAI_API_KEY} OllamaLLM: @@ -1084,10 +1084,10 @@ TTS: selected_module: VAD: SileroVAD ASR: GroqASR - LLM: OpenaiLLM + LLM: GroqLLM VLLM: ChatGLMVLLM - # TTS: FishDualStreamTTS + TTS: FishDualStreamTTS # TODO: temporarily, fish speech doesn't reuse the wesocket connection, need to discuss further. - TTS: FishSpeech + # TTS: FishSpeech Memory: memu Intent: function_call \ No newline at end of file