From fa6126e17fab0d3101ad891da58f41c27bf07d82 Mon Sep 17 00:00:00 2001 From: EJClaw Date: Fri, 16 Oct 2026 05:01:14 +0900 Subject: [PATCH] =?UTF-8?q?v1.3.6:=20=EB=AA=A9=EC=86=8C=EB=A6=AC=20?= =?UTF-8?q?=EA=B9=A8=EC=A7=90(RTP=20=EA=B8=B0=EC=A4=80=20=EC=89=BC=20?= =?UTF-8?q?=EC=B1=84=EC=9A=B0=EA=B8=B0)=20=C2=B7=20=EC=95=8C=20=EC=88=98?= =?UTF-8?q?=20=EC=97=86=EC=9D=8C=20=C2=B7=20=EC=9E=A1=EC=9D=8C=20=EC=88=A8?= =?UTF-8?q?=EA=B8=B0=EA=B8=B0/=EC=82=AD=EC=A0=9C=20=C2=B7=20=EC=82=AC?= =?UTF-8?q?=EC=9D=B4=ED=8A=B8=20=EB=A1=9C=EA=B7=B8=20=C2=B7=20=EC=A7=80?= =?UTF-8?q?=EA=B8=88=20=EA=B2=8C=EC=9E=84=20=C2=B7=20TTS=20=EC=86=8D?= =?UTF-8?q?=EB=8F=84=20=C2=B7=20=EC=8B=9C=EC=9E=91=20=EC=B0=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 녹음기: 패킷 도착 간격 대신 RTP 타임스탬프로 자리를 정한다. 게임 중 몰려 온 패킷 사이에 무음이 끼어 목소리가 깨졌다. 예전 녹음은 한 번 고친 뒤 다시 변환 - users.updated 를 빈 목록으로 보내 사이트에서 말한 사람이 '알 수 없음'이 되던 것 - 잡음은 숨기고 ogg 삭제, 로그에 잡음으로 남김. 짧은 목소리도 Whisper 로, 반복 고리는 줄여서 보여 줌 - 사이트: 재생 음량, 발화 우클릭(자세한 정보 · ogg 다운로드), 사이트 로그(/logs, 게임 PC 꺼져도), 지금 게임 상태 - 앱: 지금 게임 상태, 녹음 안내 말 속도 0.1~2.0, 포터블 · 앱 시작 창 - 발로란트 데스매치 가짜 라운드 · 에이스, 빈 선수 이름 Co-Authored-By: Claude Opus 5.5 --- README.md | 14 +- app/package-lock.json | 6 +- app/package.json | 5 +- app/src/core/api/server.ts | 44 +++- app/src/core/db/db.ts | 11 +- app/src/core/discord/bot.ts | 6 +- app/src/core/discord/ogg.ts | 55 ++++ app/src/core/discord/recorder.ts | 83 +++++- app/src/core/discord/tts.ts | 68 ++++- app/src/core/games/lol.ts | 87 ++++++- app/src/core/games/manager.ts | 46 ++-- app/src/core/games/modes.ts | 34 +++ app/src/core/games/types.ts | 3 + app/src/core/games/valorant.ts | 103 +++++++- app/src/core/index.ts | 10 +- app/src/core/settings.ts | 3 + app/src/core/stt/pipeline.ts | 76 ++++++ app/src/core/timeline.ts | 4 +- app/src/core/util/events.ts | 6 +- app/src/main/api-types.ts | 6 +- app/src/main/ipc.ts | 12 +- app/src/main/main.ts | 51 +++- app/src/renderer/mock-gvr.ts | 12 + app/src/renderer/styles.css | 40 +++ app/src/renderer/tabs/DiscordTab.tsx | 7 +- app/src/renderer/tabs/GamesTab.tsx | 35 ++- app/test/core.test.ts | 108 +++++++- app/test/e2e-stt.test.ts | 13 +- app/test/games.test.ts | 35 +++ app/test/mock/riot.ts | 1 + assets/app/splash.bmp | Bin 0 -> 334134 bytes docs/dev/test-results.md | 12 + packages/shared/src/index.ts | 1 + packages/shared/src/live-game.ts | 35 +++ packages/shared/src/protocol.ts | 75 +++++- site/server/src/app-auth.ts | 2 +- site/server/src/app.ts | 68 ++++- site/server/src/main.ts | 2 +- site/server/src/relay.ts | 22 +- site/server/src/site-log.ts | 109 ++++++++ site/server/test/relay.test.ts | 16 +- site/web/mock/server.mjs | 41 ++- site/web/src/App.tsx | 11 + site/web/src/components/Header.tsx | 29 +++ site/web/src/components/Icons.tsx | 11 + site/web/src/components/LockOverlay.tsx | 5 + site/web/src/components/PlayerBar.tsx | 30 ++- site/web/src/components/UttMenu.tsx | 218 ++++++++++++++++ site/web/src/components/UtteranceRow.tsx | 11 +- site/web/src/lib/api.ts | 10 +- site/web/src/lib/audio.ts | 9 + site/web/src/lib/filters.ts | 6 +- site/web/src/lib/report.ts | 29 +++ site/web/src/pages/LogsPage.tsx | 121 +++++++++ site/web/src/pages/Sidebar.tsx | 10 +- site/web/src/pages/TimelinePage.tsx | 44 +++- site/web/src/store/app.tsx | 11 +- site/web/src/store/settings.ts | 3 + site/web/src/styles.css | 313 +++++++++++++++++++++++ site/web/vite.config.ts | 1 + worker/gvr_worker/main.py | 9 + worker/gvr_worker/noise.py | 23 +- worker/gvr_worker/stt.py | 6 + worker/gvr_worker/tempo.py | 69 +++++ worker/tests/test_noise.py | 15 +- worker/tests/test_tempo.py | 32 +++ 66 files changed, 2265 insertions(+), 128 deletions(-) create mode 100644 app/src/core/games/modes.ts create mode 100644 assets/app/splash.bmp create mode 100644 packages/shared/src/live-game.ts create mode 100644 site/server/src/site-log.ts create mode 100644 site/web/src/components/UttMenu.tsx create mode 100644 site/web/src/lib/report.ts create mode 100644 site/web/src/pages/LogsPage.tsx create mode 100644 worker/gvr_worker/tempo.py create mode 100644 worker/tests/test_tempo.py diff --git a/README.md b/README.md index 9c969c2..cb70454 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ - 설계·계획: [`docs/gemnoki-project-plan.pdf`](docs/gemnoki-project-plan.pdf), 개발 구조·인터페이스: [`docs/dev/ARCHITECTURE.md`](docs/dev/ARCHITECTURE.md) - 범인찾기 · 리플레이 동기화 계획서 v1.2 (결정 반영): [`docs/culprit-finder-plan.pdf`](docs/culprit-finder-plan.pdf) · 원본 · 비용 계산 · 프롬프트 초안: `docs/report/culprit/` (실제로 쓰는 프롬프트는 `site/server/prompt/`) - **제작 완료 보고서 (M0~M8)**: [`docs/gemnoki-final-report.pdf`](docs/gemnoki-final-report.pdf) · 단계별 테스트 기록: [`docs/dev/test-results.md`](docs/dev/test-results.md) -- Windows 실행 파일: Gitea 릴리스 [v1.3.5](https://git.tkrmagid.kr/tkrmagid/game_voice_recorder/releases/tag/v1.3.5) (`GameVoiceRecorder-1.3.5-win-x64.zip` 권장, 단일 파일 `GameVoiceRecorder-1.3.5-portable.exe`) · 처음 버전 [v1.0.0](https://git.tkrmagid.kr/tkrmagid/game_voice_recorder/releases/tag/v1.0.0) +- Windows 실행 파일: Gitea 릴리스 [v1.3.6](https://git.tkrmagid.kr/tkrmagid/game_voice_recorder/releases/tag/v1.3.6) (`GameVoiceRecorder-1.3.6-win-x64.zip` 권장, 단일 파일 `GameVoiceRecorder-1.3.6-portable.exe`) · 처음 버전 [v1.0.0](https://git.tkrmagid.kr/tkrmagid/game_voice_recorder/releases/tag/v1.0.0) ## 로그인 · 관리자 (v1.2.0~) @@ -19,6 +19,18 @@ - 앱은 시작할 때와 10분마다 등록 여부를 다시 확인한다. 등록이 해제되면 바로 잠그고 봇 · 녹음 · 사이트 연결을 멈춘다. 사이트 서버에 못 붙으면 마지막 확인 뒤 3일까지는 그대로 쓴다. - 서버 쪽: `site/server/src/app-auth.ts` (`/auth/app/*`, `/app/me`, `/app/admin/users`), 앱 쪽: `app/src/core/auth.ts`, 권한 목록: `app/src/core/roles.ts`. 로그인 E2E: `app/scripts/login-e2e.mts`. +## v1.3.6 바뀐 점 + +- **목소리 깨짐**: 녹음기가 디스코드 패킷이 "도착한 간격"으로 말 사이 쉼을 채웠다. 게임 중(CPU 부하)에는 패킷이 2~3개씩 몰려 와서 말 중간에 20ms 무음이 계속 끼었다 (사용자 파일: 실제 7.0초 발화가 8.5초, 패킷 3개 중 1개가 무음). 이제 RTP 타임스탬프로 패킷 자리를 정한다 (`recorder.ts` `tapRtp` · `Utterance.place`). 예전 녹음은 처음 켤 때 한 번 끼운 무음을 빼고 다시 변환한다 (`ogg.ts` `removeInsertedSilence`) +- **말한 사람 "알 수 없음"**: 앱이 `users.updated` 를 빈 목록으로 보내 사이트가 유저 목록을 비웠다. 이제 실제 목록을 보낸다 (사이트도 빈 목록이면 다시 받아 옴) +- **잡음**: 목소리 없음 · 잡음에서 지어낸 문장 · 같은 말 반복은 사이트에 보이지 않고 ogg 도 지운다 (경기 중 실시간 판정은 경기 뒤 정밀 모델이 다시 본 다음). 로그에 "잡음 발화 … 숨김 · 음성 파일 삭제 (이유, 인식 문장)" 로 남는다. 목소리가 0.15초라도 있으면 Whisper 로 넘기고, 반복 고리는 한 번으로 줄여 남은 말을 보여 준다 +- **시작 창**: 포터블 exe 를 푸는 동안 작은 그림 창(`assets/app/splash.bmp`), 앱이 켜지는 동안 "켜는 중" 창 +- **녹음 안내 말 속도** 0.1~2.0 (Edge TTS 는 0.5~2.0, 그보다 느리면 워커 `tempo` 가 atempo 로 늘림) +- **사이트**: 재생 음량 0~200% · 발화 우클릭(재생 · 자세한 정보(원본 ogg 이름 · 게임 PC 경로 · 크기 · 인식 정보) · ogg 다운로드 · 내용 복사, 앱 `GET /api/utterances/:id/info`) +- **사이트 로그**: 사이트 서버가 `data/logs/site-날짜.log` 로 남긴다 (게임 PC 연결 · 끊김 · 기록 요청 결과 · 봇 중계 · 범인찾기 · 브라우저 오류). 관리자는 `https://gvr.tkrmagid.kr/logs` 에서 게임 PC 가 꺼져 있어도 보고 내려받는다 (잠금 화면 · 설정 메뉴에 링크). 14일 보관 +- **지금 게임**: 앱 게임 연동 탭 · 사이트(머리글 · 타임라인 오른쪽)에 연결된 게임 · 상태(메뉴 · 대기열 · 요원/챔피언 선택 · 경기 중) · 모드 · 맵 · 라운드 · 점수 · 내 요원/챔피언 · KDA · 게임 시간 +- 발로란트 데스매치 · 팀 데스매치 · 에스컬레이션: 킬 점수를 라운드로 착각해 "R63 승리" 같은 가짜 라운드와 에이스를 만들던 것 고침. 경기 상세에 선수 이름이 비어 오면 이름 서비스로 채운다 ("주인 계정 자동 연결: #" 고침) + ## v1.3.5 바뀐 점 - **표시 이름 빈틈**: 표시 이름을 정하기 전에 시작한 범인 분석이 정한 뒤에 저장되면 결과 본문에 예전 이름이 남을 수 있었다 (이미 이름이 바뀐 유저는 다시 훑지 않았음). 이제 가린 예전 이름을 기억해 두고(`meta.hidden_names`), 분석을 저장할 때마다 · 이름을 다시 받을 때마다 모든 분석에서 바꾼다 diff --git a/app/package-lock.json b/app/package-lock.json index 24206d3..43effdf 100644 --- a/app/package-lock.json +++ b/app/package-lock.json @@ -1,12 +1,12 @@ { "name": "gvr-app", - "version": "1.3.5", + "version": "1.3.6", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "gvr-app", - "version": "1.3.5", + "version": "1.3.6", "license": "UNLICENSED", "dependencies": { "@discordjs/voice": "^0.19.2", @@ -4677,7 +4677,7 @@ } }, "node_modules/prism-media": { - "version": "1.3.5", + "version": "1.3.6", "resolved": "https://registry.npmjs.org/prism-media/-/prism-media-1.3.5.tgz", "integrity": "sha512-IQdl0Q01m4LrkN1EGIE9lphov5Hy7WWlH6ulf5QdGePLlPas9p2mhgddTEHrlaXYjjFToM1/rWuwF37VF4taaA==", "peerDependencies": { diff --git a/app/package.json b/app/package.json index 27962c7..7fd9e1a 100644 --- a/app/package.json +++ b/app/package.json @@ -1,7 +1,7 @@ { "name": "gvr-app", "productName": "겜녹이", - "version": "1.3.5", + "version": "1.3.6", "description": "겜녹이 (Game Voice Recorder) - 게임 연동 디스코드 음성 기록", "private": true, "main": "dist/main.cjs", @@ -107,7 +107,8 @@ }, "portable": { "artifactName": "GameVoiceRecorder-${version}-portable.exe", - "unpackDirName": "GameVoiceRecorder" + "unpackDirName": "GameVoiceRecorder", + "splashImage": "../assets/app/splash.bmp" } } } diff --git a/app/src/core/api/server.ts b/app/src/core/api/server.ts index 818c99c..7467997 100644 --- a/app/src/core/api/server.ts +++ b/app/src/core/api/server.ts @@ -1,7 +1,7 @@ import Fastify, { type FastifyInstance } from 'fastify'; import fs from 'node:fs'; import path from 'node:path'; -import type { CulpritAnalysis, CulpritResult, MatchDetail, MatchPlayer, Overview, User, UserProfile, Word } from '@gvr/shared'; +import type { CulpritAnalysis, CulpritResult, MatchDetail, MatchPlayer, Overview, User, UserProfile, UtteranceInfo, Word } from '@gvr/shared'; import type { Culprit } from '../culprit.js'; import type { Store, UserRow } from '../db/db.js'; import type { Dictionary } from '../dict/dictionary.js'; @@ -54,6 +54,7 @@ export async function buildApi(d: ApiDeps): Promise { recording: extra.recording, users: users(), games: { valorant: { connected: gs.valorant.connected, inMatch: gs.valorant.inMatch }, lol: { connected: gs.lol.connected, inMatch: gs.lol.inMatch } }, + live: d.games.live(), counts: store.counts(), version: d.version, }; @@ -108,7 +109,6 @@ export async function buildApi(d: ApiDeps): Promise { to: q.to ? Number(q.to) : undefined, q: q.q || undefined, types: q.types ? q.types.split(',').filter(Boolean) : undefined, - hideNoise: q.hideNoise === '1' || q.hideNoise === 'true', cursor: q.cursor || undefined, limit: q.limit ? Number(q.limit) : undefined, order: q.order === 'asc' ? 'asc' : 'desc', @@ -116,6 +116,44 @@ export async function buildApi(d: ApiDeps): Promise { return timeline.query(tq); }); + // 발화 자세한 정보: 원본 ogg 이름 · 경로 등 (사이트 우클릭 → 자세한 정보) + app.get<{ Params: { id: string } }>('/api/utterances/:id/info', async (req, reply): Promise => { + const u = store.getUtterance(req.params.id); + if (!u) return reply.code(404).send({ error: 'not_found' }); + const exists = !!u.audio_path && !u.audio_deleted && fs.existsSync(u.audio_path); + const sess = u.session_id ? (store.db.prepare('SELECT channel_name FROM sessions WHERE id=?').get(u.session_id) as { channel_name: string | null } | undefined) : undefined; + const p = u.audio_path; + const win = p?.includes('\\') ?? false; + const sep = win ? '\\' : '/'; + return { + id: u.id, + userId: u.user_id, + fileName: p ? p.split(/[\\/]/).pop() ?? null : null, + path: p, + folder: p ? p.slice(0, p.lastIndexOf(sep)) || null : null, + sizeBytes: exists ? fs.statSync(p!).size : null, + deleted: exists ? null : u.noise && !u.corrected ? 'noise' : u.audio_deleted ? 'retention' : 'missing', + startedAt: u.started_at, + endedAt: u.ended_at, + durationMs: u.ended_at - u.started_at, + sessionId: u.session_id, + channel: sess?.channel_name ?? null, + matchId: u.match_id, + status: u.status, + model: u.model, + confidence: u.confidence, + lufs: u.lufs, + gainDb: u.gain_db, + rawText: u.raw_text, + text: u.text, + corrected: !!u.corrected, + noise: !!u.noise, + noiseReason: u.noise_reason, + attempts: u.attempts, + createdAt: u.created_at, + }; + }); + app.get<{ Params: { id: string } }>('/api/audio/:id', async (req, reply) => { const u = store.getUtterance(req.params.id); if (!u) return reply.code(404).send({ error: 'not_found' }); @@ -171,7 +209,7 @@ export async function buildApi(d: ApiDeps): Promise { stats: p.stats, })); const evRows = store.events(m.id); - const utts = store.db.prepare('SELECT rowid,* FROM utterances WHERE match_id=? ORDER BY started_at').all(m.id) as any[]; + const utts = store.db.prepare('SELECT rowid,* FROM utterances WHERE match_id=? AND (noise=0 OR corrected=1) ORDER BY started_at').all(m.id) as any[]; const vmap = m.game === 'valorant' ? d.games.assets.valMap(m.map) : null; return { ...sum, diff --git a/app/src/core/db/db.ts b/app/src/core/db/db.ts index 3bdc06c..aded444 100644 --- a/app/src/core/db/db.ts +++ b/app/src/core/db/db.ts @@ -322,6 +322,15 @@ export class Store { .prepare('SELECT id, audio_path FROM utterances WHERE audio_deleted=0 AND audio_path IS NOT NULL AND started_at undefined); } catch (e) { diff --git a/app/src/core/discord/ogg.ts b/app/src/core/discord/ogg.ts index 0f51ca4..311bff1 100644 --- a/app/src/core/discord/ogg.ts +++ b/app/src/core/discord/ogg.ts @@ -127,3 +127,58 @@ export class OggOpusWriter { return Math.round(this.samples / 48); } } + +/** Ogg 파일에서 Opus 패킷을 꺼낸다 (OpusHead · OpusTags 포함) */ +export function readOggPackets(buf: Buffer): Buffer[] { + const out: Buffer[] = []; + let pos = 0; + let cur: Buffer[] = []; + while (pos + 27 <= buf.length && buf.toString('ascii', pos, pos + 4) === 'OggS') { + const nseg = buf[pos + 26]; + const lacing = buf.subarray(pos + 27, pos + 27 + nseg); + let p = pos + 27 + nseg; + for (const l of lacing) { + cur.push(buf.subarray(p, p + l)); + p += l; + if (l < 255) { + out.push(Buffer.concat(cur)); + cur = []; + } + } + pos = p; + } + return out; +} + +/** + * v1.3.5 이하 녹음 고치기: 패킷이 몰려 도착할 때 말 중간에 끼워 넣은 20~60ms 무음 프레임을 뺀다. + * 디스코드는 말하는 도중에 무음 프레임을 보내지 않으므로, 앞뒤가 목소리인 1~3개짜리 무음 묶음은 녹음기가 넣은 것이다. + * @returns 뺀 프레임 수 (0 이면 파일을 건드리지 않음) + */ +export function removeInsertedSilence(file: string): number { + const all = readOggPackets(fs.readFileSync(file)); + if (all.length < 3) return 0; + const head = all[0]; + const packets = all.slice(2); + const isSil = (p: Buffer) => p.equals(SILENCE_FRAME); + const keep: Buffer[] = []; + let removed = 0; + for (let i = 0; i < packets.length; ) { + if (!isSil(packets[i])) { + keep.push(packets[i++]); + continue; + } + let j = i; + while (j < packets.length && isSil(packets[j])) j++; + if (i > 0 && j < packets.length && j - i <= 3) removed += j - i; + else keep.push(...packets.slice(i, j)); + i = j; + } + if (!removed) return 0; + const tmp = `${file}.fix`; + const w = new OggOpusWriter(tmp, head[9] || 2); + for (const p of keep) w.write(p); + w.close(); + fs.renameSync(tmp, file); + return removed; +} diff --git a/app/src/core/discord/recorder.ts b/app/src/core/discord/recorder.ts index 94d3279..b893b42 100644 --- a/app/src/core/discord/recorder.ts +++ b/app/src/core/discord/recorder.ts @@ -21,12 +21,55 @@ export interface RecorderOptions { matchAt: (ts: number) => string | null; } +/** RTP 시각 (48kHz 샘플 단위 타임스탬프 + 순번) */ +export interface RtpInfo { + seq: number; + ts: number; +} + +/** 수신기가 꺼낸 Opus 패킷 → 그 패킷이 담겨 온 RTP 헤더 */ +const rtpOf = new WeakMap(); + +export function rtpInfo(packet: Buffer): RtpInfo | undefined { + return rtpOf.get(packet); +} + +/** 테스트용: 패킷에 RTP 시각을 붙인다 */ +export function tagRtp(packet: Buffer, info: RtpInfo): Buffer { + rtpOf.set(packet, info); + return packet; +} + +/** + * @discordjs/voice 는 Opus 내용만 넘기고 RTP 순번 · 타임스탬프를 버린다. + * 패킷 도착 시각은 게임 중(CPU 부하)에 2~3개씩 몰려 와서 쉼 계산에 쓸 수 없다 (v1.3.5 까지 말 중간에 무음이 끼어 목소리가 깨짐). + * 그래서 복호화 함수를 감싸 RTP 헤더를 패킷에 붙여 둔다. + */ +export function tapRtp(receiver: unknown): boolean { + const r = receiver as { parsePacket?: (buf: Buffer, ...rest: unknown[]) => Buffer | undefined; __gvrRtp?: boolean }; + if (r.__gvrRtp) return true; + if (typeof r.parsePacket !== 'function') return false; + const orig = r.parsePacket.bind(r); + r.parsePacket = (buf: Buffer, ...rest: unknown[]) => { + const packet = orig(buf, ...rest); + if (packet && buf.length >= 12) rtpOf.set(packet, { seq: buf.readUInt16BE(2), ts: buf.readUInt32BE(4) }); + return packet; + }; + r.__gvrRtp = true; + return true; +} + +const FRAME = 960; // 20ms @48kHz + /** 발화 하나 = 파일 하나. 말이 0.8초 끊기면 끝, 최대 30초 (보고서 4장 1~3단계) */ -class Utterance { +export class Utterance { writer: OggOpusWriter; id: string; startedAt: number; lastArrival: number; + /** 첫 패킷의 RTP 타임스탬프 - 그때까지 쓴 샘플 수. 패킷 자리 = ts - rtpBase */ + rtpBase: number | null = null; + lastSeq = 0; constructor(dir: string, now: number) { this.id = newId(now); this.startedAt = now; @@ -36,6 +79,35 @@ class Utterance { fs.mkdirSync(d, { recursive: true }); this.writer = new OggOpusWriter(path.join(d, `${this.id}.ogg`)); } + + /** + * 패킷을 제자리에 쓴다. 디스코드는 말 사이 짧은 쉼에는 패킷을 안 보내므로 빈 자리를 무음 프레임으로 채운다. + * - RTP 타임스탬프가 있으면 그 값으로 자리를 정한다 (도착이 몰리거나 늦어도 소리가 늘어나지 않음) + * - 없으면 도착 시각으로 정하되, 실제 흐른 시간보다 0.2초 넘게 모자랄 때만 채운다 (몰려 온 패킷 사이에 무음을 넣지 않음) + * @returns 쓴 무음 프레임 수, 버린 패킷이면 -1 + */ + place(packet: Buffer, now: number, maxGapMs: number): number { + const rtp = rtpOf.get(packet); + let fill = 0; + if (rtp && this.rtpBase !== null) { + const d = (rtp.seq - this.lastSeq) & 0xffff; + if (d === 0 || d > 0x8000) return -1; // 중복 · 순서가 뒤바뀌어 늦게 온 패킷 (그 자리는 이미 지나감) + const behind = ((rtp.ts - this.rtpBase) >>> 0) - this.writer.samples; + if (behind >= FRAME / 2 && behind <= maxGapMs * 48) fill = Math.round(behind / FRAME); + else if (behind > maxGapMs * 48 || behind < -48000) this.rtpBase = (rtp.ts - this.writer.samples) >>> 0; // 타임스탬프가 튐: 다시 맞춘다 + } else if (!rtp) { + const lag = now - this.startedAt - this.writer.samples / 48; + if (lag > 200) fill = Math.min(Math.floor((lag - 100) / 20), Math.ceil(maxGapMs / 20)); + } + if (rtp) { + if (this.rtpBase === null) this.rtpBase = (rtp.ts - this.writer.samples) >>> 0; + this.lastSeq = rtp.seq; + } + for (let i = 0; i < fill; i++) this.writer.write(SILENCE_FRAME); + this.lastArrival = now; + this.writer.write(packet); + return fill; + } } function localDay(ts: number): string { @@ -61,6 +133,7 @@ export class Recorder { this.detach(); this.connection = connection; this.sessionId = sessionId; + if (!tapRtp(connection.receiver)) log.warn('RTP 시각을 읽을 수 없음: 도착 시각으로 쉼을 맞춤'); connection.receiver.speaking.on('start', this.onSpeak); } @@ -99,14 +172,8 @@ export class Recorder { if (!u) { u = new Utterance(this.opts.audioDir(), now - 20); this.active.set(userId, u); - } else { - // 말 사이 짧은 쉼은 디스코드가 패킷을 안 보낸다. 무음 프레임으로 채워 실제 시간과 맞춘다. - const gap = now - u.lastArrival; - const missing = Math.round(gap / 20) - 1; - if (missing > 0 && missing * 20 < this.opts.silenceMs() + 200) for (let i = 0; i < missing; i++) u.writer.write(SILENCE_FRAME); } - u.lastArrival = now; - u.writer.write(packet); + u.place(packet, now, this.opts.silenceMs() + 200); if (u.writer.samples >= this.opts.maxUtteranceSec() * 48000) { this.finish(userId); } diff --git a/app/src/core/discord/tts.ts b/app/src/core/discord/tts.ts index 26caf42..c46090e 100644 --- a/app/src/core/discord/tts.ts +++ b/app/src/core/discord/tts.ts @@ -7,6 +7,20 @@ import { logger } from '../util/log.js'; const log = logger('tts'); +/** 0.5배보다 느린 부분을 늘리는 함수 (워커 atempo). src 를 tempo 배속으로 바꿔 dst(Ogg Opus)에 쓴다 */ +export type TempoFn = (src: string, dst: string, tempo: number) => Promise; + +/** 말 속도 0.1~2.0 (Edge TTS 는 0.5~2.0 만 지원해서 그보다 느린 부분은 워커가 늘린다) */ +export function clampRate(rate: unknown): number { + const r = typeof rate === 'number' && isFinite(rate) ? rate : 1; + return Math.round(Math.min(2, Math.max(0.1, r)) * 100) / 100; +} + +/** 파일 확장자로 디스코드 재생 형식을 고른다 */ +export function isOgg(file: string): boolean { + return file.endsWith('.ogg'); +} + /** * 녹음 안내 음성. 미리 합성해서 캐시하고, 문구를 바꾸면 다시 합성한다 (보고서 7-3). * 합성은 Microsoft Edge 온라인 TTS(무료). 인터넷이 안 되면 기본 문구 음성(앱에 포함)을 쓴다. @@ -15,38 +29,66 @@ export class Announcer { constructor( private cacheDir: string, private resourcesDir: string, + private tempo: TempoFn | null = null, ) {} private bundled(): string { return path.join(this.resourcesDir, 'tts', 'announce-default.webm'); } - cachedPath(text: string, voice: string): string { - const h = crypto.createHash('sha1').update(`${voice}\n${text}`).digest('hex').slice(0, 16); - return path.join(this.cacheDir, `announce-${h}.webm`); + cachedPath(text: string, voice: string, rate = 1): string { + rate = clampRate(rate); + const key = rate === 1 ? `${voice}\n${text}` : `${voice}\n${rate}\n${text}`; + const h = crypto.createHash('sha1').update(key).digest('hex').slice(0, 16); + return path.join(this.cacheDir, `announce-${h}.${rate < 0.5 ? 'ogg' : 'webm'}`); } - /** 안내 음성 파일 경로 (WebM Opus). 없으면 합성. */ - async ensure(text: string, voice: string): Promise { - const p = this.cachedPath(text, voice); + /** 안내 음성 파일 경로 (WebM Opus, 0.5배보다 느리면 Ogg Opus). 없으면 합성. */ + async ensure(text: string, voice: string, rate = 1): Promise { + rate = clampRate(rate); + const p = this.cachedPath(text, voice, rate); if (fs.existsSync(p) && fs.statSync(p).size > 1000) return p; - if (text === DEFAULT_TTS_TEXT && voice === 'ko-KR-SunHiNeural' && fs.existsSync(this.bundled())) return this.bundled(); + if (rate === 1 && text === DEFAULT_TTS_TEXT && voice === 'ko-KR-SunHiNeural' && fs.existsSync(this.bundled())) return this.bundled(); try { - await synthesize(text, voice, p); - log.info(`안내 음성 합성: ${path.basename(p)}`); + await render(text, voice, rate, p, this.tempo); + log.info(`안내 음성 합성: ${path.basename(p)} (속도 ${rate})`); return p; } catch (e) { log.warn('안내 음성 합성 실패, 기본 음성 사용', e); + // 인터넷이 안 될 때: 기본 음성을 그 속도로만 바꿔 쓴다 + if (rate !== 1 && this.tempo && fs.existsSync(this.bundled())) { + const q = path.join(this.cacheDir, `announce-default-${rate}.ogg`); + try { + if (!fs.existsSync(q)) await this.tempo(this.bundled(), q, rate); + return q; + } catch (e2) { + log.warn('기본 음성 속도 바꾸기 실패', e2); + } + } return this.bundled(); } } } +/** 문구를 그 속도로 합성해 outFile 에 쓴다. 0.5배보다 느리면 0.5배로 합성한 뒤 워커가 더 늘린다 (outFile 은 .ogg) */ +export async function render(text: string, voice: string, rate: number, outFile: string, tempo: TempoFn | null): Promise { + rate = clampRate(rate); + if (rate >= 0.5) return synthesize(text, voice, outFile, 4, rate); + if (!tempo) throw new Error('0.5배보다 느린 속도는 음성 인식 엔진(워커)이 켜져 있어야 합니다'); + const tmp = `${outFile}.half.webm`; + try { + await synthesize(text, voice, tmp, 4, 0.5); + await tempo(tmp, outFile, rate / 0.5); + } finally { + fs.rmSync(tmp, { force: true }); + } +} + /** Edge TTS 는 짧은 시간에 여러 번 부르면 429 를 준다. 몇 번 쉬었다가 다시 시도한다. */ -export async function synthesize(text: string, voice: string, outFile: string, tries = 4): Promise { +export async function synthesize(text: string, voice: string, outFile: string, tries = 4, rate = 1): Promise { for (let i = 1; ; i++) { try { - return await synthesizeOnce(text, voice, outFile); + return await synthesizeOnce(text, voice, outFile, rate); } catch (e: any) { if (i >= tries) throw e; await new Promise((r) => setTimeout(r, 1500 * 2 ** i)); @@ -54,14 +96,14 @@ export async function synthesize(text: string, voice: string, outFile: string, t } } -async function synthesizeOnce(text: string, voice: string, outFile: string): Promise { +async function synthesizeOnce(text: string, voice: string, outFile: string, rate: number): Promise { fs.mkdirSync(path.dirname(outFile), { recursive: true }); const tts = new MsEdgeTTS(); const tmpDir = fs.mkdtempSync(path.join(path.dirname(outFile), '.tts-')); try { await tts.setMetadata(voice, OUTPUT_FORMAT.WEBM_24KHZ_16BIT_MONO_OPUS); const r = await Promise.race([ - tts.toFile(tmpDir, text), + tts.toFile(tmpDir, text, rate === 1 ? undefined : { rate: Math.min(2, Math.max(0.5, rate)) }), new Promise((_, rej) => setTimeout(() => rej(new Error('TTS 시간 초과')), 20000)), ]); fs.renameSync(r.audioFilePath, outFile); diff --git a/app/src/core/games/lol.ts b/app/src/core/games/lol.ts index 74c9876..0bc1bfc 100644 --- a/app/src/core/games/lol.ts +++ b/app/src/core/games/lol.ts @@ -1,4 +1,5 @@ -import type { ChatData, KillData, MatchPlayer, ObjectData, PlayerRef } from '@gvr/shared'; +import type { ChatData, KillData, LiveGame, MatchPlayer, ObjectData, PlayerRef } from '@gvr/shared'; +import { lolModeKo } from './modes.js'; import type { EventRow } from '../db/db.js'; import { logger } from '../util/log.js'; import { lolObjectIcon } from './assets.js'; @@ -64,6 +65,12 @@ export class LolAdapter implements GameAdapter { private summonerNames = new Map(); private lastMatchId: string | null = null; private lastErr = ''; + /** LCU 게임 진행 단계 (Lobby · Matchmaking · ChampSelect · InProgress …) */ + private phase: string | null = null; + private queueName: string | null = null; + /** 게임 클라이언트 API 마지막 값 (지금 게임 상태 표시용) */ + private snap: { at: number; gameTime: number; mode: string | null; champ: string | null; champIcon: string | null; kda: string | null; extra: string | null; teamKills: { ally: number; enemy: number } | null; players: number } | null = null; + private selfRiotId: string | null = null; constructor(private host: AdapterHost) {} @@ -81,6 +88,49 @@ export class LolAdapter implements GameAdapter { return { connected: !!this.lcu || !!this.live, inMatch: !!this.live && !this.live.ended, detail: this.lastErr || undefined }; } + liveGame(): LiveGame { + const enabled = this.host.settings().games.lol; + const inMatch = !!this.live && !this.live.ended; + const snap = inMatch && this.snap && Date.now() - this.snap.at < 15000 ? this.snap : null; + const PHASE: Record = { + None: '메인 화면', + Lobby: '로비', + Matchmaking: '대기열', + CheckedIntoTournament: '토너먼트 대기', + ReadyCheck: '수락 대기', + ChampSelect: '챔피언 선택', + GameStart: '게임 불러오는 중', + FailedToLaunch: '게임 실행 실패', + InProgress: '경기 중', + Reconnect: '다시 연결 필요', + WaitingForStats: '결과 기다리는 중', + PreEndOfGame: '경기 끝', + EndOfGame: '경기 끝 · 결과 화면', + TerminatedInError: '오류로 종료', + }; + const phase = !enabled ? '연동 꺼짐' : inMatch ? '경기 중' : this.lcu ? (PHASE[this.phase ?? ''] ?? this.phase ?? '연결됨') : '롤 클라이언트 꺼짐'; + return { + game: 'lol', + enabled, + connected: !!this.lcu || !!this.live, + phase, + inMatch, + matchId: inMatch ? this.live!.id : null, + mode: this.queueName ?? snap?.mode ?? null, + map: inMatch ? (snap?.mode === '칼바람 나락' ? '칼바람 나락' : '소환사의 협곡') : null, + mapImage: null, + startedAt: inMatch ? this.live!.startedAt : null, + round: null, + score: null, + gameTimeSec: snap ? Math.round(snap.gameTime) : null, + teamKills: snap?.teamKills ?? null, + self: this.lcu || inMatch ? { name: this.selfRiotId, character: snap?.champ ?? null, characterImage: snap?.champIcon ?? null, kda: snap?.kda ?? null, extra: snap?.extra ?? null } : null, + players: snap?.players ?? null, + error: this.lastErr || null, + updatedAt: Date.now(), + }; + } + private async lcuGet(path: string): Promise { if (!this.lcu) return null; try { @@ -160,6 +210,7 @@ export class LolAdapter implements GameAdapter { const m = this.live; m.failures = 0; m.players = d.allPlayers || m.players; + this.snapshot(d, m); // 게임 시간과 PC 시계로 시작 시각을 계속 다듬는다 (가장 이른 값 = 지연이 가장 적은 값) m.startedAt = Math.min(m.startedAt, now - gameTime * 1000); for (const ev of d.events?.Events || []) { @@ -181,6 +232,26 @@ export class LolAdapter implements GameAdapter { } } + /** 지금 게임 상태 표시용: 게임 시간 · 내 챔피언 · KDA · 팀 킬 */ + private snapshot(d: any, m: LiveMatch): void { + const all: any[] = d.allPlayers || []; + const me = all.find((p) => p.riotId === m.selfName || p.summonerName === m.selfName); + const sc = me?.scores; + const kills = (team: string | null | undefined) => all.filter((p) => p.team === team).reduce((n, p) => n + (p.scores?.kills ?? 0), 0); + const champ = me ? this.host.assets.champion(me.rawChampionName, me.championName) : null; + this.snap = { + at: Date.now(), + gameTime: Number(d.gameData?.gameTime) || 0, + mode: lolModeKo(d.gameData?.gameMode) ?? d.gameData?.gameMode ?? null, + champ: champ?.name ?? null, + champIcon: champ?.icon ?? null, + kda: sc ? `${sc.kills ?? 0}/${sc.deaths ?? 0}/${sc.assists ?? 0}` : null, + extra: me ? `레벨 ${me.level ?? '?'} · CS ${sc?.creepScore ?? 0}` : null, + teamKills: m.selfTeam ? { ally: kills(m.selfTeam), enemy: all.filter((p) => p.team !== m.selfTeam).reduce((n, p) => n + (p.scores?.kills ?? 0), 0) } : null, + players: all.length, + }; + } + private findPlayer(m: LiveMatch, name: string | undefined): any { if (!name) return null; return m.players.find((p) => p.riotIdGameName === name || p.riotId === name || p.summonerName === name || p.riotId?.split('#')[0] === name) ?? null; @@ -371,10 +442,22 @@ export class LolAdapter implements GameAdapter { log.info('롤 클라이언트(LCU) 연결'); const me = await this.lcuGet('/lol-summoner/v1/current-summoner'); if (me?.puuid) this.host.selfAccount(me.puuid, `${me.gameName}#${me.tagLine}`); + if (me?.gameName) this.selfRiotId = `${me.gameName}#${me.tagLine ?? ''}`; } } - if (!this.lcu) return; + if (!this.lcu) { + this.phase = null; + this.queueName = null; + return; + } const phase = await this.lcuGet('/lol-gameflow/v1/gameflow-phase'); + if (phase !== this.phase) { + this.phase = phase; + // 큐 이름 (솔로 랭크 · 칼바람 나락 …): 단계가 바뀔 때만 다시 받는다 + const sess = phase && phase !== 'None' ? await this.lcuGet('/lol-gameflow/v1/session') : null; + const q = sess?.gameData?.queue; + this.queueName = q ? (lolModeKo(q.id) ?? q.description ?? null) : null; + } if (phase === 'ChampSelect' || phase === 'InProgress' || phase === 'PreEndOfGame' || phase === 'EndOfGame') await this.pollLcuChat(phase); } diff --git a/app/src/core/games/manager.ts b/app/src/core/games/manager.ts index 9d8930c..86fd679 100644 --- a/app/src/core/games/manager.ts +++ b/app/src/core/games/manager.ts @@ -1,4 +1,4 @@ -import type { MatchSummary } from '@gvr/shared'; +import type { LiveGame, MatchSummary } from '@gvr/shared'; import type { EventRow, MatchRow, Store } from '../db/db.js'; import type { Settings } from '../settings.js'; import type { SttPipeline } from '../stt/pipeline.js'; @@ -11,6 +11,7 @@ import type { GameAssets } from './assets.js'; import { LolAdapter } from './lol.js'; import type { AdapterHost, GameAdapter, MatchStart } from './types.js'; import { ValorantAdapter } from './valorant.js'; +import { lolModeKo, valModeKo } from './modes.js'; const log = logger('games'); @@ -38,12 +39,15 @@ export class GameManager implements AdapterHost { start(): void { void this.assets.refresh(); for (const a of this.adapters) a.start(); + this.watchLive(); // 앱이 꺼졌다 켜졌을 때 'live' 로 남은 경기는 끝난 것으로 정리 for (const m of this.store.listMatches({ limit: 20 })) if (m.status === 'live') this.store.upsertMatch({ id: m.id, game: m.game, started_at: m.started_at, status: 'complete', ended_at: m.ended_at ?? Date.now() }); } stop(): void { for (const a of this.adapters) a.stop(); + if (this.liveTimer) clearInterval(this.liveTimer); + this.liveTimer = null; } status() { const out: Record = {}; @@ -51,6 +55,25 @@ export class GameManager implements AdapterHost { return out as { valorant: { connected: boolean; inMatch: boolean }; lol: { connected: boolean; inMatch: boolean } }; } + /** 지금 게임 상태 (앱 게임 연동 탭 · 사이트) */ + live(): LiveGame[] { + return this.adapters.map((a) => a.liveGame()); + } + + private liveTimer: NodeJS.Timeout | null = null; + private lastLive = ''; + /** 게임 상태가 바뀌면 사이트로 알린다 (2초마다 확인) */ + private watchLive(): void { + if (this.liveTimer) return; + this.liveTimer = setInterval(() => { + const live = this.live(); + const key = JSON.stringify(live.map(({ updatedAt: _u, ...rest }) => rest)); + if (key === this.lastLive) return; + this.lastLive = key; + this.bus.live({ type: 'games.state', data: live }); + }, 2000); + } + /** 지금 진행 중인 경기 (녹음 시 발화에 붙인다) */ liveMatchAt(ts: number): string | null { const m = this.store.matchAt(ts); @@ -110,6 +133,8 @@ export class GameManager implements AdapterHost { selfAccount(puuid: string, riotId: string): void { const owner = this.ownerUserId(); this.store.setMeta('riot_self_puuid', puuid); + // 경기 상세에 이름이 빠져 오면("#") 연결하지 않는다 (v1.3.5: "주인 계정 자동 연결: #") + if (!/^[^#]+#[^#]+$/.test(riotId)) return; if (!owner || !this.store.getUser(owner)) return; const have = this.store.listAccounts().some((a) => a.user_id === owner && a.puuid === puuid); if (have) return; @@ -159,21 +184,6 @@ export class GameManager implements AdapterHost { } function modeKo(m: MatchRow): string { - const q = (m.queue || m.mode || '').toLowerCase(); - if (m.game === 'valorant') { - const map: Record = { - competitive: '경쟁전', - unrated: '일반전', - swiftplay: '신속플레이', - spikerush: '스파이크 돌격', - deathmatch: '데스매치', - hurm: '팀 데스매치', - premier: '프리미어', - custom: '사용자 지정', - ggteam: '에스컬레이션', - }; - return map[q] || m.mode || '발로란트'; - } - const lq: Record = { '420': '솔로 랭크', '440': '자유 랭크', '400': '일반', '430': '일반', '450': '칼바람 나락', '490': '빠른 대전', '1700': '아레나', classic: '소환사의 협곡', aram: '칼바람 나락' }; - return lq[q] || m.mode || '리그 오브 레전드'; + const q = m.queue || m.mode || ''; + return m.game === 'valorant' ? (valModeKo(q) ?? m.mode ?? '발로란트') : (lolModeKo(q) ?? m.mode ?? '리그 오브 레전드'); } diff --git a/app/src/core/games/modes.ts b/app/src/core/games/modes.ts new file mode 100644 index 0000000..a353d04 --- /dev/null +++ b/app/src/core/games/modes.ts @@ -0,0 +1,34 @@ +// 게임 모드 이름 (경기 목록 · 지금 게임 상태에서 함께 쓴다) + +/** 발로란트 큐 ID → 모드 이름 (모르는 큐면 null) */ +export function valModeKo(queue: string | null | undefined): string | null { + const q = (queue || '').toLowerCase(); + { + const map: Record = { + competitive: '경쟁전', + unrated: '일반전', + swiftplay: '신속플레이', + spikerush: '스파이크 돌격', + deathmatch: '데스매치', + hurm: '팀 데스매치', + premier: '프리미어', + custom: '사용자 지정', + ggteam: '에스컬레이션', + newmap: '새 맵', + snowball: '눈싸움', + }; + return map[q] || null; + } +} + +/** 롤 큐 ID · 게임 모드 → 이름 (모르면 null) */ +export function lolModeKo(queue: string | number | null | undefined): string | null { + const q = String(queue ?? '').toLowerCase(); + const lq: Record = { '420': '솔로 랭크', '440': '자유 랭크', '400': '일반', '430': '일반', '450': '칼바람 나락', '490': '빠른 대전', '1700': '아레나', '900': '우르프', '1900': '우르프', classic: '소환사의 협곡', aram: '칼바람 나락', cherry: '아레나', urf: '우르프', practicetool: '연습 모드', tutorial: '튜토리얼' }; + return lq[q] || null; +} + +/** 발로란트에서 라운드가 없는 모드 (점수 = 킬). 이 모드는 라운드 구분선 · 라운드 번호를 쓰지 않는다 */ +export function valNoRounds(queue: string | null | undefined): boolean { + return ['deathmatch', 'hurm', 'ggteam', 'snowball'].includes((queue || '').toLowerCase()); +} diff --git a/app/src/core/games/types.ts b/app/src/core/games/types.ts index f3e6ca2..57328e4 100644 --- a/app/src/core/games/types.ts +++ b/app/src/core/games/types.ts @@ -1,3 +1,4 @@ +import type { LiveGame } from '@gvr/shared'; import type { EventRow, MatchRow, Store } from '../db/db.js'; import type { Settings } from '../settings.js'; import type { WorkerClient } from '../stt/worker.js'; @@ -38,4 +39,6 @@ export interface GameAdapter { start(): void; stop(): void; status(): { connected: boolean; inMatch: boolean; detail?: string }; + /** 지금 게임 상태 (자세히) */ + liveGame(): LiveGame; } diff --git a/app/src/core/games/valorant.ts b/app/src/core/games/valorant.ts index 347de64..31af413 100644 --- a/app/src/core/games/valorant.ts +++ b/app/src/core/games/valorant.ts @@ -1,4 +1,5 @@ -import type { KillData, ChatData, RoundEndData, PlayerRef, MatchPlayer, MatchRound, PlayerStats } from '@gvr/shared'; +import type { KillData, ChatData, LiveGame, RoundEndData, PlayerRef, MatchPlayer, MatchRound, PlayerStats } from '@gvr/shared'; +import { valModeKo, valNoRounds } from './modes.js'; import type { EventRow, RoundRow } from '../db/db.js'; import { logger } from '../util/log.js'; import type { GameAssets } from './assets.js'; @@ -21,6 +22,8 @@ interface Presence { ally: number | null; enemy: number | null; provisioning: string | null; + /** 파티 상태: DEFAULT · MATCHMAKING · MATCHMADE_GAME_STARTING … */ + partyState: string | null; } export function decodePresence(b64: string): Presence | null { @@ -35,6 +38,7 @@ export function decodePresence(b64: string): Presence | null { ally: num(pp.partyOwnerMatchScoreAllyTeam ?? p.partyOwnerMatchScoreAllyTeam), enemy: num(pp.partyOwnerMatchScoreEnemyTeam ?? p.partyOwnerMatchScoreEnemyTeam), provisioning: mp.provisioningFlow || p.provisioningFlow || null, + partyState: pp.partyState || p.partyState || null, }; } catch { return null; @@ -65,7 +69,9 @@ export class ValorantAdapter implements GameAdapter { private auth: Auth | null = null; private authAt = 0; private presence: Presence | null = null; - private match: { id: string; matchId: string; startedAt: number; ally: number; enemy: number } | null = null; + private match: { id: string; matchId: string; startedAt: number; ally: number; enemy: number; queue: string | null; selfAgent: string | null; players: number } | null = null; + /** 내 Riot ID (로컬 채팅 세션) */ + private selfName: string | null = null; private seenChat = new Set(); private detailQueue = new Map(); private polling = false; @@ -86,6 +92,54 @@ export class ValorantAdapter implements GameAdapter { return { connected: !!this.auth, inMatch: !!this.match, detail: this.lastErr || undefined }; } + liveGame(): LiveGame { + const p = this.presence; + const m = this.match; + const enabled = this.host.settings().games.valorant; + const queue = m?.queue ?? p?.queue ?? null; + const custom = p?.provisioning === 'CustomGame'; + const mapUrl = p?.map || null; + const map = this.host.assets.valMap(mapUrl); + const phase = !enabled + ? '연동 꺼짐' + : !this.auth + ? 'Riot 클라이언트 꺼짐' + : !p + ? '발로란트 꺼짐' + : p.state === 'INGAME' + ? '경기 중' + : p.state === 'PREGAME' + ? '요원 선택' + : p.partyState === 'MATCHMAKING' + ? '대기열' + : p.partyState === 'MATCHMADE_GAME_STARTING' + ? '경기 찾음 · 시작 중' + : '메뉴'; + const inGame = !!m && p?.state === 'INGAME'; + const roundBased = !valNoRounds(queue); + const score = inGame && p?.ally != null && p?.enemy != null ? { ally: p.ally, enemy: p.enemy } : null; + return { + game: 'valorant', + enabled, + connected: !!this.auth, + phase, + inMatch: !!m, + matchId: m?.id ?? null, + mode: custom ? '사용자 지정' : queue ? (valModeKo(queue) ?? queue) : null, + map: map?.name ?? (mapUrl ? mapUrl.split('/').pop() ?? null : null), + mapImage: map?.image ?? null, + startedAt: m?.startedAt ?? null, + round: inGame && roundBased && score ? score.ally + score.enemy + 1 : null, + score, + gameTimeSec: null, + teamKills: null, + self: this.auth ? { name: this.selfName, character: m?.selfAgent ?? null, characterImage: null, kda: null, extra: null } : null, + players: m?.players || null, + error: this.lastErr || null, + updatedAt: Date.now(), + }; + } + private async local(path: string): Promise { const lock = this.auth?.lock ?? readLockfile(riotClientLockfilePath()); if (!lock) return null; @@ -123,6 +177,8 @@ export class ValorantAdapter implements GameAdapter { } this.auth = { lock, accessToken: ent.data.accessToken, entitlement: ent.data.token, puuid: ent.data.subject, region, shard, clientVersion }; this.authAt = Date.now(); + const chat = await request(`${base}/chat/v1/session`, { headers: h, local: true }).catch(() => null); + if (chat?.data?.game_name) this.selfName = `${chat.data.game_name}#${chat.data.game_tag ?? ''}`; log.info(`Riot 클라이언트 연결 (region=${region}, shard=${shard})`); return this.auth; } @@ -173,7 +229,8 @@ export class ValorantAdapter implements GameAdapter { if (!p) return; if (p.state === 'INGAME' && !this.match) await this.beginMatch(a, p); else if (p.state !== 'INGAME' && this.match && prev?.state === 'INGAME') this.endMatch(); - else if (this.match && p.ally !== null && p.enemy !== null) { + else if (this.match && p.ally !== null && p.enemy !== null && !valNoRounds(this.match.queue)) { + // 데스매치 · 팀 데스매치 · 에스컬레이션은 점수가 킬 수라서 라운드로 보지 않는다 (v1.3.5: "R63 승리 · 26:37" 같은 가짜 라운드) const m = this.match; const total = p.ally + p.enemy; if (total > m.ally + m.enemy) { @@ -220,7 +277,8 @@ export class ValorantAdapter implements GameAdapter { team: pl.TeamID, character: this.host.assets.agent(pl.CharacterID), })); - this.match = { id, matchId: matchId ?? '', startedAt: now, ally: p.ally ?? 0, enemy: p.enemy ?? 0 }; + const selfAgent = players.find((pl: { puuid: string }) => pl.puuid === a.puuid)?.character?.name ?? null; + this.match = { id, matchId: matchId ?? '', startedAt: now, ally: p.ally ?? 0, enemy: p.enemy ?? 0, queue: p.queue, selfAgent: selfAgent && selfAgent !== '?' ? selfAgent : null, players: players.length }; this.seenChat.clear(); this.host.matchStarted({ id, @@ -299,6 +357,7 @@ export class ValorantAdapter implements GameAdapter { const r = await request(`${this.pd(a)}/match-details/v1/matches/${matchId}`, { headers: this.pvpHeaders(a), timeoutMs: 15000 }); if (r.status === 200 && r.data?.matchInfo) { this.detailQueue.delete(id); + await this.fillNames(a, r.data); this.applyDetails(id, r.data, a.puuid, q.startedLocal); continue; } @@ -313,6 +372,30 @@ export class ValorantAdapter implements GameAdapter { } } + /** + * 경기 상세에 선수 이름이 비어 오면(Riot 이 이름을 가림) 이름 서비스로 채운다. 내 이름은 로컬 채팅 세션 값으로. + * v1.3.5 는 빈 이름을 그대로 써서 "주인 계정 자동 연결: #" 이 남았다. + */ + private async fillNames(a: Auth, md: any): Promise { + const players: any[] = md.players || []; + const missing = players.filter((p) => !p.gameName).map((p) => p.subject); + if (!missing.length) return; + try { + const r = await request(`${this.pd(a)}/name-service/v2/players`, { method: 'PUT', headers: this.pvpHeaders(a), body: missing, timeoutMs: 8000 }); + for (const n of Array.isArray(r.data) ? r.data : []) { + const p = players.find((x) => x.subject === n.Subject); + if (p && n.GameName) { + p.gameName = n.GameName; + p.tagLine = n.TagLine ?? p.tagLine; + } + } + } catch (e) { + log.debug('이름 서비스 조회 실패', e); + } + const me = players.find((p) => p.subject === a.puuid); + if (me && !me.gameName && this.selfName) [me.gameName, me.tagLine] = this.selfName.split('#'); + } + applyDetails(id: string, md: any, selfPuuid: string, startedLocal: number): void { const res = processMatchDetails(md, selfPuuid, this.host.assets, id, startedLocal); this.host.store.replaceRounds(id, res.rounds); @@ -359,6 +442,8 @@ export function processMatchDetails(md: any, selfPuuid: string, assets: GameAsse const rr: any[] = md.roundResults || []; const n = rr.length; + // 데스매치 · 팀 데스매치 · 에스컬레이션: 경기 전체가 "라운드 1" 하나로 온다. 라운드 · 에이스(한 라운드 5킬)를 만들지 않는다 + const noRounds = valNoRounds(info.queueID); // 라운드 전투 시작 시각(게임 시간) = 킬 gameTime - roundTime const combat: (number | null)[] = rr.map((r) => { let best: number | null = null; @@ -427,7 +512,7 @@ export function processMatchDetails(md: any, selfPuuid: string, assets: GameAsse } if (r.bombPlanter) tally(r.bombPlanter).plants++; if (r.bombDefuser) tally(r.bombDefuser).defuses++; - rounds.push({ + if (!noRounds) rounds.push({ match_id: id, num, started_at: S + start, @@ -439,7 +524,7 @@ export function processMatchDetails(md: any, selfPuuid: string, assets: GameAsse enemy_score: enemy, economy: JSON.stringify(economy), }); - roundsDetail.push({ + if (!noRounds) roundsDetail.push({ num, startedAt: S + start + clockOffset, endedAt: S + end + clockOffset, @@ -485,7 +570,7 @@ export function processMatchDetails(md: any, selfPuuid: string, assets: GameAsse }); } for (const [puuid, cnt] of Object.entries(killsBy)) { - if (cnt >= 4) { + if (cnt >= 4 && !noRounds) { const last = kills.filter((k: any) => k.killer === puuid).pop(); events.push({ id: `${id}:${cnt >= 5 ? 'ace' : 'multikill'}:${num}:${puuid}`, @@ -530,7 +615,7 @@ export function processMatchDetails(md: any, selfPuuid: string, assets: GameAsse }); } const rd: RoundEndData = { round: num, win, result: roundResultKo(r.roundResult), score: { ally, enemy } }; - events.push({ + if (!noRounds) events.push({ id: `${id}:round_end:${num}`, match_id: id, game: 'valorant', @@ -570,7 +655,7 @@ export function processMatchDetails(md: any, selfPuuid: string, assets: GameAsse mode: assets.val?.modes[info.gameMode] ?? info.queueID ?? null, result: { win: selfTeamInfo ? !!selfTeamInfo.won : null, - score: { ally: selfTeamInfo?.roundsWon ?? ally, enemy: enemyTeamInfo?.roundsWon ?? enemy }, + score: noRounds ? null : { ally: selfTeamInfo?.roundsWon ?? ally, enemy: enemyTeamInfo?.roundsWon ?? enemy }, }, }; } diff --git a/app/src/core/index.ts b/app/src/core/index.ts index 1a1308b..69959f3 100644 --- a/app/src/core/index.ts +++ b/app/src/core/index.ts @@ -1,7 +1,7 @@ import fs from 'node:fs'; import path from 'node:path'; import type { FastifyInstance } from 'fastify'; -import { buildApi } from './api/server.js'; +import { buildApi, toUser } from './api/server.js'; import { Culprit } from './culprit.js'; import { Store } from './db/db.js'; import { Dictionary } from './dict/dictionary.js'; @@ -52,6 +52,10 @@ export async function startCore(opts: CoreOptions) { const store = new Store(paths().db); const bus = new Bus(); bus.setMaxListeners(50); + bus.usersProvider = () => { + const acc = store.listAccounts(); + return store.listUsers().map((u) => toUser(u, acc)); + }; const timeline = new Timeline(store); const dict = new Dictionary(store, opts.resourcesDir, () => S().dictionary.packs); dict.seed(); @@ -75,7 +79,9 @@ export async function startCore(opts: CoreOptions) { }, matchAt: (ts) => games.liveMatchAt(ts), }); - const announcer = new Announcer(paths().tts, opts.resourcesDir); + const announcer = new Announcer(paths().tts, opts.resourcesDir, async (src, dst, tempo) => { + await worker.request('tempo', { src, dst, tempo }, 120000); + }); const bot: Bot = new Bot(store, recorder, announcer, bus, S, (gid) => { if (!S().discord.guildId) settings.update({ discord: { guildId: gid } }); }); diff --git a/app/src/core/settings.ts b/app/src/core/settings.ts index ec71553..26d4284 100644 --- a/app/src/core/settings.ts +++ b/app/src/core/settings.ts @@ -17,6 +17,8 @@ export interface Settings { ttsText: string; ttsOnNewMember: boolean; ttsVoice: string; + /** 녹음 안내 말 속도 0.1~2.0 (1.0 = 보통) */ + ttsRate: number; }; games: { valorant: boolean; @@ -94,6 +96,7 @@ export function defaultSettings(): Settings { ttsText: DEFAULT_TTS_TEXT, ttsOnNewMember: true, ttsVoice: 'ko-KR-SunHiNeural', + ttsRate: 1, }, games: { valorant: true, diff --git a/app/src/core/stt/pipeline.ts b/app/src/core/stt/pipeline.ts index 2a3d549..5cec10b 100644 --- a/app/src/core/stt/pipeline.ts +++ b/app/src/core/stt/pipeline.ts @@ -5,10 +5,18 @@ import type { Settings } from '../settings.js'; import type { Timeline } from '../timeline.js'; import type { Bus } from '../util/events.js'; import { logger } from '../util/log.js'; +import { removeInsertedSilence } from '../discord/ogg.js'; import { WorkerClient, WorkerError, type TranscribeResult } from './worker.js'; const log = logger('stt'); +const NOISE_REASON: Record = { + vad: '목소리 없음', + no_speech: '말소리 아님', + hallucination: '잡음에서 지어낸 문장', + repetition: '같은 말만 반복', +}; + type Slot = 'realtime' | 'precise'; interface Job { id: string; @@ -132,6 +140,8 @@ export class SttPipeline { /** 시작 시 미처리분 복구 */ resumePending(): void { + this.purgeOldNoise(); + this.repairOldAudio(); const rows = this.store.pendingUtterances(); if (rows.length) log.info(`미처리 발화 ${rows.length}개 다시 대기열에 넣음`); for (const r of rows) this.enqueue(r.id, 'realtime', 5); @@ -270,11 +280,77 @@ export class SttPipeline { model: r.model, status: slot, }); + if (r.noise) this.onNoise(u, r, slot); if (!r.noise && r.lufs !== null && r.duration_s >= 1) this.store.updateGainProfile(u.user_id, r.lufs); if (r.text) this.store.hitDict(r.words.map((w) => w.w)); this.emit(u.id); } + /** + * 잡음 발화: 사이트에 보이지 않고(타임라인 조회에서 뺌) 음성 파일도 지운다. 로그에는 "잡음"으로 남긴다. + * 경기 중 실시간 모델 결과는 경기 뒤 정밀 모델이 다시 보므로 그때까지 파일을 남긴다 (목소리 없음(VAD)은 모델과 상관없어 바로 지움). + */ + private onNoise(u: UtteranceRow, r: TranscribeResult, slot: Slot): void { + const s = this.settings().stt; + const recheck = slot === 'realtime' && r.noise_reason !== 'vad' && this.inMatch && s.reprocessAfterMatch && s.preciseModel !== s.realtimeModel; + const name = this.store.getUser(u.user_id)?.name ?? u.user_id; + const dur = ((u.ended_at - u.started_at) / 1000).toFixed(1); + const why = NOISE_REASON[r.noise_reason ?? ''] ?? r.noise_reason ?? '?'; + const heard = r.raw_text ? `, 인식 "${r.raw_text.slice(0, 60)}"` : ''; + if (recheck) { + log.info(`잡음 발화 ${u.id} (${name}, ${dur}초, ${why}${heard}) · 경기 뒤 정밀 모델로 다시 확인`); + return; + } + this.deleteAudio(u); + log.info(`잡음 발화 ${u.id} 숨김 · 음성 파일 삭제 (${name}, ${dur}초, ${why}${heard})`); + } + + private deleteAudio(u: UtteranceRow): void { + if (u.audio_path) { + try { + fs.rmSync(u.audio_path, { force: true }); + } catch (e) { + log.warn(`잡음 파일 삭제 실패 ${u.audio_path}`, e); + return; + } + } + this.store.markAudioDeleted(u.id); + } + + /** + * 한 번만: v1.3.5 이하 녹음에서 말 중간에 끼운 무음을 빼고(목소리 깨짐) 다시 변환한다. + * 사람이 고친 발화는 파일만 고치고 글은 그대로 둔다. + */ + private repairOldAudio(): void { + const KEY = 'audio_repair_v136'; + if (this.store.meta(KEY)) return; + this.store.setMeta(KEY, String(Date.now())); + const rows = this.store.db + .prepare(`SELECT rowid,* FROM utterances WHERE audio_deleted=0 AND audio_path IS NOT NULL AND noise=0 ORDER BY started_at`) + .all() as UtteranceRow[]; + let fixed = 0; + for (const u of rows) { + if (!u.audio_path || !fs.existsSync(u.audio_path)) continue; + try { + const removed = removeInsertedSilence(u.audio_path); + if (!removed) continue; + fixed++; + this.store.db.prepare('UPDATE utterances SET ended_at=ended_at-? WHERE id=?').run(removed * 20, u.id); + if (!u.corrected) this.enqueue(u.id, 'realtime', 20); + } catch (e) { + log.warn(`예전 녹음 고치기 실패 ${u.id}`, e); + } + } + if (fixed) log.info(`예전 녹음 ${fixed}개에서 말 중간에 끼운 무음을 빼고 다시 변환`); + } + + /** v1.3.5 이하에서 잡음으로 판정된 발화의 남은 파일 정리 */ + private purgeOldNoise(): void { + const rows = this.store.noiseWithAudio(); + for (const r of rows) this.deleteAudio(r); + if (rows.length) log.info(`예전 잡음 발화 ${rows.length}개의 음성 파일 삭제`); + } + private emit(id: string): void { const row = this.store.getUtterance(id); if (row) this.bus.live({ type: 'utterance.updated', data: this.timeline.utteranceItem(row) }); diff --git a/app/src/core/timeline.ts b/app/src/core/timeline.ts index daab7f9..728a20f 100644 --- a/app/src/core/timeline.ts +++ b/app/src/core/timeline.ts @@ -138,7 +138,8 @@ export class Timeline { where.push('u.started_at <= ?'); args.push(q.to); } - if (q.hideNoise) where.push('(u.noise = 0 OR u.corrected = 1)'); + // 잡음은 보여 주지 않는다 (v1.3.6~, 파일도 지움). 사람이 고친 발화는 보인다 + where.push('(u.noise = 0 OR u.corrected = 1)'); if (q.q) { const kw = q.q.trim(); if ([...kw].length >= 3) { @@ -224,7 +225,6 @@ export interface TimelineQuery { to?: number; q?: string; types?: string[]; - hideNoise?: boolean; cursor?: string; limit?: number; order?: 'asc' | 'desc'; diff --git a/app/src/core/util/events.ts b/app/src/core/util/events.ts index 527cb6a..48b2cc8 100644 --- a/app/src/core/util/events.ts +++ b/app/src/core/util/events.ts @@ -1,9 +1,13 @@ import { EventEmitter } from 'node:events'; -import type { LiveEvent } from '@gvr/shared'; +import type { LiveEvent, User } from '@gvr/shared'; /** 코어 내부 이벤트 버스. 'live' 는 사이트로 그대로 나가는 이벤트. */ export class Bus extends EventEmitter { + /** 'users.updated' 에 실을 유저 목록. 보내는 쪽은 신호만 주고 목록은 여기서 채운다 (빈 목록이 나가면 사이트에서 모든 발화가 "알 수 없음"이 됨) */ + usersProvider: (() => User[]) | null = null; + live(ev: LiveEvent): void { + if (ev.type === 'users.updated' && this.usersProvider) ev = { type: 'users.updated', data: this.usersProvider() }; this.emit('live', ev); } } diff --git a/app/src/main/api-types.ts b/app/src/main/api-types.ts index c4af119..89e9f01 100644 --- a/app/src/main/api-types.ts +++ b/app/src/main/api-types.ts @@ -1,5 +1,5 @@ // 설정 창(렌더러) ↔ Electron 메인 프로세스 IPC 계약. preload 가 window.gvr 로 노출한다. -import type { AppRole, AppUserInfo, AppUserRow, User } from '@gvr/shared'; +import type { AppRole, AppUserInfo, AppUserRow, LiveGame, User } from '@gvr/shared'; import type { AuthState } from '../core/auth.js'; import type { DiagItem } from '../core/diagnostics.js'; import type { BotState } from '../core/discord/bot.js'; @@ -66,6 +66,8 @@ export interface AppState { stt: SttStatus; relay: RelayStatus; games: { valorant: { connected: boolean; inMatch: boolean; detail?: string }; lol: { connected: boolean; inMatch: boolean; detail?: string } }; + /** 지금 게임 상태 (v1.3.6~) */ + liveGames?: LiveGame[]; counts: { utterances: number; matches: number }; excludedUsers: { id: string; name: string }[]; autoStart: boolean; @@ -91,7 +93,7 @@ export interface GvrApi { testBotToken(token?: string): Promise<{ ok: boolean; bot?: { id: string; name: string; avatar: string | null }; guilds?: { id: string; name: string }[]; error?: string }>; restartBot(): Promise<{ ok: boolean; error?: string }>; guildMembers(): Promise<{ id: string; name: string; avatar: string | null; bot: boolean; me: boolean; admin: boolean }[]>; - previewTts(text: string, voice: string): Promise<{ ok: boolean; dataUrl?: string; error?: string }>; + previewTts(text: string, voice: string, rate?: number): Promise<{ ok: boolean; dataUrl?: string; error?: string }>; gpuInfo(): Promise; models(): Promise; download(target: 'model' | 'cuda_runtime', name?: string): Promise<{ ok: boolean; error?: string }>; diff --git a/app/src/main/ipc.ts b/app/src/main/ipc.ts index 88b9312..ca74d19 100644 --- a/app/src/main/ipc.ts +++ b/app/src/main/ipc.ts @@ -4,7 +4,7 @@ import path from 'node:path'; import { toUser } from '../core/api/server.js'; import type { AppAuth, AuthState } from '../core/auth.js'; import { runDiagnostics } from '../core/diagnostics.js'; -import { synthesize } from '../core/discord/tts.js'; +import { clampRate, isOgg, render } from '../core/discord/tts.js'; import type { Core } from '../core/index.js'; import { registerDevice } from '../core/relay/client.js'; import { dirSize } from '../core/retention.js'; @@ -31,6 +31,7 @@ export function buildState(core: Core, opts: { dataDir: string; portable: boolea stt: core.stt.status, relay: core.relay.status, games: core.games.status() as AppState['games'], + liveGames: core.games.live(), counts: core.store.counts(), excludedUsers: core.store .listUsers() @@ -131,13 +132,14 @@ export function registerIpc(ctx: IpcContext) { .map((m) => ({ id: m.id, name: core.store.displayNames()[m.id] ?? m.name, avatar: m.avatar, bot: m.bot, me: m.id === meId, admin: admins.includes(m.id) })) .sort((a, b) => rank(a) - rank(b) || a.name.localeCompare(b.name, 'ko')); }, - previewTts: async (text: string, voice: string) => { + previewTts: async (text: string, voice: string, rate = 1) => { try { - const f = path.join(core.paths().tts, `preview-${Date.now()}.webm`); - await synthesize(text, voice, f); + const r = clampRate(rate); + const f = path.join(core.paths().tts, `preview-${Date.now()}.${r < 0.5 ? 'ogg' : 'webm'}`); + await render(text, voice, r, f, (src, dst, tempo) => core.worker.request('tempo', { src, dst, tempo }, 120000)); const data = fs.readFileSync(f); fs.rmSync(f, { force: true }); - return { ok: true, dataUrl: `data:audio/webm;base64,${data.toString('base64')}` }; + return { ok: true, dataUrl: `data:audio/${isOgg(f) ? 'ogg' : 'webm'};base64,${data.toString('base64')}` }; } catch (e: any) { return { ok: false, error: `음성 합성 실패: ${e.message}` }; } diff --git a/app/src/main/main.ts b/app/src/main/main.ts index 8d5124c..66abb29 100644 --- a/app/src/main/main.ts +++ b/app/src/main/main.ts @@ -94,7 +94,10 @@ function openWindow(route?: string): void { win.setMenu(null); win.on('page-title-updated', (e) => e.preventDefault()); win.loadFile(path.join(rendererDir(), 'index.html'), { hash: r }); - win.once('ready-to-show', () => win?.show()); + win.once('ready-to-show', () => { + win?.show(); + closeSplash(); + }); // 창을 닫아도 트레이에서 계속 돈다 (녹음·사이트 연결 유지) win.on('close', (e) => { if (!quitting) { @@ -104,6 +107,46 @@ function openWindow(route?: string): void { }); } +// ── 시작 창: 포터블 exe 는 풀고 켜는 데 시간이 걸린다. 큰 창이 뜨기 전까지 작은 "켜는 중" 창을 바로 띄운다 ── +let splash: BrowserWindow | null = null; + +function showSplash(): void { + const banner = path.join(brandDir(), 'banner.png'); + const img = fs.existsSync(banner) ? `data:image/png;base64,${fs.readFileSync(banner).toString('base64')}` : ''; + const html = `${img ? `` : '
'}
겜녹이를 켜는 중입니다…
`; + splash = new BrowserWindow({ + width: 480, + height: 232, + frame: false, + resizable: false, + movable: true, + center: true, + show: false, + title: '겜녹이 · 켜는 중', + icon: path.join(brandDir(), 'icon.png'), + backgroundColor: '#0b141c', + webPreferences: { sandbox: true, contextIsolation: true, nodeIntegration: false, javascript: true }, + }); + splash.once('ready-to-show', () => splash?.show()); + splash.on('closed', () => (splash = null)); + void splash.loadURL(`data:text/html;charset=utf-8,${encodeURIComponent(html)}`).catch(() => undefined); +} + +function splashText(text: string): void { + if (splash && !splash.isDestroyed()) splash.webContents.executeJavaScript(`document.getElementById('t').textContent=${JSON.stringify(text)}`).catch(() => undefined); +} + +function closeSplash(): void { + if (splash && !splash.isDestroyed()) splash.destroy(); + splash = null; +} + function updateTray(): void { if (!tray) return; if (!core) { @@ -299,6 +342,7 @@ app.whenReady().then(async () => { // 마이크 · 카메라 · 위치 · 알림 등 권한 요청은 모두 거절한다 (아이디 복사용 클립보드 쓰기만 허용) session.defaultSession.setPermissionRequestHandler((_wc, perm, cb) => cb(perm === 'clipboard-sanitized-write')); if (SMOKE) return smoke(); + if (!flag('hidden')) showSplash(); settings = new SettingsStore(dataDir, dpapiCodec()); auth = new AppAuth(settings, { version: app.getVersion(), openUrl: (u) => shell.openExternal(u) }); const a = auth; @@ -336,9 +380,14 @@ app.whenReady().then(async () => { buildTrayMenu(); pushState(); }, 1500); + splashText('로그인 확인 중…'); await first; + if (a.ok) splashText('녹음 · 음성 인식 엔진 시작 중…'); await authChain; if (!flag('hidden') || !settings.get().firstRunDone || !a.ok) openWindow(); + else closeSplash(); + // 창이 끝내 안 뜨는 경우(오류 등)에도 시작 창이 남지 않게 + setTimeout(closeSplash, 30000); if (process.env.GVR_CAPTURE_DIR) void captureScreens(process.env.GVR_CAPTURE_DIR); }); diff --git a/app/src/renderer/mock-gvr.ts b/app/src/renderer/mock-gvr.ts index 16a8826..4c7eefe 100644 --- a/app/src/renderer/mock-gvr.ts +++ b/app/src/renderer/mock-gvr.ts @@ -24,6 +24,7 @@ function defaults(): Settings { ttsText: '겜녹이가 이 음성채널을 녹음합니다. 녹음된 대화는 AI 경기 분석에 쓰일 수 있어요. 녹음을 원하지 않으시면 녹음제외 명령을 입력해 주세요.', ttsOnNewMember: true, ttsVoice: 'ko-KR-SunHiNeural', + ttsRate: 1, }, games: { valorant: true, lol: true, lolLogsDir: null }, stt: { @@ -158,6 +159,17 @@ export function createMockGvr(): GvrApi { valorant: { connected: true, inMatch: false, detail: 'Riot Client 연결됨 · 대기실' }, lol: { connected: false, inMatch: false, detail: '클라이언트 꺼짐' }, }, + liveGames: [ + { + game: 'valorant', enabled: true, connected: true, phase: '경기 중', inMatch: true, matchId: 'val-demo', mode: '경쟁전', map: '어센트', mapImage: null, + startedAt: now - 23 * 60000, round: 15, score: { ally: 8, enemy: 6 }, gameTimeSec: null, teamKills: null, + self: { name: '하늘#KR1', character: '제트', characterImage: null, kda: null, extra: null }, players: 10, error: null, updatedAt: now, + }, + { + game: 'lol', enabled: true, connected: true, phase: '로비', inMatch: false, matchId: null, mode: '솔로 랭크', map: null, mapImage: null, + startedAt: null, round: null, score: null, gameTimeSec: null, teamKills: null, self: { name: '하늘#KR1', character: null, characterImage: null, kda: null, extra: null }, players: null, error: null, updatedAt: now, + }, + ], counts: { utterances: 1824, matches: 37 }, excludedUsers: noToken ? [] : [{ id: 'u4', name: '현우' }], autoStart: false, diff --git a/app/src/renderer/styles.css b/app/src/renderer/styles.css index 2c4cb15..4ede4ac 100644 --- a/app/src/renderer/styles.css +++ b/app/src/renderer/styles.css @@ -316,3 +316,43 @@ input[type='number'].input { flex: none; padding: 7px 8px; } .admin-list { list-style: none; display: flex; flex-direction: column; gap: 6px; font-size: 13px; } .admin-list li { display: flex; gap: 8px; align-items: baseline; } .admin-list li .muted { font-size: 12px; } + +/* 지금 게임 (게임 연동 탭) */ +.live-games { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 12px; +} +.live-game { + border: 1px solid var(--line, #22313f); + border-radius: 10px; + padding: 12px 14px; + background: rgba(255, 255, 255, 0.02); +} +.live-game.in-match.valorant { + border-color: rgba(255, 70, 85, 0.55); +} +.live-game.in-match.lol { + border-color: rgba(200, 170, 110, 0.6); +} +.live-game-top { + display: flex; + align-items: center; + gap: 8px; + margin-bottom: 8px; +} +.live-game-top .badge { + margin-left: auto; +} +.live-rows { + width: 100%; + font-size: 12.5px; + border-collapse: collapse; +} +.live-rows td { + padding: 3px 0; + vertical-align: top; +} +.live-rows td:first-child { + width: 42%; +} diff --git a/app/src/renderer/tabs/DiscordTab.tsx b/app/src/renderer/tabs/DiscordTab.tsx index e1eed62..7b2ca9a 100644 --- a/app/src/renderer/tabs/DiscordTab.tsx +++ b/app/src/renderer/tabs/DiscordTab.tsx @@ -1,7 +1,7 @@ import { useEffect, useRef, useState } from 'react'; import type { GvrApi } from '../../main/api-types'; import { gvr, useAction, useApp, useLoad } from '../store'; -import { AdminOnly, Avatar, Btn, DraftInput, Err, Line, Ok, Page, Section, Select, ToggleLine, useIsAdmin } from '../ui'; +import { AdminOnly, Avatar, Btn, DraftInput, Err, Line, Ok, Page, Section, Select, Slider, ToggleLine, useIsAdmin } from '../ui'; import { errMsg, fmtClock, fmtDuration } from '../util'; type TestResult = Awaited>; @@ -248,7 +248,7 @@ function TtsPreview() { { - const r = await act.run(() => gvr.previewTts(settings.discord.ttsText, settings.discord.ttsVoice)); + const r = await act.run(() => gvr.previewTts(settings.discord.ttsText, settings.discord.ttsVoice, settings.discord.ttsRate)); if (r?.ok && r.dataUrl) { audio.current?.pause(); audio.current = new Audio(r.dataUrl); @@ -337,6 +337,9 @@ export function DiscordTab() { settings.set({ reduceMotion: e.target.checked })} /> 모션 줄이기 + {canViewLogs && ( + <> +
문제 해결
+ + 📄 사이트 로그 보기 · 내려받기 + + + )}
단축키: Space 재생 · ←/→ 이전·다음 발화 · / 검색 · Esc 닫기
); } +/** 지금 게임: 경기 중이면 "발로란트 · 경쟁전 · 어센트 · R15 8:6", 아니면 연결된 게임 상태 */ +function GamePill() { + const { overview } = useData(); + const live = (overview?.live ?? []).filter((g) => g.enabled && g.connected); + const g = live.find((x) => x.inMatch) ?? live[0]; + if (!g) return null; + const tip = liveGameRows(g) + .map(([k, v]) => `${k}: ${v}`) + .join('\n'); + return ( +
+ {GAME_NAME[g.game]} + {liveGameLine(g)} +
+ ); +} + export function SearchBox() { const [params, setParams] = useSearchParams(); const loc = useLocation(); @@ -170,6 +198,7 @@ export function Header() { 녹음 중 )} + {!locked && } {device && (
diff --git a/site/web/src/components/Icons.tsx b/site/web/src/components/Icons.tsx index 98b56b3..32f128c 100644 --- a/site/web/src/components/Icons.tsx +++ b/site/web/src/components/Icons.tsx @@ -65,6 +65,17 @@ export const IVolume = (p: SVGProps) => ( ); +export const IMute = (p: SVGProps) => ( + + + + +); +export const IDownload = (p: SVGProps) => ( + + + +); export const IUsers = (p: SVGProps) => ( diff --git a/site/web/src/components/LockOverlay.tsx b/site/web/src/components/LockOverlay.tsx index 8537a11..2e6d4e6 100644 --- a/site/web/src/components/LockOverlay.tsx +++ b/site/web/src/components/LockOverlay.tsx @@ -123,6 +123,11 @@ export function LockOverlay() { > ↻ {checking ? '확인 중…' : '지금 다시 확인'} + {auth.status === 'ok' && auth.me.canViewLogs && ( + + 📄 사이트 로그 보기 + + )} diff --git a/site/web/src/components/PlayerBar.tsx b/site/web/src/components/PlayerBar.tsx index 1c4fa39..530c8c1 100644 --- a/site/web/src/components/PlayerBar.tsx +++ b/site/web/src/components/PlayerBar.tsx @@ -6,7 +6,8 @@ import { useData } from '../store/app'; import { sfx } from '../lib/sfx'; import { fmtClock, fmtSec } from '../lib/format'; import { Avatar } from './common'; -import { IClose, ILoop, INext, IPause, IPlay, IPrev, IVolume } from './Icons'; +import { IClose, ILoop, IMute, INext, IPause, IPlay, IPrev, IVolume } from './Icons'; +import { clampVolume } from '../lib/audio'; const RATES = [1, 1.25, 1.5, 2]; @@ -51,6 +52,32 @@ function SceneLanes({ scene }: { scene: SceneInfo }) { ); } +/** 녹음 재생 음량 0~200% (아이콘을 누르면 음소거 / 되돌리기) */ +function VolumeControl() { + const cfg = useSettings(); + const v = clampVolume(cfg.playVolume); + const last = useRef(v || 1); + if (v > 0) last.current = v; + return ( +
+ + settings.set({ playVolume: Number(e.target.value) / 100 })} + aria-label="재생 음량" + style={{ ['--p' as string]: `${(v / 2) * 100}%` }} + /> + {Math.round(v * 100)}% +
+ ); +} + export function PlayerBar() { const s = usePlayer((x) => x); const cfg = useSettings(); @@ -145,6 +172,7 @@ export function PlayerBar() { + + + + +
+ )} + {info && } + {err &&
{err}
} + + ); +} + +const STATUS: Record = { pending: '변환 대기', realtime: '실시간 모델', precise: '정밀 모델', failed: '인식 실패' }; +const DELETED: Record = { retention: '보관 기간이 지나 삭제됨', noise: '잡음이라 삭제됨', missing: '파일을 찾을 수 없음' }; + +function fmtBytes(n: number): string { + return n >= 1024 * 1024 ? `${(n / 1024 / 1024).toFixed(2)} MB` : `${(n / 1024).toFixed(1)} KB`; +} + +function InfoDialog({ item, onError }: { item: UtteranceItem; onError: (m: string) => void }) { + const { userById } = useData(); + const [info, setInfo] = useState(null); + const [failed, setFailed] = useState(null); + const [copied, setCopied] = useState(null); + + useEffect(() => { + let alive = true; + api + .utteranceInfo(item.id) + .then((r) => alive && setInfo(r)) + .catch((e) => { + if (!alive) return; + // v1.3.5 이하 앱에는 이 기능이 없다 + setFailed(e instanceof ApiError && e.status === 404 ? '게임 PC 의 겜녹이가 예전 버전입니다. v1.3.6 이상으로 업데이트하면 볼 수 있습니다.' : '정보를 받지 못했습니다.'); + }); + const onKey = (e: KeyboardEvent) => e.key === 'Escape' && closeInfo(); + window.addEventListener('keydown', onKey); + return () => { + alive = false; + window.removeEventListener('keydown', onKey); + }; + }, [item.id]); + + const doCopy = (label: string, v: string) => { + void copy(v); + setCopied(label); + setTimeout(() => setCopied(null), 1500); + }; + const user = userById(item.userId); + const rows: [string, ReactNode][] = info + ? [ + ['말한 사람', user?.name ?? info.userId], + ['원본 파일', {info.fileName ?? '-'}], + [ + '경로 (게임 PC)', + info.path ? ( + + {info.path}{' '} + + + ) : ( + '-' + ), + ], + ['파일 상태', info.deleted ? DELETED[info.deleted] : info.sizeBytes != null ? `있음 · ${fmtBytes(info.sizeBytes)}` : '-'], + ['녹음 시각', `${fmtWhen(info.startedAt)} · ${(info.durationMs / 1000).toFixed(1)}초`], + ['음성채널', info.channel ?? '-'], + ['경기', info.matchId ?? '경기 밖'], + ['인식', `${STATUS[info.status] ?? info.status}${info.model ? ` · ${info.model}` : ''}${info.confidence != null ? ` · 신뢰도 ${Math.round(info.confidence * 100)}%` : ''}`], + ['원래 인식 결과', info.rawText ?? '-'], + ...(info.corrected ? ([['교정', '사람이 고친 글']] as [string, ReactNode][]) : []), + ['음량', `${info.lufs != null ? `${info.lufs.toFixed(1)} LUFS` : '-'} · 재생 보정 ${info.gainDb != null ? `${info.gainDb > 0 ? '+' : ''}${info.gainDb.toFixed(1)} dB` : '-'}`], + ['발화 ID', {info.id}], + ] + : []; + + return ( +
+
e.stopPropagation()}> +
+ 발화 자세한 정보 + +
+ {failed &&

{failed}

} + {!info && !failed &&

불러오는 중…

} + {info && ( +
+ {rows.map(([k, v]) => ( +
+
{k}
+
{v}
+
+ ))} +
+ )} +
+ + +
+
+
+ ); +} diff --git a/site/web/src/components/UtteranceRow.tsx b/site/web/src/components/UtteranceRow.tsx index 0a5405a..8128bef 100644 --- a/site/web/src/components/UtteranceRow.tsx +++ b/site/web/src/components/UtteranceRow.tsx @@ -7,6 +7,7 @@ import { sfx } from '../lib/sfx'; import { realTip } from '../lib/format'; import { Avatar, TimeCell } from './common'; import { IEdit } from './Icons'; +import { openUttMenu } from './UttMenu'; const STATUS: Record = { realtime: ['실시간', 'st-rt'], @@ -152,6 +153,12 @@ export const UtteranceRow = memo(function UtteranceRow({ item, variant = 'full', if (active && player.state.mode === 'single') player.toggle(); else void player.play(item); }; + // 우클릭: 재생 · 자세한 정보(원본 ogg 이름 · 경로) · 다운로드 + const menu = (e: MouseEvent) => { + if (editing) return; + e.preventDefault(); + openUttMenu(item, e.clientX, e.clientY); + }; const edit = (e: MouseEvent) => { e.stopPropagation(); sfx('click'); @@ -178,7 +185,7 @@ export const UtteranceRow = memo(function UtteranceRow({ item, variant = 'full', if (variant === 'compact') { return ( -
+
{timeText ?? item.time.primary} @@ -199,7 +206,7 @@ export const UtteranceRow = memo(function UtteranceRow({ item, variant = 'full', } return ( -
+
diff --git a/site/web/src/lib/api.ts b/site/web/src/lib/api.ts index d95c48d..7facae8 100644 --- a/site/web/src/lib/api.ts +++ b/site/web/src/lib/api.ts @@ -10,9 +10,12 @@ import type { UserProfile, User, UtteranceItem, + UtteranceInfo, GameType, } from '@gvr/shared'; +import { reportClient } from './report'; + /** 전역 신호: 401 → 로그인 화면, 503 device_offline → 잠금 화면 */ type Signal = 'unauthorized' | 'not_member' | 'device_offline'; const listeners = new Set<(s: Signal) => void>(); @@ -55,12 +58,16 @@ async function request(path: string, init: RequestInit = {}): Promise { if (res.status === 401) emit('unauthorized'); else if (res.status === 403 && code === 'not_member') emit('not_member'); else if (res.status === 503 && code === 'device_offline') emit('device_offline'); + // 게임 PC 쪽 오류 · 시간 초과는 사이트 로그에도 남긴다 (게임 PC 꺼짐은 서버가 이미 남김) + else if (res.status >= 500) reportClient('error', `요청 실패 ${res.status} ${code}: ${init.method ?? 'GET'} ${path.split('?')[0]}`); throw new ApiError(res.status, code); } export interface Me { user: { id: string; name: string; avatar: string | null }; isOwner: boolean; + /** 사이트 로그를 볼 수 있는지 (관리자 · 최고 관리자, v1.3.6~) */ + canViewLogs?: boolean; } export interface StatusResponse { device: DeviceStatus; @@ -75,7 +82,6 @@ export interface TimelineQuery { to?: number; q?: string; types?: string[]; - hideNoise?: boolean; cursor?: string | null; limit?: number; order?: 'asc' | 'desc'; @@ -117,7 +123,6 @@ export const api = { to: q.to, q: q.q, types: q.types?.length ? q.types.join(',') : undefined, - hideNoise: q.hideNoise ? 1 : undefined, cursor: q.cursor, limit: q.limit ?? 100, order: q.order, @@ -152,6 +157,7 @@ export const api = { if (res.status === 503 && b.error === 'device_offline') emit('device_offline'); return { ok: false, status: res.status, error: b.error ?? 'error', message: b.message ?? '분석을 시작하지 못했습니다' }; }, + utteranceInfo: (id: string) => request(`/api/utterances/${encodeURIComponent(id)}/info`), correct: (id: string, text: string) => request(`/api/utterances/${encodeURIComponent(id)}`, { method: 'PATCH', body: JSON.stringify({ text }) }), }; diff --git a/site/web/src/lib/audio.ts b/site/web/src/lib/audio.ts index 4c3a624..03d7992 100644 --- a/site/web/src/lib/audio.ts +++ b/site/web/src/lib/audio.ts @@ -1,3 +1,5 @@ +import { settings } from '../store/settings'; + /** 공용 AudioContext 와 출력 체인 (플레이어 + 효과음) */ let ctx: AudioContext | null = null; let playerBus: GainNode | null = null; @@ -14,6 +16,11 @@ export function audioCtx(): AudioContext { limiter.attack.value = 0.002; limiter.release.value = 0.12; playerBus = ctx.createGain(); + // 녹음 재생 음량 (플레이어 막대의 음량 조절). 리미터 앞에서 바꿔 크게 키워도 찢어지지 않는다 + playerBus.gain.value = clampVolume(settings.get().playVolume); + settings.subscribe(() => { + if (playerBus) playerBus.gain.value = clampVolume(settings.get().playVolume); + }); playerBus.connect(limiter).connect(ctx.destination); sfxBus = ctx.createGain(); sfxBus.connect(ctx.destination); @@ -35,4 +42,6 @@ export function sfxOutput(): GainNode { return sfxBus!; } +export const clampVolume = (v: unknown) => (typeof v === 'number' && isFinite(v) ? Math.min(2, Math.max(0, v)) : 1); + export const dbToGain = (db: number) => Math.pow(10, db / 20); diff --git a/site/web/src/lib/filters.ts b/site/web/src/lib/filters.ts index c56414b..30cbb96 100644 --- a/site/web/src/lib/filters.ts +++ b/site/web/src/lib/filters.ts @@ -11,7 +11,6 @@ export interface Filters { to: number | undefined; q: string; types: TypeGroup[]; - hideNoise: boolean; order: 'asc' | 'desc' | null; } @@ -28,7 +27,6 @@ export function parseFilters(p: URLSearchParams): Filters { to: num(p.get('to')), q: p.get('q') ?? '', types: (p.get('types')?.split(',').filter(Boolean) ?? []) as TypeGroup[], - hideNoise: p.get('hideNoise') === '1', order: order === 'asc' || order === 'desc' ? order : null, }; } @@ -42,7 +40,6 @@ export function writeFilters(f: Filters): URLSearchParams { if (f.to != null) p.set('to', String(f.to)); if (f.q) p.set('q', f.q); if (f.types.length) p.set('types', f.types.join(',')); - if (f.hideNoise) p.set('hideNoise', '1'); if (f.order) p.set('order', f.order); return p; } @@ -59,7 +56,6 @@ export function toQuery(f: Filters): TimelineQuery { to: f.to, q: f.q || undefined, types: f.types, - hideNoise: f.hideNoise, order: effectiveOrder(f), }; } @@ -76,7 +72,7 @@ export function matchesFilter(it: TimelineItem, f: Filters): boolean { const kw = f.q.trim().toLowerCase(); if (it.kind === 'utterance') { if (f.users.length && !f.users.includes(it.userId)) return false; - if (f.hideNoise && it.noise) return false; + if (it.noise) return false; // 잡음은 보여 주지 않는다 if (kw && !(it.text ?? '').toLowerCase().includes(kw)) return false; } else { if (f.users.length && it.userId && !f.users.includes(it.userId)) return false; diff --git a/site/web/src/lib/report.ts b/site/web/src/lib/report.ts new file mode 100644 index 0000000..567f9b2 --- /dev/null +++ b/site/web/src/lib/report.ts @@ -0,0 +1,29 @@ +/** 브라우저 오류를 사이트 로그([web])에 남긴다. 같은 내용은 30초에 한 번만 */ +const recent = new Map(); + +export function reportClient(level: 'warn' | 'error', message: string, detail?: string): void { + const key = `${level}:${message}`; + const now = Date.now(); + if ((recent.get(key) ?? 0) > now - 30000) return; + recent.set(key, now); + if (recent.size > 200) recent.clear(); + void fetch('/site/client-log', { + method: 'POST', + credentials: 'include', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ level, message: message.slice(0, 500), detail: detail?.slice(0, 2000), page: location.pathname + location.search }), + keepalive: true, + }).catch(() => undefined); +} + +let installed = false; +export function installErrorReporting(): void { + if (installed) return; + installed = true; + window.addEventListener('error', (e) => reportClient('error', `화면 오류: ${e.message}`, e.error?.stack ?? `${e.filename}:${e.lineno}:${e.colno}`)); + window.addEventListener('unhandledrejection', (e) => { + const r = e.reason; + if (r?.name === 'AbortError') return; + reportClient('error', `처리 안 된 오류: ${r?.message ?? String(r)}`, r?.stack); + }); +} diff --git a/site/web/src/pages/LogsPage.tsx b/site/web/src/pages/LogsPage.tsx new file mode 100644 index 0000000..3f8d9dd --- /dev/null +++ b/site/web/src/pages/LogsPage.tsx @@ -0,0 +1,121 @@ +import { useCallback, useEffect, useMemo, useState } from 'react'; +import { useAuth } from '../store/app'; +import { Brand } from '../components/common'; + +/** + * 사이트 로그 (관리자만). 게임 PC 와 연결이 끊겨 사이트가 잠겨 있어도 볼 수 있게 잠금 화면 밖에서 그린다. + * exe 로그(게임 PC 의 GVR-Data\logs\gvr-날짜.log)와 이 로그를 같이 보내면 대부분의 문제를 찾을 수 있다. + */ +type Level = 'all' | 'warn' | 'error'; +const LEVEL_RE: Record = { all: /./, warn: /^\S+ (WARN|ERROR|FATAL)/, error: /^\S+ (ERROR|FATAL)/ }; + +export function LogsPage() { + const { auth } = useAuth(); + const [days, setDays] = useState<{ date: string; size: number }[] | null>(null); + const [date, setDate] = useState(null); + const [text, setText] = useState(''); + const [err, setErr] = useState(null); + const [level, setLevel] = useState('all'); + const [q, setQ] = useState(''); + const [live, setLive] = useState(true); + + useEffect(() => { + fetch('/site/logs', { credentials: 'include' }) + .then(async (r) => { + if (r.status === 403) throw new Error('사이트 로그는 관리자만 볼 수 있습니다.'); + if (!r.ok) throw new Error(`로그 목록을 받지 못했습니다 (${r.status})`); + const b = (await r.json()) as { days: { date: string; size: number }[] }; + setDays(b.days); + setDate((d) => d ?? b.days[0]?.date ?? null); + }) + .catch((e) => setErr(e.message)); + }, []); + + const load = useCallback(async () => { + if (!date) return; + const r = await fetch(`/site/logs/${date}`, { credentials: 'include', cache: 'no-store' }); + if (r.ok) setText(await r.text()); + }, [date]); + + useEffect(() => { + void load(); + // 오늘 로그는 5초마다 새로 받는다 + if (!live || date !== days?.[0]?.date) return; + const t = window.setInterval(() => void load(), 5000); + return () => window.clearInterval(t); + }, [load, live, date, days]); + + // 줄 단위로 나누되, 오류 스택(들여쓴 줄)은 위 줄에 붙인다 + const entries = useMemo(() => { + const out: string[] = []; + for (const line of text.split('\n')) { + if (!line) continue; + if (line.startsWith(' ') && out.length) out[out.length - 1] += '\n' + line; + else out.push(line); + } + return out; + }, [text]); + const shown = useMemo(() => { + const kw = q.trim().toLowerCase(); + return entries.filter((e) => LEVEL_RE[level].test(e) && (!kw || e.toLowerCase().includes(kw))).reverse(); + }, [entries, level, q]); + + const name = auth.status === 'ok' ? auth.me.user.name : ''; + return ( +
+
+ + + +

사이트 로그

+ {name} +
+

+ 사이트 서버(gvr.tkrmagid.kr)가 남긴 기록입니다. 게임 PC 프로그램과 연결이 끊겨도 볼 수 있습니다. 문제를 알릴 때는 이 로그와 게임 PC 의 exe 로그( + GVR-Data\logs\gvr-날짜.log)를 같이 보내 주세요. 시각은 UTC(한국 시각 -9시간)입니다. +

+ {err &&
{err}
} + {days && ( +
+ +
+ {(['all', 'warn', 'error'] as Level[]).map((l) => ( + + ))} +
+ setQ(e.target.value)} placeholder="찾기 (예: 게임 PC, 503, 범인찾기)" /> + {date === days[0]?.date && ( + + )} + {date && ( + + ⬇ 내려받기 (gvr-site-{date}.log) + + )} +
+ )} + {days && !days.length &&

아직 로그가 없습니다.

} +
+ {shown.map((e, i) => { + const lv = /^\S+ (\w+)/.exec(e)?.[1] ?? 'INFO'; + return ( +
+              {e}
+            
+ ); + })} + {days && date && !shown.length &&

조건에 맞는 줄이 없습니다.

} +
+
+ ); +} diff --git a/site/web/src/pages/Sidebar.tsx b/site/web/src/pages/Sidebar.tsx index a6a3192..a7f48cf 100644 --- a/site/web/src/pages/Sidebar.tsx +++ b/site/web/src/pages/Sidebar.tsx @@ -105,12 +105,7 @@ export function Sidebar({ f, update, users, matches, detail }: { f: Filters; upd
- -
@@ -151,9 +146,6 @@ export function MobileFilters({ f, update, users, matches }: { f: Filters; updat {t.icon} {t.label} ))} -
); } diff --git a/site/web/src/pages/TimelinePage.tsx b/site/web/src/pages/TimelinePage.tsx index c1c57cb..5644692 100644 --- a/site/web/src/pages/TimelinePage.tsx +++ b/site/web/src/pages/TimelinePage.tsx @@ -13,6 +13,7 @@ import { Avatar, ErrorBox, Spinner } from '../components/common'; import { IWaves } from '../components/Icons'; import { MobileFilters, Sidebar } from './Sidebar'; import { TalkBars } from '../components/TalkBars'; +import { GAME_NAME, liveGameRows } from '@gvr/shared'; function NowPlayingCard() { const item = usePlayer((s) => (s.mode === 'single' ? s.item : null)); @@ -143,6 +144,7 @@ function RightPanel({ items, detail }: { items: TimelineItem[]; detail: MatchDet )}
)} + {!detail && }
{detail ? '이 경기 발화량' : '지금 목록의 발화량'}
@@ -151,6 +153,37 @@ function RightPanel({ items, detail }: { items: TimelineItem[]; detail: MatchDet ); } +/** 게임 PC 에 지금 연결된 게임 · 진행 중인 경기 */ +function LiveGamesCard() { + const { overview } = useData(); + const live = (overview?.live ?? []).filter((g) => g.enabled); + if (!overview?.live) return null; + return ( +
+
게임 상태
+ {!live.length &&
게임 연동이 꺼져 있습니다.
} + {live.map((g) => ( +
+
+ + {GAME_NAME[g.game]} + {g.phase} +
+ {(g.connected || g.inMatch) && + liveGameRows(g) + .slice(1) + .map(([k, v]) => ( +
+ {k} + {v} +
+ ))} +
+ ))} +
+ ); +} + export function TimelinePage() { const [params, setParams] = useSearchParams(); const f = useMemo(() => parseFilters(params), [params]); @@ -277,7 +310,16 @@ export function TimelinePage() { else if (it.type === 'kill') sfx('kill'); else if (it.type === 'round_end') sfx('round'); } else if (e.type === 'utterance.updated') { - setItems((prev) => prev.map((p) => (p.id === e.data.id ? e.data : p))); + const it = e.data; + // 잡음으로 판정되면 목록에서 뺀다. 경기 뒤 정밀 변환에서 말이 나오면 다시 넣는다 + if (!matchesFilter(it, f)) setItems((prev) => prev.filter((p) => p.id !== it.id)); + else + setItems((prev) => { + if (prev.some((p) => p.id === it.id)) return prev.map((p) => (p.id === it.id ? it : p)); + const i = prev.findIndex((p) => (order === 'desc' ? p.ts < it.ts : p.ts > it.ts)); + if (i < 0) return order === 'asc' && next ? prev : [...prev, it]; + return [...prev.slice(0, i), it, ...prev.slice(i)]; + }); } }); diff --git a/site/web/src/store/app.tsx b/site/web/src/store/app.tsx index 3a34cd5..9b45008 100644 --- a/site/web/src/store/app.tsx +++ b/site/web/src/store/app.tsx @@ -140,8 +140,17 @@ export function DataProvider({ children }: { children: ReactNode }) { }; }, [epoch, locked]); useLive((e) => { - if (e.type === 'users.updated') setOverview((o) => (o ? { ...o, users: e.data } : o)); + if (e.type === 'users.updated') { + // v1.3.5 이하 앱은 빈 목록을 보낸다: 그대로 쓰면 모든 발화가 "알 수 없음"이 되니 다시 받아 온다 + if (e.data.length) setOverview((o) => (o ? { ...o, users: e.data } : o)); + else + api + .users() + .then((users) => setOverview((o) => (o ? { ...o, users } : o))) + .catch(() => {}); + } if (e.type === 'recording.state') setOverview((o) => (o ? { ...o, recording: e.data } : o)); + if (e.type === 'games.state') setOverview((o) => (o ? { ...o, live: e.data } : o)); }); const users = overview?.users ?? []; const map = useMemo(() => new Map(users.map((u) => [u.id, u])), [users]); diff --git a/site/web/src/store/settings.ts b/site/web/src/store/settings.ts index 4528454..2ce0f44 100644 --- a/site/web/src/store/settings.ts +++ b/site/web/src/store/settings.ts @@ -8,6 +8,8 @@ export interface Settings { rate: number; continuous: boolean; normalize: boolean; + /** 녹음 재생 음량 0..2 (1 = 원래 크기) */ + playVolume: number; } const KEY = 'gvr.settings.v1'; @@ -18,6 +20,7 @@ const DEFAULTS: Settings = { rate: 1, continuous: true, normalize: true, + playVolume: 1, }; function load(): Settings { diff --git a/site/web/src/styles.css b/site/web/src/styles.css index 11c9c98..70f8c3d 100644 --- a/site/web/src/styles.css +++ b/site/web/src/styles.css @@ -3430,3 +3430,316 @@ button.match:hover { .cu-row { grid-template-columns: 34px 1fr auto; } .cu-row .cu-st { grid-column: 2 / -1; justify-self: start; } } + +/* ── 재생 음량 (플레이어 막대) ── */ +.pb-vol { + display: flex; + align-items: center; + gap: 6px; + flex: none; +} +.pb-vol .icon-btn { + color: var(--muted); +} +.pb-vol .icon-btn.muted-on { + color: var(--accent); +} +.pb-vol input[type='range'] { + -webkit-appearance: none; + appearance: none; + width: 90px; + height: 4px; + border-radius: 2px; + background: linear-gradient(90deg, var(--mint, #14c1b7) var(--p, 50%), #2a3a4a var(--p, 50%)); + cursor: pointer; +} +.pb-vol input[type='range']::-webkit-slider-thumb { + -webkit-appearance: none; + width: 12px; + height: 12px; + border-radius: 50%; + background: #fff; +} +.pb-vol input[type='range']::-moz-range-thumb { + width: 12px; + height: 12px; + border: 0; + border-radius: 50%; + background: #fff; +} +.pb-vol-n { + font-size: 11.5px; + width: 36px; + color: var(--muted); +} +@media (max-width: 720px) { + .pb-vol input[type='range'], + .pb-vol-n { + display: none; + } +} + +/* ── 발화 우클릭 메뉴 · 자세한 정보 ── */ +.ctx-menu { + position: fixed; + z-index: 80; + min-width: 210px; + background: #0f1923; + border: 1px solid #2c3f52; + border-radius: 10px; + padding: 5px; + box-shadow: 0 18px 48px rgba(0, 0, 0, 0.55); +} +.ctx-menu button { + display: flex; + align-items: center; + gap: 9px; + width: 100%; + padding: 8px 10px; + border-radius: 7px; + font-size: 13px; + color: var(--text, #e6edf3); + text-align: left; +} +.ctx-menu button:hover:not(:disabled) { + background: #1b2a38; +} +.ctx-menu button:disabled { + opacity: 0.4; + cursor: default; +} +.ctx-ic { + width: 14px; + text-align: center; + font-size: 13px; +} +.ctx-dim { + position: fixed; + inset: 0; + z-index: 90; + background: rgba(3, 8, 12, 0.6); + display: flex; + align-items: center; + justify-content: center; + padding: 16px; +} +.ctx-dialog { + width: min(620px, 100%); + max-height: 90vh; + overflow: auto; + background: #0f1923; + border: 1px solid #2c3f52; + border-radius: 14px; + padding: 16px 18px; + box-shadow: 0 24px 70px rgba(0, 0, 0, 0.6); +} +.ctx-head { + display: flex; + align-items: center; + justify-content: space-between; + margin-bottom: 10px; +} +.ctx-rows { + margin: 0; + font-size: 13px; +} +.ctx-rows > div { + display: grid; + grid-template-columns: 120px 1fr; + gap: 10px; + padding: 6px 0; + border-bottom: 1px solid #1c2a37; +} +.ctx-rows dt { + color: var(--muted); +} +.ctx-rows dd { + margin: 0; + word-break: break-all; +} +.ctx-rows .path { + font-size: 12px; +} +.ctx-foot { + display: flex; + gap: 8px; + justify-content: flex-end; + margin-top: 14px; +} +.ctx-toast { + position: fixed; + left: 50%; + bottom: calc(var(--player-h) + 16px); + transform: translateX(-50%); + z-index: 95; + background: #2a1418; + border: 1px solid #5a2630; + color: #ffb3bb; + padding: 8px 14px; + border-radius: 8px; + font-size: 13px; +} + +/* ── 사이트 로그 (/logs) ── */ +.logs-page { + min-height: 100vh; + padding: 18px 26px 40px; + max-width: 1500px; + margin: 0 auto; +} +.logs-head { + display: flex; + align-items: center; + gap: 16px; + margin-bottom: 8px; +} +.logs-head h1 { + font-size: 18px; + margin: 0; +} +.logs-back { + display: flex; +} +.logs-help { + color: var(--muted); + font-size: 13px; + line-height: 1.6; + margin: 0 0 14px; +} +.logs-err { + background: #2a1418; + border: 1px solid #5a2630; + color: #ffb3bb; + padding: 10px 14px; + border-radius: 8px; + margin-bottom: 14px; +} +.logs-bar { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 10px; + margin-bottom: 12px; +} +.logs-bar select, +.logs-q { + background: #0f1923; + border: 1px solid #2c3f52; + color: inherit; + border-radius: 8px; + padding: 7px 10px; + font-size: 13px; +} +.logs-q { + flex: 1; + min-width: 200px; +} +.logs-seg { + display: flex; + gap: 6px; +} +.logs-live { + font-size: 13px; + color: var(--muted); + display: flex; + align-items: center; + gap: 5px; +} +.logs-list { + background: #0a121a; + border: 1px solid #1c2a37; + border-radius: 10px; + padding: 8px 0; + font-size: 12.5px; +} +.logs-list pre { + margin: 0; + padding: 3px 14px; + white-space: pre-wrap; + word-break: break-all; + font: inherit; +} +.logs-list pre:hover { + background: #111d28; +} +.lg-warn { + color: #ffd27a; +} +.lg-error, +.lg-fatal { + color: #ff8a95; +} +.lg-info { + color: #c9d4de; +} + +/* ── 지금 게임 (헤더 · 타임라인 오른쪽) ── */ +.game-pill { + display: flex; + align-items: center; + gap: 6px; + font-size: 12px; + border-radius: 999px; + padding: 5px 10px; + white-space: nowrap; + border: 1px solid #2c3f52; + color: #b9c6d2; + max-width: 260px; + min-width: 0; + flex-shrink: 1; + overflow: hidden; +} +.me-nm { + white-space: nowrap; +} +.game-pill .gp-name { + font-weight: 700; +} +.game-pill .gp-txt { + overflow: hidden; + text-overflow: ellipsis; +} +.game-pill.valorant.in { + border-color: rgba(255, 70, 85, 0.6); + color: #ffd0d4; +} +.game-pill.lol.in { + border-color: rgba(200, 170, 110, 0.6); + color: #f0e2c0; +} +@media (max-width: 1500px) { + .game-pill .gp-txt { + display: none; + } +} +.live-g + .live-g { + margin-top: 10px; + padding-top: 10px; + border-top: 1px solid #1c2a37; +} +.live-g-top { + display: flex; + align-items: center; + gap: 7px; + font-size: 13px; +} +.live-g-top .dim { + margin-left: auto; +} +.ldot { + width: 8px; + height: 8px; + border-radius: 50%; + background: #4d5d6c; +} +.ldot.mid { + background: #e3b341; +} +.ldot.on { + background: #45d39a; + box-shadow: 0 0 6px rgba(69, 211, 154, 0.6); +} +.live-g.valorant.in .ldot.on { + background: var(--accent); + box-shadow: 0 0 6px rgba(255, 70, 85, 0.6); +} diff --git a/site/web/vite.config.ts b/site/web/vite.config.ts index 7c2d045..9026f18 100644 --- a/site/web/vite.config.ts +++ b/site/web/vite.config.ts @@ -10,6 +10,7 @@ const proxy = { '/auth': { target: backend, changeOrigin: false }, '/game-assets': { target: backend, changeOrigin: false }, '/mock': { target: backend, changeOrigin: false }, + '/site': { target: backend, changeOrigin: false }, '/ws': { target: backend.replace(/^http/, 'ws'), ws: true }, }; diff --git a/worker/gvr_worker/main.py b/worker/gvr_worker/main.py index 46bd0a3..098635c 100644 --- a/worker/gvr_worker/main.py +++ b/worker/gvr_worker/main.py @@ -80,6 +80,15 @@ def build_server(writer: Writer) -> Server: raise WorkerError("bad_request", "since_ms 는 숫자(Unix ms) 또는 null 이어야 합니다") return read(require(req, "logs_dir"), since) + @server.route("tempo", "thread") + def tempo(req: dict[str, Any], ctx: Context) -> dict[str, Any]: + from .tempo import change_tempo + + t = req.get("tempo") + if not isinstance(t, (int, float)): + raise WorkerError("bad_request", "tempo 는 숫자여야 합니다") + return change_tempo(require(req, "src"), require(req, "dst"), float(t)) + @server.route("train", "thread") def train(req: dict[str, Any], ctx: Context) -> dict[str, Any]: return run_finetune(req, ctx) diff --git a/worker/gvr_worker/noise.py b/worker/gvr_worker/noise.py index 33961d4..7ff25d1 100644 --- a/worker/gvr_worker/noise.py +++ b/worker/gvr_worker/noise.py @@ -95,7 +95,6 @@ class SegInfo: @dataclass class Thresholds: - vad_ratio: float vad_min_speech_s: float no_speech_prob: float logprob: float @@ -109,7 +108,6 @@ class Thresholds: def thresholds(sensitivity: float) -> Thresholds: s = min(max(float(sensitivity), 0.0), 1.0) return Thresholds( - vad_ratio=0.03 + 0.17 * s, # 0.5 → 0.115 vad_min_speech_s=0.08 + 0.14 * s, # 0.5 → 0.15s no_speech_prob=0.85 - 0.3 * s, # 0.5 → 0.70 logprob=-1.3 + 0.6 * s, # 0.5 → -1.0 @@ -122,8 +120,13 @@ def thresholds(sensitivity: float) -> Thresholds: def judge_vad(speech_ratio: float, speech_s: float, sensitivity: float) -> bool: + """목소리가 조금이라도(0.5 기준 0.15초) 있으면 Whisper 로 넘긴다. + + v1.3.5 까지는 말소리 비율(길이 대비 11.5%)도 봐서, 긴 잡음 속 짧은 한마디도 잡음으로 버렸다. + """ + del speech_ratio # 비율은 보지 않는다 (호환용 인자) t = thresholds(sensitivity) - return speech_ratio < t.vad_ratio or speech_s < t.vad_min_speech_s + return speech_s < t.vad_min_speech_s def judge_no_speech(segs: list[SegInfo], text: str, sensitivity: float) -> bool: @@ -180,6 +183,20 @@ def judge_repetition(text: str, segs: list[SegInfo], sensitivity: float) -> bool return any(s.compression_ratio > t.compression + 0.4 for s in segs) and len(norm) >= 12 +_REPEAT_RE = re.compile(r"(.{1,10}?)(?:\s*\1){2,}") + + +def collapse_repetition(text: str) -> str: + """Whisper 반복 고리("페이스페이스페이스…", "아 아 아 아")를 한 번으로 줄인다.""" + out = text.strip() + for _ in range(3): + nxt = _REPEAT_RE.sub(lambda m: m.group(1), out) + if nxt == out: + break + out = nxt + return re.sub(r"\s{2,}", " ", out).strip() + + def judge_text( text: str, segs: list[SegInfo], confidence: float, duration_s: float, sensitivity: float ) -> str | None: diff --git a/worker/gvr_worker/stt.py b/worker/gvr_worker/stt.py index ef5208a..dfa7319 100644 --- a/worker/gvr_worker/stt.py +++ b/worker/gvr_worker/stt.py @@ -196,6 +196,12 @@ class SttEngine: result.update(raw_text=raw_text or None, confidence=round(confidence, 3)) reason = noise.judge_text(raw_text, infos, confidence, prep.duration_s, sensitivity) + if reason == "repetition": + # 반복 고리는 한 번으로 줄여서, 알아들은 말이 남으면 그 말을 쓴다 (단어 하나라도 있으면 보여 준다) + collapsed = noise.collapse_repetition(raw_text) + if noise.normalize(collapsed) and noise.judge_hallucination(collapsed, confidence, prep.duration_s, sensitivity) is False: + raw_text, words, reason = collapsed, [], None + result.update(raw_text=raw_text, collapsed_repetition=True) if reason: return done(reason) diff --git a/worker/gvr_worker/tempo.py b/worker/gvr_worker/tempo.py new file mode 100644 index 0000000..43432ee --- /dev/null +++ b/worker/gvr_worker/tempo.py @@ -0,0 +1,69 @@ +"""녹음 안내(TTS) 속도 바꾸기. + +Edge TTS 는 말 속도를 0.5배까지만 늦춘다. 그보다 느리게(0.1~0.5배) 하려면 0.5배로 합성한 음성을 +여기서 atempo 필터로 한 번 더 늘린다. 결과는 디스코드에 바로 보낼 수 있는 Ogg Opus (48kHz). +""" + +from __future__ import annotations + +from fractions import Fraction + +from .protocol import WorkerError + + +def atempo_chain(tempo: float) -> list[float]: + """atempo 한 단계는 0.5~2.0 만 받는다. 0.5 보다 느리면 여러 단계로 나눈다.""" + if not 0.05 <= tempo <= 2.0: + raise WorkerError("bad_request", "tempo 는 0.05~2.0 이어야 합니다") + out: list[float] = [] + t = tempo + while t < 0.5: + out.append(0.5) + t /= 0.5 + out.append(round(t, 6)) + return out + + +def change_tempo(src: str, dst: str, tempo: float) -> dict[str, float]: + import av + import av.filter + + chain = atempo_chain(tempo) + with av.open(src) as inp, av.open(dst, "w", format="ogg") as out: + ist = inp.streams.audio[0] + ost = out.add_stream("libopus", rate=48000) + ost.layout = "mono" + graph = av.filter.Graph() + node = graph.add_abuffer(template=ist) + for t in chain: + nxt = graph.add("atempo", str(t)) + node.link_to(nxt) + node = nxt + fmt = graph.add("aformat", "sample_fmts=s16:sample_rates=48000:channel_layouts=mono") + node.link_to(fmt) + sink = graph.add("abuffersink") + fmt.link_to(sink) + graph.configure() + dur = 0.0 + + def drain() -> None: + nonlocal dur + while True: + try: + f = sink.pull() + except (av.error.BlockingIOError, av.error.EOFError): + return + f.pts = None + f.time_base = Fraction(1, 48000) + dur += f.samples / 48000 + for p in ost.encode(f): + out.mux(p) + + for frame in inp.decode(ist): + graph.push(frame) + drain() + graph.push(None) + drain() + for p in ost.encode(None): + out.mux(p) + return {"duration_s": round(dur, 3), "stages": len(chain)} diff --git a/worker/tests/test_noise.py b/worker/tests/test_noise.py index f3fe979..989b714 100644 --- a/worker/tests/test_noise.py +++ b/worker/tests/test_noise.py @@ -1,6 +1,6 @@ from __future__ import annotations -from gvr_worker.noise import HALLUCINATION_PHRASES, SegInfo, judge_text, judge_vad, thresholds +from gvr_worker.noise import HALLUCINATION_PHRASES, SegInfo, collapse_repetition, judge_text, judge_vad, thresholds GOOD = [SegInfo(0.05, -0.3, 1.2)] @@ -36,5 +36,14 @@ def test_vad_and_sensitivity() -> None: assert judge_vad(0.0, 0.0, 0.5) assert not judge_vad(0.7, 2.0, 0.5) lo, hi = thresholds(0.0), thresholds(1.0) - assert lo.vad_ratio < hi.vad_ratio and lo.no_speech_prob > hi.no_speech_prob - assert judge_vad(0.15, 0.4, 1.0) and not judge_vad(0.15, 0.4, 0.0) + assert lo.vad_min_speech_s < hi.vad_min_speech_s and lo.no_speech_prob > hi.no_speech_prob + assert judge_vad(0.02, 0.2, 1.0) and not judge_vad(0.02, 0.2, 0.0) + # 긴 잡음 속 짧은 한마디(0.3초)도 Whisper 로 넘긴다 (예전: 비율 5% 라 잡음) + assert not judge_vad(0.05, 0.3, 0.5) + + +def test_collapse_repetition() -> None: + assert collapse_repetition("엘리베이 아이스페이스페이스페이스페이스페이스") == "엘리베이 아이스페이스" + assert collapse_repetition("아 아 아 아 아 아 아 아") == "아" + assert collapse_repetition("가자 가자") == "가자 가자" + assert collapse_repetition("레이즈 궁 빠졌어") == "레이즈 궁 빠졌어" diff --git a/worker/tests/test_tempo.py b/worker/tests/test_tempo.py new file mode 100644 index 0000000..fded3ac --- /dev/null +++ b/worker/tests/test_tempo.py @@ -0,0 +1,32 @@ +from __future__ import annotations + +from pathlib import Path + +import pytest + +from gvr_worker.protocol import WorkerError +from gvr_worker.tempo import atempo_chain, change_tempo + +SRC = Path(__file__).resolve().parents[2] / "app" / "resources" / "tts" / "announce-default.webm" + + +def test_chain() -> None: + assert atempo_chain(1.0) == [1.0] + assert atempo_chain(0.2) == [0.5, 0.5, 0.8] + assert atempo_chain(2.0) == [2.0] + with pytest.raises(WorkerError): + atempo_chain(0.01) + + +@pytest.mark.skipif(not SRC.exists(), reason="기본 안내 음성 없음") +def test_change_tempo(tmp_path: Path) -> None: + import av + + with av.open(str(SRC)) as f: + base = sum(fr.samples / fr.sample_rate for fr in f.decode(audio=0)) + out = tmp_path / "slow.ogg" + r = change_tempo(str(SRC), str(out), 0.4) + assert abs(r["duration_s"] - base / 0.4) < 0.5 + with av.open(str(out)) as f: + s = f.streams.audio[0] + assert s.codec_context.name == "opus" and s.rate == 48000