// src/main/services/caption/StreamingCaptionTrack.ts // // 오디오 한 줄기(마이크 또는 시스템 소리)의 실시간 자막 트랙. // 판단은 core `decideCaptionTick` 이 하고, 이 클래스는 오디오 버퍼와 인식 호출만 맡는다. import { CAPTION_STREAMING_DEFAULTS, agreedCaptionPrefix, decideCaptionTick, planForcedCommit, splitCaptionWords, type CaptionTimedSegment } from '@d3ro/core/caption-streaming' /** 16kHz · 16bit · mono PCM → 1ms = 32 bytes */ const BYTES_PER_MS = 32 export interface CaptionTranscription { text: string segments: CaptionTimedSegment[] } export interface StreamingCaptionTrackDeps { transcribe: (audio: Buffer, opts: { initialPrompt: string; partial: boolean }) => Promise /** 이 조각에 소리가 있는가 (RMS 등) */ isVoiced: (chunk: Buffer) => boolean /** 확정되지 않은 현재 문장 — stable 은 두 번 연속 같게 나온 앞부분 */ onPartial: (text: string, stable: string) => void onFinal: (text: string) => void onError: (error: unknown) => void now?: () => number } export class StreamingCaptionTrack { private _buffer: Buffer = Buffer.alloc(0) private _busy = false private _lastVoiceAt = 0 private _lastPartialAt = 0 private _previousWords: string[] = [] private _context = '' /** 버퍼를 자를 때마다 바뀐다 — 자르기 전에 시작한 인식 결과는 버린다 */ private _epoch = 0 private readonly _now: () => number constructor(private readonly _deps: StreamingCaptionTrackDeps, initialContext = '') { this._now = _deps.now ?? Date.now this._context = initialContext } get bufferMs(): number { return this._buffer.length / BYTES_PER_MS } push(chunk: Buffer): void { this._buffer = this._buffer.length === 0 ? chunk : Buffer.concat([this._buffer, chunk]) if (this._deps.isVoiced(chunk)) this._lastVoiceAt = this._now() } /** 주기적으로 부른다. 한 번에 인식 한 건만 돈다. */ async tick(): Promise { const now = this._now() const action = decideCaptionTick({ bufferMs: this.bufferMs, hasVoice: this._lastVoiceAt > 0, sinceVoiceMs: this._lastVoiceAt > 0 ? now - this._lastVoiceAt : Number.MAX_SAFE_INTEGER, sincePartialMs: now - this._lastPartialAt, busy: this._busy }) if (action === 'trim-idle') { this._keepTail(CAPTION_STREAMING_DEFAULTS.idleKeepMs) return } if (action === 'partial') return this._run(() => this._partial()) if (action === 'finalize') return this._run(() => this._finalize()) if (action === 'force-commit') { // 말이 끊기지 않고 너무 길어지면(배경 음악 등으로 무음이 없는 경우 포함) 앞쪽만 확정한다. // 확정할 구간 경계가 끝내 안 나오면 두 배 길이에서 통째로 확정한다. const hardLimit = this.bufferMs >= CAPTION_STREAMING_DEFAULTS.maxBufferMs * 2 return this._run(() => (hardLimit ? this._finalize() : this._forceCommit())) } } /** 세션 종료 — 남은 말을 확정한다. */ async flush(): Promise { if (this._lastVoiceAt === 0 || this.bufferMs < CAPTION_STREAMING_DEFAULTS.minAudioMs) return while (this._busy) await new Promise((resolve) => setTimeout(resolve, 20)) await this._run(() => this._finalize()) } private async _run(job: () => Promise): Promise { this._busy = true try { await job() } catch (error) { this._deps.onError(error) } finally { this._busy = false } } private async _partial(): Promise { this._lastPartialAt = this._now() const epoch = this._epoch const result = await this._deps.transcribe(this._buffer, { initialPrompt: this._context, partial: true }) if (epoch !== this._epoch) return const words = splitCaptionWords(result.text) if (words.length === 0) return const stable = agreedCaptionPrefix(this._previousWords, words) this._previousWords = words this._deps.onPartial(words.join(' '), stable.join(' ')) } private async _finalize(): Promise { const snapshotBytes = this._buffer.length const takenAt = this._now() const result = await this._deps.transcribe(this._buffer.subarray(0, snapshotBytes), { initialPrompt: this._context, partial: false }) this._cut(snapshotBytes) // 인식하는 동안 들어온 오디오에 소리가 있었으면 그 소리는 다음 문장이다. if (this._lastVoiceAt <= takenAt) this._lastVoiceAt = 0 this._emitFinal(result.text) } private async _forceCommit(): Promise { const snapshotBytes = this._buffer.length const result = await this._deps.transcribe(this._buffer.subarray(0, snapshotBytes), { initialPrompt: this._context, partial: false }) const plan = planForcedCommit( result.segments, snapshotBytes / BYTES_PER_MS / 1000, CAPTION_STREAMING_DEFAULTS.keepTailMs / 1000 ) if (!plan) return this._cut(Math.min(snapshotBytes, Math.round(plan.cutAtSec * 1000) * BYTES_PER_MS)) this._emitFinal(plan.text) } private _emitFinal(raw: string): void { const text = raw.trim() this._previousWords = [] if (!text) return this._context = `${this._context} ${text}`.trim().slice(-CAPTION_STREAMING_DEFAULTS.contextChars) this._deps.onFinal(text) } private _cut(bytes: number): void { this._buffer = this._buffer.subarray(bytes - (bytes % 2)) this._epoch += 1 } private _keepTail(ms: number): void { const keep = ms * BYTES_PER_MS if (this._buffer.length > keep) this._buffer = this._buffer.subarray(this._buffer.length - keep) } }