fix(voice): stop mic-test ref stealing, unblock action queue, keep tail audio, and move context/LLM routing behind ports and pure policies

This commit is contained in:
Yun Chan 2026-09-28 02:16:16 +09:00
parent 2cd462333f
commit 2f94d24c99
13 changed files with 1672 additions and 353 deletions

View file

@ -18,8 +18,44 @@ 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<void>
}
/** 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
@ -59,6 +95,12 @@ class AudioCaptureService extends EventEmitter {
private _soxProcess: ChildProcess | null = null
private _stream: Readable | null = null
private _levelInterval: ReturnType<typeof setInterval> | 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)
@ -83,6 +125,28 @@ class AudioCaptureService extends EventEmitter {
return this._currentDevice
}
/**
* 캡처 참조를 하나 잡고 임대(lease)로 돌려준다. 참조를 잡지 않은 쪽이 stop() 을 불러
* 다른 소비자(회의·자막·받아쓰기)의 참조를 빼앗는 일을 막는다.
*/
async acquire(deviceId?: string): Promise<CaptureLease> {
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<void> {
if (this._state === 'capturing') {
this._refCount++
@ -90,6 +154,17 @@ class AudioCaptureService extends EventEmitter {
return
}
// 마지막 참조가 꼬리를 받는 중에 새 소비자가 오면 정지를 취소하고 같은 SoX 로 이어 간다
if (this._state === 'stopping' && this._pendingStopToken !== 0) {
this._pendingStopToken = 0
this._cancelTailWait?.()
this._state = 'capturing'
this._refCount = 1
this._startLevelTimer()
logger.debug('Pending stop cancelled by a new consumer — capture continues')
return
}
if (this._state !== 'idle' && this._state !== 'error') {
logger.warn(`Cannot start capture in state: ${this._state}`)
return
@ -119,33 +194,15 @@ class AudioCaptureService extends EventEmitter {
? selectedDeviceId
: 'default'
// Windows: sox -t waveaudio <device> --no-show-progress -r 16000 -c 1 -b 16 -e signed-integer -t raw -
// Linux/Mac: sox -d --no-show-progress ...
const soxArgs = process.platform === 'win32'
? [
'-t', 'waveaudio', deviceArg,
'--no-show-progress',
'-r', String(AUDIO_FORMAT.SAMPLE_RATE),
'-c', String(AUDIO_FORMAT.CHANNELS),
'-b', '16',
'-e', 'signed-integer',
'-t', 'raw',
'-',
]
: [
'-d',
'--no-show-progress',
'-r', String(AUDIO_FORMAT.SAMPLE_RATE),
'-c', String(AUDIO_FORMAT.CHANNELS),
'-b', '16',
'-e', 'signed-integer',
'-t', 'raw',
'-',
]
// Windows: sox --buffer 1024 -t waveaudio <device> --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(' ')}`)
this._soxProcess = spawn(soxExe, soxArgs, { stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true })
this._stream = this._soxProcess.stdout
const child = spawn(soxExe, soxArgs, { stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true })
this._soxProcess = child
this._generation++
this._stream = child.stdout
this._residualBuffer = Buffer.alloc(0)
this._levelAccumulator = []
@ -159,13 +216,16 @@ class AudioCaptureService extends EventEmitter {
})
// SoX stderr → 로그
this._soxProcess.stderr?.on('data', (chunk: Buffer) => {
child.stderr?.on('data', (chunk: Buffer) => {
const msg = chunk.toString().trim()
if (msg) logger.warn(`SoX stderr: ${msg}`)
})
// SoX 프로세스 종료 감지
this._soxProcess.on('close', (code) => {
// SoX 프로세스 종료 감지.
// 자기 프로세스인지 먼저 확인한다 — 예전엔 kill 한 옛 SoX 의 'close' 가 몇 ms 뒤에 와서
// 그사이 시작된 새 캡처('capturing')를 오류로 끝냈다(회의 중 마이크 테스트로 회의 마이크가 끊김).
child.on('close', (code) => {
if (this._soxProcess !== child) return
if (this._state === 'capturing') {
logger.warn(`SoX process exited unexpectedly (code: ${code})`)
this._handleError(
@ -175,7 +235,8 @@ class AudioCaptureService extends EventEmitter {
}
})
this._soxProcess.on('error', (err: Error) => {
child.on('error', (err: Error) => {
if (this._soxProcess !== child) return
logger.error(`SoX process spawn error: ${err.message}`)
const hint =
soxExe === 'sox' && (err as NodeJS.ErrnoException).code === 'ENOENT'
@ -197,9 +258,7 @@ class AudioCaptureService extends EventEmitter {
this._refCount = 1
// 100ms 간격으로 audio-level 이벤트 emit
this._levelInterval = setInterval(() => {
this._emitAudioLevel()
}, TIMING.AUDIO_LEVEL_INTERVAL)
this._startLevelTimer()
this.emit('started', { deviceId: this._currentDevice.deviceId })
logger.info('Audio capture started')
@ -225,7 +284,17 @@ class AudioCaptureService extends EventEmitter {
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
@ -233,6 +302,48 @@ class AudioCaptureService extends EventEmitter {
logger.info('Audio capture stopped')
}
/** TAIL_FLUSH_MS 만큼(또는 SoX 가 먼저 끝날 때까지, 또는 정지가 취소될 때까지) 기다린다 */
private _waitForTail(): Promise<void> {
const child = this._soxProcess
return new Promise<void>((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<AudioDevice[]> {
// 캐싱: 네이티브 프로세스 호출이 느리므로 한번만 실행
if (this._cachedDevices) return this._cachedDevices
@ -378,6 +489,8 @@ class AudioCaptureService extends EventEmitter {
}
dispose(): void {
this._pendingStopToken = 0
this._cancelTailWait?.()
this._cleanup()
this._state = 'idle'
this._currentDevice = null
@ -396,13 +509,7 @@ class AudioCaptureService extends EventEmitter {
? selectedDeviceId
: 'default'
const soxArgs = process.platform === 'win32'
? ['-t', 'waveaudio', deviceArg, '--no-show-progress',
'-r', String(AUDIO_FORMAT.SAMPLE_RATE), '-c', String(AUDIO_FORMAT.CHANNELS),
'-b', '16', '-e', 'signed-integer', '-t', 'raw', '-']
: ['-d', '--no-show-progress',
'-r', String(AUDIO_FORMAT.SAMPLE_RATE), '-c', String(AUDIO_FORMAT.CHANNELS),
'-b', '16', '-e', 'signed-integer', '-t', 'raw', '-']
const soxArgs = buildSoxRecordArgs(deviceArg)
return new Promise((resolve, reject) => {
const proc = spawn(soxExe, soxArgs, { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true })
@ -505,6 +612,7 @@ class AudioCaptureService extends EventEmitter {
this._cleanup()
this._state = 'error'
this._refCount = 0
this._currentDevice = null
this.emit('error', { error })
this.emit('stopped', { reason: stopReason })
@ -514,10 +622,7 @@ class AudioCaptureService extends EventEmitter {
* 녹음 프로세스와 타이머를 정리한다.
*/
private _cleanup(): void {
if (this._levelInterval) {
clearInterval(this._levelInterval)
this._levelInterval = null
}
this._stopLevelTimer()
if (this._stream) {
this._stream.removeAllListeners()
@ -525,12 +630,19 @@ class AudioCaptureService extends EventEmitter {
}
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 {
this._soxProcess.kill()
child.kill()
} catch {
// 이미 종료된 프로세스 kill 시 에러 무시
}
this._soxProcess = null
}
this._residualBuffer = Buffer.alloc(0)