import crypto from 'node:crypto'; import fs from 'node:fs'; import path from 'node:path'; import { EndBehaviorType, type VoiceConnection } from '@discordjs/voice'; import type { Store } from './db.js'; import { OggOpusWriter, SILENCE_FRAME } from './ogg.js'; const FRAME = 960; // 20ms @48kHz const SILENCE_MS = 800; // 말이 0.8초 끊기면 한 파일 끝 const MAX_SEC = 30; // 한 파일 최대 30초 const MIN_MS = 500; // 0.5초보다 짧으면 버림 (키 소리 · 끊긴 패킷) /** 수신기가 꺼낸 Opus 패킷 → RTP 순번 · 타임스탬프 (패킷 도착이 몰려도 말 사이에 무음이 끼지 않게) */ const rtpOf = new WeakMap(); function tapRtp(receiver: unknown): void { const r = receiver as { parsePacket?: (buf: Buffer, ...rest: unknown[]) => Buffer | undefined; __rtp?: boolean }; if (r.__rtp || typeof r.parsePacket !== 'function') return; 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.__rtp = true; } class Utterance { readonly writer: OggOpusWriter; readonly id = `${Date.now().toString(36)}-${crypto.randomBytes(4).toString('hex')}`; readonly startedAt = Date.now(); private rtpBase: number | null = null; private lastSeq = 0; constructor(dir: string) { fs.mkdirSync(dir, { recursive: true }); this.writer = new OggOpusWriter(path.join(dir, `${this.id}.ogg`)); } /** 말 사이 짧은 쉼(디스코드는 패킷을 안 보냄)을 RTP 타임스탬프로 무음 프레임으로 채운다 */ place(packet: Buffer): void { 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; // 중복 · 늦게 온 패킷 const behind = ((rtp.ts - this.rtpBase) >>> 0) - this.writer.samples; if (behind >= FRAME / 2 && behind <= SILENCE_MS * 48) fill = Math.round(behind / FRAME); else if (behind > SILENCE_MS * 48 || behind < -48000) this.rtpBase = (rtp.ts - this.writer.samples) >>> 0; } 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.writer.write(packet); } } /** * 한 음성 연결에서 동의한 사람만 사람별로 따로 녹음한다. * 동의하지 않은 사람의 음성 스트림은 구독하지 않으므로 받지도 저장하지도 않는다. */ export class Recorder { private active = new Map(); private onSpeak = (userId: string) => this.subscribe(userId); constructor( private store: Store, private dataDir: string, private connection: VoiceConnection, readonly guildId: string, readonly channelId: string, /** 지금 이 채널에 있고 동의한 사람인지 (말할 때마다 다시 확인) */ private allowed: (userId: string) => boolean, ) { tapRtp(connection.receiver); connection.receiver.speaking.on('start', this.onSpeak); } private subscribe(userId: string): void { const recv = this.connection.receiver; if (recv.subscriptions.has(userId) || !this.allowed(userId)) return; const stream = recv.subscribe(userId, { end: { behavior: EndBehaviorType.AfterSilence, duration: SILENCE_MS } }); stream.on('data', (packet: Buffer) => { if (!this.allowed(userId)) return this.stopUser(userId); // 녹음 도중 철회 · 채널 이동 let u = this.active.get(userId); if (!u) { u = new Utterance(path.join(this.dataDir, 'recordings', userId, new Date().toISOString().slice(0, 10))); this.active.set(userId, u); } u.place(packet); if (u.writer.samples >= MAX_SEC * 48000) this.finish(userId); }); stream.once('end', () => this.finish(userId)); stream.once('close', () => this.finish(userId)); stream.on('error', (e) => console.warn(`[rec] 수신 오류 ${userId}`, e)); } /** 이 사람 녹음을 바로 멈추고 쓰던 파일은 버린다 (철회 · 채널을 나감) */ stopUser(userId: string): void { this.connection.receiver.subscriptions.get(userId)?.destroy(); const u = this.active.get(userId); if (!u) return; this.active.delete(userId); u.writer.close(); fs.rmSync(u.writer.path, { force: true }); } private finish(userId: string): void { const u = this.active.get(userId); if (!u) return; this.active.delete(userId); u.writer.close(); if (u.writer.durationMs < MIN_MS || !this.allowed(userId)) { fs.rmSync(u.writer.path, { force: true }); return; } this.store.addRecording({ id: u.id, user_id: userId, guild_id: this.guildId, channel_id: this.channelId, started_at: u.startedAt, duration_ms: u.writer.durationMs, path: u.writer.path, }); } /** 지금 녹음 중인 파일을 모두 저장하고 연결 수신을 끊는다 */ close(): void { this.connection.receiver.speaking.off('start', this.onSpeak); for (const id of [...this.active.keys()]) this.finish(id); for (const s of this.connection.receiver.subscriptions.values()) s.destroy(); } }