diff --git a/src/classes/TTSClient.ts b/src/classes/TTSClient.ts index 050e2bc..e10bd13 100644 --- a/src/classes/TTSClient.ts +++ b/src/classes/TTSClient.ts @@ -35,6 +35,9 @@ export class TTSClient { private map: Map = new Map(); private maxLength = 300; private leaveTime = 1000*60*10; // 10분 + // 채팅이 도착한 순서. 합성이 늦게 끝난 이전 채팅이 이미 재생 중인 + // 최신 채팅을 덮어쓰지 않도록 VoiceSession.play()에 함께 넘긴다. + private seq = 0; public findSession(guildId: string) { return this.map.get(guildId); @@ -66,13 +69,16 @@ export class TTSClient { return; } + const seq = ++this.seq; + const startedAt = Date.now(); text = this.textEditor(channel.guild, text); const voice = this.resolveUserVoice(channel.guild.id, member.id); - const buf = await this.getSource(text, voice); + const { buf, parts, failed } = await this.getSource(text, voice); + Logger.info(`[TTS] guild=${channel.guild.id} seq=${seq} parts=${parts} failed=${failed} synth=${Date.now() - startedAt}ms`); if (!buf) return; const session = this.getSession(channel.guild, voiceChannel); - session.play(buf); + session.play(buf, seq); } private readonly onSessionEnd = (guildId: string) => { @@ -105,32 +111,30 @@ export class TTSClient { return DEFAULT_VOICE; } - private async getSource(text: string, voice: VoiceType): Promise { + private async getSource(text: string, voice: VoiceType): Promise<{ buf: Buffer | null; parts: number; failed: number }> { // 시그니처 목록이 비어 있으면 split을 건너뛰고 원문을 한 번에 합성한다. // (SignatureClient.regex가 빈 목록일 때 never-match 패턴을 돌려주지만, // 소비자 측에서도 명시적으로 가드해 의도를 분명히 한다.) const names = signature.nameSet; - const parts = names.size === 0 ? [text] : text.split(signature.regex); - const bufferList: Buffer[] = []; + const parts = (names.size === 0 ? [text] : text.split(signature.regex)).filter(Boolean); + let failed = 0; + const synth = (part: string) => textToSpeech(this.textReplace(part), voice).catch((err) => { + failed++; + Logger.warn(String(err?.message ?? err)); + return null; + }); - for (const part of parts) { - if (!part) continue; - if (signature.nameSet.has(part)) { + // 조각을 동시에 합성하고 결과는 원래 순서대로 이어 붙인다. + const bufferList = await Promise.all(parts.map(async (part) => { + if (names.has(part)) { const buf = await signature.getBuffer(part); - if (buf) { - bufferList.push(buf); - } else { - const buf = await textToSpeech(this.textReplace(part), voice).catch(() => null); - if (buf) bufferList.push(buf); - } - } else { - const buf = await textToSpeech(this.textReplace(part), voice).catch(() => null); - if (buf) bufferList.push(buf); + if (buf) return buf; } - } + return synth(part); + })); - if (bufferList.length === 0) return null; - return Buffer.concat(bufferList); + const valid = bufferList.filter((b): b is Buffer => !!b); + return { buf: valid.length === 0 ? null : Buffer.concat(valid), parts: parts.length, failed }; } private textEditor(guild: Guild, text: string): string { diff --git a/src/classes/VoiceSession.ts b/src/classes/VoiceSession.ts index 5f3b6f1..ef4afd9 100644 --- a/src/classes/VoiceSession.ts +++ b/src/classes/VoiceSession.ts @@ -6,7 +6,8 @@ import { createResourceFromMp3Buffer } from "../utils/Transcode"; export class VoiceSession { private player = createAudioPlayer({ behaviors: { noSubscriber: NoSubscriberBehavior.Pause } }); - private generation = 0; + // 마지막으로 재생을 시작한 채팅의 도착 순번(TTSClient.seq). + private lastPlayedSeq = 0; private isSessionEnd = false; private lastTime = Date.now(); private endTimer?: NodeJS.Timeout | null; @@ -29,7 +30,33 @@ export class VoiceSession { this.init(); } + private get tag() { + return `[Voice] guild=${this.guild.id}`; + } + + // 끊김 원인 추적용: 음성 연결 상태 변화와 오류를 남긴다. + private watchConnection(connection: VoiceConnection) { + connection.on("stateChange", (oldState, newState) => { + if (oldState.status === newState.status) return; + const reason = newState.status === VoiceConnectionStatus.Disconnected + ? ` reason=${newState.reason} closeCode=${"closeCode" in newState ? newState.closeCode : "-"}` + : ""; + Logger.info(`${this.tag} connection ${oldState.status} -> ${newState.status}${reason}`); + }); + connection.on("error", (e) => { + Logger.error(`${this.tag} connection error: ${String(e)}`); + }); + } + private async init() { + this.watchConnection(this.connection); + // 재생 중 일시정지(연결 미준비로 AutoPaused 등)는 음성이 끊기는 직접 신호다. + this.player.on("stateChange", (oldState, newState) => { + const s = [oldState.status, newState.status]; + if (s.includes(AudioPlayerStatus.AutoPaused) || s.includes(AudioPlayerStatus.Paused)) { + Logger.info(`${this.tag} player ${oldState.status} -> ${newState.status}`); + } + }); this.connection.subscribe(this.player); await entersState(this.connection, VoiceConnectionStatus.Ready, 20_000).catch(() => {}); this.player.on(AudioPlayerStatus.Playing, () => { @@ -64,18 +91,23 @@ export class VoiceSession { * 새 TTS가 들어오면 이전 재생을 의도적으로 interrupt한다 (큐잉 없음). * 다중 사용자 환경에서 모든 메시지를 큐로 쌓으면 자기 발화가 수십 초 * 밀려 채팅 맥락과 어긋나므로, "최신 발화 우선, 앞건 잘림"을 정책으로 - * 채택했다. generation 카운터는 같은 메시지에 대해 한 번만 play 되도록 - * 보호하는 용도이고, 이전 mp3가 잘리는 동작 자체는 설계 의도이다. + * 채택했다. 이전 mp3가 잘리는 동작 자체는 설계 의도이다. + * 단, "최신"은 합성 완료 순서가 아니라 채팅 도착 순서(seq)로 판단한다. + * 먼저 온 채팅의 합성이 늦게 끝났다면, 이미 재생을 시작한 더 최신 + * 채팅을 덮어쓰지 않고 버린다. */ - public async play(mp3Buf: Buffer) { + public async play(mp3Buf: Buffer, seq: number) { if (this.isSessionEnd) return; - const myGen = ++this.generation; + if (seq <= this.lastPlayedSeq) { + Logger.info(`${this.tag} seq=${seq} dropped (newer seq=${this.lastPlayedSeq} already playing)`); + return; + } + this.lastPlayedSeq = seq; this.lastTime = Date.now(); this.startEndTimer(); const res = createResourceFromMp3Buffer(mp3Buf); - if (myGen !== this.generation || this.isSessionEnd) return; // try { this.player.stop(true); } catch {}; try { this.player.play(res); } catch {}; } @@ -94,6 +126,7 @@ export class VoiceSession { selfDeaf: true, selfMute: false, }); + this.watchConnection(this.connection); this.connection.subscribe(this.player); await entersState(this.connection, VoiceConnectionStatus.Ready, 20_000).catch(() => {}); } diff --git a/src/utils/tts/Chzzk.ts b/src/utils/tts/Chzzk.ts index 760404c..5056c08 100644 --- a/src/utils/tts/Chzzk.ts +++ b/src/utils/tts/Chzzk.ts @@ -1,5 +1,6 @@ import axios from "axios"; import { Config } from "../Config"; +import { Logger } from "../Logger"; export enum VoiceType { // 현재(25.08.27) @@ -22,30 +23,64 @@ const defHeaders = { "Cookie": Object.entries(Config.chzzk).map(([key, value]) => key+'='+value).join(';'), }; -const getToken = () => new Promise((res, rej) => { - axios.get("https://api.chzzk.naver.com/service/v1/alerts/token", { - headers: defHeaders, - responseType: "json" - }).then((val) => { - if (!val.data?.content?.token) return rej(val.data?.message || "오류"); - return res(val.data.content.token); - }).catch((err) => { - return rej(err.response?.data?.message || "오류"); - }); -}); +// 치지직이 응답하지 않을 때 봇이 무한정 기다리지 않도록 요청마다 타임아웃을 둔다. +const TOKEN_TIMEOUT_MS = 3_000; +const TTS_TIMEOUT_MS = 8_000; -export const textToSpeech = (text: string, voice: VoiceType) => new Promise(async (res, rej) => { - axios.post("https://api.chzzk.naver.com/service/v1/alerts/tts", { - message: text, - token: await getToken().catch(() => "undefined"), - type: "n"+voice - }, { - headers: defHeaders, - responseType: "arraybuffer" - }).then((val) => { - if (val.status !== 200) return rej(val.data?.message || "오류"); - return res(val.data); - }).catch((err) => { - return rej(err.response?.data?.message || "오류"); - }); -}); \ No newline at end of file +// 토큰 발급 결과 캐시. 성공하면 잠시 재사용하고, 실패(쿠키 만료 등)하면 +// 한동안 발급 요청 자체를 건너뛴다. 토큰 없이도 TTS 요청은 동작하므로 +// 실패 시에는 기존과 같이 "undefined" 토큰으로 보낸다. +const TOKEN_OK_TTL_MS = 5 * 60_000; +const TOKEN_FAIL_TTL_MS = 10 * 60_000; +const NO_TOKEN = "undefined"; +let tokenCache: { token: string; expiresAt: number } | null = null; +let tokenInflight: Promise | null = null; + +const errMessage = (err: any): string => { + const status = err?.response?.status; + const code = err?.code; + return [status && `status=${status}`, code && `code=${code}`, err?.message].filter(Boolean).join(" ") || "오류"; +}; + +const fetchToken = async (): Promise => { + try { + const val = await axios.get("https://api.chzzk.naver.com/service/v1/alerts/token", { + headers: defHeaders, + responseType: "json", + timeout: TOKEN_TIMEOUT_MS, + }); + const token = val.data?.content?.token; + if (!token) throw new Error(val.data?.message || "토큰 없음"); + tokenCache = { token, expiresAt: Date.now() + TOKEN_OK_TTL_MS }; + return token; + } catch (err) { + Logger.warn(`[Chzzk] 토큰 발급 실패(${errMessage(err)}), ${TOKEN_FAIL_TTL_MS / 60_000}분간 토큰 없이 요청`); + tokenCache = { token: NO_TOKEN, expiresAt: Date.now() + TOKEN_FAIL_TTL_MS }; + return NO_TOKEN; + } +}; + +const getToken = (): Promise => { + if (tokenCache && tokenCache.expiresAt > Date.now()) return Promise.resolve(tokenCache.token); + // 동시에 여러 채팅이 와도 발급 요청은 한 번만 보낸다. + if (!tokenInflight) tokenInflight = fetchToken().finally(() => { tokenInflight = null; }); + return tokenInflight; +}; + +export const textToSpeech = async (text: string, voice: VoiceType): Promise => { + const token = await getToken(); + try { + const val = await axios.post("https://api.chzzk.naver.com/service/v1/alerts/tts", { + message: text, + token, + type: "n"+voice + }, { + headers: defHeaders, + responseType: "arraybuffer", + timeout: TTS_TIMEOUT_MS, + }); + return Buffer.from(val.data); + } catch (err) { + throw new Error(`[Chzzk] TTS 요청 실패(${errMessage(err)})`); + } +};