// src/main/services/CaptionService.ts // Phase 10.1: Live Caption — 실시간 자막 서비스 // 스트리밍 전사: 1초마다 중간 결과를 갱신하고, 말이 멈추면 문장을 확정한다 // (StreamingCaptionTrack). 확정된 줄은 로컬 LLM이 문맥에 맞게 다듬는다. // 싱글톤 + EventEmitter 패턴. import { EventEmitter } from 'events' import { app } from 'electron' import { getLogger } from './LoggerService' import { getAudioCaptureService, calculateRMS } from './AudioCaptureService' import { getSoundEffectService } from './SoundEffectService' import { getLocalSTTService } from './LocalSTTService' import { getLocalLLMService } from './LocalLLMService' import { getHistoryService } from './HistoryService' import { configGet } from './ConfigService' import { buildCaptionRefinePrompt } from './llm-prompts' import { StreamingCaptionTrack, type CaptionTranscription } from './caption/StreamingCaptionTrack' import { CaptionAudioSources } from './caption/CaptionAudioSources' import { acceptCaptionRefinement } from '@d3ro/core/caption-streaming' import { showCaptionOverlay, hideCaptionOverlay, sendToCaptionOverlay, } from '../windows/WindowManager' import { IPC_CHANNELS } from '@d3ro/core/ipc-channels' import { D3ROError, ErrorCode } from '@d3ro/core/errors' import type { CaptionState, CaptionSegment, CaptionConfig, CaptionSessionSummary, } from '@d3ro/core/types' import { getMainWindow } from '../windows/WindowManager' const logger = getLogger('CaptionService') /** 로딩을 기다리던 start() 가 stop()·새 start 로 무효화됐다 (내부 신호) */ class CaptionStartCancelledError extends Error { constructor() { super('caption start cancelled') this.name = 'CaptionStartCancelledError' } } /** 트랙 판단 주기 (ms) — 인식 주기는 트랙이 정한다(중간 결과 1초) */ const TICK_INTERVAL_MS = 250 /** RMS 무음 임계값 — 이하면 무음으로 판정 (SoX 캡처 레벨이 낮으므로 0.003 사용) */ const SILENCE_RMS_THRESHOLD = 0.003 /** 문맥 다듬기 대기열 상한 — 밀리면 오래된 줄은 다듬지 않고 넘긴다 */ const REFINE_QUEUE_LIMIT = 3 const REFINE_TIMEOUT_MS = 6000 const REFINE_KEEP_ALIVE = '10m' /** 기본 자막 설정 */ const DEFAULT_CONFIG: CaptionConfig = { fontSize: 18, opacity: 0.85, maxLines: 3, autoClearMs: 5000, audioSource: 'mic', } /** * 자막 세션의 소유자. 회의 모드가 시작한 세션은 사용자 핫키/IPC 가 끌 수 없다 * (예전엔 핫키가 회의의 마이크 캡처를 조용히 끊고 회의 UI 는 계속 '녹음 중'이었다). */ export type CaptionOwner = 'user' | 'meeting' /** 자막 세션 시작 옵션 — 생략하면 기존(사용자 자막) 동작과 같다 */ export interface CaptionStartOptions { /** 기본 'user' */ owner?: CaptionOwner /** 이번 세션에만 쓸 오디오 소스. 생략 시 설정값(captionAudioSource). 전역 설정은 건드리지 않는다. */ audioSource?: CaptionConfig['audioSource'] /** 자막 오버레이 표시 여부 (기본 true) */ showOverlay?: boolean /** 세션을 'caption' 히스토리로 저장하고 session-saved 를 알릴지 (기본 true) */ persistHistory?: boolean } /** 종료된 세션 요약 + 저장된 히스토리 행 id (저장하지 않았으면 null) */ export type CaptionSessionResult = CaptionSessionSummary & { historyId: string | null } interface ResolvedStartOptions { owner: CaptionOwner showOverlay: boolean persistHistory: boolean } const DEFAULT_START_OPTIONS: ResolvedStartOptions = { owner: 'user', showOverlay: true, persistHistory: true, } interface CaptionServiceEvents { 'state-changed': (state: CaptionState) => void 'segment': (segment: CaptionSegment) => void 'delta': (data: { text: string; isFinal: boolean }) => void 'session-saved': (summary: CaptionSessionResult) => void /** * 인식·시작 실패 알림. 'error' 가 아니다 — 리스너 없는 'error' 는 EventEmitter 가 던져서, * 정지 중 마지막 문장 인식이 실패하면 stop() 이 해제 전에 튕겨 나가 서비스가 'stopping' 에 * 마이크가 열린 채 굳었다. */ 'failure': (error: D3ROError) => void } class CaptionService extends EventEmitter { private _state: CaptionState = 'inactive' private _config: CaptionConfig = { ...DEFAULT_CONFIG } private _sessionId: string | null = null private _sessionStartedAt: number | null = null private _segments: CaptionSegment[] = [] private _tickTimer: ReturnType | null = null private _disposed = false /** 마이크 트랙 (audioSource='mic' 또는 'both') */ private _micTrack: StreamingCaptionTrack | null = null /** 시스템 소리 트랙 (audioSource='system' 또는 'both') */ private _systemTrack: StreamingCaptionTrack | null = null /** 'auto' 언어일 때 첫 확정 결과로 고정한다 — 중간 결과마다 언어가 흔들리지 않게 */ private _sessionLanguage: string | null = null /** 자막 전용 모델 (null 이면 받아쓰기 모델) */ private _captionModelId: string | null = null private _refineQueue: CaptionSegment[] = [] private _refining = false /** 이번 세션이 잡은 오디오 소스(마이크 캡처·시스템 소리 요청) — 해제는 멱등 */ private _audio: CaptionAudioSources = this._createAudioSources() /** 현재 세션 옵션(소유자·오버레이·히스토리 저장) — 세션이 없으면 기본값 */ private _session: ResolvedStartOptions = { ...DEFAULT_START_OPTIONS } /** * 시작 세대. start() 마다 올리고, 'starting' 중 stop() 도 올린다 — 모델 로딩을 기다리던 start 가 * 깨어났을 때 세대가 바뀌었으면 마이크를 열지 않고 물러난다(취소한 자막이 오버레이 없이 켜지던 문제). */ private _startEpoch = 0 // ── 공개 접근자 ── getState(): CaptionState { return this._state } /** 현재 세션 소유자 (세션이 없으면 null) */ getOwner(): CaptionOwner | null { return this._state === 'inactive' ? null : this._session.owner } getConfig(): CaptionConfig { return { ...this._config } } setConfig(partial: Partial): void { this._config = { ...this._config, ...partial } logger.debug(`Caption config updated: ${JSON.stringify(this._config)}`) // 오버레이에 설정 변경 알림 sendToCaptionOverlay('caption:config', this._config) } // ── 시작 ── async start(options: CaptionStartOptions = {}): Promise { if (this._disposed) { throw new D3ROError( ErrorCode.CaptionStartFailed, 'CaptionService가 이미 dispose되었습니다', ) } if (this._state !== 'inactive') { throw new D3ROError( ErrorCode.CaptionAlreadyActive, `캡션이 이미 활성 상태입니다: ${this._state}`, ) } this._session = { owner: options.owner ?? DEFAULT_START_OPTIONS.owner, showOverlay: options.showOverlay ?? DEFAULT_START_OPTIONS.showOverlay, persistHistory: options.persistHistory ?? DEFAULT_START_OPTIONS.persistHistory, } const epoch = ++this._startEpoch const assertCurrent = (): void => { if (epoch !== this._startEpoch || this._disposed) throw new CaptionStartCancelledError() } let ownAudio: CaptionAudioSources | null = null this._setState('starting') // 오버레이를 즉시 표시 (로딩 상태) — 회의 모드처럼 자체 UI 가 있으면 띄우지 않는다 if (this._session.showOverlay) { showCaptionOverlay() sendToCaptionOverlay('caption:config', this._config) sendToCaptionOverlay(IPC_CHANNELS.CAPTION.STATE_CHANGED, { state: 'starting' }) } try { // STT 초기화 (모델 로딩 — 시간 소요) const sttService = getLocalSTTService() await sttService.initialize() assertCurrent() // 자막 전용 모델을 골랐으면 받아쓰기 모델과 별도로 올려 둔다(보조 자리). this._captionModelId = configGet('captionSttModelId') ?? null if (this._captionModelId) await sttService.ensureAuxModel(this._captionModelId) assertCurrent() // 세션 초기화 this._sessionId = crypto.randomUUID() this._sessionStartedAt = Date.now() this._segments = [] this._refineQueue = [] this._sessionLanguage = null // 초기 컨텍스트 힌트 — Whisper 첫 청크 환각 방지 const lang = configGet('sttLanguage') as string | undefined const initialContext = lang === 'ko' ? '다음은 한국어 대화입니다.' : '' // 오디오 소스: 호출자 지정값(이번 세션 한정) → 저장된 설정 순. // 호출자 지정값은 this._config 에 쓰지 않는다 — 다음 사용자 세션으로 새지 않게. let audioSource: CaptionConfig['audioSource'] if (options.audioSource) { audioSource = options.audioSource } else { const savedSource = configGet('captionAudioSource' as keyof import('@d3ro/core/types').AppConfig) as unknown as string if (savedSource && (savedSource === 'mic' || savedSource === 'system' || savedSource === 'both')) { this._config.audioSource = savedSource as 'mic' | 'system' | 'both' } audioSource = this._config.audioSource } logger.info(`Caption audioSource: ${audioSource} (owner: ${this._session.owner})`) // 트랙 먼저 — 마이크 첫 청크부터 받을 수 있게 if (audioSource === 'mic' || audioSource === 'both') { this._micTrack = this._createTrack('mic', initialContext) } if (audioSource === 'system' || audioSource === 'both') { this._systemTrack = this._createTrack('system', initialContext) } // 마이크 캡처(mic/both) + 시스템 오디오 캡처 요청(system/both — 렌더러에 시작 요청) ownAudio = this._createAudioSources() this._audio = ownAudio await ownAudio.acquire(audioSource, { onMicChunk: (buffer) => this._onAudioData(buffer) }) assertCurrent() // 트랙 판단 타이머 — 각 트랙은 한 번에 인식 한 건만 돌린다 this._tickTimer = setInterval(() => { void this._micTrack?.tick() void this._systemTrack?.tick() }, TICK_INTERVAL_MS) this._setState('active') getSoundEffectService().play('recording-start') logger.info(`Live Caption 시작: sessionId=${this._sessionId}`) } catch (err) { if (err instanceof CaptionStartCancelledError) { // 기다리는 사이 stop()(또는 새 start)이 세션을 가져갔다 — 공유 상태는 건드리지 않고 // 이 시도가 연 자원만 돌려준다(release 는 멱등). await ownAudio?.release() logger.info('캡션 시작 취소: 로딩 중 정지됨') throw new D3ROError(ErrorCode.CaptionStartFailed, '캡션 시작이 취소되었습니다') } if (this._tickTimer) { clearInterval(this._tickTimer) this._tickTimer = null } this._micTrack = null this._systemTrack = null await this._audio.release() this._hideOverlaySafely() this._session = { ...DEFAULT_START_OPTIONS } this._setState('inactive') const d3roErr = err instanceof D3ROError ? err : new D3ROError( ErrorCode.CaptionStartFailed, `캡션 시작 실패: ${err instanceof Error ? err.message : String(err)}`, ) this._reportFailure(d3roErr) throw d3roErr } } // ── 중지 ── /** * 자막 세션을 멈추고 요약을 돌려준다(말하던 마지막 문장 flush 포함). * * @param owner 생략하면 강제 정지(앱 종료·로그아웃·회의 강제 초기화). * 지정하면 그 소유자의 세션일 때만 멈추고, 아니면 false 를 돌려준다. * @returns 세션 요약(세그먼트가 없으면 null), 다른 소유자라 거부했으면 false */ async stop(owner?: CaptionOwner): Promise { if (this._state !== 'active' && this._state !== 'starting') { logger.warn(`캡션 중지 불가: 현재 상태=${this._state}`) return null } if (owner && owner !== this._session.owner) { logger.warn(`캡션 중지 거부: 세션 소유자=${this._session.owner}, 요청=${owner}`) return false } // 로딩 중(start 가 모델을 기다리는 중)이면 그 start 를 무효화한다 — 깨어나도 마이크를 열지 않는다. if (this._state === 'starting') this._startEpoch += 1 this._setState('stopping') // 타이머 정리 if (this._tickTimer) { clearInterval(this._tickTimer) this._tickTimer = null } // 잔여 오디오 처리 — 말하던 중이면 마지막 문장을 확정한다. // 인식이 실패해도(사이드카 500·타임아웃) 아래 해제·초기화는 반드시 실행한다 — 예전엔 여기서 튕겨 // 마이크가 열린 채 'stopping' 에 굳어 재시작 전까지 자막·회의를 다시 시작할 수 없었다. try { const results = await Promise.allSettled([this._micTrack?.flush(), this._systemTrack?.flush()]) for (const result of results) { if (result.status === 'rejected') this._reportFailure(this._toSttError(result.reason, 'flush')) } } finally { this._micTrack = null this._systemTrack = null // 마이크 캡처 정리 + 시스템 오디오 캡처 중지 요청 (멱등, 실패해도 계속) await this._audio.release() // 오버레이 숨김 this._hideOverlaySafely() } // 세션을 히스토리에 저장 (회의 모드처럼 저장을 끈 소유자는 요약만 돌려받는다) const persist = this._session.persistHistory let summary: CaptionSessionResult | null = null try { summary = this._saveSession(persist) } catch (err) { logger.error(`캡션 세션 요약 실패: ${err instanceof Error ? err.message : String(err)}`) } this._sessionId = null this._sessionStartedAt = null this._refineQueue = [] this._sessionLanguage = null this._session = { ...DEFAULT_START_OPTIONS } this._setState('inactive') getSoundEffectService().play('recording-stop') logger.info('Live Caption 중지') if (summary && persist) { this.emit('session-saved', summary) this._sendToMainWindow(IPC_CHANNELS.CAPTION.SESSION_SAVED, summary) } return summary } // ── dispose ── async dispose(): Promise { if (this._disposed) return this._disposed = true if (this._state === 'active' || this._state === 'starting') { await this.stop() } this.removeAllListeners() logger.info('CaptionService disposed') } // ── 내부: 오디오 데이터 수집 ── private _onAudioData(buffer: Buffer): void { if (this._state !== 'active') return this._micTrack?.push(buffer) } /** * 시스템 오디오 PCM16 데이터를 수신한다 (렌더러 → IPC → 여기). * 렌더러의 systemAudioCapture.ts가 이미 16kHz mono PCM16으로 변환하여 전송. */ onSystemAudioData(buffer: Buffer): void { if (this._state !== 'active') return this._systemTrack?.push(buffer) } // ── 내부: 스트리밍 트랙 ── private _createTrack(source: 'mic' | 'system', initialContext: string): StreamingCaptionTrack { return new StreamingCaptionTrack( { transcribe: (audio, opts) => this._transcribe(audio, opts), isVoiced: (chunk) => calculateRMS(chunk) >= SILENCE_RMS_THRESHOLD, onPartial: (text, stable) => this._emitPartial(text, stable), onFinal: (text) => this._emitFinal(text, source), // 절대 던지지 않는 보고 경로 — 트랙의 인식 실패가 정지·틱을 깨뜨리지 않게 onError: (err) => this._reportFailure(this._toSttError(err, source)), }, initialContext, ) } private _toSttError(err: unknown, source: string): D3ROError { return err instanceof D3ROError ? err : new D3ROError( ErrorCode.CaptionSTTFailed, `자막 전사 실패(${source}): ${err instanceof Error ? err.message : String(err)}`, ) } /** 실패를 로그와 'failure' 이벤트로 알린다. 리스너가 던져도 호출자에게 새지 않는다. */ private _reportFailure(error: D3ROError): void { logger.error(error.message) try { this.emit('failure', error) } catch (err) { logger.warn(`caption failure listener threw: ${err instanceof Error ? err.message : String(err)}`) } } private _hideOverlaySafely(): void { try { hideCaptionOverlay() } catch (err) { logger.warn(`캡션 오버레이 숨기기 실패: ${err instanceof Error ? err.message : String(err)}`) } } /** 오디오 소스 어댑터 — 마이크는 AudioCaptureService, 시스템 소리는 렌더러 IPC */ private _createAudioSources(): CaptionAudioSources { return new CaptionAudioSources({ mic: () => { const capture = getAudioCaptureService() return { onChunk: (listener) => { const handler = (payload: { buffer: Buffer; timestamp: number }): void => listener(payload.buffer) capture.on('audio-data', handler) return () => { capture.off('audio-data', handler) } }, start: () => capture.start(), stop: () => capture.stop(), } }, system: { requestStart: () => this._sendToMainWindow(IPC_CHANNELS.CAPTION.START_SYSTEM_AUDIO, {}), requestStop: () => this._sendToMainWindow(IPC_CHANNELS.CAPTION.STOP_SYSTEM_AUDIO, {}), }, onReleaseError: (stage, err) => { logger.warn(`캡션 오디오 해제 실패(${stage}): ${err instanceof Error ? err.message : String(err)}`) }, }) } /** 자막은 항상 로컬 엔진으로 인식한다 — 1초마다 다시 인식하므로 클라우드로는 보낼 수 없다. */ private async _transcribe( audio: Buffer, opts: { initialPrompt: string; partial: boolean }, ): Promise { const configured = (configGet('sttLanguage') as string | undefined) ?? 'auto' const language = configured === 'auto' ? (this._sessionLanguage ?? 'auto') : configured const result = await getLocalSTTService().transcribe(audio, { language, initialPrompt: opts.initialPrompt, vadFilter: true, partial: opts.partial, modelId: this._captionModelId ?? undefined, }) if (!opts.partial && configured === 'auto' && !this._sessionLanguage && result.text.trim() && result.language) { this._sessionLanguage = result.language } return { text: result.text, segments: result.segments.map((segment) => ({ text: segment.text, start: segment.start, end: segment.end, })), } } private _emitPartial(text: string, stable: string): void { if (this._state !== 'active') return const delta = { text, stable, isFinal: false } this.emit('delta', delta) sendToCaptionOverlay(IPC_CHANNELS.CAPTION.DELTA, delta) this._sendToMainWindow(IPC_CHANNELS.CAPTION.DELTA, delta) } private _emitFinal(text: string, source: 'mic' | 'system'): void { const segment: CaptionSegment = { id: crypto.randomUUID(), text, timestamp: Date.now(), isFinal: true, } this._segments.push(segment) this.emit('segment', segment) sendToCaptionOverlay(IPC_CHANNELS.CAPTION.SEGMENT, segment) this._sendToMainWindow(IPC_CHANNELS.CAPTION.SEGMENT, segment) logger.debug(`자막 확정(${source}): "${segment.text.substring(0, 50)}"`) this._enqueueRefine(segment) } // ── 내부: 문맥 다듬기 ── private _enqueueRefine(segment: CaptionSegment): void { if (configGet('captionRefineEnabled') === false) return if (!getLocalLLMService().isAvailable()) return this._refineQueue.push(segment) // 모델이 밀리면 오래된 줄은 포기한다 — 이미 지나간 자막을 늦게 고쳐 봐야 소용없다. while (this._refineQueue.length > REFINE_QUEUE_LIMIT) this._refineQueue.shift() if (!this._refining) void this._drainRefineQueue() } private async _drainRefineQueue(): Promise { this._refining = true try { for (let next = this._refineQueue.shift(); next; next = this._refineQueue.shift()) { await this._refine(next) } } finally { this._refining = false } } private async _refine(segment: CaptionSegment): Promise { const index = this._segments.findIndex((item) => item.id === segment.id) if (index === -1) return const previous = this._segments.slice(Math.max(0, index - 2), index).map((item) => item.text) const { systemPrompt, text } = buildCaptionRefinePrompt({ text: segment.text, previous }) try { const result = await getLocalLLMService().generate(text, { systemPrompt, temperature: 0, maxTokens: Math.min(256, segment.text.length * 2 + 32), timeoutMs: REFINE_TIMEOUT_MS, keepAlive: REFINE_KEEP_ALIVE, }) const refined = acceptCaptionRefinement(segment.text, result.text) if (!refined) return const current = this._segments.find((item) => item.id === segment.id) if (!current) return current.text = refined const update = { id: segment.id, text: refined } sendToCaptionOverlay(IPC_CHANNELS.CAPTION.SEGMENT_UPDATED, update) this._sendToMainWindow(IPC_CHANNELS.CAPTION.SEGMENT_UPDATED, update) } catch (err) { logger.debug(`자막 다듬기 건너뜀: ${err instanceof Error ? err.message : String(err)}`) } } // ── 내부: 세션 저장 ── private _saveSession(persist: boolean): CaptionSessionResult | null { if (!this._sessionId || !this._sessionStartedAt || this._segments.length === 0) { return null } const endedAt = Date.now() const totalDurationMs = endedAt - this._sessionStartedAt const fullText = this._segments.map((s) => s.text).join(' ') const wordCount = fullText.split(/\s+/).filter((w) => w.length > 0).length // 히스토리에 저장 (mode: 'caption'). 만들어진 행 id 를 요약에 싣는다 — // 자동 요약은 이 id 로 히스토리를 찾는다(예전엔 자막 세션 id 로 찾아 항상 실패했다). const historyId = persist ? this._persistHistory(fullText, totalDurationMs, wordCount) : null const summary: CaptionSessionResult = { sessionId: this._sessionId, historyId, segments: [...this._segments], startedAt: this._sessionStartedAt, endedAt, totalDurationMs, } this._segments = [] return summary } /** 'caption' 히스토리 행을 만들고 id 를 돌려준다. 실패하면 로그만 남기고 null. */ private _persistHistory(fullText: string, totalDurationMs: number, wordCount: number): string | null { try { const entry = getHistoryService().create({ originalText: fullText, polishedText: null, focusedApp: null, focusedAppName: null, focusedAppWindowTitle: null, mode: 'caption', status: 'completed', errorCode: null, audioLocalPath: null, duration: totalDurationMs / 1000, detectedLanguage: null, micDevice: null, wordCount, sttModel: configGet('sttModelId') as string | null, llmModel: null, sttLatencyMs: null, llmLatencyMs: null, appVersion: app.getVersion(), }) logger.info( `캡션 세션 저장: ${this._segments.length}개 세그먼트, ${wordCount}단어, ${Math.round(totalDurationMs / 1000)}초`, ) return entry.id } catch (err) { logger.error( `캡션 세션 저장 실패: ${err instanceof Error ? err.message : String(err)}`, ) return null } } // ── 내부: 상태 전이 ── private _setState(newState: CaptionState): void { if (this._state === newState) return const prev = this._state this._state = newState logger.debug(`CaptionState: ${prev} -> ${newState}`) this.emit('state-changed', newState) this._sendToMainWindow(IPC_CHANNELS.CAPTION.STATE_CHANGED, { state: newState }) sendToCaptionOverlay(IPC_CHANNELS.CAPTION.STATE_CHANGED, { state: newState }) } // ── 내부: 메인 윈도우에 IPC 전송 ── private _sendToMainWindow(channel: string, data: unknown): void { const win = getMainWindow() if (win && !win.isDestroyed()) { win.webContents.send(channel, data) } } // ── 타입 안전한 이벤트 메서드 오버라이드 ── override emit( event: K, ...args: Parameters ): boolean { return super.emit(event, ...args) } override on( event: K, listener: CaptionServiceEvents[K], ): this { return super.on(event, listener) } override off( event: K, listener: CaptionServiceEvents[K], ): this { return super.off(event, listener) } } // ── 싱글톤 ── let instance: CaptionService | null = null export function resetCaptionServiceForTests(): void { if (instance) instance.removeAllListeners() instance = null } export function getCaptionService(): CaptionService { if (!instance) { instance = new CaptionService() } return instance } export { CaptionService }