// src/main/services/AudioCaptureService.ts // 마이크 PCM 캡처 서비스. 설계서 01의 IAudioCaptureService 구현. // Windows: SoX 직접 spawn (-t waveaudio). 기타: node-record-lpcm16. import { EventEmitter } from 'events' import { existsSync } from 'fs' import { spawn, type ChildProcess } from 'child_process' import type { Readable } from 'stream' import { getLogger } from './LoggerService' import { configGet } from './ConfigService' import { getSoxPath } from '../utils/paths' import type { AudioDevice } from '@d3ro/core/types' import { AUDIO_FORMAT, TIMING } from '@d3ro/core/constants' import { D3ROError, ErrorCode } from '@d3ro/core/errors' import { secureWipeAudioChunks, secureZeroBuffer } from '@d3ro/core/utils/secure-memory' const logger = getLogger('AudioCaptureService') /** 60ms 프레임 크기 (바이트): 16000 * 2 * 0.06 = 1920 */ const FRAME_SIZE_BYTES = (AUDIO_FORMAT.SAMPLE_RATE * AUDIO_FORMAT.BYTES_PER_SAMPLE * 60) / 1000 /** * SoX stdout 버퍼 크기(바이트). SoX 기본값 8192 는 16kHz 16bit mono 에서 256ms 라, 청크가 늦게 오고 * 정지 시 버퍼에 남은 최대 256ms(끝 음절)가 버려졌다. 1024 = 32ms. */ export const SOX_BUFFER_BYTES = 1024 /** * 마지막 참조를 놓을 때 SoX 를 죽이기 전에 버퍼·파이프에 남은 꼬리 오디오를 받아 내는 시간. * SoX 버퍼(32ms)의 두 배 이상이어야 정지 직전까지의 소리가 한 번은 쓰여 나온다. */ export const TAIL_FLUSH_MS = 80 export type CaptureState = 'idle' | 'starting' | 'capturing' | 'stopping' | 'error' /** * 캡처 참조 한 개. release() 는 멱등이고, 그사이 캡처가 죽었다 다시 시작됐으면(세대가 바뀜) * 다른 소비자의 참조를 깎지 않는다. */ export interface CaptureLease { release(): Promise } /** SoX 녹음 인자 (Windows: -t waveaudio 필수, 그 외: -d) */ export function buildSoxRecordArgs(deviceArg: string, platform: NodeJS.Platform = process.platform): string[] { const input = platform === 'win32' ? ['-t', 'waveaudio', deviceArg] : ['-d'] return [ '--buffer', String(SOX_BUFFER_BYTES), ...input, '--no-show-progress', '-r', String(AUDIO_FORMAT.SAMPLE_RATE), '-c', String(AUDIO_FORMAT.CHANNELS), '-b', '16', '-e', 'signed-integer', '-t', 'raw', '-', ] } interface AudioCaptureEvents { 'audio-data': (payload: { buffer: Buffer; timestamp: number }) => void 'audio-level': (payload: { level: number; timestamp: number }) => void 'device-changed': (payload: { previous: AudioDevice | null current: AudioDevice }) => void started: (payload: { deviceId: string }) => void stopped: (payload: { reason: 'manual' | 'device-lost' | 'error' }) => void error: (payload: { error: D3ROError }) => void } /** * PCM16 버퍼에서 RMS(Root Mean Square) 오디오 레벨을 계산한다. * 반환값은 0.0 ~ 1.0 범위로 정규화된다. */ export function calculateRMS(buffer: Buffer): number { const samples = buffer.length / AUDIO_FORMAT.BYTES_PER_SAMPLE if (samples === 0) return 0 let sumSquares = 0 for (let i = 0; i < buffer.length; i += AUDIO_FORMAT.BYTES_PER_SAMPLE) { const sample = buffer.readInt16LE(i) sumSquares += sample * sample } const rms = Math.sqrt(sumSquares / samples) // PCM16 최대값 32768로 나눠서 0.0~1.0 범위로 정규화 return Math.min(1.0, rms / 32768) } class AudioCaptureService extends EventEmitter { private _state: CaptureState = 'idle' private _currentDevice: AudioDevice | null = null private _refCount = 0 private _cachedDevices: AudioDevice[] | null = null private _soxProcess: ChildProcess | null = null private _soxExited = false private _stream: Readable | null = null private _levelInterval: ReturnType | null = null /** 새 SoX 를 띄울 때마다 증가 — 임대(lease)가 자기 캡처인지 판단한다 */ private _generation = 0 /** 진행 중인 꼬리 수집 정지의 토큰 (0 = 없음). start() 가 0 으로 만들어 정지를 취소한다 */ private _pendingStopToken = 0 private _stopSeq = 0 private _cancelTailWait: (() => void) | null = null /** 프레임 조립용 잔여 바이트 버퍼 */ private _residualBuffer: Buffer = Buffer.alloc(0) /** RMS 계산용 누적 버퍼 (100ms 간격 emit) */ private _levelAccumulator: Buffer[] = [] constructor() { super() // EventEmitter 는 'error' 리스너가 없으면 emit('error') 에서 ERR_UNHANDLED_ERROR 를 던진다. // 예전엔 SoX 가 장치를 못 열고 끝나면 'close' 콜백 안에서 이 예외가 나 뒤이은 'stopped' 가 // 영영 나가지 않았고, 받아쓰기는 녹음 팁만 띄운 채 조용히 아무것도 하지 않았다. // 기본 sink 로 막고, 소비자는 'stopped'(reason) 로 캡처 종료를 안다. 로깅은 호출 지점에서 한다. this.on('error', () => { /* default sink */ }) } get state(): CaptureState { return this._state } get currentDevice(): AudioDevice | null { return this._currentDevice } /** * 캡처 참조를 하나 잡고 임대(lease)로 돌려준다. 참조를 잡지 않은 쪽이 stop() 을 불러 * 다른 소비자(회의·자막·받아쓰기)의 참조를 빼앗는 일을 막는다. */ async acquire(deviceId?: string): Promise { await this.start(deviceId) if (this._state !== 'capturing') { throw new D3ROError(ErrorCode.AudioCaptureStartFailed, `Audio capture not running (state: ${this._state})`) } const generation = this._generation let released = false return { release: async () => { if (released) return released = true // 캡처가 죽었다가(장치 분리 등) 다시 시작됐으면 이 임대는 이미 무효다 if (this._generation !== generation) return await this.stop() }, } } async start(deviceId?: string): Promise { if (this._state === 'capturing') { this._refCount++ logger.debug(`Reference count increased to ${this._refCount}`) return } // 마지막 참조가 꼬리를 받는 중에 새 소비자가 오면 SoX가 아직 살아 있을 때만 정지를 취소하고 이어 간다 if (this._state === 'stopping' && this._pendingStopToken !== 0) { this._pendingStopToken = 0 this._cancelTailWait?.() if (this._isSoxProcessAlive()) { this._state = 'capturing' this._refCount = 1 this._startLevelTimer() logger.debug('Pending stop cancelled by a new consumer — capture continues') return } this._emitResidual() this._cleanup() this._currentDevice = null this._state = 'idle' } if (this._state !== 'idle' && this._state !== 'error') { logger.warn(`Cannot start capture in state: ${this._state}`) return } this._state = 'starting' const selectedDeviceId = deviceId ?? configGet('selectedDeviceId') try { logger.info( `Starting audio capture (device: ${selectedDeviceId ?? 'default'}, ` + `format: ${AUDIO_FORMAT.SAMPLE_RATE}Hz ${AUDIO_FORMAT.CHANNELS}ch ${AUDIO_FORMAT.BIT_DEPTH}bit)` ) // SoX 직접 spawn (Windows: -t waveaudio 필수) const soxExe = getSoxPath() logger.info(`Using SoX: ${soxExe}`) if (!existsSync(soxExe) && soxExe !== 'sox') { throw new D3ROError( ErrorCode.AudioCaptureStartFailed, `SoX 실행 파일을 찾을 수 없습니다: ${soxExe}` ) } const deviceArg = selectedDeviceId && selectedDeviceId !== 'default' ? selectedDeviceId : 'default' // Windows: sox --buffer 1024 -t waveaudio --no-show-progress -r 16000 -c 1 -b 16 -e signed-integer -t raw - // Linux/Mac: sox --buffer 1024 -d --no-show-progress ... const soxArgs = buildSoxRecordArgs(deviceArg) logger.info(`SoX args: ${soxArgs.join(' ')}`) const child = spawn(soxExe, soxArgs, { stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true }) this._soxProcess = child this._soxExited = false this._generation++ this._stream = child.stdout this._residualBuffer = Buffer.alloc(0) this._levelAccumulator = [] if (!this._stream) { throw new D3ROError(ErrorCode.AudioCaptureStartFailed, 'SoX stdout stream is null') } // 스트림 데이터 수신: 60ms 프레임 단위로 잘라 emit this._stream.on('data', (chunk: Buffer) => { this._onAudioChunk(chunk) }) // SoX stderr → 로그 child.stderr?.on('data', (chunk: Buffer) => { const msg = chunk.toString().trim() if (msg) logger.warn(`SoX stderr: ${msg}`) }) child.once('exit', () => { if (this._soxProcess === child) { this._soxExited = true } }) // SoX 프로세스 종료 감지. // 자기 프로세스인지 먼저 확인한다 — 예전엔 kill 한 옛 SoX 의 'close' 가 몇 ms 뒤에 와서 // 그사이 시작된 새 캡처('capturing')를 오류로 끝냈다(회의 중 마이크 테스트로 회의 마이크가 끊김). child.on('close', (code) => { if (this._soxProcess !== child) return this._soxExited = true if (this._state === 'capturing') { logger.warn(`SoX process exited unexpectedly (code: ${code})`) this._handleError( new D3ROError(ErrorCode.AudioCaptureFailed, `SoX process exited with code ${code}`), 'device-lost' ) } }) child.on('error', (err: Error) => { if (this._soxProcess !== child) return this._soxExited = true logger.error(`SoX process spawn error: ${err.message}`) const hint = soxExe === 'sox' && (err as NodeJS.ErrnoException).code === 'ENOENT' ? ' 번들된 SoX(resources/sox/sox.exe)도, 시스템 PATH의 sox도 없습니다. `npm --prefix apps/desktop run setup:sox`로 내려받으세요.' : '' this._handleError( new D3ROError(ErrorCode.AudioCaptureStartFailed, `SoX 프로세스 시작 실패: ${err.message}.${hint}`), 'error' ) }) this._currentDevice = { deviceId: selectedDeviceId ?? 'default', label: 'Default Microphone', isDefault: !selectedDeviceId || selectedDeviceId === 'default' } this._state = 'capturing' this._refCount = 1 // 100ms 간격으로 audio-level 이벤트 emit this._startLevelTimer() this.emit('started', { deviceId: this._currentDevice.deviceId }) logger.info('Audio capture started') } catch (error) { this._cleanup() this._state = 'error' const d3roError = new D3ROError( ErrorCode.AudioCaptureStartFailed, `Failed to start audio capture: ${error instanceof Error ? error.message : String(error)}` ) this.emit('error', { error: d3roError }) throw d3roError } } async stop(): Promise { if (this._state !== 'capturing') { return } this._refCount-- if (this._refCount > 0) { logger.debug(`Reference count decreased to ${this._refCount}`) return } // 곧바로 kill 하면 SoX 버퍼·파이프에 남은 끝부분(끝 음절)이 버려진다. // 잠깐 더 읽어 소비자에게 흘려보낸 뒤 정리한다. 그사이 start() 가 오면 정지를 취소한다. this._state = 'stopping' this._stopLevelTimer() const token = ++this._stopSeq this._pendingStopToken = token await this._waitForTail() if (this._pendingStopToken !== token || this._state !== 'stopping') return this._pendingStopToken = 0 this._emitResidual() this._cleanup() this._state = 'idle' this._currentDevice = null this.emit('stopped', { reason: 'manual' }) logger.info('Audio capture stopped') } /** TAIL_FLUSH_MS 만큼(또는 SoX 가 먼저 끝날 때까지, 또는 정지가 취소될 때까지) 기다린다 */ private _waitForTail(): Promise { const child = this._soxProcess return new Promise((resolve) => { let done = false const finish = (): void => { if (done) return done = true clearTimeout(timer) child?.off('close', finish) if (this._cancelTailWait === finish) this._cancelTailWait = null resolve() } const timer = setTimeout(finish, TAIL_FLUSH_MS) child?.once('close', finish) this._cancelTailWait = finish }) } /** 60ms 프레임에 못 미친 잔여 바이트를 마지막 프레임으로 내보낸다 (샘플 경계로 자름) */ private _emitResidual(): void { const usable = this._residualBuffer.length - (this._residualBuffer.length % AUDIO_FORMAT.BYTES_PER_SAMPLE) if (usable <= 0) return const frame = Buffer.from(this._residualBuffer.subarray(0, usable)) this._residualBuffer = Buffer.alloc(0) this.emit('audio-data', { buffer: frame, timestamp: Date.now() }) } private _startLevelTimer(): void { this._stopLevelTimer() this._levelInterval = setInterval(() => { this._emitAudioLevel() }, TIMING.AUDIO_LEVEL_INTERVAL) } private _stopLevelTimer(): void { if (this._levelInterval) { clearInterval(this._levelInterval) this._levelInterval = null } } async getDevices(): Promise { // 캐싱: 네이티브 프로세스 호출이 느리므로 한번만 실행 if (this._cachedDevices) return this._cachedDevices const devices: AudioDevice[] = [ { deviceId: 'default', label: '시스템 기본 마이크', isDefault: true }, ] try { if (process.platform === 'win32') { devices.push(...(await this._getDevicesWindows())) } else if (process.platform === 'darwin') { devices.push(...(await this._getDevicesMac())) } // linux: default 1개만 (pulseaudio/alsa 열거는 sox fallback -d 로 충분) } catch (err) { logger.warn( `Failed to enumerate audio devices: ${err instanceof Error ? err.message : String(err)}`, ) } this._cachedDevices = devices logger.debug(`Found ${devices.length} audio device(s) on ${process.platform}`) return devices } /** * Windows: PowerShell로 AudioEndpoint 열거 (비차단 비동기). * SoX -t waveaudio는 이름으로 매칭하므로 FriendlyName을 deviceId로 사용. */ private async _getDevicesWindows(): Promise { const { exec } = await import('child_process') const psCommand = `[Console]::OutputEncoding = [Text.Encoding]::UTF8; Get-PnpDevice -Class AudioEndpoint -Status OK | Select-Object InstanceId, FriendlyName | ConvertTo-Json -Compress` return new Promise((resolve) => { exec( `powershell -NoProfile -Command "${psCommand}"`, { encoding: 'utf8', timeout: 3000, env: { ...process.env, PYTHONIOENCODING: 'utf-8' }, windowsHide: true }, (err, stdout) => { if (err || !stdout?.trim()) { return resolve([ { deviceId: 'default', label: '기본 마이크 (Default)', isDefault: true } ]) } try { const output = stdout.trim() const parsed: unknown = JSON.parse(output.startsWith('[') ? output : `[${output}]`) if (!Array.isArray(parsed) || parsed.length === 0) { return resolve([ { deviceId: 'default', label: '기본 마이크 (Default)', isDefault: true } ]) } const result: AudioDevice[] = [] for (const dev of parsed) { const d = dev as { InstanceId?: string; FriendlyName?: string } if (d.InstanceId && d.FriendlyName) { result.push({ deviceId: d.FriendlyName, label: d.FriendlyName, isDefault: result.length === 0, }) } } resolve(result.length > 0 ? result : [ { deviceId: 'default', label: '기본 마이크 (Default)', isDefault: true } ]) } catch { resolve([ { deviceId: 'default', label: '기본 마이크 (Default)', isDefault: true } ]) } } ) }) } /** * macOS: system_profiler SPAudioDataType -json 으로 CoreAudio 디바이스 열거. * input 전용 디바이스만 필터 (coreaudio_device_input > 0). * macOS SoX 빌드는 실제 디바이스 선택에 -d(default)만 지원하는 경우가 대부분이므로 * label은 UI 표시 용도, deviceId는 'default'로 통일해 실제 캡처 경로를 단순화한다. */ private async _getDevicesMac(): Promise { const { execFile } = await import('child_process') const output: string = await new Promise((resolve, reject) => { execFile( '/usr/sbin/system_profiler', ['SPAudioDataType', '-json'], { encoding: 'utf8', timeout: 5000, maxBuffer: 1024 * 1024 }, (err, stdout) => { if (err) reject(err) else resolve(stdout) }, ) }) if (!output) return [] interface MacAudioItem { _name?: string coreaudio_device_input?: number coreaudio_default_audio_input_device?: string coreaudio_input_source?: string } interface MacAudioGroup { _items?: MacAudioItem[] } interface MacAudioJson { SPAudioDataType?: MacAudioGroup[] } const parsed = JSON.parse(output) as MacAudioJson const groups = parsed.SPAudioDataType ?? [] const result: AudioDevice[] = [] for (const group of groups) { const items = group._items ?? [] for (const item of items) { const hasInput = typeof item.coreaudio_device_input === 'number' && item.coreaudio_device_input > 0 const name = item._name ?? item.coreaudio_input_source if (!hasInput || !name) continue // 중복 방지 (name 기준) if (result.some((d) => d.label === name)) continue result.push({ // macOS SoX record 경로는 -d(default) 고정이므로 선택 시 default로 매핑. // 라벨만 사용자 구분용으로 노출. deviceId: 'default', label: name, isDefault: item.coreaudio_default_audio_input_device === 'spaudio_yes', }) } } return result } getCurrentDevice(): AudioDevice | null { return this._currentDevice } dispose(): void { this._pendingStopToken = 0 this._cancelTailWait?.() this._cleanup() this._state = 'idle' this._currentDevice = null this._refCount = 0 this.removeAllListeners() logger.info('AudioCaptureService disposed') } /** * 지정 시간(ms) 동안 마이크 캡처 후 평균/피크 레벨을 반환한다. */ async testCapture(durationMs: number): Promise<{ averageLevel: number; peakLevel: number; hasAudio: boolean }> { const soxExe = getSoxPath() const selectedDeviceId = configGet('selectedDeviceId') const deviceArg = selectedDeviceId && selectedDeviceId !== 'default' ? selectedDeviceId : 'default' const soxArgs = buildSoxRecordArgs(deviceArg) return new Promise((resolve, reject) => { const proc = spawn(soxExe, soxArgs, { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true }) const buffers: Buffer[] = [] let peakRms = 0 proc.stdout?.on('data', (chunk: Buffer) => { buffers.push(chunk) const rms = calculateRMS(chunk) if (rms > peakRms) peakRms = rms }) let settled = false const durationTimer = setTimeout(() => { proc.kill() }, durationMs) proc.on('error', (err) => { if (settled) return settled = true clearTimeout(durationTimer) reject(new D3ROError(ErrorCode.AudioCaptureStartFailed, `SoX 실행 실패: ${err.message}`)) }) proc.on('close', () => { if (settled) return settled = true clearTimeout(durationTimer) if (buffers.length === 0) { resolve({ averageLevel: 0, peakLevel: 0, hasAudio: false }) return } const combined = Buffer.concat(buffers) const avgRms = calculateRMS(combined) const avgLevel = avgRms > 0 ? Math.min(1.0, Math.pow(avgRms, 0.28)) : 0 const peakLevel = peakRms > 0 ? Math.min(1.0, Math.pow(peakRms, 0.28)) : 0 resolve({ averageLevel: avgLevel, peakLevel: peakLevel, hasAudio: avgRms > 0.001, }) }) }) } /** * 수신된 오디오 청크를 60ms 프레임(1920 bytes) 단위로 분할하여 emit한다. * 잔여 바이트는 다음 청크와 결합한다. */ private _onAudioChunk(chunk: Buffer): void { // 잔여 버퍼와 새 청크를 결합 const combined = this._residualBuffer.length > 0 ? Buffer.concat([this._residualBuffer, chunk]) : chunk let offset = 0 // 60ms 프레임 단위로 분할하여 emit while (offset + FRAME_SIZE_BYTES <= combined.length) { const frame = combined.subarray(offset, offset + FRAME_SIZE_BYTES) offset += FRAME_SIZE_BYTES this.emit('audio-data', { buffer: Buffer.from(frame), // 방어적 복사 timestamp: Date.now() }) // RMS 계산용 누적 this._levelAccumulator.push(frame) } // 남은 바이트는 잔여 버퍼에 보관 if (offset < combined.length) { this._residualBuffer = Buffer.from(combined.subarray(offset)) } else { this._residualBuffer = Buffer.alloc(0) } } /** * 100ms 간격으로 누적된 오디오 데이터의 RMS 레벨을 계산하여 emit한다. */ private _emitAudioLevel(): void { if (this._levelAccumulator.length === 0) { this.emit('audio-level', { level: 0, timestamp: Date.now() }) return } // 누적된 프레임들을 하나로 합쳐서 RMS 계산 const combined = Buffer.concat(this._levelAccumulator) this._levelAccumulator = [] const rawLevel = calculateRMS(combined) // 로그 스케일: 작은 소리도 크게, 큰 소리는 압축 (DAW 미터 방식) // pow(x, 0.28) → 0.001→0.04, 0.01→0.14, 0.05→0.35, 0.1→0.52, 0.3→0.80 const level = rawLevel > 0 ? Math.min(1.0, Math.pow(rawLevel, 0.28)) : 0 this.emit('audio-level', { level, timestamp: Date.now() }) } /** * 에러 발생 시 리소스 정리 + 에러 이벤트 emit. */ private _handleError(error: D3ROError, stopReason: 'device-lost' | 'error'): void { if (this._state === 'idle' || this._state === 'stopping') { return } this._cleanup() this._state = 'error' this._refCount = 0 this._currentDevice = null this.emit('error', { error }) this.emit('stopped', { reason: stopReason }) } /** 현재 보유 중인 SoX 프로세스가 아직 살아 있는지 확인한다 */ private _isSoxProcessAlive(): boolean { const child = this._soxProcess if (!child || this._soxExited) return false return child.exitCode == null && !child.killed } /** * 녹음 프로세스와 타이머를 정리한다. */ private _cleanup(): void { this._stopLevelTimer() this._soxExited = false if (this._stream) { this._stream.removeAllListeners() this._stream = null } if (this._soxProcess) { const child = this._soxProcess this._soxProcess = null // 이 프로세스의 늦은 'close'/'error' 가 다음 캡처를 건드리지 못하게 떼어 낸다. // 'error' 는 리스너가 없으면 throw 하므로 빈 sink 를 남긴다. child.removeAllListeners('close') child.removeAllListeners('error') child.on('error', () => { /* 정리된 프로세스의 늦은 에러 무시 */ }) child.stderr?.removeAllListeners('data') try { child.kill() } catch { // 이미 종료된 프로세스 kill 시 에러 무시 } } secureZeroBuffer(this._residualBuffer) secureWipeAudioChunks(this._levelAccumulator) this._residualBuffer = Buffer.alloc(0) } // EventEmitter 타입 오버라이드 override on( event: K, listener: AudioCaptureEvents[K] ): this { return super.on(event, listener) } override off( event: K, listener: AudioCaptureEvents[K] ): this { return super.off(event, listener) } override emit( event: K, ...args: Parameters ): boolean { return super.emit(event, ...args) } } // 싱글톤 let instance: AudioCaptureService | null = null export function getAudioCaptureService(): AudioCaptureService { if (!instance) { instance = new AudioCaptureService() } return instance } export function resetAudioCaptureServiceForTests(): void { if (instance) instance.removeAllListeners() instance = null } export { AudioCaptureService }