import fs from 'node:fs'; // 출처: game_voice_recorder app/src/core/discord/ogg.ts (같은 작성자) // Ogg Opus 파일 쓰기 (RFC 7845). 디스코드에서 받은 Opus 패킷을 다시 인코딩하지 않고 그대로 담는다. const CRC_TABLE = (() => { const t = new Uint32Array(256); for (let i = 0; i < 256; i++) { let r = i << 24; for (let j = 0; j < 8; j++) r = r & 0x80000000 ? (r << 1) ^ 0x04c11db7 : r << 1; t[i] = r >>> 0; } return t; })(); function crc32(buf: Buffer): number { let crc = 0; for (let i = 0; i < buf.length; i++) crc = ((crc << 8) ^ CRC_TABLE[((crc >>> 24) & 0xff) ^ buf[i]]) >>> 0; return crc >>> 0; } /** Opus 패킷 TOC 로 48kHz 기준 샘플 수 계산 */ export function opusSamples(packet: Buffer): number { if (!packet.length) return 0; const toc = packet[0]; const config = toc >> 3; let frame: number; if (config < 12) frame = [480, 960, 1920, 2880][config & 3]; else if (config < 16) frame = [480, 960][config & 1]; else frame = [120, 240, 480, 960][config & 3]; const c = toc & 3; const count = c === 0 ? 1 : c === 3 ? (packet[1] ?? 0) & 0x3f : 2; return frame * count; } /** 20ms 무음 Opus 프레임 (디스코드가 말이 끝날 때 보내는 것과 같은 값) */ export const SILENCE_FRAME = Buffer.from([0xf8, 0xff, 0xfe]); export class OggOpusWriter { private fd: number; private serial = (Math.random() * 0xffffffff) >>> 0; private seq = 0; private granule = 0n; private packets: Buffer[] = []; private closed = false; /** 담긴 오디오 길이 (48kHz 샘플) */ samples = 0; bytes = 0; constructor( readonly path: string, channels = 2, ) { this.fd = fs.openSync(path, 'w'); const head = Buffer.alloc(19); head.write('OpusHead', 0, 'ascii'); head[8] = 1; head[9] = channels; head.writeUInt16LE(0, 10); // pre-skip head.writeUInt32LE(48000, 12); head.writeInt16LE(0, 16); head[18] = 0; this.writePage([head], 0n, 0x02); const vendor = Buffer.from('voice_copy', 'ascii'); const tags = Buffer.alloc(8 + 4 + vendor.length + 4); tags.write('OpusTags', 0, 'ascii'); tags.writeUInt32LE(vendor.length, 8); vendor.copy(tags, 12); tags.writeUInt32LE(0, 12 + vendor.length); this.writePage([tags], 0n, 0); } write(packet: Buffer): void { if (this.closed) return; this.packets.push(packet); this.samples += opusSamples(packet); if (this.packets.length >= 50) this.flush(false); } private flush(last: boolean): void { if (!this.packets.length && !last) return; this.granule = BigInt(this.samples); this.writePage(this.packets, this.granule, last ? 0x04 : 0); this.packets = []; } private writePage(packets: Buffer[], granule: bigint, flags: number): void { const lacing: number[] = []; for (const p of packets) { let n = p.length; while (n >= 255) { lacing.push(255); n -= 255; } lacing.push(n); } if (lacing.length > 255) { // 한 페이지 최대 255 세그먼트. 넘으면 나눠 쓴다 (50패킷이면 생기지 않음) const half = Math.ceil(packets.length / 2); this.writePage(packets.slice(0, half), granule, flags & 0x02); this.writePage(packets.slice(half), granule, flags & 0x04); return; } const header = Buffer.alloc(27 + lacing.length); header.write('OggS', 0, 'ascii'); header[4] = 0; header[5] = flags; header.writeBigInt64LE(granule, 6); header.writeUInt32LE(this.serial, 14); header.writeUInt32LE(this.seq++, 18); header.writeUInt32LE(0, 22); header[26] = lacing.length; for (let i = 0; i < lacing.length; i++) header[27 + i] = lacing[i]; const page = Buffer.concat([header, ...packets]); page.writeUInt32LE(crc32(page), 22); fs.writeSync(this.fd, page); this.bytes += page.length; } close(): void { if (this.closed) return; this.flush(true); this.closed = true; fs.closeSync(this.fd); } get durationMs(): number { return Math.round(this.samples / 48); } }