v1.3.6: 목소리 깨짐(RTP 기준 쉼 채우기) · 알 수 없음 · 잡음 숨기기/삭제 · 사이트 로그 · 지금 게임 · TTS 속도 · 시작 창

- 녹음기: 패킷 도착 간격 대신 RTP 타임스탬프로 자리를 정한다. 게임 중 몰려 온 패킷 사이에 무음이 끼어 목소리가 깨졌다. 예전 녹음은 한 번 고친 뒤 다시 변환
- users.updated 를 빈 목록으로 보내 사이트에서 말한 사람이 '알 수 없음'이 되던 것
- 잡음은 숨기고 ogg 삭제, 로그에 잡음으로 남김. 짧은 목소리도 Whisper 로, 반복 고리는 줄여서 보여 줌
- 사이트: 재생 음량, 발화 우클릭(자세한 정보 · ogg 다운로드), 사이트 로그(/logs, 게임 PC 꺼져도), 지금 게임 상태
- 앱: 지금 게임 상태, 녹음 안내 말 속도 0.1~2.0, 포터블 · 앱 시작 창
- 발로란트 데스매치 가짜 라운드 · 에이스, 빈 선수 이름

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-16 05:01:14 +09:00
parent 2ffb18263c
commit fa6126e17f
66 changed files with 2265 additions and 128 deletions

View File

@@ -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<FastifyInstance> {
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<FastifyInstance> {
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<FastifyInstance> {
return timeline.query(tq);
});
// 발화 자세한 정보: 원본 ogg 이름 · 경로 등 (사이트 우클릭 → 자세한 정보)
app.get<{ Params: { id: string } }>('/api/utterances/:id/info', async (req, reply): Promise<UtteranceInfo | void> => {
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<FastifyInstance> {
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,

View File

@@ -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<?')
.all(before) as any[];
}
/** 잡음으로 끝난 발화 중 아직 음성 파일이 남은 것 (v1.3.5 이하에서 녹음한 것) */
noiseWithAudio(): UtteranceRow[] {
return this.db
.prepare(
`SELECT rowid,* FROM utterances WHERE noise=1 AND corrected=0 AND audio_deleted=0 AND audio_path IS NOT NULL
AND (status='precise' OR noise_reason='vad')`,
)
.all() as UtteranceRow[];
}
markAudioDeleted(id: string): void {
this.db.prepare('UPDATE utterances SET audio_deleted=1 WHERE id=?').run(id);
}
@@ -472,7 +481,7 @@ export class Store {
// ---------------------------------------------------------------- stats
counts(): { utterances: number; matches: number } {
const u = (this.db.prepare('SELECT count(*) n FROM utterances').get() as any).n;
const u = (this.db.prepare('SELECT count(*) n FROM utterances WHERE noise=0 OR corrected=1').get() as any).n;
const m = (this.db.prepare('SELECT count(*) n FROM matches').get() as any).n;
return { utterances: u, matches: m };
}

View File

@@ -18,7 +18,7 @@ import { newId } from '../util/ids.js';
import type { BotGateway, GChannel, GCommand, GMember, GVoiceEvent } from './gateway.js';
import { logger } from '../util/log.js';
import type { Recorder } from './recorder.js';
import type { Announcer } from './tts.js';
import { isOgg, type Announcer } from './tts.js';
const log = logger('bot');
@@ -290,9 +290,9 @@ export class Bot {
if (!this.player) return;
const s = this.settings().discord;
try {
const file = await this.announcer.ensure(s.ttsText, s.ttsVoice);
const file = await this.announcer.ensure(s.ttsText, s.ttsVoice, s.ttsRate);
if (!this.player) return;
const res = createAudioResource(fs.createReadStream(file), { inputType: StreamType.WebmOpus });
const res = createAudioResource(fs.createReadStream(file), { inputType: isOgg(file) ? StreamType.OggOpus : StreamType.WebmOpus });
this.player.play(res);
await entersState(this.player, AudioPlayerStatus.Playing, 5000).catch(() => undefined);
} catch (e) {

View File

@@ -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;
}

View File

@@ -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<Buffer, RtpInfo>();
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);
}

View File

@@ -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<void>;
/** 말 속도 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<string> {
const p = this.cachedPath(text, voice);
/** 안내 음성 파일 경로 (WebM Opus, 0.5배보다 느리면 Ogg Opus). 없으면 합성. */
async ensure(text: string, voice: string, rate = 1): Promise<string> {
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<void> {
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<void> {
export async function synthesize(text: string, voice: string, outFile: string, tries = 4, rate = 1): Promise<void> {
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<void> {
async function synthesizeOnce(text: string, voice: string, outFile: string, rate: number): Promise<void> {
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<never>((_, rej) => setTimeout(() => rej(new Error('TTS 시간 초과')), 20000)),
]);
fs.renameSync(r.audioFilePath, outFile);

View File

@@ -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<string, string>();
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<string, string> = {
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<T = any>(path: string): Promise<T | null> {
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<any>('/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<string>('/lol-gameflow/v1/gameflow-phase');
if (phase !== this.phase) {
this.phase = phase;
// 큐 이름 (솔로 랭크 · 칼바람 나락 …): 단계가 바뀔 때만 다시 받는다
const sess = phase && phase !== 'None' ? await this.lcuGet<any>('/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);
}

View File

@@ -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<string, { connected: boolean; inMatch: boolean; detail?: string }> = {};
@@ -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<string, string> = {
competitive: '경쟁전',
unrated: '일반전',
swiftplay: '신속플레이',
spikerush: '스파이크 돌격',
deathmatch: '데스매치',
hurm: '팀 데스매치',
premier: '프리미어',
custom: '사용자 지정',
ggteam: '에스컬레이션',
};
return map[q] || m.mode || '발로란트';
}
const lq: Record<string, string> = { '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 ?? '리그 오브 레전드');
}

View File

@@ -0,0 +1,34 @@
// 게임 모드 이름 (경기 목록 · 지금 게임 상태에서 함께 쓴다)
/** 발로란트 큐 ID → 모드 이름 (모르는 큐면 null) */
export function valModeKo(queue: string | null | undefined): string | null {
const q = (queue || '').toLowerCase();
{
const map: Record<string, string> = {
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<string, string> = { '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());
}

View File

@@ -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;
}

View File

@@ -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<string>();
private detailQueue = new Map<string, { tries: number; endedAt: number; startedLocal: number }>();
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<T = any>(path: string): Promise<T | null> {
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<void> {
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 },
},
};
}

View File

@@ -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 } });
});

View File

@@ -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,

View File

@@ -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<string, string> = {
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) });

View File

@@ -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';

View File

@@ -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);
}
}