import { parseSequencerAudioSessionReport, SEQUENCER_AUDIO_SESSION_SCHEMA, type SequencerAudioSessionIssueCode, type SequencerAudioSessionReportIR, } from "../../../protocol/sequencer-audio-session"; interface AudioParamLike { value: number; cancelScheduledValues?(startTime: number): void; setValueAtTime(value: number, startTime: number): unknown; } interface GainNodeLike { readonly gain: AudioParamLike; connect(destination: unknown): unknown; disconnect(): void; } export interface AudioContextLike { readonly state: "suspended" | "running" | "closed" | string; readonly currentTime: number; readonly destination: unknown; createGain(): GainNodeLike; resume(): Promise; suspend(): Promise; close(): Promise; } export interface SequencerAudioSessionOptions { scope?: object; contextFactory?: () => AudioContextLike; outputGain?: number; } type AudioContextConstructor = new () => AudioContextLike; export class SequencerAudioSession { private readonly scope: object; private readonly contextFactory?: () => AudioContextLike; private readonly nominalGain: number; private context: AudioContextLike | null = null; private output: GainNodeLike | null = null; private mutedValue = false; private disposed = false; private revisionValue = 0; private issueCode: SequencerAudioSessionIssueCode | null = null; constructor(options: SequencerAudioSessionOptions = {}) { const outputGain = options.outputGain ?? 1; if (typeof outputGain !== "number" || !Number.isFinite(outputGain) || outputGain <= 0 || outputGain > 1) { const error = new Error("SEQUENCER_AUDIO_CONTEXT_INVALID: outputGain must be in (0, 1]") as Error & { code: string }; error.code = "SEQUENCER_AUDIO_CONTEXT_INVALID"; throw error; } this.scope = options.scope ?? globalThis; this.contextFactory = options.contextFactory; this.nominalGain = outputGain; } snapshot(): SequencerAudioSessionReportIR { return this.report(); } async initialize(): Promise { this.revisionValue += 1; if (this.disposed) return this.report(); if (!this.context || this.context.state === "closed") await this.openContext(); return this.report(); } async resume(): Promise { this.revisionValue += 1; if (this.disposed) return this.report(); if (!this.context || this.context.state === "closed") await this.openContext(); if (!this.context) return this.report(); try { if (this.context.state !== "running") await this.context.resume(); if (this.context.state !== "running") throw new Error("AudioContext did not enter running state"); this.issueCode = null; this.applyGain(); } catch { this.issueCode = "SEQUENCER_AUDIO_RESUME_FAILED"; } return this.report(); } async suspend(): Promise { this.revisionValue += 1; if (this.disposed) return this.report(); if (!this.context) { this.issueCode = "SEQUENCER_AUDIO_DEVICE_UNAVAILABLE"; return this.report(); } try { if (this.context.state === "running") await this.context.suspend(); if (this.context.state !== "suspended") throw new Error("AudioContext did not enter suspended state"); this.issueCode = null; } catch { this.issueCode = "SEQUENCER_AUDIO_SUSPEND_FAILED"; } return this.report(); } setMuted(muted: boolean): SequencerAudioSessionReportIR { if (typeof muted !== "boolean") { const error = new Error("SEQUENCER_AUDIO_CONTEXT_INVALID: muted must be boolean") as Error & { code: string }; error.code = "SEQUENCER_AUDIO_CONTEXT_INVALID"; throw error; } this.revisionValue += 1; if (!this.disposed) { this.mutedValue = muted; this.applyGain(); } return this.report(); } async recoverDevice(): Promise { this.revisionValue += 1; if (this.disposed) return this.report(); await this.releaseContext(); this.issueCode = null; await this.openContext(); return this.report(); } async close(): Promise { this.revisionValue += 1; if (!this.disposed) { this.disposed = true; await this.releaseContext(); this.issueCode = null; } return this.report(); } private createContext(): AudioContextLike | null { if (this.contextFactory) return this.contextFactory(); const constructor = (this.scope as { AudioContext?: unknown }).AudioContext; if (typeof constructor !== "function") return null; return new (constructor as AudioContextConstructor)(); } private async openContext(): Promise { try { const context = this.createContext(); if (!context || context.state === "closed") { this.issueCode = "SEQUENCER_AUDIO_DEVICE_UNAVAILABLE"; return; } const output = context.createGain(); output.connect(context.destination); this.context = context; this.output = output; this.issueCode = null; this.applyGain(); } catch { this.context = null; this.output = null; this.issueCode = "SEQUENCER_AUDIO_DEVICE_UNAVAILABLE"; } } private applyGain(): void { if (!this.context || !this.output || this.context.state === "closed") return; const value = this.mutedValue ? 0 : this.nominalGain; this.output.gain.cancelScheduledValues?.(this.context.currentTime); this.output.gain.setValueAtTime(value, this.context.currentTime); } private async releaseContext(): Promise { const context = this.context; const output = this.output; this.context = null; this.output = null; if (context && output) { try { output.gain.cancelScheduledValues?.(context.currentTime); output.gain.setValueAtTime(0, context.currentTime); } catch { /* Context loss can invalidate AudioParam before release. */ } try { output.disconnect(); } catch { /* A disconnected node is already released. */ } } if (context && context.state !== "closed") { try { await context.close(); } catch { /* The session still drops all references on close failure. */ } } } private report(): SequencerAudioSessionReportIR { if (this.disposed) { return parseSequencerAudioSessionReport({ schemaVersion: SEQUENCER_AUDIO_SESSION_SCHEMA, revision: this.revisionValue, contextState: "CLOSED", outputState: "SILENT", muted: this.mutedValue, outputGain: 0, issueCode: null, }); } if (!this.context || !this.output || this.context.state === "closed") { return parseSequencerAudioSessionReport({ schemaVersion: SEQUENCER_AUDIO_SESSION_SCHEMA, revision: this.revisionValue, contextState: "UNAVAILABLE", outputState: "BLOCKED", muted: this.mutedValue, outputGain: 0, issueCode: "SEQUENCER_AUDIO_DEVICE_UNAVAILABLE", }); } const contextState = this.context.state === "running" ? "RUNNING" : "SUSPENDED"; const outputGain = this.mutedValue ? 0 : this.nominalGain; return parseSequencerAudioSessionReport({ schemaVersion: SEQUENCER_AUDIO_SESSION_SCHEMA, revision: this.revisionValue, contextState, outputState: contextState === "RUNNING" && !this.mutedValue && this.issueCode === null ? "ENABLED" : "SILENT", muted: this.mutedValue, outputGain, issueCode: this.issueCode, }); } } export type { SequencerAudioSessionReportIR };