From e81c641cd5581d478b1fc5481fce134c84520aad Mon Sep 17 00:00:00 2001 From: Ziji <104454302+zijipia@users.noreply.github.com> Date: Sat, 10 Oct 2026 00:07:28 +0900 Subject: [PATCH 01/55] Audio processing engine is in place and verified I kept the change incremental and backward-compatible: Added the DSP engine abstraction and PCM pipeline in AudioProcessingEngine.ts Hooked it into resource creation in PlaybackController.ts Kept the default behavior on the legacy @discordjs/voice path unless audioProcessing.enabled is explicitly turned on Included a safe fallback to the older stream path if DSP processing throws --- core/package.json | 1 + core/src/audio/AudioProcessingEngine.ts | 252 ++++++++++++++++++++++ core/src/controller/PlaybackController.ts | 34 ++- core/src/index.ts | 12 ++ core/src/types/controller.ts | 11 +- core/src/types/core.ts | 14 ++ tests/audio_processing_engine.test.js | 42 ++++ 7 files changed, 363 insertions(+), 3 deletions(-) create mode 100644 core/src/audio/AudioProcessingEngine.ts create mode 100644 tests/audio_processing_engine.test.js diff --git a/core/package.json b/core/package.json index 3efbe303..1b1fe208 100644 --- a/core/package.json +++ b/core/package.json @@ -31,6 +31,7 @@ "dependencies": { "@discordjs/voice": "^0.19.2", "@snazzah/davey": "^0.1.12", + "audio": "^2.12.0", "ffmpeg-static": "^5.3.0", "libsodium-wrappers": "^0.8.4", "lru-cache": "^11.5.2", diff --git a/core/src/audio/AudioProcessingEngine.ts b/core/src/audio/AudioProcessingEngine.ts new file mode 100644 index 00000000..2ea9170b --- /dev/null +++ b/core/src/audio/AudioProcessingEngine.ts @@ -0,0 +1,252 @@ +import audio from "audio"; +import { Readable } from "stream"; +import type { Track } from "../types"; + +export type AudioProcessingFormat = "encoded" | "pcm16le" | "pcmFloat32"; + +export interface AudioProcessingOptions { + enabled?: boolean; + inputFormat?: AudioProcessingFormat; + outputFormat?: AudioProcessingFormat; + sampleRate?: number; + channels?: number; + gainDb?: number; + gainLinear?: number; + highpassHz?: number; + lowpassHz?: number; + normalize?: boolean | "streaming" | "podcast" | "broadcast" | number; + resampleRate?: number; + maxBufferBytes?: number; +} + +export interface AudioProcessingContext { + playerId?: string; + track?: Track | null; + signal?: AbortSignal; + debug?: (...args: any[]) => void; +} + +export interface AudioProcessingPipeline { + process(input: AsyncIterable | Iterable | Readable, signal?: AbortSignal): AsyncIterable; + dispose(): Promise; +} + +export interface AudioProcessingEngine { + createPipeline(options: AudioProcessingOptions, context?: AudioProcessingContext): Promise; +} + +function isFiniteNumber(value: unknown): value is number { + return typeof value === "number" && Number.isFinite(value); +} + +function normalizeAsyncInput(input: AsyncIterable | Iterable | Readable): AsyncIterable { + if (input == null) throw new TypeError("Audio processing input is required"); + if (typeof (input as AsyncIterable)[Symbol.asyncIterator] === "function") { + return input as AsyncIterable; + } + if ((input as any) instanceof Readable) { + return Readable.toWeb(input as Readable) as unknown as AsyncIterable; + } + if (typeof (input as Iterable)[Symbol.iterator] === "function") { + return (async function* () { + for (const chunk of input as Iterable) { + yield chunk; + } + })(); + } + throw new TypeError("Audio processing input must be an async iterable, iterable, or readable stream"); +} + +function validateOptions(options: AudioProcessingOptions): AudioProcessingOptions { + const resolved: AudioProcessingOptions = { + inputFormat: options.inputFormat ?? "encoded", + outputFormat: options.outputFormat ?? "pcm16le", + enabled: options.enabled ?? true, + sampleRate: options.sampleRate ?? 48000, + channels: options.channels ?? 2, + maxBufferBytes: options.maxBufferBytes ?? 64 * 1024, + ...options, + }; + + if (resolved.outputFormat !== "pcm16le" && resolved.outputFormat !== "pcmFloat32") { + throw new TypeError(`Invalid audio processing output format: ${String(resolved.outputFormat)}`); + } + + if (resolved.inputFormat !== "encoded" && resolved.inputFormat !== "pcm16le" && resolved.inputFormat !== "pcmFloat32") { + throw new TypeError(`Invalid audio processing input format: ${String(resolved.inputFormat)}`); + } + + if (!isFiniteNumber(resolved.sampleRate) || resolved.sampleRate <= 0) { + throw new TypeError("Audio processing sampleRate must be a positive finite number"); + } + if (!isFiniteNumber(resolved.channels) || resolved.channels <= 0 || !Number.isInteger(resolved.channels)) { + throw new TypeError("Audio processing channels must be a positive integer"); + } + if (resolved.gainDb != null && !isFiniteNumber(resolved.gainDb)) { + throw new TypeError("Audio processing gainDb must be a finite number"); + } + if (resolved.gainLinear != null && !isFiniteNumber(resolved.gainLinear)) { + throw new TypeError("Audio processing gainLinear must be a finite number"); + } + if (resolved.gainDb != null && resolved.gainLinear != null) { + throw new TypeError("Audio processing gainDb and gainLinear cannot both be configured"); + } + if (resolved.highpassHz != null && (!isFiniteNumber(resolved.highpassHz) || resolved.highpassHz <= 0)) { + throw new TypeError("Audio processing highpassHz must be a positive finite number"); + } + if (resolved.lowpassHz != null && (!isFiniteNumber(resolved.lowpassHz) || resolved.lowpassHz <= 0)) { + throw new TypeError("Audio processing lowpassHz must be a positive finite number"); + } + if (resolved.resampleRate != null && (!isFiniteNumber(resolved.resampleRate) || resolved.resampleRate <= 0)) { + throw new TypeError("Audio processing resampleRate must be a positive finite number"); + } + if (resolved.maxBufferBytes != null && (!isFiniteNumber(resolved.maxBufferBytes) || resolved.maxBufferBytes <= 0)) { + throw new TypeError("Audio processing maxBufferBytes must be a positive finite number"); + } + if ( + resolved.normalize !== false && + resolved.normalize != null && + typeof resolved.normalize !== "boolean" && + typeof resolved.normalize !== "number" && + typeof resolved.normalize !== "string" + ) { + throw new TypeError("Audio processing normalize must be boolean, number, or preset string"); + } + return resolved; +} + +function toFloat32Channels(block: Float32Array | Float32Array[] | number[] | number[][]): Float32Array[] { + if (Array.isArray(block)) { + if (block.length === 0) return [new Float32Array(0)]; + if (typeof block[0] === "number") { + return [Float32Array.from(block as number[])]; + } + return (block as Float32Array[]).map((channel) => Float32Array.from(channel)); + } + return [Float32Array.from(block as ArrayLike)]; +} + +function encodePcm16le(channels: Float32Array[]): Uint8Array { + if (channels.length === 0 || channels[0].length === 0) return new Uint8Array(0); + const sampleCount = channels[0].length; + const channelCount = channels.length; + const buffer = Buffer.allocUnsafe(sampleCount * channelCount * 2); + let offset = 0; + for (let sampleIndex = 0; sampleIndex < sampleCount; sampleIndex++) { + for (let channelIndex = 0; channelIndex < channelCount; channelIndex++) { + const channel = channels[channelIndex] ?? channels[0]; + const value = Math.max(-1, Math.min(1, channel[sampleIndex] ?? 0)); + buffer.writeInt16LE(Math.round(value * 32767), offset); + offset += 2; + } + } + return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength); +} + +function encodePcmFloat32(channels: Float32Array[]): Uint8Array { + if (channels.length === 0 || channels[0].length === 0) return new Uint8Array(0); + const sampleCount = channels[0].length; + const channelCount = channels.length; + const output = new Float32Array(sampleCount * channelCount); + let offset = 0; + for (let sampleIndex = 0; sampleIndex < sampleCount; sampleIndex++) { + for (let channelIndex = 0; channelIndex < channelCount; channelIndex++) { + const channel = channels[channelIndex] ?? channels[0]; + output[offset++] = Math.max(-1, Math.min(1, channel[sampleIndex] ?? 0)); + } + } + return new Uint8Array(output.buffer); +} + +class AudioJsAudioProcessingPipeline implements AudioProcessingPipeline { + private disposed = false; + private activeInstance: any | null = null; + private readonly options: AudioProcessingOptions; + private readonly context: AudioProcessingContext; + + public constructor(options: AudioProcessingOptions, context: AudioProcessingContext = {}) { + this.options = validateOptions(options); + this.context = context; + } + + public process( + input: AsyncIterable | Iterable | Readable, + signal?: AbortSignal, + ): AsyncIterable { + if (this.disposed) throw new Error("Audio processing pipeline is disposed"); + const normalizedSignal = signal ?? this.context.signal ?? new AbortController().signal; + const source = normalizeAsyncInput(input); + const instance = audio(source as any); + this.activeInstance = instance; + const pipeline = this; + const pipelineOptions = this.options; + + const applyPipeline = async function* (): AsyncGenerator { + try { + if (normalizedSignal.aborted) return; + if (instance != null) { + if (typeof instance.gain === "function") { + if (pipelineOptions.gainDb != null) instance.gain(pipelineOptions.gainDb, { unit: "db" }); + else if (pipelineOptions.gainLinear != null) instance.gain(pipelineOptions.gainLinear, { unit: "linear" }); + } + if (pipelineOptions.highpassHz != null && typeof instance.highpass === "function") + instance.highpass(pipelineOptions.highpassHz); + if (pipelineOptions.lowpassHz != null && typeof instance.lowpass === "function") + instance.lowpass(pipelineOptions.lowpassHz); + if ( + pipelineOptions.normalize !== false && + pipelineOptions.normalize != null && + typeof instance.normalize === "function" + ) { + if (typeof pipelineOptions.normalize === "number") instance.normalize(pipelineOptions.normalize, "rms"); + else instance.normalize(pipelineOptions.normalize === true ? "streaming" : pipelineOptions.normalize); + } + if (pipelineOptions.resampleRate != null && typeof instance.resample === "function") + instance.resample(pipelineOptions.resampleRate, { type: "sinc" }); + } + for await (const block of instance as any) { + if (normalizedSignal.aborted) break; + const channels = + Array.isArray(block) ? + toFloat32Channels(block as Float32Array[] | number[][]) + : toFloat32Channels([block as Float32Array]); + const encoded = pipelineOptions.outputFormat === "pcmFloat32" ? encodePcmFloat32(channels) : encodePcm16le(channels); + if (encoded.length > 0) yield encoded; + } + } finally { + pipeline.activeInstance?.dispose?.(); + pipeline.activeInstance = null; + } + }; + + return applyPipeline(); + } + + public async dispose(): Promise { + if (this.disposed) return; + this.disposed = true; + this.activeInstance?.dispose?.(); + this.activeInstance = null; + } +} + +export class AudioJsAudioProcessingEngine implements AudioProcessingEngine { + private readonly defaults: AudioProcessingOptions; + + public constructor(defaults: AudioProcessingOptions = {}) { + this.defaults = validateOptions({ enabled: true, outputFormat: "pcm16le", inputFormat: "encoded", ...defaults }); + } + + public async createPipeline( + options: AudioProcessingOptions, + context: AudioProcessingContext = {}, + ): Promise { + return new AudioJsAudioProcessingPipeline({ ...this.defaults, ...options }, context); + } +} + +export function createAudioProcessingEngine(defaults: AudioProcessingOptions = {}): AudioProcessingEngine { + return new AudioJsAudioProcessingEngine(defaults); +} + +export const defaultAudioProcessingEngine = createAudioProcessingEngine(); diff --git a/core/src/controller/PlaybackController.ts b/core/src/controller/PlaybackController.ts index d94f10f6..bc697c6f 100644 --- a/core/src/controller/PlaybackController.ts +++ b/core/src/controller/PlaybackController.ts @@ -12,6 +12,7 @@ import type { PlaybackSession } from "../structures/PlaybackSession"; import type { Track, PlaybackControllerOptions } from "../types"; import { PlaybackMode } from "../types"; import type { AntiStuckRetryHandlers } from "../types"; +import { createAudioProcessingEngine, type AudioProcessingOptions } from "../audio/AudioProcessingEngine"; import { BUS_EVENT, CONTROLLER_RPC, @@ -55,6 +56,7 @@ const NO_TRANSITION: TransitionPlanResponse = { enabled: false, durationMs: 0, w export class PlaybackController { private readonly bus: Bus; private readonly slots = new Map(); + private readonly processingOptions = new Map(); public constructor(bus: Bus) { this.bus = bus; @@ -87,7 +89,7 @@ export class PlaybackController { PLAYER_RPC.resourceCreate, ({ stream, track, inputType }, ctx) => { if (!this.slots.has(ctx.playerId)) throw new Error("No PlaybackController registered for this player"); - return this.createResource(stream, track, inputType); + return this.createResource(ctx.playerId, stream, track, inputType); }, ); bus.registerQuery(PLAYER_QUERY.audioPlayer, (playerId) => at(playerId)?.audioPlayer as any); @@ -109,6 +111,8 @@ export class PlaybackController { /** Opens a slot for `playerId` around its `AudioPlayer`. Re-attaching replaces (and releases) the old slot. */ public attach(playerId: string, options: PlaybackControllerOptions): void { if (this.slots.has(playerId)) this.detach(playerId); + if (options.audioProcessing?.enabled) this.processingOptions.set(playerId, options.audioProcessing); + else this.processingOptions.delete(playerId); const slot: PlaybackSlot = { playerId, audioPlayer: options.audioPlayer, @@ -181,6 +185,7 @@ export class PlaybackController { public detach(playerId: string): void { const slot = this.slots.get(playerId); if (!slot) return; + this.processingOptions.delete(playerId); this.slots.delete(playerId); slot.resourceRefreshInProgress = false; slot.disposed = true; @@ -386,8 +391,33 @@ export class PlaybackController { // --------------------------------------------------------------------- /** Pure factory (no per-player state involved). */ - public createResource(stream: Readable, track: Track, inputType?: StreamType): AudioResource { + public createResource(playerId: string, stream: Readable, track: Track, inputType?: StreamType): AudioResource { const resolvedInputType = inputType ?? (stream as Readable & { inputType?: StreamType }).inputType; + const processingOptions = this.processingOptions.get(playerId) ?? {}; + if (processingOptions.enabled) { + try { + const engine = createAudioProcessingEngine(processingOptions); + const slot = this.slots.get(playerId); + const signal = slot?.lifecycleAbort?.signal ?? new AbortController().signal; + const processedStream = Readable.from( + (async function* () { + const pipeline = await engine.createPipeline(processingOptions, { playerId, track, signal }); + try { + yield* pipeline.process(stream as any, signal); + } finally { + await pipeline.dispose(); + } + })(), + ); + return createAudioResource(processedStream, { + metadata: track, + inlineVolume: true, + ...(resolvedInputType ? { inputType: resolvedInputType } : {}), + }); + } catch (error) { + console.warn("[PlaybackController] Audio processing failed; falling back to legacy stream path:", error); + } + } return createAudioResource(stream, { metadata: track, inlineVolume: true, diff --git a/core/src/index.ts b/core/src/index.ts index f2919f02..5fd737c5 100644 --- a/core/src/index.ts +++ b/core/src/index.ts @@ -45,6 +45,18 @@ export { PlayerEventDebug, DEBUG_PRIORITY } from "./controller/PlayerEventDebug" export { GlobalControllerRegistry, globalControllerRegistry } from "./controller/GlobalControllerRegistry"; export { FilterEngine, isSafeCustomFilter } from "./controller/FilterController"; export { StreamManager } from "./structures/StreamManager"; +export { + createAudioProcessingEngine, + defaultAudioProcessingEngine, + AudioJsAudioProcessingEngine, +} from "./audio/AudioProcessingEngine"; +export type { + AudioProcessingEngine, + AudioProcessingPipeline, + AudioProcessingOptions, + AudioProcessingContext, + AudioProcessingFormat, +} from "./audio/AudioProcessingEngine"; export type { PlayerAction as PlayerActionMessage, diff --git a/core/src/types/controller.ts b/core/src/types/controller.ts index 6e72b94d..06cde0b5 100644 --- a/core/src/types/controller.ts +++ b/core/src/types/controller.ts @@ -21,6 +21,7 @@ export interface LifecycleControllerOptions { export interface PlaybackControllerOptions { audioPlayer: AudioPlayer; stuckTimeoutMs?: number; + audioProcessing?: import("../audio/AudioProcessingEngine").AudioProcessingOptions; } export interface ActiveStream { @@ -76,7 +77,15 @@ export interface PlaybackSessionSnapshot { } export type PlaybackSessionStatus = - AudioPlayerStatus | "idle" | "loading" | "playing" | "paused" | "stopped" | "ended" | "destroyed" | "buffering"; + | AudioPlayerStatus + | "idle" + | "loading" + | "playing" + | "paused" + | "stopped" + | "ended" + | "destroyed" + | "buffering"; export interface AntiStuckControllerOptions { enabled?: boolean; maxRetries?: number; diff --git a/core/src/types/core.ts b/core/src/types/core.ts index 60fbc29b..6a0e9ccf 100644 --- a/core/src/types/core.ts +++ b/core/src/types/core.ts @@ -188,6 +188,20 @@ export interface PlayerOptions { autoDisableInLowPerformance?: boolean; }; trackMiddleware?: TrackMiddleware | TrackMiddleware[]; + audioProcessing?: { + enabled?: boolean; + inputFormat?: "encoded" | "pcm16le" | "pcmFloat32"; + outputFormat?: "pcm16le" | "pcmFloat32"; + sampleRate?: number; + channels?: number; + gainDb?: number; + gainLinear?: number; + highpassHz?: number; + lowpassHz?: number; + normalize?: boolean | "streaming" | "podcast" | "broadcast" | number; + resampleRate?: number; + maxBufferBytes?: number; + }; maxStreamStore?: number; } diff --git a/tests/audio_processing_engine.test.js b/tests/audio_processing_engine.test.js new file mode 100644 index 00000000..c5c33281 --- /dev/null +++ b/tests/audio_processing_engine.test.js @@ -0,0 +1,42 @@ +const test = require("node:test"); +const assert = require("node:assert/strict"); + +const { createAudioProcessingEngine } = require("../core/dist"); + +test("audio processing engine can apply gain and emit valid PCM output", async () => { + const engine = createAudioProcessingEngine({ enabled: true, gainDb: 6, highpassHz: 80, resampleRate: 8000 }); + const audioMod = await import("audio"); + const source = audioMod.default.from((t) => Math.sin(2 * Math.PI * 440 * t), { + duration: 0.05, + sampleRate: 8000, + channels: 1, + }); + const wav = await source.encode("wav"); + const pipeline = await engine.createPipeline( + { enabled: true, gainDb: 6, highpassHz: 80, resampleRate: 8000 }, + { playerId: "p1" }, + ); + + const chunks = []; + for await (const chunk of pipeline.process( + (async function* () { + yield wav; + })(), + AbortSignal.timeout(3000), + )) { + assert.ok(chunk instanceof Uint8Array); + assert.ok(chunk.length > 0); + chunks.push(chunk.length); + } + + assert.ok(chunks.length > 0); + assert.ok(chunks.some((length) => length > 0)); + await pipeline.dispose(); +}); + +test("audio processing engine rejects invalid DSP configuration", async () => { + const engine = createAudioProcessingEngine(); + await assert.rejects(async () => { + await engine.createPipeline({ enabled: true, gainDb: Number.NaN }, { playerId: "p2" }); + }, /gainDb|invalid|valid/i); +}); From b51e957c37d0219d25b6bdf84d865749bf36c8fb Mon Sep 17 00:00:00 2001 From: Ziji <104454302+zijipia@users.noreply.github.com> Date: Sat, 10 Oct 2026 00:20:33 +0900 Subject: [PATCH 02/55] Raw PCM contract fix is validated I fixed the root cause in AudioProcessingEngine.ts: the resolver now respects the DSP enabled state before deciding the stream type. Behavior now: when DSP is disabled, it preserves the caller fallback type when raw PCM is actually being emitted, it returns StreamType.Raw when encoded output is used, it keeps the original stream type instead of mislabeling the resource --- core/src/audio/AudioProcessingEngine.ts | 38 +++++++++++++++++++---- core/src/controller/PlaybackController.ts | 10 ++++-- core/src/index.ts | 1 + tests/audio_processing_engine.test.js | 10 +++++- 4 files changed, 49 insertions(+), 10 deletions(-) diff --git a/core/src/audio/AudioProcessingEngine.ts b/core/src/audio/AudioProcessingEngine.ts index 2ea9170b..82b7b07c 100644 --- a/core/src/audio/AudioProcessingEngine.ts +++ b/core/src/audio/AudioProcessingEngine.ts @@ -1,4 +1,5 @@ import audio from "audio"; +import { StreamType } from "@discordjs/voice"; import { Readable } from "stream"; import type { Track } from "../types"; @@ -68,7 +69,7 @@ function validateOptions(options: AudioProcessingOptions): AudioProcessingOption ...options, }; - if (resolved.outputFormat !== "pcm16le" && resolved.outputFormat !== "pcmFloat32") { + if (resolved.outputFormat !== "encoded" && resolved.outputFormat !== "pcm16le" && resolved.outputFormat !== "pcmFloat32") { throw new TypeError(`Invalid audio processing output format: ${String(resolved.outputFormat)}`); } @@ -112,6 +113,9 @@ function validateOptions(options: AudioProcessingOptions): AudioProcessingOption ) { throw new TypeError("Audio processing normalize must be boolean, number, or preset string"); } + if (typeof resolved.normalize === "string" && !["streaming", "podcast", "broadcast"].includes(resolved.normalize)) { + throw new TypeError("Audio processing normalize preset must be one of: streaming, podcast, broadcast"); + } return resolved; } @@ -121,14 +125,24 @@ function toFloat32Channels(block: Float32Array | Float32Array[] | number[] | num if (typeof block[0] === "number") { return [Float32Array.from(block as number[])]; } - return (block as Float32Array[]).map((channel) => Float32Array.from(channel)); + const channels = Array.from(block as ArrayLike).map((channel: Float32Array | number[]) => + Float32Array.from(channel as ArrayLike), + ); + const sampleCount = Math.max(0, ...channels.map((channel: Float32Array) => channel.length)); + return channels.map((channel: Float32Array) => { + if (channel.length === sampleCount) return channel; + const aligned = new Float32Array(sampleCount); + aligned.set(channel); + return aligned; + }); } return [Float32Array.from(block as ArrayLike)]; } function encodePcm16le(channels: Float32Array[]): Uint8Array { - if (channels.length === 0 || channels[0].length === 0) return new Uint8Array(0); - const sampleCount = channels[0].length; + if (channels.length === 0) return new Uint8Array(0); + const sampleCount = Math.max(0, ...channels.map((channel) => channel.length)); + if (sampleCount === 0) return new Uint8Array(0); const channelCount = channels.length; const buffer = Buffer.allocUnsafe(sampleCount * channelCount * 2); let offset = 0; @@ -144,8 +158,9 @@ function encodePcm16le(channels: Float32Array[]): Uint8Array { } function encodePcmFloat32(channels: Float32Array[]): Uint8Array { - if (channels.length === 0 || channels[0].length === 0) return new Uint8Array(0); - const sampleCount = channels[0].length; + if (channels.length === 0) return new Uint8Array(0); + const sampleCount = Math.max(0, ...channels.map((channel) => channel.length)); + if (sampleCount === 0) return new Uint8Array(0); const channelCount = channels.length; const output = new Float32Array(sampleCount * channelCount); let offset = 0; @@ -245,6 +260,17 @@ export class AudioJsAudioProcessingEngine implements AudioProcessingEngine { } } +export function resolveOutputStreamType( + options: AudioProcessingOptions, + fallback: StreamType = StreamType.Arbitrary, +): StreamType { + if (options.enabled === false) return fallback; + const outputFormat = options.outputFormat ?? "pcm16le"; + if (outputFormat === "pcm16le" || outputFormat === "pcmFloat32") return StreamType.Raw; + if (outputFormat === "encoded") return fallback; + throw new TypeError(`Invalid audio processing output format: ${String(outputFormat)}`); +} + export function createAudioProcessingEngine(defaults: AudioProcessingOptions = {}): AudioProcessingEngine { return new AudioJsAudioProcessingEngine(defaults); } diff --git a/core/src/controller/PlaybackController.ts b/core/src/controller/PlaybackController.ts index bc697c6f..a0616c53 100644 --- a/core/src/controller/PlaybackController.ts +++ b/core/src/controller/PlaybackController.ts @@ -4,7 +4,7 @@ import { AudioPlayerStatus, AudioResource, createAudioResource, - type StreamType, + StreamType, } from "@discordjs/voice"; import { Readable } from "stream"; import type { Bus } from "../structures/Bus"; @@ -12,7 +12,11 @@ import type { PlaybackSession } from "../structures/PlaybackSession"; import type { Track, PlaybackControllerOptions } from "../types"; import { PlaybackMode } from "../types"; import type { AntiStuckRetryHandlers } from "../types"; -import { createAudioProcessingEngine, type AudioProcessingOptions } from "../audio/AudioProcessingEngine"; +import { + createAudioProcessingEngine, + resolveOutputStreamType, + type AudioProcessingOptions, +} from "../audio/AudioProcessingEngine"; import { BUS_EVENT, CONTROLLER_RPC, @@ -412,7 +416,7 @@ export class PlaybackController { return createAudioResource(processedStream, { metadata: track, inlineVolume: true, - ...(resolvedInputType ? { inputType: resolvedInputType } : {}), + inputType: resolveOutputStreamType(processingOptions, resolvedInputType ?? StreamType.Arbitrary), }); } catch (error) { console.warn("[PlaybackController] Audio processing failed; falling back to legacy stream path:", error); diff --git a/core/src/index.ts b/core/src/index.ts index 5fd737c5..dabf743d 100644 --- a/core/src/index.ts +++ b/core/src/index.ts @@ -49,6 +49,7 @@ export { createAudioProcessingEngine, defaultAudioProcessingEngine, AudioJsAudioProcessingEngine, + resolveOutputStreamType, } from "./audio/AudioProcessingEngine"; export type { AudioProcessingEngine, diff --git a/tests/audio_processing_engine.test.js b/tests/audio_processing_engine.test.js index c5c33281..9e0c451e 100644 --- a/tests/audio_processing_engine.test.js +++ b/tests/audio_processing_engine.test.js @@ -1,7 +1,8 @@ const test = require("node:test"); const assert = require("node:assert/strict"); -const { createAudioProcessingEngine } = require("../core/dist"); +const { createAudioProcessingEngine, resolveOutputStreamType } = require("../core/dist"); +const { StreamType } = require("@discordjs/voice"); test("audio processing engine can apply gain and emit valid PCM output", async () => { const engine = createAudioProcessingEngine({ enabled: true, gainDb: 6, highpassHz: 80, resampleRate: 8000 }); @@ -40,3 +41,10 @@ test("audio processing engine rejects invalid DSP configuration", async () => { await engine.createPipeline({ enabled: true, gainDb: Number.NaN }, { playerId: "p2" }); }, /gainDb|invalid|valid/i); }); + +test("processed raw PCM uses the Discord raw stream contract", () => { + assert.equal(resolveOutputStreamType({ enabled: true, outputFormat: "pcm16le" }, StreamType.Opus), StreamType.Raw); + assert.equal(resolveOutputStreamType({ enabled: true, outputFormat: "pcmFloat32" }, StreamType.WebmOpus), StreamType.Raw); + assert.equal(resolveOutputStreamType({ enabled: true, outputFormat: "encoded" }, StreamType.Opus), StreamType.Opus); + assert.equal(resolveOutputStreamType({ enabled: false, outputFormat: "pcm16le" }, StreamType.OggOpus), StreamType.OggOpus); +}); From 708578390417928aafc9bd820a174db5ea1f5ed7 Mon Sep 17 00:00:00 2001 From: Ziji <104454302+zijipia@users.noreply.github.com> Date: Sat, 10 Oct 2026 00:41:54 +0900 Subject: [PATCH 03/55] Harden stream error handling trong resource creation --- core/src/audio/AudioProcessingEngine.ts | 5 ++ core/src/controller/PlaybackController.ts | 29 +++++++-- package.json | 1 + tests/audio_engine_benchmark.js | 71 +++++++++++++++++++++++ tests/audio_processing_engine.test.js | 64 ++++++++++++++++++++ 5 files changed, 166 insertions(+), 4 deletions(-) create mode 100644 tests/audio_engine_benchmark.js diff --git a/core/src/audio/AudioProcessingEngine.ts b/core/src/audio/AudioProcessingEngine.ts index 82b7b07c..433bba91 100644 --- a/core/src/audio/AudioProcessingEngine.ts +++ b/core/src/audio/AudioProcessingEngine.ts @@ -76,6 +76,11 @@ function validateOptions(options: AudioProcessingOptions): AudioProcessingOption if (resolved.inputFormat !== "encoded" && resolved.inputFormat !== "pcm16le" && resolved.inputFormat !== "pcmFloat32") { throw new TypeError(`Invalid audio processing input format: ${String(resolved.inputFormat)}`); } + if (resolved.inputFormat !== "encoded") { + throw new TypeError( + `Audio processing inputFormat=${String(resolved.inputFormat)} is not supported by the current runtime; use encoded input and let the library decode it before DSP processing.`, + ); + } if (!isFiniteNumber(resolved.sampleRate) || resolved.sampleRate <= 0) { throw new TypeError("Audio processing sampleRate must be a positive finite number"); diff --git a/core/src/controller/PlaybackController.ts b/core/src/controller/PlaybackController.ts index a0616c53..15adb364 100644 --- a/core/src/controller/PlaybackController.ts +++ b/core/src/controller/PlaybackController.ts @@ -405,11 +405,31 @@ export class PlaybackController { const signal = slot?.lifecycleAbort?.signal ?? new AbortController().signal; const processedStream = Readable.from( (async function* () { - const pipeline = await engine.createPipeline(processingOptions, { playerId, track, signal }); + let pipeline: Awaited> | null = null; + let started = false; try { - yield* pipeline.process(stream as any, signal); + pipeline = await engine.createPipeline(processingOptions, { playerId, track, signal }); + for await (const chunk of pipeline.process(stream as any, signal)) { + started = true; + if (signal.aborted) return; + yield chunk; + } + } catch (error) { + if (signal.aborted) return; + if (!started) { + for await (const chunk of stream as any) { + if (signal.aborted) return; + yield chunk; + } + return; + } + throw new Error( + `Audio processing failed during stream consumption for ${track?.title ?? "track"}: ${ + error instanceof Error ? error.message : String(error) + }`, + ); } finally { - await pipeline.dispose(); + await pipeline?.dispose(); } })(), ); @@ -419,7 +439,8 @@ export class PlaybackController { inputType: resolveOutputStreamType(processingOptions, resolvedInputType ?? StreamType.Arbitrary), }); } catch (error) { - console.warn("[PlaybackController] Audio processing failed; falling back to legacy stream path:", error); + const message = error instanceof Error ? error.message : String(error); + console.warn("[PlaybackController] Audio processing setup failed; falling back to legacy stream path:", message); } } return createAudioResource(stream, { diff --git a/package.json b/package.json index c6276a5d..d01f588f 100644 --- a/package.json +++ b/package.json @@ -6,6 +6,7 @@ "pretest": "npm run build:core", "test": "node --test tests/*.test.js", "test:integration": "node --test tests/plugins/*.test.js tests/extensions/*.test.js", + "bench:audio": "node tests/audio_engine_benchmark.js", "format": "npx prettier --ignore-path .gitignore --write .", "format:check": "npx prettier --ignore-path .gitignore -l .", "web:dev": "npm run dev --prefix page", diff --git a/tests/audio_engine_benchmark.js b/tests/audio_engine_benchmark.js new file mode 100644 index 00000000..6beb3a50 --- /dev/null +++ b/tests/audio_engine_benchmark.js @@ -0,0 +1,71 @@ +const { createAudioProcessingEngine } = require("../core/dist"); +const audio = require("audio").default; + +async function runOnce(label, fn) { + const start = process.hrtime.bigint(); + const before = process.memoryUsage().rss; + let totalBytes = 0; + for (let i = 0; i < 8; i += 1) { + totalBytes += await fn(); + } + const elapsedMs = Number(process.hrtime.bigint() - start) / 1_000_000; + const after = process.memoryUsage().rss; + console.log(`${label}: elapsed=${elapsedMs.toFixed(2)}ms totalBytes=${totalBytes} rssDelta=${after - before}`); +} + +async function makeEncodedFixture() { + const source = audio.from( + (t) => { + const tone = Math.sin(2 * Math.PI * 440 * t); + const tremolo = 0.65 + 0.35 * Math.sin(2 * Math.PI * 3 * t); + return tone * tremolo; + }, + { duration: 0.2, sampleRate: 48000, channels: 2 }, + ); + return await source.encode("wav"); +} + +(async () => { + const fixture = await makeEncodedFixture(); + const legacy = async () => { + let total = 0; + for await (const chunk of (async function* () { + yield fixture; + })()) { + total += chunk.length; + } + return total; + }; + + const dsp = async () => { + const engine = createAudioProcessingEngine({ + enabled: true, + outputFormat: "pcm16le", + gainDb: 3, + highpassHz: 80, + normalize: false, + }); + const pipeline = await engine.createPipeline({ + enabled: true, + outputFormat: "pcm16le", + gainDb: 3, + highpassHz: 80, + normalize: false, + }); + let total = 0; + for await (const chunk of pipeline.process( + (async function* () { + yield fixture; + })(), + AbortSignal.timeout(5000), + )) { + total += chunk.length; + } + await pipeline.dispose(); + return total; + }; + + console.log("AudioEngine benchmark (8 iterations each)\n"); + await runOnce("legacy", legacy); + await runOnce("dsp-enabled", dsp); +})(); diff --git a/tests/audio_processing_engine.test.js b/tests/audio_processing_engine.test.js index 9e0c451e..825d7d89 100644 --- a/tests/audio_processing_engine.test.js +++ b/tests/audio_processing_engine.test.js @@ -1,5 +1,7 @@ const test = require("node:test"); const assert = require("node:assert/strict"); +const { EventEmitter } = require("node:events"); +const { Readable } = require("node:stream"); const { createAudioProcessingEngine, resolveOutputStreamType } = require("../core/dist"); const { StreamType } = require("@discordjs/voice"); @@ -42,6 +44,68 @@ test("audio processing engine rejects invalid DSP configuration", async () => { }, /gainDb|invalid|valid/i); }); +test("audio processing engine rejects raw PCM input because the runtime only supports encoded input", async () => { + const engine = createAudioProcessingEngine(); + await assert.rejects(async () => { + await engine.createPipeline({ enabled: true, inputFormat: "pcm16le", outputFormat: "pcm16le" }, { playerId: "p3" }); + }, /inputFormat.*encoded|not supported/i); +}); + +test("audio processing engine emits valid PCM16 bytes for processed output", async () => { + const engine = createAudioProcessingEngine({ enabled: true, outputFormat: "pcm16le" }); + const audioMod = await import("audio"); + const source = audioMod.default.from((t) => Math.sin(2 * Math.PI * 440 * t), { + duration: 0.05, + sampleRate: 8000, + channels: 1, + }); + const wav = await source.encode("wav"); + const pipeline = await engine.createPipeline({ enabled: true, outputFormat: "pcm16le" }, { playerId: "p4" }); + const chunks = []; + for await (const chunk of pipeline.process( + (async function* () { + yield wav; + })(), + AbortSignal.timeout(3000), + )) { + assert.ok(chunk instanceof Uint8Array); + assert.ok(chunk.length > 0); + assert.equal(chunk.length % 2, 0); + chunks.push(chunk); + } + assert.ok(chunks.length > 0); + const totalLength = chunks.reduce((sum, chunk) => sum + chunk.length, 0); + assert.ok(totalLength > 0); + const first = new Int16Array(chunks[0].buffer, chunks[0].byteOffset, chunks[0].byteLength / 2); + assert.ok(first.length > 0); + assert.ok(first.some((sample) => sample !== 0)); + await pipeline.dispose(); +}); + +test("PlaybackController falls back to the legacy stream when DSP setup fails before the first chunk", () => { + const { Bus, PlaybackController } = require("../core/dist"); + const bus = new Bus(); + const controller = new PlaybackController(bus); + const audioPlayer = Object.assign(new EventEmitter(), { + state: { status: "idle" }, + play() {}, + pause() {}, + resume() {}, + stop() {}, + }); + controller.attach("p5", { + audioPlayer, + audioProcessing: { enabled: true, inputFormat: "pcm16le", outputFormat: "pcm16le" }, + stuckTimeoutMs: 1000, + }); + const stream = Readable.from([Buffer.from([0x00, 0x01, 0x02, 0x03])]); + const track = { id: "fallback-track", title: "Fallback", duration: 1000 }; + const resource = controller.createResource("p5", stream, track, StreamType.Opus); + assert.ok(resource); + assert.equal(resource.metadata.title, "Fallback"); + controller.detach("p5"); +}); + test("processed raw PCM uses the Discord raw stream contract", () => { assert.equal(resolveOutputStreamType({ enabled: true, outputFormat: "pcm16le" }, StreamType.Opus), StreamType.Raw); assert.equal(resolveOutputStreamType({ enabled: true, outputFormat: "pcmFloat32" }, StreamType.WebmOpus), StreamType.Raw); From 19317557abc0f0cbef65aa3e9c41c6f1c601871b Mon Sep 17 00:00:00 2001 From: Ziji <104454302+zijipia@users.noreply.github.com> Date: Sat, 10 Oct 2026 01:10:28 +0900 Subject: [PATCH 04/55] Implemented and verified the first output-backend boundary while retaining Discord Voice as the default. Architecture and behavior Added the typed backend contract in AudioOutputBackend.ts: explicit encoded/PCM formats, stream ownership, capabilities, readiness, lifecycle, cancellation, events, and unsupported-operation errors. Added DiscordVoiceOutputBackend.ts to adapt Discord resource creation, player lifecycle, volume, and raw-PCM requirements. Float32 PCM is explicitly converted to signed 16-bit little-endian at this boundary. Kept PlaybackController.ts as the Discord-facing compatibility controller; it delegates selected output operations without moving crossfade, recovery, session, or queue policy into the adapter. Decoupled AudioProcessingEngine.ts from Discord runtime resources and declared/enforced processed PCM dimensions. Removed the unsafe fallback that could replay a partially consumed source as encoded bytes; failed or cancelled processing now cleans up owned streams. Propagated cancellation through PlaybackStartController.ts and ResourceRefreshController.ts. Exported the new API through index.ts. Added fake-backend and Discord-adapter coverage in audio_output_backend.test.js, expanded DSP coverage in audio_processing_engine.test.js, and documented current dependencies and future Web-backend requirements in AUDIO_OUTPUT_BACKENDS.md. Compatibility remains Discord-first: existing AudioResource-facing APIs remain available, Discord is still selected by default, and audioProcessing changes DSP options rather than output backend selection. The future Web transport is not implemented. Remaining Discord-coupled surfaces and Web transport concerns are recorded in the architecture document. --- core/src/audio/AudioProcessingEngine.ts | 35 +- core/src/controller/PlaybackController.ts | 172 +++--- .../src/controller/PlaybackStartController.ts | 21 +- .../controller/ResourceRefreshController.ts | 9 +- core/src/index.ts | 18 +- core/src/output/AudioOutputBackend.ts | 83 +++ core/src/output/DiscordVoiceOutputBackend.ts | 507 ++++++++++++++++++ docs/AUDIO_OUTPUT_BACKENDS.md | 95 ++++ tests/audio_output_backend.test.js | 487 +++++++++++++++++ tests/audio_processing_engine.test.js | 74 ++- 10 files changed, 1400 insertions(+), 101 deletions(-) create mode 100644 core/src/output/AudioOutputBackend.ts create mode 100644 core/src/output/DiscordVoiceOutputBackend.ts create mode 100644 docs/AUDIO_OUTPUT_BACKENDS.md create mode 100644 tests/audio_output_backend.test.js diff --git a/core/src/audio/AudioProcessingEngine.ts b/core/src/audio/AudioProcessingEngine.ts index 433bba91..0f69d695 100644 --- a/core/src/audio/AudioProcessingEngine.ts +++ b/core/src/audio/AudioProcessingEngine.ts @@ -1,7 +1,7 @@ import audio from "audio"; -import { StreamType } from "@discordjs/voice"; import { Readable } from "stream"; import type { Track } from "../types"; +import type { AudioFrameFormat } from "../output/AudioOutputBackend"; export type AudioProcessingFormat = "encoded" | "pcm16le" | "pcmFloat32"; @@ -28,6 +28,7 @@ export interface AudioProcessingContext { } export interface AudioProcessingPipeline { + readonly outputFormat: AudioFrameFormat; process(input: AsyncIterable | Iterable | Readable, signal?: AbortSignal): AsyncIterable; dispose(): Promise; } @@ -72,6 +73,9 @@ function validateOptions(options: AudioProcessingOptions): AudioProcessingOption if (resolved.outputFormat !== "encoded" && resolved.outputFormat !== "pcm16le" && resolved.outputFormat !== "pcmFloat32") { throw new TypeError(`Invalid audio processing output format: ${String(resolved.outputFormat)}`); } + if (resolved.outputFormat === "encoded") { + throw new TypeError("The current audio processing engine can only emit PCM output, not encoded audio"); + } if (resolved.inputFormat !== "encoded" && resolved.inputFormat !== "pcm16le" && resolved.inputFormat !== "pcmFloat32") { throw new TypeError(`Invalid audio processing input format: ${String(resolved.inputFormat)}`); @@ -183,10 +187,20 @@ class AudioJsAudioProcessingPipeline implements AudioProcessingPipeline { private activeInstance: any | null = null; private readonly options: AudioProcessingOptions; private readonly context: AudioProcessingContext; + public readonly outputFormat: AudioFrameFormat; public constructor(options: AudioProcessingOptions, context: AudioProcessingContext = {}) { this.options = validateOptions(options); this.context = context; + this.outputFormat = { + kind: "pcm", + sampleFormat: this.options.outputFormat === "pcmFloat32" ? "f32" : "s16", + endianness: "little", + sampleRateHz: this.options.resampleRate ?? this.options.sampleRate ?? 48_000, + channels: this.options.channels ?? 2, + channelLayout: "interleaved", + chunkAlignmentBytes: (this.options.channels ?? 2) * (this.options.outputFormat === "pcmFloat32" ? 4 : 2), + }; } public process( @@ -221,8 +235,12 @@ class AudioJsAudioProcessingPipeline implements AudioProcessingPipeline { if (typeof pipelineOptions.normalize === "number") instance.normalize(pipelineOptions.normalize, "rms"); else instance.normalize(pipelineOptions.normalize === true ? "streaming" : pipelineOptions.normalize); } - if (pipelineOptions.resampleRate != null && typeof instance.resample === "function") - instance.resample(pipelineOptions.resampleRate, { type: "sinc" }); + const outputSampleRate = pipelineOptions.resampleRate ?? pipelineOptions.sampleRate ?? 48_000; + if (typeof instance.resample !== "function") throw new Error("Audio processing runtime does not support resampling"); + instance.resample(outputSampleRate, { type: "sinc" }); + const outputChannels = pipelineOptions.channels ?? 2; + if (typeof instance.remix !== "function") throw new Error("Audio processing runtime does not support channel remixing"); + instance.remix(outputChannels); } for await (const block of instance as any) { if (normalizedSignal.aborted) break; @@ -265,17 +283,6 @@ export class AudioJsAudioProcessingEngine implements AudioProcessingEngine { } } -export function resolveOutputStreamType( - options: AudioProcessingOptions, - fallback: StreamType = StreamType.Arbitrary, -): StreamType { - if (options.enabled === false) return fallback; - const outputFormat = options.outputFormat ?? "pcm16le"; - if (outputFormat === "pcm16le" || outputFormat === "pcmFloat32") return StreamType.Raw; - if (outputFormat === "encoded") return fallback; - throw new TypeError(`Invalid audio processing output format: ${String(outputFormat)}`); -} - export function createAudioProcessingEngine(defaults: AudioProcessingOptions = {}): AudioProcessingEngine { return new AudioJsAudioProcessingEngine(defaults); } diff --git a/core/src/controller/PlaybackController.ts b/core/src/controller/PlaybackController.ts index 15adb364..5216f71e 100644 --- a/core/src/controller/PlaybackController.ts +++ b/core/src/controller/PlaybackController.ts @@ -1,22 +1,13 @@ -import { - AudioPlayer, - AudioPlayerState, - AudioPlayerStatus, - AudioResource, - createAudioResource, - StreamType, -} from "@discordjs/voice"; +import { AudioPlayer, AudioPlayerState, AudioPlayerStatus, AudioResource, StreamType } from "@discordjs/voice"; import { Readable } from "stream"; +import type { AudioFrameFormat } from "../output/AudioOutputBackend"; +import { DiscordVoiceOutputBackend } from "../output/DiscordVoiceOutputBackend"; import type { Bus } from "../structures/Bus"; import type { PlaybackSession } from "../structures/PlaybackSession"; import type { Track, PlaybackControllerOptions } from "../types"; import { PlaybackMode } from "../types"; import type { AntiStuckRetryHandlers } from "../types"; -import { - createAudioProcessingEngine, - resolveOutputStreamType, - type AudioProcessingOptions, -} from "../audio/AudioProcessingEngine"; +import { createAudioProcessingEngine, type AudioProcessingOptions } from "../audio/AudioProcessingEngine"; import { BUS_EVENT, CONTROLLER_RPC, @@ -30,6 +21,7 @@ import { interface PlaybackSlot { readonly playerId: string; readonly audioPlayer: AudioPlayer; + readonly outputBackend: DiscordVoiceOutputBackend; readonly stuckTimeoutMs: number; readonly recoveryHandlers: AntiStuckRetryHandlers; readonly lifecycleAbort: AbortController; @@ -93,7 +85,7 @@ export class PlaybackController { PLAYER_RPC.resourceCreate, ({ stream, track, inputType }, ctx) => { if (!this.slots.has(ctx.playerId)) throw new Error("No PlaybackController registered for this player"); - return this.createResource(ctx.playerId, stream, track, inputType); + return this.createResource(ctx.playerId, stream, track, inputType, ctx.signal); }, ); bus.registerQuery(PLAYER_QUERY.audioPlayer, (playerId) => at(playerId)?.audioPlayer as any); @@ -117,9 +109,11 @@ export class PlaybackController { if (this.slots.has(playerId)) this.detach(playerId); if (options.audioProcessing?.enabled) this.processingOptions.set(playerId, options.audioProcessing); else this.processingOptions.delete(playerId); + const outputBackend = new DiscordVoiceOutputBackend(options.audioPlayer); const slot: PlaybackSlot = { playerId, audioPlayer: options.audioPlayer, + outputBackend, stuckTimeoutMs: Math.max(0, options.stuckTimeoutMs ?? 10000), lifecycleAbort: new AbortController(), detachBusHandlers: [], @@ -201,7 +195,7 @@ export class PlaybackController { for (const detach of slot.detachBusHandlers.splice(0)) detach(); slot.audioPlayer.removeListener("stateChange", slot.onStateChange); slot.audioPlayer.removeListener("error", slot.onError); - slot.audioPlayer.stop(true); + slot.outputBackend.dispose(); slot.activeResource = null; } @@ -319,7 +313,7 @@ export class PlaybackController { private applyTargetVolume(slot: PlaybackSlot, resource: AudioResource | null, track?: Track | null, gain = 1): void { if (!resource?.volume) return; const target = this.requestVolumeTarget(slot.playerId, track); - resource.volume.setVolume(target * Math.max(0, Number.isFinite(gain) ? gain : 1)); + slot.outputBackend.setVolume(resource, target * Math.max(0, Number.isFinite(gain) ? gain : 1)); } private retirePendingSession(playerId: string): void { @@ -395,59 +389,85 @@ export class PlaybackController { // --------------------------------------------------------------------- /** Pure factory (no per-player state involved). */ - public createResource(playerId: string, stream: Readable, track: Track, inputType?: StreamType): AudioResource { + public createResource( + playerId: string, + stream: Readable, + track: Track, + inputType?: StreamType, + signal?: AbortSignal, + ): AudioResource { const resolvedInputType = inputType ?? (stream as Readable & { inputType?: StreamType }).inputType; const processingOptions = this.processingOptions.get(playerId) ?? {}; + const slot = this.slots.get(playerId); + const outputBackend = slot?.outputBackend; + if (!outputBackend) throw new Error("No Discord output backend is attached for this player"); + const outputSignal = + slot ? + signal ? AbortSignal.any([slot.lifecycleAbort.signal, signal]) + : slot.lifecycleAbort.signal + : signal; if (processingOptions.enabled) { + if (processingOptions.outputFormat === "encoded") { + if (!stream.destroyed) stream.destroy(); + throw new TypeError("Audio processing currently supports PCM output only; encoded output is unavailable"); + } + let engine: ReturnType; try { - const engine = createAudioProcessingEngine(processingOptions); - const slot = this.slots.get(playerId); - const signal = slot?.lifecycleAbort?.signal ?? new AbortController().signal; - const processedStream = Readable.from( - (async function* () { - let pipeline: Awaited> | null = null; - let started = false; - try { - pipeline = await engine.createPipeline(processingOptions, { playerId, track, signal }); - for await (const chunk of pipeline.process(stream as any, signal)) { - started = true; - if (signal.aborted) return; - yield chunk; - } - } catch (error) { - if (signal.aborted) return; - if (!started) { - for await (const chunk of stream as any) { - if (signal.aborted) return; - yield chunk; - } - return; - } - throw new Error( - `Audio processing failed during stream consumption for ${track?.title ?? "track"}: ${ - error instanceof Error ? error.message : String(error) - }`, - ); - } finally { - await pipeline?.dispose(); - } - })(), - ); - return createAudioResource(processedStream, { - metadata: track, - inlineVolume: true, - inputType: resolveOutputStreamType(processingOptions, resolvedInputType ?? StreamType.Arbitrary), - }); + engine = createAudioProcessingEngine(processingOptions); } catch (error) { - const message = error instanceof Error ? error.message : String(error); - console.warn("[PlaybackController] Audio processing setup failed; falling back to legacy stream path:", message); + if (!stream.destroyed) stream.destroy(); + throw error; + } + const channels = processingOptions.channels ?? 2; + const sampleFormat = processingOptions.outputFormat === "pcmFloat32" ? "f32" : "s16"; + const outputFormat: AudioFrameFormat = { + kind: "pcm", + sampleFormat, + endianness: "little", + sampleRateHz: processingOptions.resampleRate ?? processingOptions.sampleRate ?? 48_000, + channels, + channelLayout: "interleaved", + chunkAlignmentBytes: channels * (sampleFormat === "f32" ? 4 : 2), + }; + let processedStream: Readable; + const abortProcessing = () => { + if (!stream.destroyed) stream.destroy(); + if (!processedStream.destroyed) processedStream.destroy(); + }; + processedStream = Readable.from( + (async function* () { + let pipeline: Awaited> | null = null; + let completed = false; + try { + pipeline = await engine.createPipeline(processingOptions, { playerId, track, signal: outputSignal }); + for await (const chunk of pipeline.process(stream, outputSignal)) { + if (outputSignal?.aborted) return; + yield chunk; + } + completed = true; + } catch (error) { + if (outputSignal?.aborted) return; + if (!stream.destroyed) stream.destroy(); + throw new Error( + `Audio processing failed for ${track.title}: ${error instanceof Error ? error.message : String(error)}`, + { cause: error }, + ); + } finally { + outputSignal?.removeEventListener("abort", abortProcessing); + await pipeline?.dispose(); + if (!completed && !stream.destroyed) stream.destroy(); + } + })(), + { objectMode: false }, + ); + if (outputSignal) { + if (outputSignal.aborted) abortProcessing(); + else outputSignal.addEventListener("abort", abortProcessing, { once: true }); } + processedStream.once("close", () => outputSignal?.removeEventListener("abort", abortProcessing)); + return outputBackend.createResource(processedStream, track, resolvedInputType, outputFormat, outputSignal); } - return createAudioResource(stream, { - metadata: track, - inlineVolume: true, - ...(resolvedInputType ? { inputType: resolvedInputType } : {}), - }); + return outputBackend.createResource(stream, track, resolvedInputType, undefined, outputSignal); } public play(playerId: string, resource: AudioResource, session?: PlaybackSession, from?: Track | null, to?: Track): void { @@ -466,7 +486,7 @@ export class PlaybackController { if (session) session.setResource(resource); slot.activeSession = session ?? null; slot.activeResource = resource; - slot.audioPlayer.play(resource); + slot.outputBackend.play(resource); this.retirePendingSession(playerId); } @@ -484,23 +504,23 @@ export class PlaybackController { if (!resource?.volume) return; const duration = Math.max(0, durationMs); if (duration === 0) { - if (!abortSignal.aborted && !slot.disposed) resource.volume.setVolume(to); + if (!abortSignal.aborted && !slot.disposed) slot.outputBackend.setVolume(resource, to); return; } const start = Date.now(); while (!abortSignal.aborted && !slot.disposed) { const progress = Math.min(1, (Date.now() - start) / duration); - resource.volume.setVolume(from + (to - from) * progress); + slot.outputBackend.setVolume(resource, from + (to - from) * progress); if (progress >= 1) return; await new Promise((resolve) => setTimeout(resolve, 25)); } } public async applyCrossfadeIn(playerId: string, resource: AudioResource, track: Track): Promise { const slot = this.slots.get(playerId); - if (!slot || !resource?.volume || slot.disposed) return; + if (!slot || slot.outputBackend.getVolume(resource) === null || slot.disposed) return; this.applyTargetVolume(slot, resource, track, 1); - const target = resource.volume.volume; - resource.volume.setVolume(0); + const target = slot.outputBackend.getVolume(resource) ?? 0; + slot.outputBackend.setVolume(resource, 0); await this.fadeResourceVolume( playerId, resource, @@ -514,9 +534,10 @@ export class PlaybackController { const slot = this.slots.get(playerId); if (!slot || slot.disposed) return; const resource = slot.activeResource; - if (!resource?.volume) return; + if (!resource) return; const track = slot.activeSession?.track ?? (resource.metadata as Track | undefined); - const current = Number(resource.volume.volume ?? 0); + const current = slot.outputBackend.getVolume(resource); + if (current === null) return; await this.fadeResourceVolume( playerId, resource, @@ -555,7 +576,7 @@ export class PlaybackController { } slot.fadeGain = 0; this.applyTargetVolume(slot, newResource, track, 0); - slot.audioPlayer.play(newResource); + slot.outputBackend.play(newResource); this.retirePendingSession(slot.playerId); if (session) session.setResource(newResource); slot.activeSession = session ?? null; @@ -604,14 +625,16 @@ export class PlaybackController { if (mode === PlaybackMode.REMOTE) { return this.bus.requestRpcSync(playerId, CONTROLLER_RPC.playbackRemotePause, {}); } - return this.slots.get(playerId)?.audioPlayer.pause(true) ?? false; + const slot = this.slots.get(playerId); + return slot?.outputBackend.pause(slot.activeResource) ?? false; } public resume(playerId: string): boolean { const mode = this.bus.querySync(playerId, PLAYER_QUERY.playbackMode); if (mode === PlaybackMode.REMOTE) { return this.bus.requestRpcSync(playerId, CONTROLLER_RPC.playbackRemoteResume, {}); } - return this.slots.get(playerId)?.audioPlayer.unpause() ?? false; + const slot = this.slots.get(playerId); + return slot?.outputBackend.resume(slot.activeResource) ?? false; } public stop(playerId: string): boolean { const mode = this.bus.querySync(playerId, PLAYER_QUERY.playbackMode); @@ -621,9 +644,10 @@ export class PlaybackController { const slot = this.slots.get(playerId); if (!slot) return false; this.cancelTransition(slot); + const resource = slot.activeResource; slot.activeSession = null; slot.activeResource = null; - return slot.audioPlayer.stop(true); + return slot.outputBackend.stop(resource); } public async seek(playerId: string, position: number, session?: PlaybackSession): Promise { if (!this.slots.has(playerId)) return false; diff --git a/core/src/controller/PlaybackStartController.ts b/core/src/controller/PlaybackStartController.ts index 4fd10060..cdab167f 100644 --- a/core/src/controller/PlaybackStartController.ts +++ b/core/src/controller/PlaybackStartController.ts @@ -90,14 +90,23 @@ export class PlaybackStartController { import("../types").ActiveStream >(this.playerId, CONTROLLER_RPC.streamReplace, { streamInfo: activeStream, session }); if (context.signal.aborted || !this.isCurrentSession(session, context)) return; - const resource = this.bus.requestRpcSync< + const resource = await this.bus.requestRpc< { stream: import("stream").Readable; track: Track; inputType?: import("@discordjs/voice").StreamType }, AudioResource - >(this.playerId, CONTROLLER_RPC.resourceCreate, { - stream: active.stream, - track, - inputType: active.inputType ?? activeStream.inputType, - }); + >( + this.playerId, + CONTROLLER_RPC.resourceCreate, + { + stream: active.stream, + track, + inputType: active.inputType ?? activeStream.inputType, + }, + { signal: context.signal }, + ); + if (context.signal.aborted || !this.isCurrentSession(session, context)) { + resource.playStream.destroy(); + return; + } session.setResource(resource); this.bus.requestRpcSync(this.playerId, CONTROLLER_RPC.playbackPlay, { resource, session, from, to: track }); session.markPlaying(0); diff --git a/core/src/controller/ResourceRefreshController.ts b/core/src/controller/ResourceRefreshController.ts index 81949d78..337eba23 100644 --- a/core/src/controller/ResourceRefreshController.ts +++ b/core/src/controller/ResourceRefreshController.ts @@ -103,10 +103,15 @@ export class ResourceRefreshController { import("../types").ActiveStream >(playerId, CONTROLLER_RPC.streamReplace, { streamInfo: processed, session }); if (!isCurrentRefresh()) throw new Error("Playback resource refresh superseded"); - const resource = this.bus.requestRpcSync< + const resource = await this.bus.requestRpc< { stream: import("stream").Readable; track: Track; inputType?: StreamType }, AudioResource - >(playerId, PLAYER_RPC.resourceCreate, { stream: active.stream, track: session.track, inputType: active.inputType }); + >( + playerId, + PLAYER_RPC.resourceCreate, + { stream: active.stream, track: session.track, inputType: active.inputType }, + { signal }, + ); if (!isCurrentRefresh()) throw new Error("Playback resource refresh superseded"); session.setResource(resource); session.setPlaybackOffset(Math.max(0, position)); diff --git a/core/src/index.ts b/core/src/index.ts index dabf743d..c815b6a6 100644 --- a/core/src/index.ts +++ b/core/src/index.ts @@ -27,6 +27,23 @@ export { PlayerAction } from "./structures/PlayerAction"; export { PlaybackOrchestrator, createPlaybackOrchestrator } from "./structures/PlaybackOrchestrator"; export { createSharedControllers } from "./structures/PlayerManager"; export { PlaybackSession } from "./structures/PlaybackSession"; +export { + DiscordVoiceOutputBackend, + audioFrameFormatFromDiscordStreamType, + convertFloat32PcmToS16Le, + resolveOutputStreamType, +} from "./output/DiscordVoiceOutputBackend"; +export type { + AudioFrameFormat, + AudioOutputInput, + AudioOutputCapabilities, + AudioOutputContext, + AudioOutputEvent, + AudioOutputHandle, + AudioOutputState, + AudioOutputBackend, +} from "./output/AudioOutputBackend"; +export { AudioOutputUnsupportedOperationError } from "./output/AudioOutputBackend"; export { TrackLoader } from "./structures/TrackLoader"; export { PlaybackController } from "./controller/PlaybackController"; export { ConnectionController } from "./controller/ConnectionController"; @@ -49,7 +66,6 @@ export { createAudioProcessingEngine, defaultAudioProcessingEngine, AudioJsAudioProcessingEngine, - resolveOutputStreamType, } from "./audio/AudioProcessingEngine"; export type { AudioProcessingEngine, diff --git a/core/src/output/AudioOutputBackend.ts b/core/src/output/AudioOutputBackend.ts new file mode 100644 index 00000000..d479b6bb --- /dev/null +++ b/core/src/output/AudioOutputBackend.ts @@ -0,0 +1,83 @@ +import type { Readable } from "stream"; + +export type AudioFrameFormat = + | { + kind: "encoded"; + codec?: string; + container?: string; + } + | { + kind: "pcm"; + sampleFormat: "s16" | "f32"; + endianness: "little"; + sampleRateHz: number; + channels: number; + channelLayout: "interleaved"; + frameSamplesPerChannel?: number; + chunkAlignmentBytes?: number; + }; + +export interface AudioOutputInput { + stream: Readable; + format: AudioFrameFormat; + ownership: "transfer" | "borrow"; +} + +export interface AudioOutputCapabilities { + pause: boolean; + resume: boolean; + stop: boolean; + seek: "native" | "replace" | "unsupported"; + replacement: "atomic" | "stop-before-start" | "unsupported"; + ownership: "transfer" | "borrow" | "both"; + volume: "backend" | "upstream" | "unsupported"; + backpressure: "source" | "bounded" | "unbounded"; + maxBufferedBytes: number | null; +} + +export type AudioOutputState = "ready" | "buffering" | "playing" | "paused" | "stopped" | "ended" | "failed"; + +export type AudioOutputEvent = { type: "state"; state: AudioOutputState } | { type: "error"; error: Error }; + +export interface AudioOutputContext { + signal?: AbortSignal; + metadata?: unknown; +} + +export interface AudioOutputHandle { + readonly resource: TResource; + readonly format: AudioFrameFormat; + readonly ready: Promise; + readonly state: AudioOutputState; + readonly bufferedBytes: number | null; + start(signal?: AbortSignal): void | Promise; + pause(signal?: AbortSignal): boolean | Promise; + resume(signal?: AbortSignal): boolean | Promise; + stop(signal?: AbortSignal): boolean | Promise; + seek(positionMs: number, signal?: AbortSignal): boolean | Promise; + replace(input: AudioOutputInput, signal?: AbortSignal): AudioOutputHandle | Promise>; + setVolume(value: number, signal?: AbortSignal): void | Promise; + onEvent(listener: (event: AudioOutputEvent) => void): () => void; + dispose(): void | Promise; +} + +export interface AudioOutputBackend { + readonly capabilities: AudioOutputCapabilities; + readonly ready: Promise; + initialize(signal?: AbortSignal): Promise; + createSession(input: AudioOutputInput, context?: AudioOutputContext): AudioOutputHandle; + dispose(): void | Promise; +} + +export class AudioOutputUnsupportedOperationError extends Error { + public constructor(operation: string) { + super(`Audio output does not support ${operation}`); + this.name = "AudioOutputUnsupportedOperationError"; + } +} + +export function createAudioAbortError(): Error { + const error = new Error("Audio output operation was aborted"); + error.name = "AbortError"; + return error; +} diff --git a/core/src/output/DiscordVoiceOutputBackend.ts b/core/src/output/DiscordVoiceOutputBackend.ts new file mode 100644 index 00000000..47f42de4 --- /dev/null +++ b/core/src/output/DiscordVoiceOutputBackend.ts @@ -0,0 +1,507 @@ +import { + AudioPlayer, + AudioPlayerState, + AudioPlayerStatus, + AudioResource, + createAudioResource, + StreamType, +} from "@discordjs/voice"; +import { Readable } from "stream"; +import type { + AudioFrameFormat, + AudioOutputBackend, + AudioOutputCapabilities, + AudioOutputContext, + AudioOutputEvent, + AudioOutputHandle, + AudioOutputInput, + AudioOutputState, +} from "./AudioOutputBackend"; +import { AudioOutputUnsupportedOperationError, createAudioAbortError } from "./AudioOutputBackend"; + +const DISCORD_CAPABILITIES: AudioOutputCapabilities = { + pause: true, + resume: true, + stop: true, + seek: "unsupported", + replacement: "atomic", + ownership: "transfer", + volume: "backend", + backpressure: "source", + maxBufferedBytes: null, +}; + +function isAbortError(signal?: AbortSignal): boolean { + return Boolean(signal?.aborted); +} + +function assertNotAborted(signal?: AbortSignal): void { + if (isAbortError(signal)) throw createAudioAbortError(); +} + +function isCurrentResource(state: AudioPlayerState, resource: AudioResource): boolean { + return "resource" in state && state.resource === resource; +} + +function discordStreamType(format: AudioFrameFormat): StreamType { + if (format.kind === "pcm") { + if ( + format.sampleRateHz !== 48_000 || + format.channels !== 2 || + format.channelLayout !== "interleaved" || + format.endianness !== "little" + ) { + throw new TypeError("Discord raw PCM requires interleaved 48 kHz stereo little-endian samples"); + } + if (format.sampleFormat !== "s16" && format.sampleFormat !== "f32") { + throw new TypeError(`Unsupported Discord PCM sample format: ${format.sampleFormat}`); + } + return StreamType.Raw; + } + + if (format.codec === "opus" && format.container === "ogg") return StreamType.OggOpus; + if (format.codec === "opus" && format.container === "webm") return StreamType.WebmOpus; + if (format.codec === "opus") return StreamType.Opus; + return StreamType.Arbitrary; +} + +export function audioFrameFormatFromDiscordStreamType(streamType?: StreamType): AudioFrameFormat { + switch (streamType) { + case StreamType.Opus: + return { kind: "encoded", codec: "opus" }; + case StreamType.OggOpus: + return { kind: "encoded", codec: "opus", container: "ogg" }; + case StreamType.WebmOpus: + return { kind: "encoded", codec: "opus", container: "webm" }; + case StreamType.Raw: + return { + kind: "pcm", + sampleFormat: "s16", + endianness: "little", + sampleRateHz: 48_000, + channels: 2, + channelLayout: "interleaved", + chunkAlignmentBytes: 4, + }; + default: + return { kind: "encoded" }; + } +} + +export function resolveOutputStreamType( + options: { enabled?: boolean; outputFormat?: "encoded" | "pcm16le" | "pcmFloat32" }, + fallback: StreamType = StreamType.Arbitrary, +): StreamType { + if (options.enabled === false) return fallback; + const outputFormat = options.outputFormat ?? "pcm16le"; + if (outputFormat === "pcm16le" || outputFormat === "pcmFloat32") return StreamType.Raw; + if (outputFormat === "encoded") return fallback; + throw new TypeError(`Invalid audio processing output format: ${String(outputFormat)}`); +} + +export function convertFloat32PcmToS16Le(input: Readable): Readable { + return Readable.from( + (async function* () { + let remainder = Buffer.alloc(0); + for await (const chunk of input) { + const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk); + const data = remainder.length ? Buffer.concat([remainder, bytes]) : bytes; + const alignedLength = data.length - (data.length % 4); + if (alignedLength > 0) { + const output = Buffer.allocUnsafe((alignedLength / 4) * 2); + for (let inputOffset = 0, outputOffset = 0; inputOffset < alignedLength; inputOffset += 4, outputOffset += 2) { + const sample = Math.max(-1, Math.min(1, data.readFloatLE(inputOffset))); + output.writeInt16LE(Math.round(sample * 32767), outputOffset); + } + yield output; + } + remainder = data.subarray(alignedLength); + } + if (remainder.length !== 0) throw new Error("Float32 PCM stream ended with an incomplete sample"); + })(), + { objectMode: false }, + ); +} + +class DiscordVoiceOutputHandle implements AudioOutputHandle { + private stateValue: AudioOutputState = "ready"; + private disposed = false; + private readonly listeners = new Set<(event: AudioOutputEvent) => void>(); + private readonly detachListeners = new Set<() => void>(); + private readonly detachSignal?: () => void; + private readonly detachInputClose: () => void; + + public readonly ready: Promise; + + public constructor( + private readonly backend: DiscordVoiceOutputBackend, + public readonly resource: AudioResource, + public readonly format: AudioFrameFormat, + private readonly input: AudioOutputInput, + private readonly signal?: AbortSignal, + ) { + this.ready = backend.ready; + const onInputClose = () => { + if (!backend.isCurrent(this)) this.dispose(); + }; + input.stream.once("close", onInputClose); + this.detachInputClose = () => input.stream.off("close", onInputClose); + if (signal) { + const abort = () => { + this.stateValue = "stopped"; + this.backend.stopHandle(this); + void this.dispose(); + }; + if (signal.aborted) abort(); + else { + signal.addEventListener("abort", abort, { once: true }); + this.detachSignal = () => signal.removeEventListener("abort", abort); + } + } + } + + public get state(): AudioOutputState { + if (this.disposed) return this.stateValue; + const playerState = this.backend.player.state; + if (isCurrentResource(playerState, this.resource)) { + if (playerState.status === AudioPlayerStatus.Playing) return "playing"; + if (playerState.status === AudioPlayerStatus.Paused || playerState.status === AudioPlayerStatus.AutoPaused) return "paused"; + if (playerState.status === AudioPlayerStatus.Buffering) return "buffering"; + } + return this.stateValue; + } + + public get bufferedBytes(): number | null { + return null; + } + + public start(signal?: AbortSignal): void { + assertNotAborted(this.signal); + assertNotAborted(signal); + this.backend.startHandle(this); + this.stateValue = "buffering"; + this.emit({ type: "state", state: "buffering" }); + } + + public pause(signal?: AbortSignal): boolean { + assertNotAborted(this.signal); + assertNotAborted(signal); + const changed = this.backend.pauseHandle(this); + if (changed) { + this.stateValue = "paused"; + this.emit({ type: "state", state: "paused" }); + } + return changed; + } + + public resume(signal?: AbortSignal): boolean { + assertNotAborted(this.signal); + assertNotAborted(signal); + const changed = this.backend.resumeHandle(this); + if (changed) { + this.stateValue = "playing"; + this.emit({ type: "state", state: "playing" }); + } + return changed; + } + + public stop(signal?: AbortSignal): boolean { + assertNotAborted(signal); + if (this.disposed) return false; + const changed = this.backend.stopHandle(this); + this.stateValue = "stopped"; + this.emit({ type: "state", state: "stopped" }); + this.destroyTransferredInput(); + return changed; + } + + public seek(_positionMs: number, signal?: AbortSignal): boolean { + assertNotAborted(signal); + throw new AudioOutputUnsupportedOperationError("seeking; replace the resource at the requested position"); + } + + public replace(input: AudioOutputInput, signal?: AbortSignal): AudioOutputHandle { + assertNotAborted(signal); + const replacement = this.backend.createSession(input, { signal }); + replacement.start(signal); + void this.dispose(); + return replacement; + } + + public setVolume(value: number, signal?: AbortSignal): void { + assertNotAborted(signal); + this.backend.setVolume(this.resource, value); + } + + public onEvent(listener: (event: AudioOutputEvent) => void): () => void { + if (this.disposed) return () => undefined; + this.listeners.add(listener); + let active = true; + const detach = () => { + if (!active) return; + active = false; + this.listeners.delete(listener); + this.detachListeners.delete(detach); + }; + this.detachListeners.add(detach); + return detach; + } + + public dispose(): void { + if (this.disposed) return; + this.disposed = true; + this.detachSignal?.(); + this.detachInputClose(); + for (const detach of [...this.detachListeners]) detach(); + if (this.backend.isCurrent(this)) this.backend.stopHandle(this); + this.destroyTransferredInput(); + this.backend.release(this); + this.stateValue = "stopped"; + } + + public markEnded(): void { + if (this.disposed || this.stateValue === "stopped") return; + this.stateValue = "ended"; + this.emit({ type: "state", state: "ended" }); + this.detachSignal?.(); + this.detachInputClose(); + for (const detach of [...this.detachListeners]) detach(); + this.destroyTransferredInput(); + this.disposed = true; + this.backend.release(this); + } + + public markFailed(error: Error): void { + if (this.disposed) return; + this.stateValue = "failed"; + this.emit({ type: "error", error }); + } + + private emit(event: AudioOutputEvent): void { + for (const listener of this.listeners) listener(event); + } + + public emitEvent(event: AudioOutputEvent): void { + this.emit(event); + } + + public observeState(state: AudioOutputState): void { + if (this.disposed) return; + this.stateValue = state; + this.emit({ type: "state", state }); + } + + private destroyTransferredInput(): void { + if (this.input.ownership === "transfer" && !this.input.stream.destroyed) this.input.stream.destroy(); + } +} + +export class DiscordVoiceOutputBackend implements AudioOutputBackend { + public readonly capabilities = DISCORD_CAPABILITIES; + public readonly ready = Promise.resolve(); + private readonly handles = new Map(); + private activeHandle: DiscordVoiceOutputHandle | null = null; + private disposed = false; + private readonly onPlayerStateChange = (oldState: AudioPlayerState, newState: AudioPlayerState) => { + const handle = this.activeHandle; + if (!handle) return; + if (isCurrentResource(newState, handle.resource)) { + switch (newState.status) { + case AudioPlayerStatus.Buffering: + handle.observeState("buffering"); + break; + case AudioPlayerStatus.Playing: + handle.observeState("playing"); + break; + case AudioPlayerStatus.Paused: + case AudioPlayerStatus.AutoPaused: + handle.observeState("paused"); + break; + } + return; + } + if (isCurrentResource(oldState, handle.resource)) { + this.activeHandle = null; + handle.markEnded(); + } + }; + private readonly onPlayerError = (error: Error & { resource?: AudioResource }) => { + const handle = error.resource ? this.handles.get(error.resource) : this.activeHandle; + handle?.markFailed(error); + }; + + public constructor(public readonly player: AudioPlayer) { + player.on("stateChange", this.onPlayerStateChange); + player.on("error", this.onPlayerError); + } + + public async initialize(signal?: AbortSignal): Promise { + if (this.disposed) throw new Error("Discord voice output backend is disposed"); + assertNotAborted(signal); + await this.ready; + assertNotAborted(signal); + } + + public createSession(input: AudioOutputInput, context: AudioOutputContext = {}): AudioOutputHandle { + try { + return this.createSessionWithInputType(input, context, discordStreamType(input.format)); + } catch (error) { + this.discardTransferredInput(input); + throw error; + } + } + + private createSessionWithInputType( + input: AudioOutputInput, + context: AudioOutputContext, + inputType: StreamType | undefined, + ): AudioOutputHandle { + if (this.disposed) throw new Error("Discord voice output backend is disposed"); + assertNotAborted(context.signal); + if (input.ownership !== "transfer") { + throw new TypeError( + "Discord voice output requires transferred stream ownership because AudioPlayer destroys replaced resources", + ); + } + let outputStream = input.stream; + try { + if (input.format.kind === "pcm" && input.format.sampleFormat === "f32") { + outputStream = convertFloat32PcmToS16Le(input.stream); + } + const resource = createAudioResource(outputStream, { + metadata: context.metadata, + inlineVolume: true, + ...(inputType === undefined ? {} : { inputType }), + }); + const handle = new DiscordVoiceOutputHandle(this, resource, input.format, input, context.signal); + this.handles.set(resource, handle); + return handle; + } catch (error) { + if (outputStream !== input.stream && !outputStream.destroyed) outputStream.destroy(); + this.discardTransferredInput(input); + throw error; + } + } + + public createResource( + stream: Readable, + metadata: unknown, + inputType?: StreamType, + format?: AudioFrameFormat, + signal?: AbortSignal, + ): AudioResource { + const inferredInputType = inputType ?? (stream as Readable & { inputType?: StreamType }).inputType; + const inputFormat = format ?? audioFrameFormatFromDiscordStreamType(inferredInputType); + const discordInputType = format ? discordStreamType(format) : inferredInputType; + const input: AudioOutputInput = { stream, format: inputFormat, ownership: "transfer" }; + try { + return this.createSessionWithInputType(input, { metadata, signal }, discordInputType).resource; + } catch (error) { + this.discardTransferredInput(input); + throw error; + } + } + + public play(resource: AudioResource, signal?: AbortSignal): void { + this.handleFor(resource).start(signal); + } + + public pause(resource?: AudioResource | null, signal?: AbortSignal): boolean { + assertNotAborted(signal); + if (resource && this.activeHandle?.resource !== resource) return false; + return this.player.pause(true); + } + + public resume(resource?: AudioResource | null, signal?: AbortSignal): boolean { + assertNotAborted(signal); + if (resource && this.activeHandle?.resource !== resource) return false; + return this.player.unpause(); + } + + public stop(resource?: AudioResource | null, signal?: AbortSignal): boolean { + assertNotAborted(signal); + if (resource && this.activeHandle?.resource !== resource) return false; + const stopped = this.player.stop(true); + if (this.activeHandle) { + this.activeHandle.markEnded(); + this.activeHandle = null; + } + return stopped; + } + + public setVolume(resource: AudioResource, value: number): void { + if (!resource.volume) throw new AudioOutputUnsupportedOperationError("backend volume control"); + resource.volume.setVolume(value); + } + + public getVolume(resource: AudioResource): number | null { + return resource.volume?.volume ?? null; + } + + public isCurrent(handle: DiscordVoiceOutputHandle): boolean { + return this.activeHandle === handle; + } + + public startHandle(handle: DiscordVoiceOutputHandle): void { + if (this.disposed) throw new Error("Discord voice output backend is disposed"); + const previousHandle = this.activeHandle; + this.activeHandle = handle; + try { + this.player.play(handle.resource); + } catch (error) { + this.activeHandle = previousHandle; + throw error; + } + if (previousHandle && previousHandle !== handle) previousHandle.markEnded(); + } + + public pauseHandle(handle: DiscordVoiceOutputHandle): boolean { + if (this.activeHandle !== handle) return false; + return this.player.pause(true); + } + + public resumeHandle(handle: DiscordVoiceOutputHandle): boolean { + if (this.activeHandle !== handle) return false; + return this.player.unpause(); + } + + public stopHandle(handle: DiscordVoiceOutputHandle): boolean { + if (this.activeHandle !== handle) return false; + const stopped = this.player.stop(true); + this.activeHandle = null; + return stopped; + } + + public release(handle: DiscordVoiceOutputHandle): void { + this.handles.delete(handle.resource); + if (this.activeHandle === handle) this.activeHandle = null; + } + + private discardTransferredInput(input: AudioOutputInput): void { + if (input.ownership === "transfer" && !input.stream.destroyed) input.stream.destroy(); + } + + public dispose(): void { + if (this.disposed) return; + this.disposed = true; + for (const handle of [...this.handles.values()]) handle.dispose(); + this.player.stop(true); + this.activeHandle = null; + this.player.off("stateChange", this.onPlayerStateChange); + this.player.off("error", this.onPlayerError); + } + + private handleFor(resource: AudioResource): DiscordVoiceOutputHandle { + const existing = this.handles.get(resource); + if (existing) return existing; + const format = audioFrameFormatFromDiscordStreamType(undefined); + const input: AudioOutputInput = { + stream: resource.playStream ?? Readable.from([]), + format, + ownership: "transfer", + }; + const handle = new DiscordVoiceOutputHandle(this, resource, format, input); + this.handles.set(resource, handle); + return handle; + } +} diff --git a/docs/AUDIO_OUTPUT_BACKENDS.md b/docs/AUDIO_OUTPUT_BACKENDS.md new file mode 100644 index 00000000..44d3e506 --- /dev/null +++ b/docs/AUDIO_OUTPUT_BACKENDS.md @@ -0,0 +1,95 @@ +# Audio output backend boundary + +ZiPlayer remains Discord-first. `PlayerManager` creates a Discord `AudioPlayer`, `ConnectionController` subscribes it to a Discord +voice connection, and `PlaybackController` remains the compatibility-facing owner of its Discord playback state. The first +extracted seam is deliberately limited to resource construction and output operations; it does not move queueing, track +resolution, recovery, fades, preload, or session policy into the adapter. + +## Current dependency map + +```text +Player / PlaybackOrchestrator + -> Bus RPCs for stream replacement, resource creation, and play/stop + -> PlaybackSession (currently stores AudioResource) + -> PlaybackController (Discord player state, resource state, fades, watchdog) + -> DiscordVoiceOutputBackend + -> createAudioResource / StreamType / AudioPlayer start-pause-resume-stop + -> Discord inline volume and PCM conversion + +AudioProcessingEngine + -> audio DSP (encoded stream decode -> DSP -> interleaved PCM) + -> AudioFrameFormat (no Discord runtime or Discord types) + +Still Discord-specific outside that seam: + ConnectionController, PlayerManager's player factory, FilterController's legacy + stream typing, TTSController, ForwardController, LifecycleController, and compatibility + resource/player types in Player, PlaybackSession, and types/bus.ts. +``` + +The last group is intentionally not hidden by the new contract. In particular, `PlaybackSessionSnapshot`, preload and Bus RPCs +still expose `AudioResource`, and the public `Player` surface exposes Discord connection/player concepts. Removing those leaks +requires a follow-up migration of session identity, event state, preload promotion, forwarding, TTS and public compatibility +types; doing that in this extraction would make it a broad, risky rewrite. + +## Output contract + +`AudioOutputBackend`, `AudioOutputInput`, `AudioOutputHandle`, and `AudioFrameFormat` live in +`core/src/output/AudioOutputBackend.ts` and are exported from the core package. The contract includes: + +- An `initialize(signal)` promise and a session handle with start, pause, resume, stop, seek, replacement, volume, event, and + disposal operations. Backend initialization and per-session readiness can both reject. +- Capability declarations for unsupported operations, replacement behavior, volume ownership, backpressure, and any known + buffering bound. Unsupported methods reject with `AudioOutputUnsupportedOperationError` instead of silently doing nothing. +- An `AbortSignal` at session creation and on operations. `ownership: "transfer"` means the backend must stop consuming and + dispose the stream when the session is stopped, aborted, replaced, or disposed. `"borrow"` forbids the backend from destroying + it. The ownership capability says which modes an adapter accepts; Discord accepts transfer only because its installed + `AudioPlayer` destroys the previous resource's stream during replacement. +- Encoded format metadata, or explicit PCM sample type, little-endian byte order, sample rate, channel count, interleaved layout, + and optional frame/chunk alignment. PCM frame payloads may be split across stream chunks unless the format states a stricter + boundary; backends must honor backpressure and not assume each read is a complete frame. +- Volume is identified as backend-, upstream-, or unsupported. Discord advertises backend volume because its adapter creates an + inline-volume resource. + +The Discord adapter implements this contract and owns the Discord resource factory and the controller's +start/pause/resume/stop/volume operations. The old synchronous `PlaybackController.createResource()` and `Player.createResource()` +behavior remains as a compatibility path; it returns the original `AudioResource` shape. Playback start and resource refresh now +pass cancellation to resource creation. `audioProcessing` only selects DSP options; it does not select or replace the output +backend. + +## Processed audio format and failure behavior + +`AudioProcessingEngine` only transforms audio and does not import `@discordjs/voice`. Its output format is explicit. PCM output is +little-endian, interleaved, and declares sample type, channel count, sample rate, and per-chunk alignment. The engine now applies +configured resampling and remixing rather than merely labeling output with those requested values. + +The installed `@discordjs/voice` 0.19.2 declarations describe `StreamType.Raw` as s16le PCM. Its installed transformer graph +configures raw Discord PCM as 48,000 Hz, 2 channels, signed 16-bit little-endian. The Discord adapter enforces that raw format. +Float32 PCM is converted sample-by-sample to s16le at this explicit boundary, including when a sample is split between input +chunks; it is never passed to the raw PCM decoder as though it were s16le. + +The current audio engine cannot create encoded output, so requesting `outputFormat: "encoded"` while processing is enabled is an +explicit error. Pipeline initialization, DSP, decode, and output failures do not switch to the original encoded stream: the source +may already have been consumed. The stream error flows through the Discord player error/recovery path, and cancellation destroys +owned streams rather than trying to replay them. Raw PCM from non-DSP sources must also be explicitly described as 48 kHz stereo +s16le before it can be sent down Discord's raw path. + +## Adding a Web backend later + +A `WebOutputBackend` can implement the generic session contract and consume the same encoded or explicit PCM input without +inheriting Discord behavior. It will additionally need: + +- A transport frame envelope with codec/configuration and sequence/timestamp data; PCM frames need sample boundaries and format + negotiation. +- Per-client buffering limits, backpressure/drop policy, reconnect behavior, and a bounded queue so slow clients cannot stall or + exhaust shared playback. +- Client join/leave lifecycle, ownership, and synchronization policy (shared live edge versus independently seekable sessions). +- Authentication, authorization, origin policy, TLS/deployment requirements, rate limits, and protection against a client + selecting another user's session. +- A latency budget and clock/drift strategy, especially for synchronized multi-client playback. Decoder and browser buffering + behavior also needs measurement. + +For a first one-way browser listener with ordinary internet reachability and moderate latency tolerance, a WebSocket stream is the +simpler transport to deploy and observe; it handles framing/application messages over a common browser transport but generally has +more jitter/buffering than a media-native transport. WebRTC is a better candidate when interactive controls, low latency, or +synchronized listening dominate, at the cost of signaling, NAT traversal, congestion-control and more involved client lifecycle. +These are transport choices only: neither transport, server, authentication, nor browser protocol is implemented here. diff --git a/tests/audio_output_backend.test.js b/tests/audio_output_backend.test.js new file mode 100644 index 00000000..3ac3ac4e --- /dev/null +++ b/tests/audio_output_backend.test.js @@ -0,0 +1,487 @@ +const test = require("node:test"); +const assert = require("node:assert/strict"); +const { EventEmitter, getEventListeners } = require("node:events"); +const { Readable } = require("node:stream"); +const { AudioOutputUnsupportedOperationError, DiscordVoiceOutputBackend, convertFloat32PcmToS16Le } = require("../core/dist"); +const { StreamType, TransformerType } = require("@discordjs/voice"); + +function abortError() { + const error = new Error("output aborted"); + error.name = "AbortError"; + return error; +} + +function deferred() { + let resolve; + let reject; + const promise = new Promise((res, rej) => { + resolve = res; + reject = rej; + }); + return { promise, resolve, reject }; +} + +class FakeAudioOutputHandle { + constructor(backend, input, context = {}) { + this.backend = backend; + this.input = input; + this.format = input.format; + this.ready = backend.ready; + this.state = "ready"; + this.bufferedBytes = 0; + this.listeners = new Set(); + this.disposed = false; + this.signal = context.signal; + this.onAbort = () => { + if (this.state === "playing") this.state = "stopped"; + void this.dispose(); + }; + this.signal?.addEventListener("abort", this.onAbort, { once: true }); + this.ready.catch(() => { + void this.dispose(); + }); + this.resource = { id: ++backend.nextId }; + } + + async start(signal) { + if (signal?.aborted || this.signal?.aborted) throw abortError(); + await this.waitUntilReady(signal); + if (signal?.aborted || this.signal?.aborted) throw abortError(); + this.state = "playing"; + this.emit({ type: "state", state: this.state }); + this.consumePromise = (async () => { + try { + for await (const chunk of this.input.stream) { + this.bufferedBytes = this.input.stream.readableLength ?? chunk.byteLength; + assert.ok(this.bufferedBytes <= this.backend.capabilities.maxBufferedBytes); + await new Promise((resolve) => setTimeout(resolve, 1)); + } + if (this.state === "playing") this.state = "ended"; + } catch (error) { + if (!this.disposed && this.state !== "stopped") this.fail(error); + } + })(); + } + + async waitUntilReady(signal) { + if (!signal && !this.signal) return this.ready; + return new Promise((resolve, reject) => { + let settled = false; + const clean = () => { + signal?.removeEventListener("abort", onAbort); + this.signal?.removeEventListener("abort", onAbort); + }; + const finish = (callback, value) => { + if (settled) return; + settled = true; + clean(); + callback(value); + }; + const onAbort = () => finish(reject, abortError()); + signal?.addEventListener("abort", onAbort, { once: true }); + this.signal?.addEventListener("abort", onAbort, { once: true }); + this.ready.then( + () => finish(resolve), + (error) => finish(reject, error), + ); + }); + } + + pause(signal) { + if (signal?.aborted) throw abortError(); + if (this.state !== "playing") return false; + this.state = "paused"; + this.emit({ type: "state", state: this.state }); + return true; + } + + resume(signal) { + if (signal?.aborted) throw abortError(); + if (this.state !== "paused") return false; + this.state = "playing"; + this.emit({ type: "state", state: this.state }); + return true; + } + + stop(signal) { + if (signal?.aborted) throw abortError(); + const changed = this.state === "playing" || this.state === "paused"; + this.state = "stopped"; + if (this.input.ownership === "transfer" && !this.input.stream.destroyed) this.input.stream.destroy(); + this.emit({ type: "state", state: this.state }); + return changed; + } + + seek(_position, signal) { + if (signal?.aborted) throw abortError(); + throw new AudioOutputUnsupportedOperationError("seek"); + } + + async replace(input, signal) { + if (signal?.aborted) throw abortError(); + const replacement = this.backend.createSession(input, { signal }); + await replacement.start(signal); + await this.dispose(); + return replacement; + } + + setVolume(value, signal) { + if (signal?.aborted) throw abortError(); + if (this.backend.capabilities.volume !== "backend") throw new AudioOutputUnsupportedOperationError("volume control"); + this.volume = value; + } + + onEvent(listener) { + this.listeners.add(listener); + return () => this.listeners.delete(listener); + } + + fail(error) { + this.state = "failed"; + this.emit({ type: "error", error }); + } + + async dispose() { + if (this.disposed) return; + this.disposed = true; + this.signal?.removeEventListener("abort", this.onAbort); + if (this.input.ownership === "transfer" && !this.input.stream.destroyed) this.input.stream.destroy(); + this.listeners.clear(); + this.backend.handles.delete(this); + } + + emit(event) { + for (const listener of this.listeners) listener(event); + } +} + +class FakeAudioOutputBackend { + constructor() { + this.capabilities = { + pause: true, + resume: true, + stop: true, + seek: "unsupported", + replacement: "atomic", + ownership: "both", + volume: "backend", + backpressure: "bounded", + maxBufferedBytes: 8192, + }; + this.readyGate = deferred(); + this.ready = this.readyGate.promise; + this.handles = new Set(); + this.nextId = 0; + this.disposed = false; + } + + initialize(signal) { + if (signal?.aborted) return Promise.reject(abortError()); + if (!signal) return this.ready; + return new Promise((resolve, reject) => { + const onAbort = () => { + signal.removeEventListener("abort", onAbort); + reject(abortError()); + }; + signal.addEventListener("abort", onAbort, { once: true }); + this.ready.then( + () => { + signal.removeEventListener("abort", onAbort); + resolve(); + }, + (error) => { + signal.removeEventListener("abort", onAbort); + reject(error); + }, + ); + }); + } + + createSession(input, context) { + if (this.disposed) throw new Error("fake backend is disposed"); + const handle = new FakeAudioOutputHandle(this, input, context); + this.handles.add(handle); + return handle; + } + + async dispose() { + for (const handle of [...this.handles]) await handle.dispose(); + this.disposed = true; + } +} + +function pcmFloat32(...samples) { + const result = Buffer.alloc(samples.length * 4); + samples.forEach((sample, index) => result.writeFloatLE(sample, index * 4)); + return result; +} + +class MockAudioPlayer extends EventEmitter { + constructor() { + super(); + this.state = { status: "idle" }; + this.played = []; + } + + play(resource) { + const oldState = this.state; + this.played.push(resource); + this.state = { status: "buffering", resource }; + this.emit("stateChange", oldState, this.state); + } + + enterPlaying() { + const oldState = this.state; + this.state = { status: "playing", resource: oldState.resource }; + this.emit("stateChange", oldState, this.state); + } + + pause() { + const oldState = this.state; + this.state = { status: "paused", resource: oldState.resource }; + this.emit("stateChange", oldState, this.state); + return true; + } + + unpause() { + const oldState = this.state; + this.state = { status: "playing", resource: oldState.resource }; + this.emit("stateChange", oldState, this.state); + return true; + } + + stop() { + const oldState = this.state; + this.state = { status: "idle" }; + this.emit("stateChange", oldState, this.state); + return true; + } +} + +const pcmFormat = { + kind: "pcm", + sampleFormat: "s16", + endianness: "little", + sampleRateHz: 48000, + channels: 2, + channelLayout: "interleaved", + chunkAlignmentBytes: 4, +}; + +test("fake backend readiness gates start and supports the full output lifecycle", async () => { + const backend = new FakeAudioOutputBackend(); + const handle = backend.createSession({ + stream: Readable.from([Buffer.alloc(8)]), + format: pcmFormat, + ownership: "transfer", + }); + const initialization = backend.initialize(); + let started = false; + const start = handle.start().then(() => { + started = true; + }); + await new Promise((resolve) => setImmediate(resolve)); + assert.equal(started, false); + backend.readyGate.resolve(); + await initialization; + await start; + assert.equal(handle.state, "playing"); + assert.equal(handle.pause(), true); + assert.equal(handle.state, "paused"); + assert.equal(handle.resume(), true); + assert.equal(handle.state, "playing"); + handle.setVolume(0.4); + assert.equal(handle.volume, 0.4); + assert.equal(handle.stop(), true); + assert.equal(handle.state, "stopped"); + await handle.dispose(); + assert.equal(handle.input.stream.destroyed, true); + assert.equal(backend.handles.size, 0); + await backend.dispose(); +}); + +test("fake backend propagates abort during startup and active playback", async () => { + const startupBackend = new FakeAudioOutputBackend(); + const startupAbort = new AbortController(); + const startup = startupBackend.createSession( + { stream: Readable.from([]), format: pcmFormat, ownership: "transfer" }, + { signal: startupAbort.signal }, + ); + const pendingStart = startup.start(); + startupAbort.abort(); + await assert.rejects(pendingStart, { name: "AbortError" }); + assert.equal(startup.input.stream.destroyed, true); + assert.equal(getEventListeners(startupAbort.signal, "abort").length, 0); + await startupBackend.dispose(); + + const activeBackend = new FakeAudioOutputBackend(); + activeBackend.readyGate.resolve(); + const activeAbort = new AbortController(); + const active = activeBackend.createSession( + { stream: Readable.from([Buffer.alloc(8)]), format: pcmFormat, ownership: "transfer" }, + { signal: activeAbort.signal }, + ); + await active.start(); + activeAbort.abort(); + await new Promise((resolve) => setImmediate(resolve)); + assert.equal(active.state, "stopped"); + assert.equal(active.input.stream.destroyed, true); + assert.equal(getEventListeners(activeAbort.signal, "abort").length, 0); + await activeBackend.dispose(); +}); + +test("fake backend reports initialization failure and disposes transferred streams", async () => { + const backend = new FakeAudioOutputBackend(); + const inputStream = Readable.from([Buffer.alloc(8)]); + const handle = backend.createSession({ stream: inputStream, format: pcmFormat, ownership: "transfer" }); + const initialization = backend.initialize(); + const failure = new Error("output initialization failed"); + backend.readyGate.reject(failure); + await assert.rejects(initialization, failure); + await assert.rejects(handle.ready, failure); + await new Promise((resolve) => setImmediate(resolve)); + assert.equal(inputStream.destroyed, true); + assert.equal(backend.handles.size, 0); + await backend.dispose(); +}); + +test("fake backend replacement disposes the previous session and reports output errors", async () => { + const backend = new FakeAudioOutputBackend(); + backend.readyGate.resolve(); + const first = backend.createSession({ + stream: Readable.from([]), + format: { kind: "encoded", codec: "opus" }, + ownership: "transfer", + }); + await first.start(); + const replacement = await first.replace({ + stream: Readable.from([Buffer.alloc(16)]), + format: pcmFormat, + ownership: "transfer", + }); + assert.equal(first.disposed, true); + assert.equal(replacement.state, "playing"); + + const reported = []; + replacement.onEvent((event) => reported.push(event)); + const outputError = new Error("sink failed"); + replacement.fail(outputError); + assert.equal(replacement.state, "failed"); + assert.equal(reported.at(-1).type, "error"); + assert.equal(reported.at(-1).error, outputError); + await backend.dispose(); + assert.equal(backend.handles.size, 0); +}); + +test("fake backend advertises bounded buffering and enforces stream backpressure", async () => { + const backend = new FakeAudioOutputBackend(); + backend.readyGate.resolve(); + const source = new Readable({ + highWaterMark: backend.capabilities.maxBufferedBytes, + read() { + for (let i = 0; i < 64; i++) this.push(Buffer.alloc(1024)); + this.push(null); + }, + }); + const handle = backend.createSession({ stream: source, format: pcmFormat, ownership: "transfer" }); + assert.equal(backend.capabilities.backpressure, "bounded"); + assert.equal(handle.bufferedBytes, 0); + await handle.start(); + await handle.consumePromise; + assert.ok(handle.bufferedBytes <= backend.capabilities.maxBufferedBytes); + assert.equal(backend.capabilities.seek, "unsupported"); + await backend.dispose(); + assert.equal(backend.handles.size, 0); +}); + +test("Discord backend converts float32 PCM at the adapter boundary and controls inline volume", async () => { + const player = new MockAudioPlayer(); + const backend = new DiscordVoiceOutputBackend(player); + const track = { id: "float-track", title: "Float PCM", duration: 1000 }; + const input = Readable.from([pcmFloat32(-1, -0.5, 0.5, 1)]); + const fragmentedFloatPcm = pcmFloat32(-1, -0.5, 0.5, 1); + const converterInput = Readable.from([fragmentedFloatPcm.subarray(0, 5), fragmentedFloatPcm.subarray(5)]); + const convertedChunks = []; + for await (const chunk of convertFloat32PcmToS16Le(converterInput)) convertedChunks.push(Buffer.from(chunk)); + const converted = Buffer.concat(convertedChunks); + assert.equal(converted.byteLength, 8); + assert.deepEqual( + Array.from({ length: 4 }, (_, index) => converted.readInt16LE(index * 2)), + [-32767, -16383, 16384, 32767], + ); + const resource = backend.createResource(input, track, StreamType.Raw, { + kind: "pcm", + sampleFormat: "f32", + endianness: "little", + sampleRateHz: 48000, + channels: 2, + channelLayout: "interleaved", + }); + assert.equal(resource.metadata, track); + assert.ok(resource.volume); + backend.setVolume(resource, 0.25); + assert.equal(backend.getVolume(resource), 0.25); + + assert.ok(resource.edges.some((edge) => edge.type === TransformerType.InlineVolume)); + assert.ok(resource.edges.some((edge) => edge.type === TransformerType.OpusEncoder)); + backend.dispose(); +}); + +test("Discord backend preserves lifecycle behavior and removes its player listeners on disposal", async () => { + const player = new MockAudioPlayer(); + const baselineStateListeners = player.listenerCount("stateChange"); + const baselineErrorListeners = player.listenerCount("error"); + const backend = new DiscordVoiceOutputBackend(player); + const handle = backend.createSession({ + stream: Readable.from([Buffer.alloc(8)]), + format: pcmFormat, + ownership: "transfer", + }); + const events = []; + const detach = handle.onEvent((event) => events.push(event)); + handle.start(); + assert.equal(player.played[0], handle.resource); + assert.equal(handle.state, "buffering"); + player.enterPlaying(); + assert.equal(handle.state, "playing"); + assert.equal(handle.pause(), true); + assert.equal(handle.state, "paused"); + assert.equal(handle.resume(), true); + assert.equal(handle.state, "playing"); + assert.equal(handle.stop(), true); + assert.equal(handle.state, "stopped"); + assert.ok(events.some((event) => event.type === "state")); + detach(); + handle.dispose(); + backend.dispose(); + assert.equal(player.listenerCount("stateChange"), baselineStateListeners); + assert.equal(player.listenerCount("error"), baselineErrorListeners); +}); + +test("Discord backend rejects PCM formats that do not meet the raw PCM contract", () => { + const backend = new DiscordVoiceOutputBackend(new MockAudioPlayer()); + assert.throws( + () => + backend.createSession({ + stream: Readable.from([]), + format: { ...pcmFormat, sampleRateHz: 44100 }, + ownership: "transfer", + }), + /Discord raw PCM requires interleaved 48 kHz stereo/, + ); + backend.dispose(); +}); + +test("Discord backend rejects borrowed streams because voice replacement destroys resources", () => { + const backend = new DiscordVoiceOutputBackend(new MockAudioPlayer()); + assert.throws( + () => + backend.createSession({ + stream: Readable.from([]), + format: { kind: "encoded", codec: "opus" }, + ownership: "borrow", + }), + /requires transferred stream ownership/, + ); + backend.dispose(); +}); diff --git a/tests/audio_processing_engine.test.js b/tests/audio_processing_engine.test.js index 825d7d89..b57e3f60 100644 --- a/tests/audio_processing_engine.test.js +++ b/tests/audio_processing_engine.test.js @@ -82,7 +82,35 @@ test("audio processing engine emits valid PCM16 bytes for processed output", asy await pipeline.dispose(); }); -test("PlaybackController falls back to the legacy stream when DSP setup fails before the first chunk", () => { +test("audio processing declares and enforces its PCM sample rate, channel count, and chunk alignment", async () => { + const engine = createAudioProcessingEngine({ enabled: true, outputFormat: "pcm16le" }); + const audioMod = await import("audio"); + const wav = await audioMod.default + .from((t) => Math.sin(2 * Math.PI * 440 * t), { duration: 0.02, sampleRate: 8000, channels: 1 }) + .encode("wav"); + const pipeline = await engine.createPipeline({ enabled: true, outputFormat: "pcm16le" }); + assert.deepEqual(pipeline.outputFormat, { + kind: "pcm", + sampleFormat: "s16", + endianness: "little", + sampleRateHz: 48000, + channels: 2, + channelLayout: "interleaved", + chunkAlignmentBytes: 4, + }); + const chunks = []; + let byteLength = 0; + for await (const chunk of pipeline.process([wav], AbortSignal.timeout(3000))) { + assert.equal(chunk.byteLength % pipeline.outputFormat.chunkAlignmentBytes, 0); + byteLength += chunk.byteLength; + chunks.push(chunk); + } + assert.ok(chunks.length > 0); + assert.equal(byteLength, 3840); + await pipeline.dispose(); +}); + +test("PlaybackController fails DSP setup instead of replaying a possibly consumed source stream", () => { const { Bus, PlaybackController } = require("../core/dist"); const bus = new Bus(); const controller = new PlaybackController(bus); @@ -100,12 +128,50 @@ test("PlaybackController falls back to the legacy stream when DSP setup fails be }); const stream = Readable.from([Buffer.from([0x00, 0x01, 0x02, 0x03])]); const track = { id: "fallback-track", title: "Fallback", duration: 1000 }; - const resource = controller.createResource("p5", stream, track, StreamType.Opus); - assert.ok(resource); - assert.equal(resource.metadata.title, "Fallback"); + assert.throws( + () => controller.createResource("p5", stream, track, StreamType.Opus), + /Audio processing inputFormat=pcm16le.*not supported/, + ); + assert.equal(stream.readableDidRead, false); + assert.equal(stream.destroyed, true); controller.detach("p5"); }); +test("PlaybackController reports runtime DSP failure instead of mixing in encoded source bytes", async () => { + const { Bus, PlaybackController } = require("../core/dist"); + const bus = new Bus(); + const controller = new PlaybackController(bus); + const audioPlayer = Object.assign(new EventEmitter(), { + state: { status: "idle" }, + play() {}, + pause() { + return true; + }, + unpause() { + return true; + }, + stop() { + return true; + }, + }); + controller.attach("p6", { audioPlayer, audioProcessing: { enabled: true } }); + const source = Readable.from([Buffer.from("not-a-valid-audio-container")]); + const resource = controller.createResource( + "p6", + source, + { id: "broken-track", title: "Broken source", duration: 1000 }, + StreamType.Opus, + ); + await assert.rejects(async () => { + for await (const _chunk of resource.playStream) { + assert.fail("Encoded source bytes must not be emitted as raw PCM fallback"); + } + }, /Audio processing failed for Broken source/); + assert.equal(source.readableDidRead, true); + assert.equal(source.destroyed, true); + controller.detach("p6"); +}); + test("processed raw PCM uses the Discord raw stream contract", () => { assert.equal(resolveOutputStreamType({ enabled: true, outputFormat: "pcm16le" }, StreamType.Opus), StreamType.Raw); assert.equal(resolveOutputStreamType({ enabled: true, outputFormat: "pcmFloat32" }, StreamType.WebmOpus), StreamType.Raw); From 485969381849c44130fbfe086ac27fb79dadb9c5 Mon Sep 17 00:00:00 2001 From: Ziji <104454302+zijipia@users.noreply.github.com> Date: Sat, 10 Oct 2026 11:05:23 +0900 Subject: [PATCH 05/55] refactor: update playback control methods to support async/await - Changed stopPlayback method signatures to return Promise in various controllers. - Updated calls to stopPlayback to use await for proper asynchronous handling. - Modified PreloadController to handle playback state changes asynchronously. - Enhanced error handling in audio output backend tests to ensure proper lifecycle management. - Improved documentation on audio output backend selection and lifecycle management. --- .github/workflows/node.js.yml | 50 +- core/src/controller/PlaybackController.ts | 519 +++++++++++++++--- core/src/controller/PlaybackSkipController.ts | 2 +- .../src/controller/PlaybackStartController.ts | 11 +- .../controller/PlaybackTrackEndController.ts | 2 +- core/src/controller/PreloadController.ts | 26 +- .../controller/ResourceRefreshController.ts | 2 +- core/src/index.ts | 2 + core/src/output/AudioOutputBackend.ts | 8 + core/src/output/DiscordVoiceOutputBackend.ts | 7 +- core/src/structures/PlaybackOrchestrator.ts | 12 +- core/src/structures/PlayerManager.ts | 2 + core/src/types/controller.ts | 3 +- core/src/types/core.ts | 3 + core/src/types/options.ts | 6 +- docs/AUDIO_OUTPUT_BACKENDS.md | 62 ++- tests/audio_output_backend.test.js | 263 ++++++++- 17 files changed, 833 insertions(+), 147 deletions(-) diff --git a/.github/workflows/node.js.yml b/.github/workflows/node.js.yml index 75040875..d0f08b78 100644 --- a/.github/workflows/node.js.yml +++ b/.github/workflows/node.js.yml @@ -1,9 +1,8 @@ name: Node.js CI permissions: - contents: write + contents: read issues: write - pull-requests: write on: push: @@ -12,37 +11,6 @@ on: branches: ["main"] jobs: - format-fix-on-push: - if: github.event_name == 'push' - runs-on: ubuntu-latest - steps: - - name: Checkout - uses: actions/checkout@v4 - with: - token: ${{ secrets.ACTIONS_TOKEN }} - fetch-depth: 0 - - - name: Use Node.js - uses: actions/setup-node@v4 - with: - node-version: "20.x" - - - name: Run Prettier (write) - run: npx prettier --ignore-path .gitignore --write . - - - name: Commit changes - run: | - git config --local user.email "41898282+github-actions[bot]@users.noreply.github.com" - git config --local user.name "github-actions[bot]" - git add . - git diff --cached --exit-code || git commit -m "chore: format with prettier" - - - name: Push changes - uses: ad-m/github-push-action@master - with: - github_token: ${{ secrets.ACTIONS_TOKEN }} - branch: ${{ github.head_ref || github.ref_name }} - format-check-on-pr: if: github.event_name == 'pull_request' runs-on: ubuntu-latest @@ -62,7 +30,7 @@ jobs: shell: bash run: | set -e - OUTPUT="$(npx prettier --ignore-path .gitignore -l . || true)" + OUTPUT="$(npx prettier --ignore-path .gitignore -l .)" echo "files<> "$GITHUB_OUTPUT" echo "$OUTPUT" >> "$GITHUB_OUTPUT" echo "EOF" >> "$GITHUB_OUTPUT" @@ -123,18 +91,18 @@ jobs: - name: Bootstrap core package run: | - npm -C core ci || npm -C core i --force - npm -C core run build || true + npm -C core ci + npm -C core run build - name: Bootstrap plugins package run: | - npm -C plugins ci || npm -C plugins i --force - npm -C plugins run build || true + npm -C plugins ci + npm -C plugins run build - name: Bootstrap extension package run: | - npm -C extension ci || npm -C extension i --force - npm -C extension run build || true + npm -C extension ci + npm -C extension run build - name: Run tests id: tests @@ -158,7 +126,7 @@ jobs: if: github.event_name == 'pull_request' uses: actions/github-script@v7 with: - github-token: ${{ secrets.ACTIONS_TOKEN }} + github-token: ${{ secrets.GITHUB_TOKEN }} script: | const marker = ''; const status = `${{ steps.tests.outputs.status }}` || 'unknown'; diff --git a/core/src/controller/PlaybackController.ts b/core/src/controller/PlaybackController.ts index 5216f71e..d37ab8e8 100644 --- a/core/src/controller/PlaybackController.ts +++ b/core/src/controller/PlaybackController.ts @@ -1,7 +1,14 @@ import { AudioPlayer, AudioPlayerState, AudioPlayerStatus, AudioResource, StreamType } from "@discordjs/voice"; import { Readable } from "stream"; -import type { AudioFrameFormat } from "../output/AudioOutputBackend"; -import { DiscordVoiceOutputBackend } from "../output/DiscordVoiceOutputBackend"; +import type { + AudioFrameFormat, + AudioOutputBackend, + AudioOutputHandle, + AudioOutputState, + AudioOutputInput, +} from "../output/AudioOutputBackend"; +import { AudioOutputUnsupportedOperationError } from "../output/AudioOutputBackend"; +import { audioFrameFormatFromDiscordStreamType, DiscordVoiceOutputBackend } from "../output/DiscordVoiceOutputBackend"; import type { Bus } from "../structures/Bus"; import type { PlaybackSession } from "../structures/PlaybackSession"; import type { Track, PlaybackControllerOptions } from "../types"; @@ -20,8 +27,9 @@ import { /** Everything the controller keeps for ONE player. Lives only inside `PlaybackController.slots`. */ interface PlaybackSlot { readonly playerId: string; - readonly audioPlayer: AudioPlayer; - readonly outputBackend: DiscordVoiceOutputBackend; + readonly audioPlayer: AudioPlayer | null; + readonly outputBackend: AudioOutputBackend; + backendInitialization: Promise | null; readonly stuckTimeoutMs: number; readonly recoveryHandlers: AntiStuckRetryHandlers; readonly lifecycleAbort: AbortController; @@ -29,12 +37,19 @@ interface PlaybackSlot { readonly onStateChange: (oldState: AudioPlayerState, newState: AudioPlayerState) => void; readonly onError: (error: Error) => void; activeResource: AudioResource | null; + activeHandle: AudioOutputHandle | null; + outputState: AudioOutputState; + readonly handles: Map>; + readonly handleDetachers: Map void>; + readonly volumeValues: Map; activeSession: PlaybackSession | null; transitionTimer: ReturnType | null; + transitionStartResolve: (() => void) | null; fadeTimer: ReturnType | null; stuckTimer: ReturnType | null; resourceRefreshInProgress: boolean; fadeGain: number | null; + fadeResource: AudioResource | null; disposed: boolean; } @@ -67,13 +82,13 @@ export class PlaybackController { ); bus.registerRpc(PLAYER_RPC.transitionFadeOutCurrent, (_req, ctx) => this.applyCrossfadeOutCurrent(ctx.playerId)); bus.registerRpc(PLAYER_RPC.transitionSkipAndStop, (_req, ctx) => this.crossfadeSkipAndStop(ctx.playerId)); - bus.registerRpc<{ resource: AudioResource; session?: PlaybackSession; from?: Track | null; to?: Track }, void>( + bus.registerRpc<{ resource: AudioResource; session?: PlaybackSession; from?: Track | null; to?: Track }, void | Promise>( CONTROLLER_RPC.playbackPlay, - ({ resource, session, from, to }, ctx) => this.play(ctx.playerId, resource, session, from, to), + ({ resource, session, from, to }, ctx) => this.play(ctx.playerId, resource, session, from, to, ctx.signal), ); - bus.registerRpc(CONTROLLER_RPC.playbackPause, (_req, ctx) => this.pause(ctx.playerId)); - bus.registerRpc(CONTROLLER_RPC.playbackResume, (_req, ctx) => this.resume(ctx.playerId)); - bus.registerRpc(CONTROLLER_RPC.playbackStop, (_req, ctx) => this.stop(ctx.playerId)); + bus.registerRpc(CONTROLLER_RPC.playbackPause, (_req, ctx) => this.pause(ctx.playerId, ctx.signal)); + bus.registerRpc(CONTROLLER_RPC.playbackResume, (_req, ctx) => this.resume(ctx.playerId, ctx.signal)); + bus.registerRpc(CONTROLLER_RPC.playbackStop, (_req, ctx) => this.stop(ctx.playerId, ctx.signal)); bus.registerRpc(CONTROLLER_RPC.playbackBeginResourceRefresh, (_req, ctx) => this.beginResourceRefresh(ctx.playerId), ); @@ -109,21 +124,35 @@ export class PlaybackController { if (this.slots.has(playerId)) this.detach(playerId); if (options.audioProcessing?.enabled) this.processingOptions.set(playerId, options.audioProcessing); else this.processingOptions.delete(playerId); - const outputBackend = new DiscordVoiceOutputBackend(options.audioPlayer); + if (!options.audioOutputBackendFactory && !options.audioPlayer) { + throw new TypeError("An audioPlayer is required unless an audioOutputBackendFactory is provided"); + } + const outputBackend = + options.audioOutputBackendFactory ? + options.audioOutputBackendFactory({ playerId }) + : new DiscordVoiceOutputBackend(options.audioPlayer!); const slot: PlaybackSlot = { playerId, - audioPlayer: options.audioPlayer, + audioPlayer: options.audioPlayer ?? null, outputBackend, + backendInitialization: null, stuckTimeoutMs: Math.max(0, options.stuckTimeoutMs ?? 10000), lifecycleAbort: new AbortController(), detachBusHandlers: [], activeResource: null, + activeHandle: null, + outputState: options.audioPlayer ? this.mapPlayerStatus(options.audioPlayer.state.status) : "ready", + handles: new Map(), + handleDetachers: new Map(), + volumeValues: new Map(), activeSession: null, transitionTimer: null, + transitionStartResolve: null, fadeTimer: null, stuckTimer: null, resourceRefreshInProgress: false, fadeGain: null, + fadeResource: null, disposed: false, recoveryHandlers: { retry: async ({ session }) => { @@ -144,6 +173,7 @@ export class PlaybackController { this.bus.action(playerId, { type: PLAYER_ACTION.skip }, { signal: session.signal, sessionId: session.sessionId }), }, onStateChange: (a, b) => { + slot.outputState = this.mapPlayerStatus(b.status); this.bus.publish(playerId, BUS_EVENT.stateChanged, a, b); if (b.status === AudioPlayerStatus.Buffering) this.armStuckWatchdog(slot); else this.clearStuckWatchdog(slot); @@ -171,11 +201,14 @@ export class PlaybackController { this.bus.subscribe(playerId, BUS_EVENT.volumeRequested, () => { if (!slot.activeResource) return; const track = slot.activeSession?.track ?? (slot.activeResource.metadata as Track | undefined); - this.applyTargetVolume(slot, slot.activeResource, track, slot.fadeGain ?? 1); + void this.applyTargetVolume(slot, slot.activeResource, track, slot.fadeGain ?? 1).catch((error) => { + const activeHandle = slot.activeHandle; + if (activeHandle) this.handleOutputError(slot, activeHandle, error instanceof Error ? error : new Error(String(error))); + }); }), ); - slot.audioPlayer.on("stateChange", slot.onStateChange); - slot.audioPlayer.on("error", slot.onError); + slot.audioPlayer?.on("stateChange", slot.onStateChange); + if (options.audioOutputBackendFactory) slot.audioPlayer?.on("error", slot.onError); this.slots.set(playerId, slot); } @@ -193,10 +226,31 @@ export class PlaybackController { slot.activeSession?.destroy(); slot.activeSession = null; for (const detach of slot.detachBusHandlers.splice(0)) detach(); - slot.audioPlayer.removeListener("stateChange", slot.onStateChange); - slot.audioPlayer.removeListener("error", slot.onError); - slot.outputBackend.dispose(); + slot.audioPlayer?.removeListener("stateChange", slot.onStateChange); + if (slot.audioPlayer && !(slot.outputBackend instanceof DiscordVoiceOutputBackend)) { + slot.audioPlayer.removeListener("error", slot.onError); + } + for (const detach of slot.handleDetachers.values()) detach(); + slot.handleDetachers.clear(); + slot.handles.clear(); + slot.volumeValues.clear(); + try { + void Promise.resolve(slot.outputBackend.dispose()).catch((error) => { + this.bus.event(playerId, { + type: BUS_EVENT.streamError, + error: error instanceof Error ? error : new Error(String(error)), + track: null, + }); + }); + } catch (error) { + this.bus.event(playerId, { + type: BUS_EVENT.streamError, + error: error instanceof Error ? error : new Error(String(error)), + track: null, + }); + } slot.activeResource = null; + slot.activeHandle = null; } /** Global shutdown: releases every player's slot. */ @@ -236,8 +290,8 @@ export class PlaybackController { let playing = 0; let paused = 0; let idle = 0; - for (const slot of this.slots.values()) { - switch (slot.audioPlayer.state.status) { + for (const playerId of this.slots.keys()) { + switch (this.status(playerId)) { case AudioPlayerStatus.Playing: playing++; break; @@ -255,10 +309,36 @@ export class PlaybackController { return this.slots.get(playerId)?.audioPlayer ?? null; } public state(playerId: string): AudioPlayerState | null { - return this.slots.get(playerId)?.audioPlayer.state ?? null; + return this.slots.get(playerId)?.audioPlayer?.state ?? null; } public status(playerId: string): AudioPlayerStatus | undefined { - return this.slots.get(playerId)?.audioPlayer.state.status; + const slot = this.slots.get(playerId); + return slot ? (slot.audioPlayer?.state.status ?? this.mapOutputState(slot.outputState)) : undefined; + } + private mapPlayerStatus(status: AudioPlayerStatus): AudioOutputState { + switch (status) { + case AudioPlayerStatus.Buffering: + return "buffering"; + case AudioPlayerStatus.Playing: + return "playing"; + case AudioPlayerStatus.Paused: + case AudioPlayerStatus.AutoPaused: + return "paused"; + case AudioPlayerStatus.Idle: + return "stopped"; + } + } + private mapOutputState(state: AudioOutputState): AudioPlayerStatus { + switch (state) { + case "buffering": + return AudioPlayerStatus.Buffering; + case "playing": + return AudioPlayerStatus.Playing; + case "paused": + return AudioPlayerStatus.Paused; + default: + return AudioPlayerStatus.Idle; + } } public currentResource(playerId: string): AudioResource | null { const slot = this.slots.get(playerId); @@ -310,10 +390,23 @@ export class PlaybackController { } } - private applyTargetVolume(slot: PlaybackSlot, resource: AudioResource | null, track?: Track | null, gain = 1): void { - if (!resource?.volume) return; + private async applyTargetVolume(slot: PlaybackSlot, resource: AudioResource | null, track?: Track | null, gain = 1): Promise { + if (!resource) return; + const handle = slot.handles.get(resource); const target = this.requestVolumeTarget(slot.playerId, track); - slot.outputBackend.setVolume(resource, target * Math.max(0, Number.isFinite(gain) ? gain : 1)); + const value = target * Math.max(0, Number.isFinite(gain) ? gain : 1); + if (slot.outputBackend.capabilities.volume === "unsupported") { + if (value === 1) return; + throw new AudioOutputUnsupportedOperationError("volume control"); + } + if (!handle && slot.outputBackend instanceof DiscordVoiceOutputBackend) { + slot.outputBackend.setVolume(resource, value); + slot.volumeValues.set(resource, value); + return; + } + if (!handle) throw new Error("No output handle is registered for the requested resource"); + await handle.setVolume(value, slot.lifecycleAbort.signal); + slot.volumeValues.set(resource, value); } private retirePendingSession(playerId: string): void { @@ -346,7 +439,7 @@ export class PlaybackController { slot.stuckTimer = null; if ( slot.resourceRefreshInProgress || - slot.audioPlayer.state.status !== AudioPlayerStatus.Buffering || + slot.outputState !== "buffering" || slot.activeResource !== resource || slot.activeSession !== session ) @@ -371,7 +464,7 @@ export class PlaybackController { const slot = this.slots.get(playerId); if (!slot) return; slot.resourceRefreshInProgress = false; - if (slot.audioPlayer.state.status === AudioPlayerStatus.Buffering) this.armStuckWatchdog(slot); + if (slot.outputState === "buffering") this.armStuckWatchdog(slot); } public reportFilterError(playerId: string, error: Error): void { const slot = this.slots.get(playerId); @@ -399,8 +492,7 @@ export class PlaybackController { const resolvedInputType = inputType ?? (stream as Readable & { inputType?: StreamType }).inputType; const processingOptions = this.processingOptions.get(playerId) ?? {}; const slot = this.slots.get(playerId); - const outputBackend = slot?.outputBackend; - if (!outputBackend) throw new Error("No Discord output backend is attached for this player"); + if (!slot) throw new Error("No output backend is attached for this player"); const outputSignal = slot ? signal ? AbortSignal.any([slot.lifecycleAbort.signal, signal]) @@ -465,31 +557,269 @@ export class PlaybackController { else outputSignal.addEventListener("abort", abortProcessing, { once: true }); } processedStream.once("close", () => outputSignal?.removeEventListener("abort", abortProcessing)); - return outputBackend.createResource(processedStream, track, resolvedInputType, outputFormat, outputSignal); + return this.createOutputResource(slot, processedStream, track, outputFormat, outputSignal); } - return outputBackend.createResource(stream, track, resolvedInputType, undefined, outputSignal); + return this.createOutputResource( + slot, + stream, + track, + audioFrameFormatFromDiscordStreamType(resolvedInputType), + outputSignal, + ); } - public play(playerId: string, resource: AudioResource, session?: PlaybackSession, from?: Track | null, to?: Track): void { + private createOutputResource( + slot: PlaybackSlot, + stream: Readable, + track: Track, + format: AudioFrameFormat, + signal?: AbortSignal, + ): AudioResource { + const input: AudioOutputInput = { stream, format, ownership: "transfer" }; + if (slot.outputBackend.capabilities.ownership !== "both" && slot.outputBackend.capabilities.ownership !== input.ownership) { + if (!stream.destroyed) stream.destroy(); + throw new TypeError(`Output backend does not accept ${input.ownership} stream ownership`); + } + try { + const handle = slot.outputBackend.createSession(input, { metadata: track, signal }); + this.registerOutputHandle(slot, handle); + return handle.resource; + } catch (error) { + if (input.ownership === "transfer" && !stream.destroyed) stream.destroy(); + throw error; + } + } + + private registerOutputHandle(slot: PlaybackSlot, handle: AudioOutputHandle): void { + if (slot.handles.get(handle.resource) === handle) return; + const detach = handle.onEvent((event) => { + if (slot.handles.get(handle.resource) !== handle) return; + if (event.type === "error") { + this.handleOutputError(slot, handle, event.error); + return; + } + slot.outputState = event.state; + if (event.state === "buffering") this.armStuckWatchdog(slot); + else this.clearStuckWatchdog(slot); + if (event.state === "ended" && slot.activeHandle === handle) { + const session = slot.activeSession; + if (session?.isActive()) this.bus.event(slot.playerId, { type: BUS_EVENT.trackEnd, session: session.snapshot() }); + slot.activeSession = null; + slot.activeResource = null; + slot.activeHandle = null; + } else if (event.state === "stopped" && slot.activeHandle === handle) { + slot.activeSession?.markStopped(); + slot.activeSession = null; + slot.activeResource = null; + slot.activeHandle = null; + } + }); + slot.handles.set(handle.resource, handle); + slot.handleDetachers.set(handle.resource, detach); + } + + private handleOutputError(slot: PlaybackSlot, handle: AudioOutputHandle, error: Error): void { + if (slot.handles.get(handle.resource) !== handle) return; + slot.outputState = "failed"; + if (slot.activeHandle !== handle) return; + const session = slot.activeSession; + if (session?.isActive()) { + this.bus.event(slot.playerId, { type: BUS_EVENT.trackError, session: session.snapshot(), error }); + void this.reportStuck(slot, session, `audio output error: ${error.message}`); + } else { + this.bus.event(slot.playerId, { type: BUS_EVENT.streamError, error, track: null }); + } + slot.activeHandle = null; + slot.activeResource = null; + void this.disposeOutputHandle(slot, handle); + } + + public play( + playerId: string, + resource: AudioResource, + session?: PlaybackSession, + from?: Track | null, + to?: Track, + signal?: AbortSignal, + ): void | Promise { const slot = this.slots.get(playerId); if (!slot) return; if (session && !session.isActive()) return; + let handle = slot.handles.get(resource); + if (!handle && slot.outputBackend instanceof DiscordVoiceOutputBackend) { + handle = slot.outputBackend.getSessionHandle(resource); + this.registerOutputHandle(slot, handle); + } + if (!handle) throw new Error("No output handle is registered for the requested resource"); + if (slot.outputBackend instanceof DiscordVoiceOutputBackend) { + return this.playDiscordCompatibility(slot, resource, handle, session, from, to); + } + return this.playWithBackend(slot, resource, handle, session, from, to, signal); + } + + private async playWithBackend( + slot: PlaybackSlot, + resource: AudioResource, + handle: AudioOutputHandle, + session?: PlaybackSession, + from?: Track | null, + to?: Track, + signal?: AbortSignal, + ): Promise { + const playerId = slot.playerId; this.cancelTransition(slot); const track = session?.track ?? to ?? (resource.metadata as Track | undefined); const plan = from && to ? this.requestTransitionPlan(playerId, from, to) : undefined; - if (plan?.enabled && slot.activeResource && slot.audioPlayer.state.status !== AudioPlayerStatus.Idle) { - this.fadeTransition(slot, slot.activeResource, resource, plan, session, track); + if ( + plan?.enabled && + slot.activeResource && + slot.outputState !== "stopped" && + slot.outputState !== "ended" && + slot.outputState !== "failed" + ) { + if (slot.outputBackend.capabilities.volume === "unsupported") { + await this.disposeOutputHandle(slot, handle); + throw new AudioOutputUnsupportedOperationError("crossfade volume control"); + } + if (slot.outputBackend.capabilities.replacement === "unsupported") { + await this.disposeOutputHandle(slot, handle); + throw new AudioOutputUnsupportedOperationError("track replacement"); + } + await this.fadeTransition(slot, slot.activeResource, resource, plan, session, track); return; } slot.fadeGain = null; - this.applyTargetVolume(slot, resource, track, 1); + await this.applyTargetVolume(slot, resource, track, 1); if (session) session.setResource(resource); slot.activeSession = session ?? null; slot.activeResource = resource; - slot.outputBackend.play(resource); + await this.startOutputHandle(slot, handle, signal ?? session?.signal); this.retirePendingSession(playerId); } + private playDiscordCompatibility( + slot: PlaybackSlot, + resource: AudioResource, + handle: AudioOutputHandle, + session?: PlaybackSession, + from?: Track | null, + to?: Track, + ): void { + this.cancelTransition(slot); + const track = session?.track ?? to ?? (resource.metadata as Track | undefined); + const plan = from && to ? this.requestTransitionPlan(slot.playerId, from, to) : undefined; + const currentStatus = slot.audioPlayer?.state.status ?? this.mapOutputState(slot.outputState); + if (plan?.enabled && slot.activeResource && currentStatus !== AudioPlayerStatus.Idle) { + if (slot.outputBackend.capabilities.volume === "unsupported") { + void this.disposeOutputHandle(slot, handle); + throw new AudioOutputUnsupportedOperationError("crossfade volume control"); + } + if (slot.outputBackend.capabilities.replacement === "unsupported") { + void this.disposeOutputHandle(slot, handle); + throw new AudioOutputUnsupportedOperationError("track replacement"); + } + void this.fadeTransition(slot, slot.activeResource, resource, plan, session, track); + return; + } + slot.fadeGain = null; + void this.applyTargetVolume(slot, resource, track, 1).catch((error) => { + this.handleOutputError(slot, handle, error instanceof Error ? error : new Error(String(error))); + }); + if (session) session.setResource(resource); + slot.activeSession = session ?? null; + slot.activeResource = resource; + slot.activeHandle = handle; + try { + handle.start(session?.signal); + slot.outputState = handle.state; + this.retirePendingSession(slot.playerId); + } catch (error) { + this.handleOutputError(slot, handle, error instanceof Error ? error : new Error(String(error))); + throw error; + } + } + + private async startOutputHandle( + slot: PlaybackSlot, + handle: AudioOutputHandle, + signal?: AbortSignal, + ): Promise { + const lifecycleSignal = slot.lifecycleAbort.signal; + const activeSignal = signal ? AbortSignal.any([lifecycleSignal, signal]) : lifecycleSignal; + try { + slot.backendInitialization ??= slot.outputBackend.initialize(lifecycleSignal); + await this.awaitWithAbort(slot.backendInitialization, activeSignal); + await this.awaitWithAbort(handle.ready, activeSignal); + if (activeSignal.aborted) throw new Error("Audio output start was aborted"); + const previous = slot.activeHandle; + if (previous && previous !== handle) { + if (slot.outputBackend.capabilities.replacement === "unsupported") { + throw new AudioOutputUnsupportedOperationError("track replacement"); + } + if (slot.outputBackend.capabilities.replacement === "stop-before-start") { + await previous.stop(activeSignal); + await this.disposeOutputHandle(slot, previous); + } + } + slot.activeHandle = handle; + await handle.start(activeSignal); + slot.outputState = handle.state; + } catch (error) { + if (!activeSignal.aborted) { + this.handleOutputError(slot, handle, error instanceof Error ? error : new Error(String(error))); + } else if (slot.activeHandle === handle) { + slot.activeHandle = null; + slot.activeResource = null; + } + await this.disposeOutputHandle(slot, handle); + throw error; + } + } + + private async awaitWithAbort(promise: Promise, signal: AbortSignal): Promise { + if (signal.aborted) throw this.outputAbortError(); + return new Promise((resolve, reject) => { + const onAbort = () => { + signal.removeEventListener("abort", onAbort); + reject(this.outputAbortError()); + }; + signal.addEventListener("abort", onAbort, { once: true }); + promise.then( + (value) => { + signal.removeEventListener("abort", onAbort); + resolve(value); + }, + (error) => { + signal.removeEventListener("abort", onAbort); + reject(error); + }, + ); + }); + } + + private outputAbortError(): Error { + const error = new Error("Audio output operation was aborted"); + error.name = "AbortError"; + return error; + } + + private async disposeOutputHandle(slot: PlaybackSlot, handle: AudioOutputHandle): Promise { + const detach = slot.handleDetachers.get(handle.resource); + detach?.(); + slot.handleDetachers.delete(handle.resource); + slot.handles.delete(handle.resource); + slot.volumeValues.delete(handle.resource); + try { + await handle.dispose(); + } catch (error) { + this.bus.event(slot.playerId, { + type: BUS_EVENT.streamError, + error: error instanceof Error ? error : new Error(String(error)), + track: slot.activeSession?.track ?? null, + }); + } + } + public async fadeResourceVolume( playerId: string, resource: AudioResource, @@ -501,26 +831,43 @@ export class PlaybackController { const slot = this.slots.get(playerId); if (!slot) return; const abortSignal = signal ?? slot.lifecycleAbort.signal; - if (!resource?.volume) return; + if (!resource) return; const duration = Math.max(0, durationMs); if (duration === 0) { - if (!abortSignal.aborted && !slot.disposed) slot.outputBackend.setVolume(resource, to); + if (!abortSignal.aborted && !slot.disposed) await this.setResourceVolume(slot, resource, to); return; } const start = Date.now(); while (!abortSignal.aborted && !slot.disposed) { const progress = Math.min(1, (Date.now() - start) / duration); - slot.outputBackend.setVolume(resource, from + (to - from) * progress); + await this.setResourceVolume(slot, resource, from + (to - from) * progress); if (progress >= 1) return; await new Promise((resolve) => setTimeout(resolve, 25)); } } + private async setResourceVolume(slot: PlaybackSlot, resource: AudioResource, value: number): Promise { + const handle = slot.handles.get(resource); + if (slot.outputBackend.capabilities.volume === "unsupported") { + throw new AudioOutputUnsupportedOperationError("volume control"); + } + if (!handle && slot.outputBackend instanceof DiscordVoiceOutputBackend) { + slot.outputBackend.setVolume(resource, value); + slot.volumeValues.set(resource, value); + return; + } + if (!handle) throw new Error("No output handle is registered for the requested resource"); + await handle.setVolume(value, slot.lifecycleAbort.signal); + slot.volumeValues.set(resource, value); + } public async applyCrossfadeIn(playerId: string, resource: AudioResource, track: Track): Promise { const slot = this.slots.get(playerId); - if (!slot || slot.outputBackend.getVolume(resource) === null || slot.disposed) return; - this.applyTargetVolume(slot, resource, track, 1); - const target = slot.outputBackend.getVolume(resource) ?? 0; - slot.outputBackend.setVolume(resource, 0); + if (!slot || slot.disposed) return; + if (slot.outputBackend.capabilities.volume === "unsupported") { + throw new AudioOutputUnsupportedOperationError("crossfade volume control"); + } + await this.applyTargetVolume(slot, resource, track, 1); + const target = slot.volumeValues.get(resource) ?? 0; + await this.setResourceVolume(slot, resource, 0); await this.fadeResourceVolume( playerId, resource, @@ -536,8 +883,10 @@ export class PlaybackController { const resource = slot.activeResource; if (!resource) return; const track = slot.activeSession?.track ?? (resource.metadata as Track | undefined); - const current = slot.outputBackend.getVolume(resource); - if (current === null) return; + const current = + slot.volumeValues.get(resource) ?? + (slot.outputBackend instanceof DiscordVoiceOutputBackend ? slot.outputBackend.getVolume(resource) : null); + if (current == null) return; await this.fadeResourceVolume( playerId, resource, @@ -550,7 +899,7 @@ export class PlaybackController { public async crossfadeSkipAndStop(playerId: string): Promise { await this.applyCrossfadeOutCurrent(playerId); const slot = this.slots.get(playerId); - if (slot && !slot.disposed) this.stop(playerId); + if (slot && !slot.disposed) await this.stop(playerId); } public getTrackTargetVolume(playerId: string, track?: Track | null): number { return this.requestVolumeTarget(playerId, track); @@ -562,25 +911,29 @@ export class PlaybackController { plan: TransitionPlanResponse, session?: PlaybackSession, track?: Track, - ): void { + ): Promise { slot.fadeGain = 0; - this.applyTargetVolume(slot, newResource, track, 0); + slot.fadeResource = newResource; + const preparedVolume = this.applyTargetVolume(slot, newResource, track, 0); const outgoingTrack = slot.activeSession?.track ?? (oldResource.metadata as Track | undefined) ?? null; const outgoingPosition = slot.activeSession?.position ?? 0; const wait = plan.waitForBeat ? this.requestBeatWait(slot.playerId, outgoingTrack, outgoingPosition) : 0; - const begin = () => { + const begin = async (): Promise => { slot.transitionTimer = null; if (slot.disposed || (session && !session.isActive())) { this.cancelFadeSlot(slot); return; } slot.fadeGain = 0; - this.applyTargetVolume(slot, newResource, track, 0); - slot.outputBackend.play(newResource); + const handle = slot.handles.get(newResource); + if (!handle) throw new Error("No output handle is registered for the transition resource"); this.retirePendingSession(slot.playerId); if (session) session.setResource(newResource); slot.activeSession = session ?? null; slot.activeResource = newResource; + await preparedVolume; + if (slot.fadeGain === null || slot.disposed || (session && !session.isActive())) return; + await this.startOutputHandle(slot, handle, session?.signal); const start = Date.now(); slot.fadeTimer = setInterval(() => { if (session && !session.isActive()) { @@ -589,15 +942,30 @@ export class PlaybackController { } const p = Math.min(1, (Date.now() - start) / Math.max(1, plan.durationMs)); slot.fadeGain = p; - this.applyTargetVolume(slot, newResource, track, p); + void this.applyTargetVolume(slot, newResource, track, p).catch((error) => + this.handleOutputError(slot, handle, error instanceof Error ? error : new Error(String(error))), + ); if (p >= 1) { this.cancelFadeSlot(slot); - this.applyTargetVolume(slot, newResource, track, 1); + void this.applyTargetVolume(slot, newResource, track, 1).catch((error) => + this.handleOutputError(slot, handle, error instanceof Error ? error : new Error(String(error))), + ); } }, 25); }; - if (wait > 0) slot.transitionTimer = setTimeout(begin, wait); - else begin(); + return new Promise((resolve, reject) => { + const run = () => { + slot.transitionTimer = null; + slot.transitionStartResolve = null; + void begin().then(resolve, reject); + }; + if (wait > 0) { + slot.transitionStartResolve = resolve; + slot.transitionTimer = setTimeout(run, wait); + } else { + run(); + } + }); } private cancelFadeSlot(slot: PlaybackSlot): void { @@ -607,9 +975,16 @@ export class PlaybackController { } if (slot.fadeGain !== null) { slot.fadeGain = null; - if (slot.activeResource) { - const track = slot.activeSession?.track ?? (slot.activeResource.metadata as Track | undefined); - this.applyTargetVolume(slot, slot.activeResource, track, 1); + const resource = slot.fadeResource ?? slot.activeResource; + slot.fadeResource = null; + if (resource) { + const track = resource === slot.activeResource ? + slot.activeSession?.track ?? (resource.metadata as Track | undefined) + : (resource.metadata as Track | undefined); + void this.applyTargetVolume(slot, resource, track, 1).catch((error) => { + const handle = slot.handles.get(resource); + if (handle) this.handleOutputError(slot, handle, error instanceof Error ? error : new Error(String(error))); + }); } } } @@ -617,26 +992,32 @@ export class PlaybackController { if (slot.transitionTimer) { clearTimeout(slot.transitionTimer); slot.transitionTimer = null; + slot.transitionStartResolve?.(); + slot.transitionStartResolve = null; } this.cancelFadeSlot(slot); } - public pause(playerId: string): boolean { + public async pause(playerId: string, signal?: AbortSignal): Promise { const mode = this.bus.querySync(playerId, PLAYER_QUERY.playbackMode); if (mode === PlaybackMode.REMOTE) { - return this.bus.requestRpcSync(playerId, CONTROLLER_RPC.playbackRemotePause, {}); + return this.bus.requestRpc(playerId, CONTROLLER_RPC.playbackRemotePause, {}); } const slot = this.slots.get(playerId); - return slot?.outputBackend.pause(slot.activeResource) ?? false; + if (!slot?.activeHandle) return false; + if (!slot.outputBackend.capabilities.pause) throw new AudioOutputUnsupportedOperationError("pause"); + return slot.activeHandle.pause(signal ?? slot.lifecycleAbort.signal); } - public resume(playerId: string): boolean { + public async resume(playerId: string, signal?: AbortSignal): Promise { const mode = this.bus.querySync(playerId, PLAYER_QUERY.playbackMode); if (mode === PlaybackMode.REMOTE) { - return this.bus.requestRpcSync(playerId, CONTROLLER_RPC.playbackRemoteResume, {}); + return this.bus.requestRpc(playerId, CONTROLLER_RPC.playbackRemoteResume, {}); } const slot = this.slots.get(playerId); - return slot?.outputBackend.resume(slot.activeResource) ?? false; + if (!slot?.activeHandle) return false; + if (!slot.outputBackend.capabilities.resume) throw new AudioOutputUnsupportedOperationError("resume"); + return slot.activeHandle.resume(signal ?? slot.lifecycleAbort.signal); } - public stop(playerId: string): boolean { + public async stop(playerId: string, signal?: AbortSignal): Promise { const mode = this.bus.querySync(playerId, PLAYER_QUERY.playbackMode); if (mode === PlaybackMode.REMOTE) { void this.bus.requestRpc(playerId, CONTROLLER_RPC.playbackRemoteStop, {}); @@ -644,10 +1025,16 @@ export class PlaybackController { const slot = this.slots.get(playerId); if (!slot) return false; this.cancelTransition(slot); - const resource = slot.activeResource; + const handle = slot.activeHandle; slot.activeSession = null; slot.activeResource = null; - return slot.outputBackend.stop(resource); + slot.activeHandle = null; + if (!handle) return false; + if (!slot.outputBackend.capabilities.stop) throw new AudioOutputUnsupportedOperationError("stop"); + const stopped = await handle.stop(signal ?? slot.lifecycleAbort.signal); + await this.disposeOutputHandle(slot, handle); + slot.outputState = "stopped"; + return stopped; } public async seek(playerId: string, position: number, session?: PlaybackSession): Promise { if (!this.slots.has(playerId)) return false; diff --git a/core/src/controller/PlaybackSkipController.ts b/core/src/controller/PlaybackSkipController.ts index 5d2ec223..6d00c298 100644 --- a/core/src/controller/PlaybackSkipController.ts +++ b/core/src/controller/PlaybackSkipController.ts @@ -92,7 +92,7 @@ export class PlaybackSkipController { oldSession.markEnded(); } if (!next) { - this.stopPlayback(context.signal); + await this.stopPlayback(context.signal); this.publishState(); this.setWaitingForQueue(true); this.bus.event(this.playerId, { type: BUS_EVENT.queueEnd }); diff --git a/core/src/controller/PlaybackStartController.ts b/core/src/controller/PlaybackStartController.ts index cdab167f..c5bdcfd8 100644 --- a/core/src/controller/PlaybackStartController.ts +++ b/core/src/controller/PlaybackStartController.ts @@ -44,7 +44,7 @@ export class PlaybackStartController { this.bus.requestRpcSync<{ track: Track }, boolean>(this.playerId, CONTROLLER_RPC.preloadHas, { track }) : (this.adapters?.hasPreload?.(track) ?? false); const transition = this.transitionEnabled(); - if (!transition) this.stopPlayback(parentContext.signal, !hasPreload); + if (!transition) await this.stopPlayback(parentContext.signal, !hasPreload); this.bus.requestRpcSync(this.playerId, CONTROLLER_RPC.trackResetRecovery, {}); @@ -104,11 +104,16 @@ export class PlaybackStartController { { signal: context.signal }, ); if (context.signal.aborted || !this.isCurrentSession(session, context)) { - resource.playStream.destroy(); return; } session.setResource(resource); - this.bus.requestRpcSync(this.playerId, CONTROLLER_RPC.playbackPlay, { resource, session, from, to: track }); + await this.bus.requestRpc( + this.playerId, + CONTROLLER_RPC.playbackPlay, + { resource, session, from, to: track }, + { signal: context.signal }, + ); + if (context.signal.aborted || !this.isCurrentSession(session, context)) return; session.markPlaying(0); this.consecutiveFailures = 0; if (transition) this.sessionController.retirePendingPrevious(this.playerId); diff --git a/core/src/controller/PlaybackTrackEndController.ts b/core/src/controller/PlaybackTrackEndController.ts index d6363e46..d91803c8 100644 --- a/core/src/controller/PlaybackTrackEndController.ts +++ b/core/src/controller/PlaybackTrackEndController.ts @@ -161,7 +161,7 @@ export class PlaybackTrackEndController { const finalSession = this.currentSession(); if (!finalSession || finalSession.id !== snapshot.id || !finalSession.isActive()) return; endedSession.markEnded(); - this.stopPlayback(context.signal); + await this.stopPlayback(context.signal); this.publishState(); this.waitingForQueue = true; this.bus.event(this.playerId, { type: BUS_EVENT.queueEnd }); diff --git a/core/src/controller/PreloadController.ts b/core/src/controller/PreloadController.ts index f4b7d170..180f4acb 100644 --- a/core/src/controller/PreloadController.ts +++ b/core/src/controller/PreloadController.ts @@ -120,18 +120,17 @@ export class PreloadController { // --------------------------------------------------------------------- public promotePreload(playerId: string, track: Track): AudioResource | null { - if (!this.bus) return null; - const session = this.bus.querySync(playerId, PLAYER_QUERY.playbackSessionInternal); + const bus = this.bus; + if (!bus) return null; + const session = bus.querySync(playerId, PLAYER_QUERY.playbackSessionInternal); if (!session) return null; - const promoted = this.bus.requestRpcSync<{ track: Track }, PromotedPreload | null>(playerId, PLAYER_RPC.preloadPromote, { - track, - }); + const promoted = bus.requestRpcSync<{ track: Track }, PromotedPreload | null>(playerId, PLAYER_RPC.preloadPromote, { track }); if (!promoted) return null; const streamInfo: StreamInfo = promoted.streamInfo ? normalizeStreamInfo(promoted.track, promoted.streamInfo) : normalizeStreamInfo(promoted.track, { stream: promoted.stream as any, type: "arbitrary" }); - const resource = this.bus.requestRpcSync< + const resource = bus.requestRpcSync< { stream: import("stream").Readable; track: Track; inputType?: import("@discordjs/voice").StreamType }, AudioResource >(playerId, PLAYER_RPC.resourceCreate, { @@ -140,9 +139,18 @@ export class PreloadController { inputType: streamInfo.inputType, }); session.setResource(resource); - this.bus.requestRpcSync(playerId, CONTROLLER_RPC.playbackPlay, { resource, session }); - session.markPlaying(0); - this.bus.event(playerId, { type: BUS_EVENT.playbackStateChanged, session: session.snapshot() }); + void bus + .requestRpc(playerId, CONTROLLER_RPC.playbackPlay, { resource, session }, { signal: session.signal }) + .then(() => { + if (!session.isActive()) return; + session.markPlaying(0); + bus.event(playerId, { type: BUS_EVENT.playbackStateChanged, session: session.snapshot() }); + }) + .catch((error) => { + if (!session.isActive()) return; + const normalized = error instanceof Error ? error : new Error(String(error)); + bus.event(playerId, { type: BUS_EVENT.trackError, session: session.snapshot(), error: normalized }); + }); return resource; } diff --git a/core/src/controller/ResourceRefreshController.ts b/core/src/controller/ResourceRefreshController.ts index 337eba23..d07c8d1e 100644 --- a/core/src/controller/ResourceRefreshController.ts +++ b/core/src/controller/ResourceRefreshController.ts @@ -115,7 +115,7 @@ export class ResourceRefreshController { if (!isCurrentRefresh()) throw new Error("Playback resource refresh superseded"); session.setResource(resource); session.setPlaybackOffset(Math.max(0, position)); - this.bus.requestRpcSync(playerId, CONTROLLER_RPC.playbackPlay, { resource, session }); + await this.bus.requestRpc(playerId, CONTROLLER_RPC.playbackPlay, { resource, session }, { signal }); session.markPlaying(Math.max(0, position)); this.bus.event(playerId, { type: BUS_EVENT.playbackStateChanged, session: session.snapshot() }); return session.snapshot(); diff --git a/core/src/index.ts b/core/src/index.ts index c815b6a6..cf7de732 100644 --- a/core/src/index.ts +++ b/core/src/index.ts @@ -37,6 +37,8 @@ export type { AudioFrameFormat, AudioOutputInput, AudioOutputCapabilities, + AudioOutputBackendFactory, + AudioOutputBackendFactoryContext, AudioOutputContext, AudioOutputEvent, AudioOutputHandle, diff --git a/core/src/output/AudioOutputBackend.ts b/core/src/output/AudioOutputBackend.ts index d479b6bb..b8dc1573 100644 --- a/core/src/output/AudioOutputBackend.ts +++ b/core/src/output/AudioOutputBackend.ts @@ -44,6 +44,14 @@ export interface AudioOutputContext { metadata?: unknown; } +export interface AudioOutputBackendFactoryContext { + playerId: string; +} + +export type AudioOutputBackendFactory = ( + context: AudioOutputBackendFactoryContext, +) => AudioOutputBackend; + export interface AudioOutputHandle { readonly resource: TResource; readonly format: AudioFrameFormat; diff --git a/core/src/output/DiscordVoiceOutputBackend.ts b/core/src/output/DiscordVoiceOutputBackend.ts index 47f42de4..63bde83f 100644 --- a/core/src/output/DiscordVoiceOutputBackend.ts +++ b/core/src/output/DiscordVoiceOutputBackend.ts @@ -43,7 +43,7 @@ function isCurrentResource(state: AudioPlayerState, resource: AudioResource): bo return "resource" in state && state.resource === resource; } -function discordStreamType(format: AudioFrameFormat): StreamType { +function discordStreamType(format: AudioFrameFormat): StreamType | undefined { if (format.kind === "pcm") { if ( format.sampleRateHz !== 48_000 || @@ -62,6 +62,7 @@ function discordStreamType(format: AudioFrameFormat): StreamType { if (format.codec === "opus" && format.container === "ogg") return StreamType.OggOpus; if (format.codec === "opus" && format.container === "webm") return StreamType.WebmOpus; if (format.codec === "opus") return StreamType.Opus; + if (!format.codec && !format.container) return undefined; return StreamType.Arbitrary; } @@ -438,6 +439,10 @@ export class DiscordVoiceOutputBackend implements AudioOutputBackend { + return this.handleFor(resource); + } + public isCurrent(handle: DiscordVoiceOutputHandle): boolean { return this.activeHandle === handle; } diff --git a/core/src/structures/PlaybackOrchestrator.ts b/core/src/structures/PlaybackOrchestrator.ts index fcc7a723..ba58e0a6 100644 --- a/core/src/structures/PlaybackOrchestrator.ts +++ b/core/src/structures/PlaybackOrchestrator.ts @@ -19,7 +19,7 @@ import { PlaybackPlayController } from "../controller/PlaybackPlayController"; interface OrchestratorCallbacks { matchesContext: (session: PlaybackSession, context: PlayerMessageContext) => boolean; transitionEnabled: (playerId: string) => boolean; - stopPlayback: (playerId: string, signal: AbortSignal, cancelPreload?: boolean) => void; + stopPlayback: (playerId: string, signal: AbortSignal, cancelPreload?: boolean) => void | Promise; nextThroughBus: (playerId: string, ignoreLoop: boolean, context: PlayerMessageContext) => Promise; publishState: (playerId: string) => void; queueSnapshot: (playerId: string) => Track[]; @@ -287,7 +287,7 @@ export class PlaybackOrchestrator { if ( session?.isActive() && this.matchesContext(session, context) && - this.bus.requestRpcSync(playerId, CONTROLLER_RPC.playbackPause, {}) + (await this.bus.requestRpc(playerId, CONTROLLER_RPC.playbackPause, {}, { signal: context.signal })) ) { session.markPaused(); this.publishState(playerId); @@ -313,7 +313,7 @@ export class PlaybackOrchestrator { if ( session?.isActive() && this.matchesContext(session, context) && - this.bus.requestRpcSync(playerId, CONTROLLER_RPC.playbackResume, {}) + (await this.bus.requestRpc(playerId, CONTROLLER_RPC.playbackResume, {}, { signal: context.signal })) ) { session.markPlaying(); this.publishState(playerId); @@ -328,7 +328,7 @@ export class PlaybackOrchestrator { void this.bus.requestRpc(playerId, CONTROLLER_RPC.playbackRemoteStop, {}); } if (session && !this.matchesContext(session, context)) break; - this.stopPlayback(playerId, context.signal); + await this.stopPlayback(playerId, context.signal); this.bus.requestRpcSync(playerId, PLAYER_RPC.queueClear, undefined); if (session?.isActive()) session.markStopped(); this.publishState(playerId); @@ -342,8 +342,8 @@ export class PlaybackOrchestrator { return session.ownsContext(context.sessionId); } - private stopPlayback(playerId: string, _s: AbortSignal, cancelPreload = true): void { - this.bus.requestRpcSync(playerId, CONTROLLER_RPC.playbackStop, {}); + private async stopPlayback(playerId: string, signal: AbortSignal, cancelPreload = true): Promise { + await this.bus.requestRpc(playerId, CONTROLLER_RPC.playbackStop, {}, { signal }); if (!cancelPreload) return; if (this.bus.hasRpc(PLAYER_RPC.preloadCancel)) { this.bus.requestRpcSync(playerId, PLAYER_RPC.preloadCancel, {}); diff --git a/core/src/structures/PlayerManager.ts b/core/src/structures/PlayerManager.ts index 4353c11c..e6c63c82 100644 --- a/core/src/structures/PlayerManager.ts +++ b/core/src/structures/PlayerManager.ts @@ -523,6 +523,8 @@ export class PlayerManager extends EventEmitter { this.controllers.playback.attach(playerId, { audioPlayer, stuckTimeoutMs: options?.antiStuck?.stuckTimeoutMs, + audioProcessing: options?.audioProcessing, + audioOutputBackendFactory: options?.audioOutputBackendFactory, }); this.controllers.preload.attach(playerId); diff --git a/core/src/types/controller.ts b/core/src/types/controller.ts index 06cde0b5..da3f53bf 100644 --- a/core/src/types/controller.ts +++ b/core/src/types/controller.ts @@ -19,9 +19,10 @@ export interface LifecycleControllerOptions { } /** Per-player resources handed to the shared `PlaybackController` via `attach(playerId, options)`. */ export interface PlaybackControllerOptions { - audioPlayer: AudioPlayer; + audioPlayer?: AudioPlayer; stuckTimeoutMs?: number; audioProcessing?: import("../audio/AudioProcessingEngine").AudioProcessingOptions; + audioOutputBackendFactory?: import("../output/AudioOutputBackend").AudioOutputBackendFactory; } export interface ActiveStream { diff --git a/core/src/types/core.ts b/core/src/types/core.ts index 6a0e9ccf..a4f2a88a 100644 --- a/core/src/types/core.ts +++ b/core/src/types/core.ts @@ -5,6 +5,7 @@ import type { AudioFilter } from "./filter"; import type { SourcePluginLike } from "./plugin"; import type { AudioResource, StreamType } from "@discordjs/voice"; import type { PlayerDebugLevel } from "./debug"; +import type { AudioOutputBackendFactory } from "../output/AudioOutputBackend"; export enum PlaybackMode { NATIVE = "native", @@ -202,6 +203,8 @@ export interface PlayerOptions { resampleRate?: number; maxBufferBytes?: number; }; + /** Creates an output backend owned by this player. Discord Voice is used when omitted. */ + audioOutputBackendFactory?: AudioOutputBackendFactory; maxStreamStore?: number; } diff --git a/core/src/types/options.ts b/core/src/types/options.ts index bd5f42f9..955795cf 100644 --- a/core/src/types/options.ts +++ b/core/src/types/options.ts @@ -12,7 +12,7 @@ export interface PlaybackStartControllerOptions { bus: Bus; sessionController: PlaybackSessionController; transitionEnabled: () => boolean; - stopPlayback: (signal: AbortSignal, cancelPreload?: boolean) => void; + stopPlayback: (signal: AbortSignal, cancelPreload?: boolean) => void | Promise; prepareTrack: (session: PlaybackSession, context: import("./bus").PlayerMessageContext) => Promise; adapters?: PlaybackOrchestratorAdapters; } @@ -26,14 +26,14 @@ export interface PlaybackPreparationControllerOptions { export interface PlaybackSkipControllerOptions { bus: Bus; nextThroughBus: (ignoreLoop: boolean, context: import("./bus").PlayerMessageContext) => Promise; - stopPlayback: (signal: AbortSignal) => void; + stopPlayback: (signal: AbortSignal) => void | Promise; publishState: () => void; setWaitingForQueue: (waiting: boolean) => void; } export interface PlaybackTrackEndControllerOptions { bus: Bus; nextThroughBus: (ignoreLoop: boolean, context: import("./bus").PlayerMessageContext) => Promise; - stopPlayback: (signal: AbortSignal) => void; + stopPlayback: (signal: AbortSignal) => void | Promise; publishState: () => void; queueSnapshot: () => Track[]; lifecycleSignal: AbortSignal; diff --git a/docs/AUDIO_OUTPUT_BACKENDS.md b/docs/AUDIO_OUTPUT_BACKENDS.md index 44d3e506..7d708fdc 100644 --- a/docs/AUDIO_OUTPUT_BACKENDS.md +++ b/docs/AUDIO_OUTPUT_BACKENDS.md @@ -1,9 +1,10 @@ # Audio output backend boundary -ZiPlayer remains Discord-first. `PlayerManager` creates a Discord `AudioPlayer`, `ConnectionController` subscribes it to a Discord -voice connection, and `PlaybackController` remains the compatibility-facing owner of its Discord playback state. The first -extracted seam is deliberately limited to resource construction and output operations; it does not move queueing, track -resolution, recovery, fades, preload, or session policy into the adapter. +ZiPlayer remains Discord-first. `PlayerManager` creates a Discord `AudioPlayer` when no custom output factory is supplied, and +`ConnectionController` subscribes that player to a Discord voice connection. `PlaybackController` is still the compatibility +boundary for legacy Discord resources and synchronous APIs, but generic playback operations use normalized backend handle +state and lifecycle methods. The extraction does not move queueing, track resolution, recovery, fades, preload, or session +policy into the adapter. ## Current dependency map @@ -11,7 +12,7 @@ resolution, recovery, fades, preload, or session policy into the adapter. Player / PlaybackOrchestrator -> Bus RPCs for stream replacement, resource creation, and play/stop -> PlaybackSession (currently stores AudioResource) - -> PlaybackController (Discord player state, resource state, fades, watchdog) + -> PlaybackController (normalized handle state; Discord compatibility state, fades, watchdog) -> DiscordVoiceOutputBackend -> createAudioResource / StreamType / AudioPlayer start-pause-resume-stop -> Discord inline volume and PCM conversion @@ -50,11 +51,38 @@ types; doing that in this extraction would make it a broad, risky rewrite. - Volume is identified as backend-, upstream-, or unsupported. Discord advertises backend volume because its adapter creates an inline-volume resource. -The Discord adapter implements this contract and owns the Discord resource factory and the controller's -start/pause/resume/stop/volume operations. The old synchronous `PlaybackController.createResource()` and `Player.createResource()` -behavior remains as a compatibility path; it returns the original `AudioResource` shape. Playback start and resource refresh now -pass cancellation to resource creation. `audioProcessing` only selects DSP options; it does not select or replace the output -backend. +The Discord adapter implements this contract and owns Discord resource creation and player start/pause/resume/stop/volume +operations. The old synchronous `PlaybackController.createResource()` and `Player.createResource()` behavior remains a +compatibility path; it returns the original `AudioResource` shape. Playback start and resource refresh pass cancellation to +resource creation. `audioProcessing` only selects DSP options; it does not select or replace the output backend. + +## Selecting a backend + +Backend selection is per player and has no global mutable default. `PlayerOptions.audioOutputBackendFactory` is optional; when +omitted, ZiPlayer constructs `DiscordVoiceOutputBackend` around the manager-created `AudioPlayer`. A factory is invoked once per +attached player and its backend instance is owned by that player's `PlaybackController` slot. Detaching/replacing the slot aborts +its lifecycle signal, disposes its handles, detaches event listeners, and disposes the backend. A caller should therefore return +a fresh backend instance for each factory invocation unless it explicitly manages safe sharing itself. + +```ts +const player = await manager.create(guildId, { + audioOutputBackendFactory: ({ playerId }) => createMyBackend(playerId), +}); +``` + +The factory is a typed injection seam, not a plugin registry. At this stage its resource type remains +`AudioOutputBackendFactory` to preserve the Bus, `PlaybackSession`, preload, and public `Player` compatibility +contracts. A custom transport can run without a Discord voice connection (as the fake integration backend does), but a fully +Discord-independent resource type is not yet supported at the public TypeScript boundary. Generalizing that identity without +breaking existing `AudioResource` consumers is follow-up work; do not treat the current seam as a completed Web backend API. + +The backend owns each session handle it creates; the slot owns the backend and registered handle-event detachers. A transferred +input stream is destroyed on stop, cancellation, replacement, failure cleanup, or disposal. A borrowed stream must not be +destroyed by the backend. Session readiness and backend initialization must settle before start; failure is reported through the +existing track-error/recovery path. A consumed stream is never replayed after DSP or sink failure. Operations unsupported by +the selected backend reject explicitly, including seek or volume operations when the capability says unsupported. The fake +backend tests cover lifecycle, startup cancellation, replacement, output failure, volume/crossfade capability, and disposal +without opening a Discord voice connection. ## Processed audio format and failure behavior @@ -93,3 +121,17 @@ simpler transport to deploy and observe; it handles framing/application messages more jitter/buffering than a media-native transport. WebRTC is a better candidate when interactive controls, low latency, or synchronized listening dominate, at the cost of signaling, NAT traversal, congestion-control and more involved client lifecycle. These are transport choices only: neither transport, server, authentication, nor browser protocol is implemented here. + +## Verification + +From the repository root, run: + +```sh +npm run build:core +node --test tests/audio_output_backend.test.js tests/audio_processing_engine.test.js +npm test +npm run format:check +``` + +The Node.js CI workflow runs required package builds without success-shaped fallbacks. It checks formatting but does not rewrite, +commit, or push source files. diff --git a/tests/audio_output_backend.test.js b/tests/audio_output_backend.test.js index 3ac3ac4e..0cc2cb05 100644 --- a/tests/audio_output_backend.test.js +++ b/tests/audio_output_backend.test.js @@ -1,7 +1,7 @@ const test = require("node:test"); const assert = require("node:assert/strict"); const { EventEmitter, getEventListeners } = require("node:events"); -const { Readable } = require("node:stream"); +const { PassThrough, Readable } = require("node:stream"); const { AudioOutputUnsupportedOperationError, DiscordVoiceOutputBackend, convertFloat32PcmToS16Le } = require("../core/dist"); const { StreamType, TransformerType } = require("@discordjs/voice"); @@ -29,11 +29,13 @@ class FakeAudioOutputHandle { this.ready = backend.ready; this.state = "ready"; this.bufferedBytes = 0; + this.volumeValues = []; this.listeners = new Set(); this.disposed = false; this.signal = context.signal; this.onAbort = () => { - if (this.state === "playing") this.state = "stopped"; + this.state = "stopped"; + this.emit({ type: "state", state: this.state }); void this.dispose(); }; this.signal?.addEventListener("abort", this.onAbort, { once: true }); @@ -49,14 +51,19 @@ class FakeAudioOutputHandle { if (signal?.aborted || this.signal?.aborted) throw abortError(); this.state = "playing"; this.emit({ type: "state", state: this.state }); + await this.backend.activate(this); + this.backend.notifyStarted(); this.consumePromise = (async () => { try { for await (const chunk of this.input.stream) { this.bufferedBytes = this.input.stream.readableLength ?? chunk.byteLength; assert.ok(this.bufferedBytes <= this.backend.capabilities.maxBufferedBytes); - await new Promise((resolve) => setTimeout(resolve, 1)); } - if (this.state === "playing") this.state = "ended"; + if (this.state === "playing") { + this.state = "ended"; + this.emit({ type: "state", state: this.state }); + await this.dispose(); + } } catch (error) { if (!this.disposed && this.state !== "stopped") this.fail(error); } @@ -129,6 +136,7 @@ class FakeAudioOutputHandle { if (signal?.aborted) throw abortError(); if (this.backend.capabilities.volume !== "backend") throw new AudioOutputUnsupportedOperationError("volume control"); this.volume = value; + this.volumeValues.push(value); } onEvent(listener) { @@ -144,9 +152,11 @@ class FakeAudioOutputHandle { async dispose() { if (this.disposed) return; this.disposed = true; + if (this.state !== "ended") this.state = "stopped"; this.signal?.removeEventListener("abort", this.onAbort); if (this.input.ownership === "transfer" && !this.input.stream.destroyed) this.input.stream.destroy(); this.listeners.clear(); + if (this.backend.activeHandle === this) this.backend.activeHandle = null; this.backend.handles.delete(this); } @@ -173,6 +183,11 @@ class FakeAudioOutputBackend { this.handles = new Set(); this.nextId = 0; this.disposed = false; + this.activeHandle = null; + this.startedCount = 0; + this.startedWaiters = []; + this.sessionWaiters = []; + this.sessionCount = 0; } initialize(signal) { @@ -200,10 +215,44 @@ class FakeAudioOutputBackend { createSession(input, context) { if (this.disposed) throw new Error("fake backend is disposed"); const handle = new FakeAudioOutputHandle(this, input, context); + handle.resource.metadata = context?.metadata; this.handles.add(handle); + for (const waiter of [...this.sessionWaiters]) { + if (this.sessionCount + 1 >= waiter.count) { + this.sessionWaiters.splice(this.sessionWaiters.indexOf(waiter), 1); + waiter.resolve(); + } + } + this.sessionCount++; return handle; } + async activate(handle) { + const previous = this.activeHandle; + this.activeHandle = handle; + if (previous && previous !== handle) await previous.dispose(); + } + + notifyStarted() { + this.startedCount++; + for (const waiter of [...this.startedWaiters]) { + if (this.startedCount >= waiter.count) { + this.startedWaiters.splice(this.startedWaiters.indexOf(waiter), 1); + waiter.resolve(); + } + } + } + + waitForStarted(count) { + if (this.startedCount >= count) return Promise.resolve(); + return new Promise((resolve) => this.startedWaiters.push({ count, resolve })); + } + + waitForSessionCount(count) { + if (this.sessionCount >= count) return Promise.resolve(); + return new Promise((resolve) => this.sessionWaiters.push({ count, resolve })); + } + async dispose() { for (const handle of [...this.handles]) await handle.dispose(); this.disposed = true; @@ -268,6 +317,102 @@ const pcmFormat = { chunkAlignmentBytes: 4, }; +function playbackContext(playerId, signal = new AbortController().signal) { + return { playerId, requestId: `request-${++playbackContext.nextId}`, source: "test", signal, timestamp: Date.now(), priority: 0 }; +} +playbackContext.nextId = 0; + +function createPlaybackHarness({ backend = new FakeAudioOutputBackend(), playerId = "fake-output", transition = false, ready = true } = {}) { + const { + BUS_EVENT, + Bus, + CONTROLLER_RPC, + PLAYER_QUERY, + PLAYER_RPC, + PlaybackController, + PlaybackSessionController, + PlaybackOrchestrator, + } = require("../core/dist"); + if (ready) backend.readyGate.resolve(); + const bus = new Bus(); + const sessions = new PlaybackSessionController(bus); + sessions.attach(playerId); + const playback = new PlaybackController(bus); + const playerErrors = []; + const recoveryReports = []; + const sources = []; + const orchestrator = new PlaybackOrchestrator(bus, { sessionController: sessions }); + orchestrator.attach(playerId); + playback.attach(playerId, { audioOutputBackendFactory: () => backend }); + bus.registerRpc(CONTROLLER_RPC.trackResetRecovery, () => {}); + bus.registerRpc(CONTROLLER_RPC.trackLoadWithRecovery, ({ track }) => { + const stream = new PassThrough(); + sources.push(stream); + return { + track, + stream: { track, stream, streamType: StreamType.Opus, inputType: StreamType.Opus }, + sessionId: sources.length, + retry: 0, + usedFallback: false, + }; + }); + bus.registerRpc(CONTROLLER_RPC.streamReplace, ({ streamInfo, session }) => ({ + sessionId: session.id, + session, + track: session.track, + stream: streamInfo.stream, + streamId: null, + inputType: streamInfo.inputType, + })); + bus.registerRpc(CONTROLLER_RPC.antiStuckReport, (request) => { + recoveryReports.push(request); + return true; + }); + bus.registerRpc(PLAYER_RPC.queueWillNext, () => {}); + bus.registerQuery(PLAYER_QUERY.filterString, () => ""); + bus.registerQuery(PLAYER_QUERY.transitionSettings, () => ({ + enabled: transition, + durationMs: 30, + waitForBeat: false, + beatAlignMaxWaitMs: 0, + })); + if (transition) { + bus.registerRpc(CONTROLLER_RPC.transitionPlan, () => ({ + enabled: true, + durationMs: 30, + waitForBeat: false, + beatAlignMaxWaitMs: 0, + })); + } + bus.subscribe(playerId, BUS_EVENT.trackError, (event) => playerErrors.push(event)); + return { + backend, + bus, + playerId, + playback, + orchestrator, + sessions, + sources, + playerErrors, + recoveryReports, + start(track, signal) { + const from = sessions.current(playerId)?.track ?? null; + return orchestrator.states.get(playerId).start.start(track, playbackContext(playerId, signal), from); + }, + async dispose() { + playback.detach(playerId); + await orchestrator.detach(playerId); + await orchestrator.dispose(); + sessions.detach(playerId); + await backend.dispose(); + }, + }; +} + +function testTrack(id) { + return { id, title: id, url: `https://example.test/${id}`, duration: 1000, requestedBy: "test", source: "test" }; +} + test("fake backend readiness gates start and supports the full output lifecycle", async () => { const backend = new FakeAudioOutputBackend(); const handle = backend.createSession({ @@ -394,6 +539,116 @@ test("fake backend advertises bounded buffering and enforces stream backpressure assert.equal(backend.handles.size, 0); }); +test("PlaybackController selects Discord Voice by default for legacy AudioPlayer callers", () => { + const { Bus, PlaybackController } = require("../core/dist"); + const player = new MockAudioPlayer(); + const controller = new PlaybackController(new Bus()); + controller.attach("default-discord", { audioPlayer: player }); + const track = testTrack("default-track"); + const resource = controller.createResource("default-discord", Readable.from([Buffer.from("opus")]), track, StreamType.Opus); + controller.play("default-discord", resource); + assert.equal(player.played[0], resource); + assert.equal(controller.getAudioPlayer("default-discord"), player); + controller.detach("default-discord"); +}); + +test("injected fake backend runs playback orchestration and replacement without a voice connection", async () => { + const harness = createPlaybackHarness(); + const firstTrack = testTrack("orchestrated-one"); + const secondTrack = testTrack("orchestrated-two"); + await harness.start(firstTrack); + const firstHandle = harness.backend.activeHandle; + assert.equal(firstHandle.state, "playing"); + assert.equal(harness.sessions.current(harness.playerId).track, firstTrack); + + await harness.start(secondTrack); + assert.equal(firstHandle.disposed, true); + assert.equal(harness.sources[0].destroyed, true); + assert.equal(harness.backend.handles.size, 1); + assert.equal(harness.backend.activeHandle.resource.metadata, secondTrack); + assert.equal(harness.sessions.current(harness.playerId).track, secondTrack); + await harness.dispose(); + assert.equal(harness.backend.handles.size, 0); + assert.equal(harness.sources[1].destroyed, true); +}); + +test("injected playback releases transferred streams when startup or active playback is cancelled", async () => { + const startupBackend = new FakeAudioOutputBackend(); + const startupHarness = createPlaybackHarness({ backend: startupBackend, playerId: "startup-cancel", ready: false }); + const startupAbort = new AbortController(); + const startup = startupHarness.start(testTrack("startup-cancel-track"), startupAbort.signal); + await startupBackend.waitForSessionCount(1); + startupAbort.abort(); + await startup; + assert.equal(startupBackend.handles.size, 0); + assert.equal(startupHarness.sources[0].destroyed, true); + await startupHarness.dispose(); + + const activeBackend = new FakeAudioOutputBackend(); + activeBackend.readyGate.resolve(); + const activeHarness = createPlaybackHarness({ backend: activeBackend, playerId: "active-cancel" }); + const activeAbort = new AbortController(); + await activeHarness.start(testTrack("active-cancel-track"), activeAbort.signal); + activeAbort.abort(); + assert.equal(activeBackend.handles.size, 0); + assert.equal(activeHarness.sources[0].destroyed, true); + await activeHarness.dispose(); +}); + +test("injected output failures reach track error and anti-stuck recovery handlers", async () => { + const harness = createPlaybackHarness({ playerId: "output-failure" }); + await harness.start(testTrack("output-failure-track")); + const handle = harness.backend.activeHandle; + const failure = new Error("fake sink failure"); + handle.fail(failure); + assert.equal(harness.playerErrors[0].error, failure); + assert.equal(harness.backend.handles.size, 0); + assert.equal(harness.sources[0].destroyed, true); + await new Promise((resolve) => setImmediate(resolve)); + assert.equal(harness.recoveryReports[0].reason, "audio output error: fake sink failure"); + await harness.dispose(); +}); + +test("injected backend crossfades through its volume operation and rejects unsupported crossfade", async () => { + const harness = createPlaybackHarness({ playerId: "fake-crossfade", transition: true }); + const first = testTrack("crossfade-one"); + const second = testTrack("crossfade-two"); + await harness.start(first); + const firstHandle = harness.backend.activeHandle; + await harness.start(second, undefined); + await harness.backend.waitForStarted(2); + const secondHandle = harness.backend.activeHandle; + assert.equal(firstHandle.disposed, true); + assert.ok(secondHandle.volumeValues?.includes(0)); + harness.playback.cancelFade(harness.playerId); + assert.equal(harness.playback.getFadeGain(harness.playerId), null); + await harness.dispose(); + + const unsupportedBackend = new FakeAudioOutputBackend(); + unsupportedBackend.capabilities.volume = "unsupported"; + unsupportedBackend.readyGate.resolve(); + const unsupported = createPlaybackHarness({ + backend: unsupportedBackend, + playerId: "unsupported-crossfade", + transition: true, + }); + await unsupported.start(testTrack("unsupported-one")); + await assert.rejects(unsupported.start(testTrack("unsupported-two")), AudioOutputUnsupportedOperationError); + assert.equal(unsupportedBackend.handles.size, 0); + await unsupported.dispose(); +}); + +test("injected backend disposal is idempotent and releases handle listeners", async () => { + const harness = createPlaybackHarness({ playerId: "idempotent-dispose" }); + await harness.start(testTrack("dispose-track")); + const handle = harness.backend.activeHandle; + assert.equal(handle.listeners.size, 1); + await harness.dispose(); + await harness.backend.dispose(); + assert.equal(harness.backend.handles.size, 0); + assert.equal(handle.listeners.size, 0); +}); + test("Discord backend converts float32 PCM at the adapter boundary and controls inline volume", async () => { const player = new MockAudioPlayer(); const backend = new DiscordVoiceOutputBackend(player); From ac2dabc6113192dc95b47958283cb1e70f3679b6 Mon Sep 17 00:00:00 2001 From: Ziji <104454302+zijipia@users.noreply.github.com> Date: Sat, 10 Oct 2026 11:41:10 +0900 Subject: [PATCH 06/55] Enhance error handling in playback controllers and backend interactions - Added error reporting to the PlaybackSkipController, PlaybackStartController, and PlaybackTrackEndController to capture and log stream errors. - Improved error handling in the PlaybackOrchestrator to ensure that errors during track end and playback stop are properly reported. - Updated tests to cover new error handling scenarios, including stop failures and remote stop actions. - Enhanced the FakeAudioOutputBackend to simulate various failure conditions for more robust testing. --- core/src/controller/PlaybackController.ts | 354 ++++++++++++---- core/src/controller/PlaybackSkipController.ts | 20 +- .../src/controller/PlaybackStartController.ts | 26 +- .../controller/PlaybackTrackEndController.ts | 14 +- core/src/structures/PlaybackOrchestrator.ts | 15 +- docs/AUDIO_OUTPUT_BACKENDS.md | 26 +- tests/audio_output_backend.test.js | 384 +++++++++++++++++- 7 files changed, 727 insertions(+), 112 deletions(-) diff --git a/core/src/controller/PlaybackController.ts b/core/src/controller/PlaybackController.ts index d37ab8e8..9246f6f5 100644 --- a/core/src/controller/PlaybackController.ts +++ b/core/src/controller/PlaybackController.ts @@ -42,6 +42,9 @@ interface PlaybackSlot { readonly handles: Map>; readonly handleDetachers: Map void>; readonly volumeValues: Map; + readonly disposalPromises: WeakMap, Promise>; + readonly stopPromises: Map, Promise>; + readonly startAbortControllers: Map, AbortController>; activeSession: PlaybackSession | null; transitionTimer: ReturnType | null; transitionStartResolve: (() => void) | null; @@ -82,9 +85,11 @@ export class PlaybackController { ); bus.registerRpc(PLAYER_RPC.transitionFadeOutCurrent, (_req, ctx) => this.applyCrossfadeOutCurrent(ctx.playerId)); bus.registerRpc(PLAYER_RPC.transitionSkipAndStop, (_req, ctx) => this.crossfadeSkipAndStop(ctx.playerId)); - bus.registerRpc<{ resource: AudioResource; session?: PlaybackSession; from?: Track | null; to?: Track }, void | Promise>( - CONTROLLER_RPC.playbackPlay, - ({ resource, session, from, to }, ctx) => this.play(ctx.playerId, resource, session, from, to, ctx.signal), + bus.registerRpc< + { resource: AudioResource; session?: PlaybackSession; from?: Track | null; to?: Track }, + void | Promise + >(CONTROLLER_RPC.playbackPlay, ({ resource, session, from, to }, ctx) => + this.play(ctx.playerId, resource, session, from, to, ctx.signal), ); bus.registerRpc(CONTROLLER_RPC.playbackPause, (_req, ctx) => this.pause(ctx.playerId, ctx.signal)); bus.registerRpc(CONTROLLER_RPC.playbackResume, (_req, ctx) => this.resume(ctx.playerId, ctx.signal)); @@ -145,6 +150,9 @@ export class PlaybackController { handles: new Map(), handleDetachers: new Map(), volumeValues: new Map(), + disposalPromises: new WeakMap(), + stopPromises: new Map(), + startAbortControllers: new Map(), activeSession: null, transitionTimer: null, transitionStartResolve: null, @@ -191,7 +199,9 @@ export class PlaybackController { const session = slot.activeSession; if (session?.isActive()) { this.bus.event(playerId, { type: BUS_EVENT.trackError, session: session.snapshot(), error: normalized }); - void this.reportStuck(slot, session, `audio player error: ${normalized.message}`); + void this.reportStuck(slot, session, `audio player error: ${normalized.message}`).catch((reportError) => + this.reportAsyncFailure(slot, reportError, session.track), + ); } else { this.bus.event(playerId, { type: BUS_EVENT.streamError, error: normalized, track: null }); } @@ -201,10 +211,9 @@ export class PlaybackController { this.bus.subscribe(playerId, BUS_EVENT.volumeRequested, () => { if (!slot.activeResource) return; const track = slot.activeSession?.track ?? (slot.activeResource.metadata as Track | undefined); - void this.applyTargetVolume(slot, slot.activeResource, track, slot.fadeGain ?? 1).catch((error) => { - const activeHandle = slot.activeHandle; - if (activeHandle) this.handleOutputError(slot, activeHandle, error instanceof Error ? error : new Error(String(error))); - }); + void this.applyTargetVolume(slot, slot.activeResource, track, slot.fadeGain ?? 1).catch((error) => + this.reportOutputOperationError(slot, slot.activeHandle, error), + ); }), ); slot.audioPlayer?.on("stateChange", slot.onStateChange); @@ -230,25 +239,12 @@ export class PlaybackController { if (slot.audioPlayer && !(slot.outputBackend instanceof DiscordVoiceOutputBackend)) { slot.audioPlayer.removeListener("error", slot.onError); } - for (const detach of slot.handleDetachers.values()) detach(); - slot.handleDetachers.clear(); - slot.handles.clear(); - slot.volumeValues.clear(); - try { - void Promise.resolve(slot.outputBackend.dispose()).catch((error) => { - this.bus.event(playerId, { - type: BUS_EVENT.streamError, - error: error instanceof Error ? error : new Error(String(error)), - track: null, - }); + const handleDisposals = [...slot.handles.values()].map((handle) => this.disposeOutputHandle(slot, handle)); + void Promise.all(handleDisposals) + .then(() => slot.outputBackend.dispose()) + .catch((error) => { + this.reportAsyncFailure(slot, error, null); }); - } catch (error) { - this.bus.event(playerId, { - type: BUS_EVENT.streamError, - error: error instanceof Error ? error : new Error(String(error)), - track: null, - }); - } slot.activeResource = null; slot.activeHandle = null; } @@ -390,7 +386,13 @@ export class PlaybackController { } } - private async applyTargetVolume(slot: PlaybackSlot, resource: AudioResource | null, track?: Track | null, gain = 1): Promise { + private async applyTargetVolume( + slot: PlaybackSlot, + resource: AudioResource | null, + track?: Track | null, + gain = 1, + signal?: AbortSignal, + ): Promise { if (!resource) return; const handle = slot.handles.get(resource); const target = this.requestVolumeTarget(slot.playerId, track); @@ -405,7 +407,7 @@ export class PlaybackController { return; } if (!handle) throw new Error("No output handle is registered for the requested resource"); - await handle.setVolume(value, slot.lifecycleAbort.signal); + await handle.setVolume(value, signal ?? slot.lifecycleAbort.signal); slot.volumeValues.set(resource, value); } @@ -446,7 +448,9 @@ export class PlaybackController { return; const currentDuration = Number(resource?.playbackDuration ?? session.position); if (currentDuration === initialDuration) - void this.reportStuck(slot, session, `buffering stalled for ${slot.stuckTimeoutMs}ms`); + void this.reportStuck(slot, session, `buffering stalled for ${slot.stuckTimeoutMs}ms`).catch((error) => + this.reportAsyncFailure(slot, error, session.track), + ); else this.armStuckWatchdog(slot); }, slot.stuckTimeoutMs); } @@ -471,10 +475,23 @@ export class PlaybackController { if (!slot) return; const session = slot.activeSession; if (!session?.isActive() || slot.resourceRefreshInProgress) { - if (session?.isActive()) void this.reportStuck(slot, session, `filter processing failed: ${error.message}`); + if (session?.isActive()) + void this.reportStuck(slot, session, `filter processing failed: ${error.message}`).catch((reportError) => + this.reportAsyncFailure(slot, reportError, session.track), + ); return; } - void this.reportStuck(slot, session, `filter processing failed: ${error.message}`); + void this.reportStuck(slot, session, `filter processing failed: ${error.message}`).catch((reportError) => + this.reportAsyncFailure(slot, reportError, session.track), + ); + } + + private reportAsyncFailure(slot: PlaybackSlot, error: unknown, track: Track | null): void { + this.bus.event(slot.playerId, { + type: BUS_EVENT.streamError, + error: error instanceof Error ? error : new Error(String(error)), + track, + }); } // --------------------------------------------------------------------- @@ -559,13 +576,7 @@ export class PlaybackController { processedStream.once("close", () => outputSignal?.removeEventListener("abort", abortProcessing)); return this.createOutputResource(slot, processedStream, track, outputFormat, outputSignal); } - return this.createOutputResource( - slot, - stream, - track, - audioFrameFormatFromDiscordStreamType(resolvedInputType), - outputSignal, - ); + return this.createOutputResource(slot, stream, track, audioFrameFormatFromDiscordStreamType(resolvedInputType), outputSignal); } private createOutputResource( @@ -598,6 +609,7 @@ export class PlaybackController { this.handleOutputError(slot, handle, event.error); return; } + if (slot.activeHandle !== handle) return; slot.outputState = event.state; if (event.state === "buffering") this.armStuckWatchdog(slot); else this.clearStuckWatchdog(slot); @@ -620,12 +632,26 @@ export class PlaybackController { private handleOutputError(slot: PlaybackSlot, handle: AudioOutputHandle, error: Error): void { if (slot.handles.get(handle.resource) !== handle) return; + if (slot.activeHandle !== handle) { + this.bus.event(slot.playerId, { + type: BUS_EVENT.streamError, + error, + track: (handle.resource as AudioResource).metadata as Track | null, + }); + void this.disposeOutputHandle(slot, handle); + return; + } slot.outputState = "failed"; - if (slot.activeHandle !== handle) return; const session = slot.activeSession; if (session?.isActive()) { this.bus.event(slot.playerId, { type: BUS_EVENT.trackError, session: session.snapshot(), error }); - void this.reportStuck(slot, session, `audio output error: ${error.message}`); + void this.reportStuck(slot, session, `audio output error: ${error.message}`).catch((reportError) => + this.bus.event(slot.playerId, { + type: BUS_EVENT.streamError, + error: reportError instanceof Error ? reportError : new Error(String(reportError)), + track: session.track, + }), + ); } else { this.bus.event(slot.playerId, { type: BUS_EVENT.streamError, error, track: null }); } @@ -634,6 +660,15 @@ export class PlaybackController { void this.disposeOutputHandle(slot, handle); } + private reportOutputOperationError(slot: PlaybackSlot, handle: AudioOutputHandle | null, error: unknown): void { + const normalized = error instanceof Error ? error : new Error(String(error)); + if (handle && slot.handles.get(handle.resource) === handle) { + this.handleOutputError(slot, handle, normalized); + return; + } + this.bus.event(slot.playerId, { type: BUS_EVENT.streamError, error: normalized, track: null }); + } + public play( playerId: string, resource: AudioResource, @@ -685,16 +720,40 @@ export class PlaybackController { await this.disposeOutputHandle(slot, handle); throw new AudioOutputUnsupportedOperationError("track replacement"); } - await this.fadeTransition(slot, slot.activeResource, resource, plan, session, track); + try { + await this.fadeTransition(slot, slot.activeResource, resource, plan, session, track); + } catch (error) { + if (slot.fadeResource === resource) { + if (slot.fadeTimer) clearInterval(slot.fadeTimer); + slot.fadeTimer = null; + slot.fadeGain = null; + slot.fadeResource = null; + } + if (slot.activeHandle === handle) { + this.handleOutputError(slot, handle, error instanceof Error ? error : new Error(String(error))); + } else { + await this.disposeOutputHandle(slot, handle); + } + throw error; + } return; } slot.fadeGain = null; - await this.applyTargetVolume(slot, resource, track, 1); - if (session) session.setResource(resource); - slot.activeSession = session ?? null; - slot.activeResource = resource; - await this.startOutputHandle(slot, handle, signal ?? session?.signal); - this.retirePendingSession(playerId); + try { + await this.startOutputHandle(slot, handle, signal ?? session?.signal, (activeSignal) => + this.applyTargetVolume(slot, resource, track, 1, activeSignal), + ); + if (slot.disposed || slot.activeHandle !== handle) { + throw this.outputAbortError(); + } + if (session) session.setResource(resource); + slot.activeSession = session ?? null; + slot.activeResource = resource; + this.retirePendingSession(playerId); + } catch (error) { + if (slot.activeHandle !== handle) await this.disposeOutputHandle(slot, handle); + throw error; + } } private playDiscordCompatibility( @@ -718,12 +777,14 @@ export class PlaybackController { void this.disposeOutputHandle(slot, handle); throw new AudioOutputUnsupportedOperationError("track replacement"); } - void this.fadeTransition(slot, slot.activeResource, resource, plan, session, track); + void this.fadeTransition(slot, slot.activeResource, resource, plan, session, track).catch((error) => + this.reportOutputOperationError(slot, slot.handles.get(resource) ?? null, error), + ); return; } slot.fadeGain = null; void this.applyTargetVolume(slot, resource, track, 1).catch((error) => { - this.handleOutputError(slot, handle, error instanceof Error ? error : new Error(String(error))); + this.reportOutputOperationError(slot, handle, error); }); if (session) session.setResource(resource); slot.activeSession = session ?? null; @@ -743,36 +804,81 @@ export class PlaybackController { slot: PlaybackSlot, handle: AudioOutputHandle, signal?: AbortSignal, + beforeStart?: (signal: AbortSignal) => void | Promise, ): Promise { const lifecycleSignal = slot.lifecycleAbort.signal; - const activeSignal = signal ? AbortSignal.any([lifecycleSignal, signal]) : lifecycleSignal; + const startAbort = new AbortController(); + slot.startAbortControllers.set(handle, startAbort); + const signals = [lifecycleSignal, startAbort.signal]; + if (signal) signals.push(signal); + const activeSignal = AbortSignal.any(signals); + let previous = slot.activeHandle; try { slot.backendInitialization ??= slot.outputBackend.initialize(lifecycleSignal); await this.awaitWithAbort(slot.backendInitialization, activeSignal); await this.awaitWithAbort(handle.ready, activeSignal); if (activeSignal.aborted) throw new Error("Audio output start was aborted"); - const previous = slot.activeHandle; + previous = slot.activeHandle; if (previous && previous !== handle) { if (slot.outputBackend.capabilities.replacement === "unsupported") { throw new AudioOutputUnsupportedOperationError("track replacement"); } if (slot.outputBackend.capabilities.replacement === "stop-before-start") { - await previous.stop(activeSignal); + try { + await previous.stop(activeSignal); + } catch (error) { + await this.disposeOutputHandle(slot, previous); + if (slot.activeHandle === previous) { + slot.activeHandle = null; + slot.activeResource = null; + slot.activeSession?.markStopped(); + slot.activeSession = null; + } + throw error; + } await this.disposeOutputHandle(slot, previous); + if (slot.activeHandle === previous) { + slot.activeHandle = null; + slot.activeResource = null; + slot.activeSession?.markStopped(); + slot.activeSession = null; + } } } - slot.activeHandle = handle; + await beforeStart?.(activeSignal); + if (activeSignal.aborted || slot.disposed) throw this.outputAbortError(); await handle.start(activeSignal); + if (activeSignal.aborted || slot.disposed) throw this.outputAbortError(); + if (slot.handles.get(handle.resource) !== handle || handle.state === "failed") { + throw new Error("Audio output handle failed during startup"); + } + slot.activeHandle = handle; slot.outputState = handle.state; + if (previous && previous !== handle) await this.disposeOutputHandle(slot, previous); } catch (error) { - if (!activeSignal.aborted) { - this.handleOutputError(slot, handle, error instanceof Error ? error : new Error(String(error))); - } else if (slot.activeHandle === handle) { + const normalized = error instanceof Error ? error : new Error(String(error)); + if (slot.activeHandle === handle) { + this.handleOutputError(slot, handle, normalized); + } else if (!activeSignal.aborted && !(normalized.name === "AbortError")) { + this.reportOutputOperationError(slot, handle, normalized); + } + if ( + previous && + slot.activeHandle === previous && + (previous.state === "stopped" || previous.state === "ended" || previous.state === "failed") + ) { slot.activeHandle = null; slot.activeResource = null; + slot.activeSession?.markStopped(); + slot.activeSession = null; + slot.outputState = previous.state; + await this.disposeOutputHandle(slot, previous); } - await this.disposeOutputHandle(slot, handle); throw error; + } finally { + if (slot.startAbortControllers.get(handle) === startAbort) { + slot.startAbortControllers.delete(handle); + } } } @@ -804,20 +910,37 @@ export class PlaybackController { } private async disposeOutputHandle(slot: PlaybackSlot, handle: AudioOutputHandle): Promise { + const existing = slot.disposalPromises.get(handle); + if (existing) return existing; const detach = slot.handleDetachers.get(handle.resource); detach?.(); slot.handleDetachers.delete(handle.resource); slot.handles.delete(handle.resource); slot.volumeValues.delete(handle.resource); + let finishDisposal!: () => void; + const disposal = new Promise((resolve) => { + finishDisposal = resolve; + }); + slot.disposalPromises.set(handle, disposal); + const reportDisposalFailure = (error: unknown) => { + try { + this.bus.event(slot.playerId, { + type: BUS_EVENT.streamError, + error: error instanceof Error ? error : new Error(String(error)), + track: slot.activeSession?.track ?? ((handle.resource as AudioResource).metadata as Track | null), + }); + } catch (reportError) { + console.error("[PlaybackController] Failed to report output disposal error:", reportError); + } finally { + finishDisposal(); + } + }; try { - await handle.dispose(); + void Promise.resolve(handle.dispose()).then(finishDisposal, reportDisposalFailure); } catch (error) { - this.bus.event(slot.playerId, { - type: BUS_EVENT.streamError, - error: error instanceof Error ? error : new Error(String(error)), - track: slot.activeSession?.track ?? null, - }); + reportDisposalFailure(error); } + return disposal; } public async fadeResourceVolume( @@ -914,7 +1037,6 @@ export class PlaybackController { ): Promise { slot.fadeGain = 0; slot.fadeResource = newResource; - const preparedVolume = this.applyTargetVolume(slot, newResource, track, 0); const outgoingTrack = slot.activeSession?.track ?? (oldResource.metadata as Track | undefined) ?? null; const outgoingPosition = slot.activeSession?.position ?? 0; const wait = plan.waitForBeat ? this.requestBeatWait(slot.playerId, outgoingTrack, outgoingPosition) : 0; @@ -927,13 +1049,37 @@ export class PlaybackController { slot.fadeGain = 0; const handle = slot.handles.get(newResource); if (!handle) throw new Error("No output handle is registered for the transition resource"); - this.retirePendingSession(slot.playerId); + await this.startOutputHandle(slot, handle, session?.signal, (activeSignal) => + this.applyTargetVolume(slot, newResource, track, 0, activeSignal), + ); + if (slot.disposed || slot.activeHandle !== handle) { + if (slot.activeHandle !== handle) await this.disposeOutputHandle(slot, handle); + return; + } + if (session && !session.isActive()) { + try { + await handle.stop(slot.lifecycleAbort.signal); + } catch (error) { + this.reportOutputOperationError(slot, handle, error); + } + await this.disposeOutputHandle(slot, handle); + if (slot.activeHandle === handle) { + slot.activeHandle = null; + slot.activeResource = null; + slot.activeSession = null; + slot.outputState = "stopped"; + } + return; + } if (session) session.setResource(newResource); slot.activeSession = session ?? null; slot.activeResource = newResource; - await preparedVolume; - if (slot.fadeGain === null || slot.disposed || (session && !session.isActive())) return; - await this.startOutputHandle(slot, handle, session?.signal); + this.retirePendingSession(slot.playerId); + if (slot.fadeGain === null) { + slot.fadeResource = null; + await this.applyTargetVolume(slot, newResource, track, 1); + return; + } const start = Date.now(); slot.fadeTimer = setInterval(() => { if (session && !session.isActive()) { @@ -943,12 +1089,12 @@ export class PlaybackController { const p = Math.min(1, (Date.now() - start) / Math.max(1, plan.durationMs)); slot.fadeGain = p; void this.applyTargetVolume(slot, newResource, track, p).catch((error) => - this.handleOutputError(slot, handle, error instanceof Error ? error : new Error(String(error))), + this.reportOutputOperationError(slot, handle, error), ); if (p >= 1) { this.cancelFadeSlot(slot); void this.applyTargetVolume(slot, newResource, track, 1).catch((error) => - this.handleOutputError(slot, handle, error instanceof Error ? error : new Error(String(error))), + this.reportOutputOperationError(slot, handle, error), ); } }, 25); @@ -963,7 +1109,7 @@ export class PlaybackController { slot.transitionStartResolve = resolve; slot.transitionTimer = setTimeout(run, wait); } else { - run(); + void begin().then(resolve, reject); } }); } @@ -978,12 +1124,13 @@ export class PlaybackController { const resource = slot.fadeResource ?? slot.activeResource; slot.fadeResource = null; if (resource) { - const track = resource === slot.activeResource ? - slot.activeSession?.track ?? (resource.metadata as Track | undefined) - : (resource.metadata as Track | undefined); + const track = + resource === slot.activeResource ? + (slot.activeSession?.track ?? (resource.metadata as Track | undefined)) + : (resource.metadata as Track | undefined); void this.applyTargetVolume(slot, resource, track, 1).catch((error) => { const handle = slot.handles.get(resource); - if (handle) this.handleOutputError(slot, handle, error instanceof Error ? error : new Error(String(error))); + this.reportOutputOperationError(slot, handle ?? null, error); }); } } @@ -992,6 +1139,11 @@ export class PlaybackController { if (slot.transitionTimer) { clearTimeout(slot.transitionTimer); slot.transitionTimer = null; + const resource = slot.fadeResource; + const handle = resource ? slot.handles.get(resource) : undefined; + if (handle && slot.activeHandle !== handle) { + void this.disposeOutputHandle(slot, handle); + } slot.transitionStartResolve?.(); slot.transitionStartResolve = null; } @@ -1020,21 +1172,55 @@ export class PlaybackController { public async stop(playerId: string, signal?: AbortSignal): Promise { const mode = this.bus.querySync(playerId, PLAYER_QUERY.playbackMode); if (mode === PlaybackMode.REMOTE) { - void this.bus.requestRpc(playerId, CONTROLLER_RPC.playbackRemoteStop, {}); + return await this.bus.requestRpc(playerId, CONTROLLER_RPC.playbackRemoteStop, {}); } const slot = this.slots.get(playerId); if (!slot) return false; this.cancelTransition(slot); + for (const startAbort of slot.startAbortControllers.values()) startAbort.abort(); const handle = slot.activeHandle; - slot.activeSession = null; - slot.activeResource = null; - slot.activeHandle = null; + const pendingDisposals = [...slot.handles.values()] + .filter((candidate) => candidate !== handle) + .map((candidate) => this.disposeOutputHandle(slot, candidate)); + await Promise.all(pendingDisposals); if (!handle) return false; - if (!slot.outputBackend.capabilities.stop) throw new AudioOutputUnsupportedOperationError("stop"); - const stopped = await handle.stop(signal ?? slot.lifecycleAbort.signal); - await this.disposeOutputHandle(slot, handle); - slot.outputState = "stopped"; - return stopped; + const ongoing = slot.stopPromises.get(handle); + if (ongoing) return ongoing; + const operation = Promise.resolve().then(async () => { + const session = slot.activeSession; + let stopped = false; + let stopError: unknown; + let stopFailed = false; + try { + if (!slot.outputBackend.capabilities.stop) { + throw new AudioOutputUnsupportedOperationError("stop"); + } + const stopSignal = signal ?? slot.lifecycleAbort.signal; + const stopOperation = Promise.resolve().then(() => handle.stop(stopSignal)); + stopped = await this.awaitWithAbort(stopOperation, stopSignal); + } catch (error) { + stopFailed = true; + stopError = error; + } + await this.disposeOutputHandle(slot, handle); + if (slot.activeHandle === handle) { + slot.activeHandle = null; + slot.activeResource = null; + slot.outputState = "stopped"; + if (slot.activeSession === session) { + session?.markStopped(); + slot.activeSession = null; + } + } + if (stopFailed) throw stopError; + return stopped; + }); + slot.stopPromises.set(handle, operation); + try { + return await operation; + } finally { + if (slot.stopPromises.get(handle) === operation) slot.stopPromises.delete(handle); + } } public async seek(playerId: string, position: number, session?: PlaybackSession): Promise { if (!this.slots.has(playerId)) return false; diff --git a/core/src/controller/PlaybackSkipController.ts b/core/src/controller/PlaybackSkipController.ts index 6d00c298..32cae504 100644 --- a/core/src/controller/PlaybackSkipController.ts +++ b/core/src/controller/PlaybackSkipController.ts @@ -41,7 +41,12 @@ export class PlaybackSkipController { } return result; - } catch { + } catch (error) { + this.bus.event(this.playerId, { + type: BUS_EVENT.streamError, + error: error instanceof Error ? error : new Error(String(error)), + track: this.currentSession()?.track ?? null, + }); return false; } } @@ -56,9 +61,18 @@ export class PlaybackSkipController { if (context.signal.aborted) return false; if (oldSession?.isActive()) { const transition = this.bus.querySync(this.playerId, PLAYER_QUERY.transitionSettings) as - { enabled?: boolean } | undefined; + | { enabled?: boolean } + | undefined; if (transition?.enabled) { - await this.bus.requestRpc(this.playerId, PLAYER_RPC.transitionFadeOutCurrent, undefined).catch(() => undefined); + try { + await this.bus.requestRpc(this.playerId, PLAYER_RPC.transitionFadeOutCurrent, undefined); + } catch (error) { + this.bus.event(this.playerId, { + type: BUS_EVENT.streamError, + error: error instanceof Error ? error : new Error(String(error)), + track: oldSession.track, + }); + } } } if (context.signal.aborted) return false; diff --git a/core/src/controller/PlaybackStartController.ts b/core/src/controller/PlaybackStartController.ts index c5bdcfd8..feb982c0 100644 --- a/core/src/controller/PlaybackStartController.ts +++ b/core/src/controller/PlaybackStartController.ts @@ -135,14 +135,28 @@ export class PlaybackStartController { this.consecutiveFailures = 0; this.bus.event(this.playerId, { type: BUS_EVENT.queueEnd }); if (this.bus.hasRpc(PLAYER_RPC.lifecycleScheduleLeave)) { - void this.bus.requestRpc(this.playerId, PLAYER_RPC.lifecycleScheduleLeave, {}); + void this.bus.requestRpc(this.playerId, PLAYER_RPC.lifecycleScheduleLeave, {}).catch((reportError) => { + this.bus.event(this.playerId, { + type: BUS_EVENT.streamError, + error: reportError instanceof Error ? reportError : new Error(String(reportError)), + track, + }); + }); } } else if (!parentContext.signal.aborted) { - void this.bus.action( - this.playerId, - { type: PLAYER_ACTION.skip, ignoreLoop: true, requestId: parentContext.requestId }, - parentContext, - ); + void this.bus + .action( + this.playerId, + { type: PLAYER_ACTION.skip, ignoreLoop: true, requestId: parentContext.requestId }, + parentContext, + ) + .catch((reportError) => { + this.bus.event(this.playerId, { + type: BUS_EVENT.streamError, + error: reportError instanceof Error ? reportError : new Error(String(reportError)), + track, + }); + }); } throw error; } diff --git a/core/src/controller/PlaybackTrackEndController.ts b/core/src/controller/PlaybackTrackEndController.ts index d91803c8..df1a26ee 100644 --- a/core/src/controller/PlaybackTrackEndController.ts +++ b/core/src/controller/PlaybackTrackEndController.ts @@ -76,9 +76,17 @@ export class PlaybackTrackEndController { if (this.lifecycleSignal.aborted || !this.waitingForQueue || this.trackEndTransition || this.queueStartPromise) return; if (!this.queueSnapshot().length) return; const generation = ++this.queueStartGeneration; - this.queueStartPromise = this.startQueuedTrackAfterEnd().finally(() => { - if (generation === this.queueStartGeneration) this.queueStartPromise = null; - }); + this.queueStartPromise = this.startQueuedTrackAfterEnd() + .catch((error) => { + this.bus.event(this.playerId, { + type: BUS_EVENT.streamError, + error: error instanceof Error ? error : new Error(String(error)), + track: this.currentSession()?.track ?? null, + }); + }) + .finally(() => { + if (generation === this.queueStartGeneration) this.queueStartPromise = null; + }); } public async onTrackEnd(snapshot: PlaybackSessionSnapshot): Promise { diff --git a/core/src/structures/PlaybackOrchestrator.ts b/core/src/structures/PlaybackOrchestrator.ts index ba58e0a6..ab65f0c9 100644 --- a/core/src/structures/PlaybackOrchestrator.ts +++ b/core/src/structures/PlaybackOrchestrator.ts @@ -175,7 +175,13 @@ export class PlaybackOrchestrator { if (!session || session.status === "ended" || session.status === "stopped") return; const current = this.sessionController.current(playerId); if (!current || current.id !== session.id) return; - void state.trackEnd.onTrackEnd(session); + void state.trackEnd.onTrackEnd(session).catch((error) => { + this.bus.event(playerId, { + type: BUS_EVENT.streamError, + error: error instanceof Error ? error : new Error(String(error)), + track: session.track, + }); + }); }); state.detachQueueEnd = this.bus.subscribe(playerId, BUS_EVENT.queueEnd, () => state.trackEnd.onQueueEnd()); state.detachQueueChanged = this.bus.subscribe(playerId, BUS_EVENT.queueChanged, () => state.trackEnd.onQueueChanged()); @@ -325,7 +331,12 @@ export class PlaybackOrchestrator { const session = this.sessionController.current(playerId); const mode = this.bus.querySync(playerId, PLAYER_QUERY.playbackMode); if (mode === PlaybackMode.REMOTE) { - void this.bus.requestRpc(playerId, CONTROLLER_RPC.playbackRemoteStop, {}); + await this.bus.requestRpc(playerId, CONTROLLER_RPC.playbackRemoteStop, {}); + this.bus.requestRpcSync(playerId, PLAYER_RPC.queueClear, undefined); + if (session?.isActive()) session.markStopped(); + this.publishState(playerId); + this.bus.event(playerId, { type: BUS_EVENT.playerStop }); + break; } if (session && !this.matchesContext(session, context)) break; await this.stopPlayback(playerId, context.signal); diff --git a/docs/AUDIO_OUTPUT_BACKENDS.md b/docs/AUDIO_OUTPUT_BACKENDS.md index 7d708fdc..5826be1f 100644 --- a/docs/AUDIO_OUTPUT_BACKENDS.md +++ b/docs/AUDIO_OUTPUT_BACKENDS.md @@ -2,9 +2,9 @@ ZiPlayer remains Discord-first. `PlayerManager` creates a Discord `AudioPlayer` when no custom output factory is supplied, and `ConnectionController` subscribes that player to a Discord voice connection. `PlaybackController` is still the compatibility -boundary for legacy Discord resources and synchronous APIs, but generic playback operations use normalized backend handle -state and lifecycle methods. The extraction does not move queueing, track resolution, recovery, fades, preload, or session -policy into the adapter. +boundary for legacy Discord resources and synchronous APIs, but generic playback operations use normalized backend handle state +and lifecycle methods. The extraction does not move queueing, track resolution, recovery, fades, preload, or session policy into +the adapter. ## Current dependency map @@ -61,8 +61,8 @@ resource creation. `audioProcessing` only selects DSP options; it does not selec Backend selection is per player and has no global mutable default. `PlayerOptions.audioOutputBackendFactory` is optional; when omitted, ZiPlayer constructs `DiscordVoiceOutputBackend` around the manager-created `AudioPlayer`. A factory is invoked once per attached player and its backend instance is owned by that player's `PlaybackController` slot. Detaching/replacing the slot aborts -its lifecycle signal, disposes its handles, detaches event listeners, and disposes the backend. A caller should therefore return -a fresh backend instance for each factory invocation unless it explicitly manages safe sharing itself. +its lifecycle signal, disposes its handles, detaches event listeners, and disposes the backend. A caller should therefore return a +fresh backend instance for each factory invocation unless it explicitly manages safe sharing itself. ```ts const player = await manager.create(guildId, { @@ -79,10 +79,18 @@ breaking existing `AudioResource` consumers is follow-up work; do not treat the The backend owns each session handle it creates; the slot owns the backend and registered handle-event detachers. A transferred input stream is destroyed on stop, cancellation, replacement, failure cleanup, or disposal. A borrowed stream must not be destroyed by the backend. Session readiness and backend initialization must settle before start; failure is reported through the -existing track-error/recovery path. A consumed stream is never replayed after DSP or sink failure. Operations unsupported by -the selected backend reject explicitly, including seek or volume operations when the capability says unsupported. The fake -backend tests cover lifecycle, startup cancellation, replacement, output failure, volume/crossfade capability, and disposal -without opening a Discord voice connection. +existing track-error/recovery path. A consumed stream is never replayed after DSP or sink failure. Operations unsupported by the +selected backend reject explicitly, including seek or volume operations when the capability says unsupported. The fake backend +tests cover lifecycle, startup cancellation, replacement, output failure, volume/crossfade capability, and disposal without +opening a Discord voice connection. + +Stop is cleanup-safe even when the backend rejects or the caller aborts while stop is pending: the controller disposes the +captured handle independently, reports disposal failure as a separate stream error, and then propagates the original stop failure. +Slot state is cleared only if that same handle is still active, so a late stop cannot erase a replacement. Concurrent stop and +disposal requests share per-handle cleanup. In remote playback mode, stop awaits the remote stop RPC and does not also stop the +local output backend. Backend start is transactional: readiness and initial volume must succeed before activation is committed, +and failed/unactivated handles are disposed; adapters should ensure a rejected `start()` does not leave an active output session +behind. ## Processed audio format and failure behavior diff --git a/tests/audio_output_backend.test.js b/tests/audio_output_backend.test.js index 0cc2cb05..42007b69 100644 --- a/tests/audio_output_backend.test.js +++ b/tests/audio_output_backend.test.js @@ -26,12 +26,13 @@ class FakeAudioOutputHandle { this.backend = backend; this.input = input; this.format = input.format; - this.ready = backend.ready; + this.ready = backend.handleReady ?? backend.ready; this.state = "ready"; this.bufferedBytes = 0; this.volumeValues = []; this.listeners = new Set(); this.disposed = false; + this.disposeCalls = 0; this.signal = context.signal; this.onAbort = () => { this.state = "stopped"; @@ -49,9 +50,11 @@ class FakeAudioOutputHandle { if (signal?.aborted || this.signal?.aborted) throw abortError(); await this.waitUntilReady(signal); if (signal?.aborted || this.signal?.aborted) throw abortError(); + if (this.backend.startFailure) throw this.backend.startFailure; this.state = "playing"; this.emit({ type: "state", state: this.state }); await this.backend.activate(this); + if (this.backend.startFailureAfterActivation) throw this.backend.startFailureAfterActivation; this.backend.notifyStarted(); this.consumePromise = (async () => { try { @@ -110,8 +113,12 @@ class FakeAudioOutputHandle { return true; } - stop(signal) { + async stop(signal) { + this.backend.stopCalls++; + this.backend.stopStarted.resolve(); + if (this.backend.stopGate) await this.backend.stopGate.promise; if (signal?.aborted) throw abortError(); + if (this.backend.stopFailure) throw this.backend.stopFailure; const changed = this.state === "playing" || this.state === "paused"; this.state = "stopped"; if (this.input.ownership === "transfer" && !this.input.stream.destroyed) this.input.stream.destroy(); @@ -134,6 +141,7 @@ class FakeAudioOutputHandle { setVolume(value, signal) { if (signal?.aborted) throw abortError(); + if (this.backend.volumeFailure) throw this.backend.volumeFailure; if (this.backend.capabilities.volume !== "backend") throw new AudioOutputUnsupportedOperationError("volume control"); this.volume = value; this.volumeValues.push(value); @@ -152,12 +160,14 @@ class FakeAudioOutputHandle { async dispose() { if (this.disposed) return; this.disposed = true; + this.disposeCalls++; if (this.state !== "ended") this.state = "stopped"; this.signal?.removeEventListener("abort", this.onAbort); if (this.input.ownership === "transfer" && !this.input.stream.destroyed) this.input.stream.destroy(); this.listeners.clear(); if (this.backend.activeHandle === this) this.backend.activeHandle = null; this.backend.handles.delete(this); + if (this.backend.disposeFailure) throw this.backend.disposeFailure; } emit(event) { @@ -188,9 +198,22 @@ class FakeAudioOutputBackend { this.startedWaiters = []; this.sessionWaiters = []; this.sessionCount = 0; + this.stopCalls = 0; + this.stopStarted = deferred(); + this.initializeStarted = deferred(); + this.stopGate = null; + this.stopFailure = null; + this.startFailure = null; + this.startFailureAfterActivation = null; + this.volumeFailure = null; + this.initializeFailure = null; + this.disposeFailure = null; + this.handleReady = null; } initialize(signal) { + if (this.initializeFailure) return Promise.reject(this.initializeFailure); + this.initializeStarted.resolve(); if (signal?.aborted) return Promise.reject(abortError()); if (!signal) return this.ready; return new Promise((resolve, reject) => { @@ -318,15 +341,28 @@ const pcmFormat = { }; function playbackContext(playerId, signal = new AbortController().signal) { - return { playerId, requestId: `request-${++playbackContext.nextId}`, source: "test", signal, timestamp: Date.now(), priority: 0 }; + return { + playerId, + requestId: `request-${++playbackContext.nextId}`, + source: "test", + signal, + timestamp: Date.now(), + priority: 0, + }; } playbackContext.nextId = 0; -function createPlaybackHarness({ backend = new FakeAudioOutputBackend(), playerId = "fake-output", transition = false, ready = true } = {}) { +function createPlaybackHarness({ + backend = new FakeAudioOutputBackend(), + playerId = "fake-output", + transition = false, + ready = true, +} = {}) { const { BUS_EVENT, Bus, CONTROLLER_RPC, + PlaybackMode, PLAYER_QUERY, PLAYER_RPC, PlaybackController, @@ -339,8 +375,12 @@ function createPlaybackHarness({ backend = new FakeAudioOutputBackend(), playerI sessions.attach(playerId); const playback = new PlaybackController(bus); const playerErrors = []; + const streamErrors = []; const recoveryReports = []; const sources = []; + let mode = PlaybackMode.NATIVE; + let remoteStopCalls = 0; + let remoteStopFailure = null; const orchestrator = new PlaybackOrchestrator(bus, { sessionController: sessions }); orchestrator.attach(playerId); playback.attach(playerId, { audioOutputBackendFactory: () => backend }); @@ -369,7 +409,14 @@ function createPlaybackHarness({ backend = new FakeAudioOutputBackend(), playerI return true; }); bus.registerRpc(PLAYER_RPC.queueWillNext, () => {}); + bus.registerRpc(CONTROLLER_RPC.playbackRemoteStop, () => { + remoteStopCalls++; + if (remoteStopFailure) throw remoteStopFailure; + return true; + }); + bus.registerRpc(PLAYER_RPC.queueClear, () => {}); bus.registerQuery(PLAYER_QUERY.filterString, () => ""); + bus.registerQuery(PLAYER_QUERY.playbackMode, () => mode); bus.registerQuery(PLAYER_QUERY.transitionSettings, () => ({ enabled: transition, durationMs: 30, @@ -385,6 +432,7 @@ function createPlaybackHarness({ backend = new FakeAudioOutputBackend(), playerI })); } bus.subscribe(playerId, BUS_EVENT.trackError, (event) => playerErrors.push(event)); + bus.subscribe(playerId, BUS_EVENT.streamError, (event) => streamErrors.push(event)); return { backend, bus, @@ -394,7 +442,15 @@ function createPlaybackHarness({ backend = new FakeAudioOutputBackend(), playerI sessions, sources, playerErrors, + streamErrors, recoveryReports, + remoteStopCalls: () => remoteStopCalls, + setMode(value) { + mode = value; + }, + setRemoteStopFailure(error) { + remoteStopFailure = error; + }, start(track, signal) { const from = sessions.current(playerId)?.track ?? null; return orchestrator.states.get(playerId).start.start(track, playbackContext(playerId, signal), from); @@ -413,6 +469,10 @@ function testTrack(id) { return { id, title: id, url: `https://example.test/${id}`, duration: 1000, requestedBy: "test", source: "test" }; } +function createOutputResource(harness, track) { + return harness.playback.createResource(harness.playerId, new PassThrough(), track, StreamType.Opus); +} + test("fake backend readiness gates start and supports the full output lifecycle", async () => { const backend = new FakeAudioOutputBackend(); const handle = backend.createSession({ @@ -437,7 +497,7 @@ test("fake backend readiness gates start and supports the full output lifecycle" assert.equal(handle.state, "playing"); handle.setVolume(0.4); assert.equal(handle.volume, 0.4); - assert.equal(handle.stop(), true); + assert.equal(await handle.stop(), true); assert.equal(handle.state, "stopped"); await handle.dispose(); assert.equal(handle.input.stream.destroyed, true); @@ -647,6 +707,320 @@ test("injected backend disposal is idempotent and releases handle listeners", as await harness.backend.dispose(); assert.equal(harness.backend.handles.size, 0); assert.equal(handle.listeners.size, 0); + assert.equal(handle.disposeCalls, 1); +}); + +test("stop failure still disposes transferred input and reports cleanup failure separately", async () => { + const harness = createPlaybackHarness({ playerId: "stop-failure" }); + await harness.start(testTrack("stop-failure-track")); + const handle = harness.backend.activeHandle; + const stopError = new Error("stop rejected"); + const cleanupError = new Error("dispose reported cleanup fault"); + harness.backend.stopFailure = stopError; + harness.backend.disposeFailure = cleanupError; + + await assert.rejects(harness.playback.stop(harness.playerId), (error) => error === stopError); + assert.equal(handle.disposed, true); + assert.equal(handle.input.stream.destroyed, true); + assert.equal(harness.backend.handles.size, 0); + assert.equal(harness.playback.getActiveResource(harness.playerId), null); + assert.ok(harness.streamErrors.some((event) => event.error === cleanupError)); + await harness.dispose(); +}); + +test("abort during a pending stop triggers cleanup without waiting for the backend stop promise", async () => { + const harness = createPlaybackHarness({ playerId: "stop-abort" }); + await harness.start(testTrack("stop-abort-track")); + const handle = harness.backend.activeHandle; + const abort = new AbortController(); + harness.backend.stopGate = deferred(); + harness.backend.stopStarted = deferred(); + + const pendingStop = harness.playback.stop(harness.playerId, abort.signal); + await harness.backend.stopStarted.promise; + abort.abort(); + await assert.rejects(pendingStop, { name: "AbortError" }); + assert.equal(handle.disposed, true); + assert.equal(handle.input.stream.destroyed, true); + assert.equal(harness.backend.handles.size, 0); + harness.backend.stopGate.resolve(); + await harness.dispose(); + assert.equal(handle.disposeCalls, 1); +}); + +test("stop cancels and disposes a handle still waiting to start", async () => { + const backend = new FakeAudioOutputBackend(); + const harness = createPlaybackHarness({ backend, playerId: "stop-pending-start", ready: false }); + const resource = createOutputResource(harness, testTrack("stop-pending-start-track")); + const handle = backend.handles.values().next().value; + const startup = harness.playback.play(harness.playerId, resource); + await backend.initializeStarted.promise; + await harness.playback.stop(harness.playerId); + await assert.rejects(startup, { name: "AbortError" }); + assert.equal(handle.disposed, true); + assert.equal(handle.input.stream.destroyed, true); + assert.equal(backend.handles.size, 0); + backend.readyGate.resolve(); + await harness.dispose(); +}); + +test("a stop completing after replacement cannot clear or dispose the replacement", async () => { + const harness = createPlaybackHarness({ playerId: "stale-stop" }); + await harness.start(testTrack("stale-stop-old")); + const oldHandle = harness.backend.activeHandle; + harness.backend.stopGate = deferred(); + harness.backend.stopStarted = deferred(); + const stopPromise = harness.playback.stop(harness.playerId); + await harness.backend.stopStarted.promise; + + const nextTrack = testTrack("stale-stop-new"); + const nextResource = createOutputResource(harness, nextTrack); + await harness.playback.play(harness.playerId, nextResource, undefined, null, undefined); + const replacement = harness.backend.activeHandle; + assert.notEqual(replacement, oldHandle); + harness.backend.stopGate.resolve(); + await stopPromise; + assert.equal(harness.playback.getActiveResource(harness.playerId), nextResource); + assert.equal(harness.backend.activeHandle, replacement); + assert.equal(replacement.disposed, false); + assert.equal(oldHandle.disposed, true); + await harness.dispose(); +}); + +test("remote stop awaits success and never stops the local output backend", async () => { + const harness = createPlaybackHarness({ playerId: "remote-stop-success" }); + await harness.start(testTrack("remote-stop-track")); + const activeHandle = harness.backend.activeHandle; + harness.setMode(require("../core/dist").PlaybackMode.REMOTE); + + assert.equal(await harness.playback.stop(harness.playerId), true); + assert.equal(harness.remoteStopCalls(), 1); + assert.equal(harness.backend.stopCalls, 0); + assert.equal(harness.backend.activeHandle, activeHandle); + assert.equal(activeHandle.disposed, false); + await harness.dispose(); +}); + +test("remote stop rejection propagates and does not stop the local backend", async () => { + const harness = createPlaybackHarness({ playerId: "remote-stop-rejected" }); + await harness.start(testTrack("remote-stop-rejected-track")); + const activeHandle = harness.backend.activeHandle; + const remoteFailure = new Error("remote stop failed"); + harness.setMode(require("../core/dist").PlaybackMode.REMOTE); + harness.setRemoteStopFailure(remoteFailure); + + await assert.rejects(harness.playback.stop(harness.playerId), (error) => error === remoteFailure); + assert.equal(harness.remoteStopCalls(), 1); + assert.equal(harness.backend.stopCalls, 0); + assert.equal(harness.backend.activeHandle, activeHandle); + assert.equal(activeHandle.disposed, false); + await harness.dispose(); +}); + +test("remote STOP action awaits remote completion without entering local stop logic", async () => { + const harness = createPlaybackHarness({ playerId: "remote-stop-action" }); + const track = testTrack("remote-stop-action-track"); + await harness.start(track); + const session = harness.sessions.current(harness.playerId); + harness.setMode(require("../core/dist").PlaybackMode.REMOTE); + const context = { ...playbackContext(harness.playerId), sessionId: session.sessionId }; + + await harness.bus.action(harness.playerId, { type: "STOP" }, context); + assert.equal(harness.remoteStopCalls(), 1); + assert.equal(harness.backend.stopCalls, 0); + assert.equal(session.status, "stopped"); + assert.equal(harness.backend.activeHandle.disposed, false); + await harness.dispose(); +}); + +test("rejected remote STOP action leaves local playback untouched and propagates failure", async () => { + const harness = createPlaybackHarness({ playerId: "remote-stop-action-rejected" }); + const track = testTrack("remote-stop-action-rejected-track"); + await harness.start(track); + const session = harness.sessions.current(harness.playerId); + const activeHandle = harness.backend.activeHandle; + const failure = new Error("remote action stop rejected"); + harness.setMode(require("../core/dist").PlaybackMode.REMOTE); + harness.setRemoteStopFailure(failure); + const context = { ...playbackContext(harness.playerId), sessionId: session.sessionId }; + + await assert.rejects(harness.bus.action(harness.playerId, { type: "STOP" }, context), (error) => error === failure); + assert.equal(harness.remoteStopCalls(), 1); + assert.equal(harness.backend.stopCalls, 0); + assert.equal(session.isActive(), true); + assert.equal(harness.backend.activeHandle, activeHandle); + await harness.dispose(); +}); + +test("volume, initialization, readiness, and start failures dispose only the unactivated handle", async () => { + for (const [caseName, configure, expectedFailure] of [ + [ + "volume", + (backend) => { + backend.volumeFailure = new Error("volume failure"); + }, + "volume failure", + ], + [ + "initialization", + (backend) => { + backend.initializeFailure = new Error("initialize failure"); + }, + "initialize failure", + ], + [ + "readiness", + (backend) => { + backend.handleReady = Promise.reject(new Error("readiness failure")); + }, + "readiness failure", + ], + [ + "start", + (backend) => { + backend.startFailure = new Error("start failure"); + }, + "start failure", + ], + ]) { + const backend = new FakeAudioOutputBackend(); + backend.readyGate.resolve(); + const harness = createPlaybackHarness({ backend, playerId: `startup-${caseName}` }); + configure(backend); + const track = testTrack(`startup-${caseName}-track`); + const resource = createOutputResource(harness, track); + const handle = backend.handles.values().next().value; + await assert.rejects(harness.playback.play(harness.playerId, resource), new RegExp(expectedFailure)); + assert.equal(handle.disposed, true, `${caseName} failure leaked handle`); + assert.equal(handle.input.stream.destroyed, true, `${caseName} failure leaked transferred stream`); + assert.equal(backend.handles.size, 0, `${caseName} failure left a registered handle`); + assert.equal(harness.playback.getActiveResource(harness.playerId), null); + await harness.dispose(); + } +}); + +test("stop-before-start replacement failure cleans both handles without restoring a disposed session", async () => { + const backend = new FakeAudioOutputBackend(); + backend.capabilities.replacement = "stop-before-start"; + const harness = createPlaybackHarness({ backend, playerId: "replacement-start-failure" }); + await harness.start(testTrack("replacement-old")); + const oldHandle = backend.activeHandle; + backend.startFailure = new Error("replacement start failed"); + const replacementTrack = testTrack("replacement-failed"); + const resource = createOutputResource(harness, replacementTrack); + const replacementHandle = [...backend.handles].find((handle) => handle !== oldHandle); + + await assert.rejects(harness.playback.play(harness.playerId, resource), /replacement start failed/); + assert.equal(oldHandle.disposed, true); + assert.equal(replacementHandle.disposed, true); + assert.equal(oldHandle.input.stream.destroyed, true); + assert.equal(replacementHandle.input.stream.destroyed, true); + assert.equal(harness.backend.handles.size, 0); + assert.equal(harness.playback.getActiveResource(harness.playerId), null); + await harness.dispose(); +}); + +test("crossfade volume failure preserves the active handle and releases the candidate", async () => { + const harness = createPlaybackHarness({ playerId: "crossfade-volume-failure", transition: true }); + const oldTrack = testTrack("crossfade-volume-old"); + await harness.start(oldTrack); + const oldHandle = harness.backend.activeHandle; + harness.backend.volumeFailure = new Error("crossfade volume failed"); + const nextTrack = testTrack("crossfade-volume-new"); + const nextResource = createOutputResource(harness, nextTrack); + const candidate = [...harness.backend.handles].find((handle) => handle !== oldHandle); + + await assert.rejects( + harness.playback.play(harness.playerId, nextResource, undefined, oldTrack, nextTrack), + /crossfade volume failed/, + ); + assert.equal(candidate.disposed, true); + assert.equal(harness.backend.activeHandle, oldHandle); + assert.equal(harness.playback.getActiveResource(harness.playerId), oldHandle.resource); + assert.equal(harness.backend.handles.size, 1); + assert.equal(harness.playback.getFadeGain(harness.playerId), null); + await harness.dispose(); +}); + +test("atomic replacement that fails after backend activation clears invalidated old output", async () => { + const harness = createPlaybackHarness({ playerId: "atomic-replacement-failure", transition: true }); + const oldTrack = testTrack("atomic-old"); + await harness.start(oldTrack); + const oldHandle = harness.backend.activeHandle; + harness.backend.startFailureAfterActivation = new Error("atomic replacement failed after activation"); + const nextTrack = testTrack("atomic-new"); + const nextResource = createOutputResource(harness, nextTrack); + const replacement = [...harness.backend.handles].find((handle) => handle !== oldHandle); + + await assert.rejects( + harness.playback.play(harness.playerId, nextResource, undefined, oldTrack, nextTrack), + /atomic replacement failed after activation/, + ); + assert.equal(oldHandle.disposed, true); + assert.equal(replacement.disposed, true); + assert.equal(harness.backend.activeHandle, null); + assert.equal(harness.backend.handles.size, 0); + assert.equal(harness.playback.getActiveResource(harness.playerId), null); + await harness.dispose(); +}); + +test("concurrent stop and detach dispose an active handle exactly once", async () => { + const harness = createPlaybackHarness({ playerId: "stop-detach" }); + await harness.start(testTrack("stop-detach-track")); + const handle = harness.backend.activeHandle; + harness.backend.stopGate = deferred(); + harness.backend.stopStarted = deferred(); + const stop = harness.playback.stop(harness.playerId); + await harness.backend.stopStarted.promise; + const duplicateStop = harness.playback.stop(harness.playerId); + harness.playback.detach(harness.playerId); + await Promise.all([assert.rejects(stop, { name: "AbortError" }), assert.rejects(duplicateStop, { name: "AbortError" })]); + harness.backend.stopGate.resolve(); + assert.equal(handle.disposeCalls, 1); + assert.equal(handle.input.stream.destroyed, true); + assert.equal(harness.backend.handles.size, 0); + await harness.orchestrator.detach(harness.playerId); + await harness.orchestrator.dispose(); + harness.sessions.detach(harness.playerId); +}); + +test("preload promotion reports asynchronous output startup failures", async () => { + const harness = createPlaybackHarness({ playerId: "preload-start-failure" }); + const track = testTrack("preloaded-track"); + harness.sessions.replace(harness.playerId, track); + const source = Readable.from([Buffer.from("encoded preload")]); + const { PreloadController } = require("../core/dist"); + const preloader = new PreloadController(harness.bus, { + loader: { + hasPreload: () => false, + cancelPreload: () => {}, + cancelPreloadSafely: async () => {}, + preloadNext: async () => {}, + }, + manager: { + takePreloaded: () => ({ + track, + stream: source, + streamInfo: { track, stream: source, type: "arbitrary", inputType: StreamType.Opus }, + streamId: null, + }), + slotState: () => ({}), + clearPreloadSlot: () => {}, + }, + }); + const reported = deferred(); + harness.bus.subscribe(harness.playerId, require("../core/dist").BUS_EVENT.trackError, (event) => { + if (event.track === track || event.session?.track === track) reported.resolve(event); + }); + harness.backend.startFailure = new Error("preload output start failed"); + + const resource = preloader.promotePreload(harness.playerId, track); + assert.ok(resource); + const event = await reported.promise; + assert.match(event.error.message, /preload output start failed/); + assert.equal(harness.backend.handles.size, 0); + assert.equal(source.destroyed, true); + await harness.dispose(); }); test("Discord backend converts float32 PCM at the adapter boundary and controls inline volume", async () => { From 51bc1892e99d9c6a91e7c72d5421012ec3be90dd Mon Sep 17 00:00:00 2001 From: Ziji <104454302+zijipia@users.noreply.github.com> Date: Sat, 10 Oct 2026 12:03:05 +0900 Subject: [PATCH 07/55] fix: harden playback lifecycle error handling Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .github/workflows/node.js.yml | 2 +- core/src/controller/PlaybackController.ts | 16 +++- .../PlaybackPreparationController.ts | 34 ++++++-- .../src/controller/PlaybackStartController.ts | 31 +++---- .../controller/PlaybackTrackEndController.ts | 81 +++++++++++++------ core/src/structures/PlaybackOrchestrator.ts | 49 ++++++++--- docs/AUDIO_OUTPUT_BACKENDS.md | 12 ++- tests/audio_output_backend.test.js | 63 ++++++++++++++- tests/playback_session_transition.test.js | 61 ++++++++++++++ 9 files changed, 285 insertions(+), 64 deletions(-) diff --git a/.github/workflows/node.js.yml b/.github/workflows/node.js.yml index d0f08b78..6881cdc0 100644 --- a/.github/workflows/node.js.yml +++ b/.github/workflows/node.js.yml @@ -6,7 +6,7 @@ permissions: on: push: - branches: ["main"] + branches: ["main", "AudioEngine"] pull_request: branches: ["main"] diff --git a/core/src/controller/PlaybackController.ts b/core/src/controller/PlaybackController.ts index 9246f6f5..4dcad948 100644 --- a/core/src/controller/PlaybackController.ts +++ b/core/src/controller/PlaybackController.ts @@ -71,6 +71,7 @@ export class PlaybackController { private readonly bus: Bus; private readonly slots = new Map(); private readonly processingOptions = new Map(); + private readonly remoteStopPromises = new Map>(); public constructor(bus: Bus) { this.bus = bus; @@ -1172,7 +1173,20 @@ export class PlaybackController { public async stop(playerId: string, signal?: AbortSignal): Promise { const mode = this.bus.querySync(playerId, PLAYER_QUERY.playbackMode); if (mode === PlaybackMode.REMOTE) { - return await this.bus.requestRpc(playerId, CONTROLLER_RPC.playbackRemoteStop, {}); + const pending = this.remoteStopPromises.get(playerId); + if (pending) return pending; + const operation = this.bus.requestRpc, boolean>( + playerId, + CONTROLLER_RPC.playbackRemoteStop, + {}, + { signal }, + ); + this.remoteStopPromises.set(playerId, operation); + try { + return await operation; + } finally { + if (this.remoteStopPromises.get(playerId) === operation) this.remoteStopPromises.delete(playerId); + } } const slot = this.slots.get(playerId); if (!slot) return false; diff --git a/core/src/controller/PlaybackPreparationController.ts b/core/src/controller/PlaybackPreparationController.ts index 695cb788..e6edf174 100644 --- a/core/src/controller/PlaybackPreparationController.ts +++ b/core/src/controller/PlaybackPreparationController.ts @@ -52,12 +52,14 @@ export class PlaybackPreparationController { return []; } - let related = await this.bus - .requestRpc<{ track: Track; history?: Track[] }, Track[]>(this.playerId, PLAYER_RPC.pluginRelatedTracks, { + let related = await this.bus.requestRpc<{ track: Track; history?: Track[] }, Track[]>( + this.playerId, + PLAYER_RPC.pluginRelatedTracks, + { track: source, history: previous, - }) - .catch(() => []); + }, + ); related = related ?? []; const upcoming = new Set(this.queueSnapshot().map((item) => item.id ?? item.url)); related = related.filter((item) => item !== source && !upcoming.has(item.id ?? item.url)); @@ -75,7 +77,12 @@ export class PlaybackPreparationController { const queueNext = (this.bus.querySync(this.playerId, PLAYER_QUERY.queueNextTrack) as Track | null) ?? null; let related = (this.bus.querySync(this.playerId, PLAYER_QUERY.relatedTracks) as Track[] | null) ?? []; if (!related.length && !this.queueSnapshot().length) { - related = await this.createRelatedTracks(session.track); + try { + related = await this.createRelatedTracks(session.track); + } catch (error) { + this.reportStreamError(session.track, error); + related = []; + } } if (!related.length) { this.bus.requestRpcSync(this.playerId, PLAYER_RPC.queueWillNext, { track: queueNext }); @@ -127,6 +134,7 @@ export class PlaybackPreparationController { this.setQueueRelated(related); } catch (error) { this.debug?.("[PlaybackPreparationController] Error preparing related tracks:", error); + if (!context.signal.aborted) this.reportStreamError(session.track, error); } } @@ -138,6 +146,20 @@ export class PlaybackPreparationController { { type: BUS_REQUEST.preloadRequest, requestId: context.requestId, track }, { signal: context.signal, timeoutMs: 30000 }, ); - } catch {} + } catch (error) { + if (!context.signal.aborted) this.reportStreamError(track, error); + } + } + + private reportStreamError(track: Track | null, error: unknown): void { + try { + this.bus.event(this.playerId, { + type: BUS_EVENT.streamError, + error: error instanceof Error ? error : new Error(String(error)), + track, + }); + } catch (reportError) { + console.error("Failed to report playback stream error", reportError); + } } } diff --git a/core/src/controller/PlaybackStartController.ts b/core/src/controller/PlaybackStartController.ts index feb982c0..cead7e1e 100644 --- a/core/src/controller/PlaybackStartController.ts +++ b/core/src/controller/PlaybackStartController.ts @@ -122,6 +122,7 @@ export class PlaybackStartController { } catch (error) { if (transition) this.sessionController.retirePendingPrevious(this.playerId); const normalized = error instanceof Error ? error : new Error(String(error)); + if (context.signal.aborted) throw error; if (!context.signal.aborted && this.isCurrentSession(session, context)) { this.bus.event(this.playerId, { type: BUS_EVENT.trackError, @@ -135,13 +136,9 @@ export class PlaybackStartController { this.consecutiveFailures = 0; this.bus.event(this.playerId, { type: BUS_EVENT.queueEnd }); if (this.bus.hasRpc(PLAYER_RPC.lifecycleScheduleLeave)) { - void this.bus.requestRpc(this.playerId, PLAYER_RPC.lifecycleScheduleLeave, {}).catch((reportError) => { - this.bus.event(this.playerId, { - type: BUS_EVENT.streamError, - error: reportError instanceof Error ? reportError : new Error(String(reportError)), - track, - }); - }); + void this.bus + .requestRpc(this.playerId, PLAYER_RPC.lifecycleScheduleLeave, {}) + .catch((reportError) => this.reportStreamError(track, reportError)); } } else if (!parentContext.signal.aborted) { void this.bus @@ -150,18 +147,24 @@ export class PlaybackStartController { { type: PLAYER_ACTION.skip, ignoreLoop: true, requestId: parentContext.requestId }, parentContext, ) - .catch((reportError) => { - this.bus.event(this.playerId, { - type: BUS_EVENT.streamError, - error: reportError instanceof Error ? reportError : new Error(String(reportError)), - track, - }); - }); + .catch((reportError) => this.reportStreamError(track, reportError)); } throw error; } } + private reportStreamError(track: Track, error: unknown): void { + try { + this.bus.event(this.playerId, { + type: BUS_EVENT.streamError, + error: error instanceof Error ? error : new Error(String(error)), + track, + }); + } catch (reportError) { + console.error("Failed to report playback stream error", reportError); + } + } + private isCurrentSession(session: PlaybackSession, context: PlayerMessageContext): boolean { return this.sessionController.current(this.playerId) === session && session.ownsContext(context.sessionId); } diff --git a/core/src/controller/PlaybackTrackEndController.ts b/core/src/controller/PlaybackTrackEndController.ts index df1a26ee..6d4c99b4 100644 --- a/core/src/controller/PlaybackTrackEndController.ts +++ b/core/src/controller/PlaybackTrackEndController.ts @@ -62,14 +62,22 @@ export class PlaybackTrackEndController { } public async waitForQueue(signal: AbortSignal): Promise { - if (!this.queueStartPromise) return; - await Promise.race([ - this.queueStartPromise, - new Promise((resolve) => { - if (signal.aborted || this.lifecycleSignal.aborted) return resolve(); - signal.addEventListener("abort", () => resolve(), { once: true }); - }), - ]); + const queueStartPromise = this.queueStartPromise; + if (!queueStartPromise) return; + await new Promise((resolve) => { + const finish = () => { + signal.removeEventListener("abort", finish); + this.lifecycleSignal.removeEventListener("abort", finish); + resolve(); + }; + if (signal.aborted || this.lifecycleSignal.aborted) { + finish(); + return; + } + signal.addEventListener("abort", finish, { once: true }); + this.lifecycleSignal.addEventListener("abort", finish, { once: true }); + void queueStartPromise.then(finish, finish); + }); } public onQueueChanged(): void { @@ -77,13 +85,7 @@ export class PlaybackTrackEndController { if (!this.queueSnapshot().length) return; const generation = ++this.queueStartGeneration; this.queueStartPromise = this.startQueuedTrackAfterEnd() - .catch((error) => { - this.bus.event(this.playerId, { - type: BUS_EVENT.streamError, - error: error instanceof Error ? error : new Error(String(error)), - track: this.currentSession()?.track ?? null, - }); - }) + .catch((error) => this.reportStreamError(this.currentSession()?.track ?? null, error)) .finally(() => { if (generation === this.queueStartGeneration) this.queueStartPromise = null; }); @@ -121,11 +123,18 @@ export class PlaybackTrackEndController { // Queue is empty -> generateRelated() const previousTracks = (this.bus.querySync(this.playerId, PLAYER_QUERY.previousTracks) as Track[] | null) ?? []; const source = previousTracks.at(-1) ?? endedSession.track; - relatedTracks = await this.bus - .requestRpc<{ track?: Track | null }, Track[]>(this.playerId, CONTROLLER_RPC.playbackCreateRelatedTracks, { - track: source, - }) - .catch(() => []); + try { + relatedTracks = await this.bus.requestRpc<{ track?: Track | null }, Track[]>( + this.playerId, + CONTROLLER_RPC.playbackCreateRelatedTracks, + { + track: source, + }, + ); + } catch (error) { + this.reportStreamError(from, error); + relatedTracks = []; + } relatedTracks = relatedTracks ?? []; next = relatedTracks[0] ?? null; isFromQueueOrLoop = false; @@ -150,8 +159,13 @@ export class PlaybackTrackEndController { const queueNext = await this.nextThroughBus(false, context); if (queueNext) { endedSession.markEnded(); - this.waitingForQueue = false; - await this.bus.requestRpc(this.playerId, CONTROLLER_RPC.playbackStart, { track: queueNext, context, from }); + try { + await this.bus.requestRpc(this.playerId, CONTROLLER_RPC.playbackStart, { track: queueNext, context, from }); + this.waitingForQueue = false; + } catch (error) { + this.waitingForQueue = true; + throw error; + } return; } } else { @@ -159,8 +173,13 @@ export class PlaybackTrackEndController { if (autoPlay && next) { endedSession.markEnded(); this.bus.requestRpcSync(this.playerId, PLAYER_RPC.queueWillNext, { track: null }); - this.waitingForQueue = false; - await this.bus.requestRpc(this.playerId, CONTROLLER_RPC.playbackStart, { track: next, context, from }); + try { + await this.bus.requestRpc(this.playerId, CONTROLLER_RPC.playbackStart, { track: next, context, from }); + this.waitingForQueue = false; + } catch (error) { + this.waitingForQueue = true; + throw error; + } return; } } @@ -193,13 +212,25 @@ export class PlaybackTrackEndController { const context = this.createContext("PlaybackTrackEndController:queue-refill"); const next = await this.nextThroughBus(false, context); if (!next || context.signal.aborted) return; - this.waitingForQueue = false; await this.bus.requestRpc(this.playerId, CONTROLLER_RPC.playbackStart, { track: next, context, from }); + this.waitingForQueue = false; } finally { this.trackEndTransition = false; } } + private reportStreamError(track: Track | null, error: unknown): void { + try { + this.bus.event(this.playerId, { + type: BUS_EVENT.streamError, + error: error instanceof Error ? error : new Error(String(error)), + track, + }); + } catch (reportError) { + console.error("Failed to report playback stream error", reportError); + } + } + private createContext(source: string): PlayerMessageContext { return { playerId: this.playerId, diff --git a/core/src/structures/PlaybackOrchestrator.ts b/core/src/structures/PlaybackOrchestrator.ts index ab65f0c9..a41f9693 100644 --- a/core/src/structures/PlaybackOrchestrator.ts +++ b/core/src/structures/PlaybackOrchestrator.ts @@ -55,6 +55,7 @@ export class PlaybackOrchestrator { private readonly sessionController: PlaybackSessionController; private readonly seekController: PlaybackSeekController; private readonly detachAction: () => void; + private readonly remoteStopOperations = new Map>(); public constructor(bus: Bus, options: PlaybackOrchestratorOptions) { this.bus = bus; @@ -175,13 +176,7 @@ export class PlaybackOrchestrator { if (!session || session.status === "ended" || session.status === "stopped") return; const current = this.sessionController.current(playerId); if (!current || current.id !== session.id) return; - void state.trackEnd.onTrackEnd(session).catch((error) => { - this.bus.event(playerId, { - type: BUS_EVENT.streamError, - error: error instanceof Error ? error : new Error(String(error)), - track: session.track, - }); - }); + void state.trackEnd.onTrackEnd(session).catch((error) => this.reportStreamError(playerId, session.track, error)); }); state.detachQueueEnd = this.bus.subscribe(playerId, BUS_EVENT.queueEnd, () => state.trackEnd.onQueueEnd()); state.detachQueueChanged = this.bus.subscribe(playerId, BUS_EVENT.queueChanged, () => state.trackEnd.onQueueChanged()); @@ -331,11 +326,7 @@ export class PlaybackOrchestrator { const session = this.sessionController.current(playerId); const mode = this.bus.querySync(playerId, PLAYER_QUERY.playbackMode); if (mode === PlaybackMode.REMOTE) { - await this.bus.requestRpc(playerId, CONTROLLER_RPC.playbackRemoteStop, {}); - this.bus.requestRpcSync(playerId, PLAYER_RPC.queueClear, undefined); - if (session?.isActive()) session.markStopped(); - this.publishState(playerId); - this.bus.event(playerId, { type: BUS_EVENT.playerStop }); + await this.stopRemotePlayback(playerId, session, context.signal); break; } if (session && !this.matchesContext(session, context)) break; @@ -349,6 +340,40 @@ export class PlaybackOrchestrator { } } + private async stopRemotePlayback(playerId: string, session: PlaybackSession | null, signal: AbortSignal): Promise { + const pending = this.remoteStopOperations.get(playerId); + if (pending) return pending; + const sessionId = session?.id ?? null; + const operation = (async () => { + const stopped = await this.bus.requestRpc(playerId, CONTROLLER_RPC.playbackRemoteStop, {}, { signal }); + if (!stopped) return; + const current = this.sessionController.current(playerId); + if ((current?.id ?? null) !== sessionId) return; + this.bus.requestRpcSync(playerId, PLAYER_RPC.queueClear, undefined); + if (session?.isActive()) session.markStopped(); + this.publishState(playerId); + this.bus.event(playerId, { type: BUS_EVENT.playerStop }); + })(); + this.remoteStopOperations.set(playerId, operation); + try { + await operation; + } finally { + if (this.remoteStopOperations.get(playerId) === operation) this.remoteStopOperations.delete(playerId); + } + } + + private reportStreamError(playerId: string, track: Track | null, error: unknown): void { + try { + this.bus.event(playerId, { + type: BUS_EVENT.streamError, + error: error instanceof Error ? error : new Error(String(error)), + track, + }); + } catch (reportError) { + console.error("Failed to report playback stream error", reportError); + } + } + private matchesContext(session: PlaybackSession, context: PlayerMessageContext): boolean { return session.ownsContext(context.sessionId); } diff --git a/docs/AUDIO_OUTPUT_BACKENDS.md b/docs/AUDIO_OUTPUT_BACKENDS.md index 5826be1f..ba661de1 100644 --- a/docs/AUDIO_OUTPUT_BACKENDS.md +++ b/docs/AUDIO_OUTPUT_BACKENDS.md @@ -88,9 +88,15 @@ Stop is cleanup-safe even when the backend rejects or the caller aborts while st captured handle independently, reports disposal failure as a separate stream error, and then propagates the original stop failure. Slot state is cleared only if that same handle is still active, so a late stop cannot erase a replacement. Concurrent stop and disposal requests share per-handle cleanup. In remote playback mode, stop awaits the remote stop RPC and does not also stop the -local output backend. Backend start is transactional: readiness and initial volume must succeed before activation is committed, -and failed/unactivated handles are disposed; adapters should ensure a rejected `start()` does not leave an active output session -behind. +local output backend. A remote `false` result means the remote endpoint did not stop; the local session and queue remain unchanged +and no successful `playerStop` event is emitted. Concurrent remote STOP actions share the in-flight RPC and commit the resulting +state transition at most once. + +Backend start is transactional: readiness and initial volume must succeed before activation is committed, and failed/unactivated +handles are disposed; adapters should ensure a rejected `start()` does not leave an active output session behind. Related-track +generation failure is reported as `streamError`, then the normal queue-end/autoplay fallback proceeds without treating the lookup +as a successful result. Queue and track-start RPC failures remain observable and restore the queue-wait/transition guards so a +later queue change can retry. ## Processed audio format and failure behavior diff --git a/tests/audio_output_backend.test.js b/tests/audio_output_backend.test.js index 42007b69..dcdc7287 100644 --- a/tests/audio_output_backend.test.js +++ b/tests/audio_output_backend.test.js @@ -381,6 +381,10 @@ function createPlaybackHarness({ let mode = PlaybackMode.NATIVE; let remoteStopCalls = 0; let remoteStopFailure = null; + let remoteStopResult = true; + let remoteStopGate = null; + const remoteStopStarted = deferred(); + let queueClearCalls = 0; const orchestrator = new PlaybackOrchestrator(bus, { sessionController: sessions }); orchestrator.attach(playerId); playback.attach(playerId, { audioOutputBackendFactory: () => backend }); @@ -411,10 +415,14 @@ function createPlaybackHarness({ bus.registerRpc(PLAYER_RPC.queueWillNext, () => {}); bus.registerRpc(CONTROLLER_RPC.playbackRemoteStop, () => { remoteStopCalls++; + remoteStopStarted.resolve(); + if (remoteStopGate) return remoteStopGate.promise; if (remoteStopFailure) throw remoteStopFailure; - return true; + return remoteStopResult; + }); + bus.registerRpc(PLAYER_RPC.queueClear, () => { + queueClearCalls++; }); - bus.registerRpc(PLAYER_RPC.queueClear, () => {}); bus.registerQuery(PLAYER_QUERY.filterString, () => ""); bus.registerQuery(PLAYER_QUERY.playbackMode, () => mode); bus.registerQuery(PLAYER_QUERY.transitionSettings, () => ({ @@ -445,9 +453,17 @@ function createPlaybackHarness({ streamErrors, recoveryReports, remoteStopCalls: () => remoteStopCalls, + remoteStopStarted: remoteStopStarted.promise, + queueClearCalls: () => queueClearCalls, setMode(value) { mode = value; }, + setRemoteStopResult(value) { + remoteStopResult = value; + }, + setRemoteStopGate(gate) { + remoteStopGate = gate; + }, setRemoteStopFailure(error) { remoteStopFailure = error; }, @@ -817,6 +833,49 @@ test("remote stop rejection propagates and does not stop the local backend", asy await harness.dispose(); }); +test("remote STOP false result preserves session, queue, and stop events", async () => { + const harness = createPlaybackHarness({ playerId: "remote-stop-false" }); + await harness.start(testTrack("remote-stop-false-track")); + const session = harness.sessions.current(harness.playerId); + const stopEvents = []; + harness.bus.subscribe(harness.playerId, "playerStop", (event) => stopEvents.push(event)); + harness.setMode(require("../core/dist").PlaybackMode.REMOTE); + harness.setRemoteStopResult(false); + const context = { ...playbackContext(harness.playerId), sessionId: session.sessionId }; + + await harness.bus.action(harness.playerId, { type: "STOP" }, context); + assert.equal(harness.remoteStopCalls(), 1); + assert.equal(harness.queueClearCalls(), 0); + assert.equal(session.isActive(), true); + assert.equal(stopEvents.length, 0); + assert.equal(harness.backend.stopCalls, 0); + await harness.dispose(); +}); + +test("overlapping remote STOP requests share one RPC and commit once", async () => { + const harness = createPlaybackHarness({ playerId: "remote-stop-repeated" }); + await harness.start(testTrack("remote-stop-repeated-track")); + const session = harness.sessions.current(harness.playerId); + let stopEvents = 0; + harness.bus.subscribe(harness.playerId, "playerStop", () => stopEvents++); + harness.setMode(require("../core/dist").PlaybackMode.REMOTE); + const gate = deferred(); + harness.setRemoteStopGate(gate); + const context = { ...playbackContext(harness.playerId), sessionId: session.sessionId }; + + const first = harness.bus.action(harness.playerId, { type: "STOP" }, context); + const second = harness.bus.action(harness.playerId, { type: "STOP" }, context); + await harness.remoteStopStarted; + assert.equal(harness.remoteStopCalls(), 1); + gate.resolve(true); + await Promise.all([first, second]); + assert.equal(harness.queueClearCalls(), 1); + assert.equal(stopEvents, 1); + assert.equal(session.status, "stopped"); + assert.equal(harness.backend.stopCalls, 0); + await harness.dispose(); +}); + test("remote STOP action awaits remote completion without entering local stop logic", async () => { const harness = createPlaybackHarness({ playerId: "remote-stop-action" }); const track = testTrack("remote-stop-action-track"); diff --git a/tests/playback_session_transition.test.js b/tests/playback_session_transition.test.js index 3d676688..42b4eb6a 100644 --- a/tests/playback_session_transition.test.js +++ b/tests/playback_session_transition.test.js @@ -140,6 +140,67 @@ test("related tracks resolve and set willNext even when autoplay is disabled", a harness.queueController.dispose(); }); +test("related-track generation failure is reported and still reaches queue-end fallback once", async () => { + const trackA = { id: "track-related-failure", title: "Track A", duration: 180000 }; + const failure = new Error("related track lookup failed"); + const harness = createOrchestrator({ + autoPlay: true, + relatedResolver: async () => { + throw failure; + }, + }); + const streamErrors = []; + let queueEndCount = 0; + harness.bus.subscribe(harness.playerId, "streamError", (event) => streamErrors.push(event.error)); + harness.bus.subscribe(harness.playerId, "queueEnd", () => queueEndCount++); + + await play(harness, trackA); + const endedSession = harness.orchestrator.getCurrentSession(harness.playerId); + harness.bus.event(harness.playerId, { type: "TRACK_END", session: endedSession.snapshot() }); + harness.bus.event(harness.playerId, { type: "TRACK_END", session: endedSession.snapshot() }); + await waitFor(() => queueEndCount === 1); + + assert.ok(streamErrors.includes(failure)); + assert.equal(queueEndCount, 1); + assert.equal(harness.orchestrator.getCurrentSession(harness.playerId).status, "ended"); + assert.deepEqual(harness.played, ["track-related-failure"]); + await harness.orchestrator.dispose(); + harness.queueController.dispose(); +}); + +test("failed queued-track start restores transition guards and retries on a later queue change", async () => { + const trackA = { id: "track-start-failure", title: "Track A", duration: 180000 }; + const trackB = { id: "track-start-failure-next", title: "Track B", duration: 180000 }; + const trackC = { id: "track-start-retry", title: "Track C", duration: 180000 }; + const harness = createOrchestrator(); + const streamErrors = []; + harness.bus.subscribe(harness.playerId, "streamError", (event) => streamErrors.push(event.error)); + + await play(harness, trackA); + harness.queueController.add(trackB); + let startAttempts = 0; + harness.bus.registerRpc("playback.start", () => { + startAttempts++; + if (startAttempts === 1) throw new Error("queued track start failed"); + }); + const endedSession = harness.orchestrator.getCurrentSession(harness.playerId); + harness.bus.event(harness.playerId, { type: "TRACK_END", session: endedSession.snapshot() }); + await waitFor(() => streamErrors.length === 1); + const trackEnd = harness.orchestrator.states.get(harness.playerId).trackEnd; + assert.equal(trackEnd.isTransitioning, false); + assert.equal(trackEnd.isWaitingForQueue, true); + + harness.queueController.add(trackC); + trackEnd.onQueueChanged(); + await trackEnd.waitForQueue(new AbortController().signal); + assert.equal(startAttempts, 2); + assert.equal(trackEnd.isWaitingForQueue, false); + assert.equal(trackEnd.isTransitioning, false); + assert.equal(streamErrors[0].message, "queued track start failed"); + await harness.orchestrator.dispose(); + harness.queueController.dispose(); +}); + test("loop off advances to the queued track after TRACK_END", async () => { const trackA = { id: "track-a", title: "Track A", duration: 180000 }; const trackB = { id: "track-b", title: "Track B", duration: 180000 }; From e85765e80f5cc0f10cd3b8191e80893cb526ec87 Mon Sep 17 00:00:00 2001 From: Ziji <104454302+zijipia@users.noreply.github.com> Date: Sat, 10 Oct 2026 12:34:15 +0900 Subject: [PATCH 08/55] fix: isolate cancellation for coalesced remote stops Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .github/workflows/node.js.yml | 10 +++- core/src/controller/PlaybackController.ts | 22 ++++--- core/src/structures/PlaybackOrchestrator.ts | 63 +++++++++++++++------ docs/AUDIO_OUTPUT_BACKENDS.md | 4 +- tests/audio_output_backend.test.js | 41 ++++++++++++-- 5 files changed, 103 insertions(+), 37 deletions(-) diff --git a/.github/workflows/node.js.yml b/.github/workflows/node.js.yml index 6881cdc0..7652d525 100644 --- a/.github/workflows/node.js.yml +++ b/.github/workflows/node.js.yml @@ -91,19 +91,23 @@ jobs: - name: Bootstrap core package run: | - npm -C core ci + # package-lock.json is ignored and no lockfiles are committed for these packages. + npm -C core install --package-lock=false npm -C core run build - name: Bootstrap plugins package run: | - npm -C plugins ci + npm -C plugins install --package-lock=false npm -C plugins run build - name: Bootstrap extension package run: | - npm -C extension ci + npm -C extension install --package-lock=false npm -C extension run build + - name: Bootstrap root package + run: npm install --no-save --package-lock=false ./core + - name: Run tests id: tests shell: bash diff --git a/core/src/controller/PlaybackController.ts b/core/src/controller/PlaybackController.ts index 4dcad948..4eca9c60 100644 --- a/core/src/controller/PlaybackController.ts +++ b/core/src/controller/PlaybackController.ts @@ -1174,19 +1174,17 @@ export class PlaybackController { const mode = this.bus.querySync(playerId, PLAYER_QUERY.playbackMode); if (mode === PlaybackMode.REMOTE) { const pending = this.remoteStopPromises.get(playerId); - if (pending) return pending; - const operation = this.bus.requestRpc, boolean>( - playerId, - CONTROLLER_RPC.playbackRemoteStop, - {}, - { signal }, - ); - this.remoteStopPromises.set(playerId, operation); - try { - return await operation; - } finally { - if (this.remoteStopPromises.get(playerId) === operation) this.remoteStopPromises.delete(playerId); + if (signal?.aborted) throw this.outputAbortError(); + let operation = pending; + if (!operation) { + operation = this.bus.requestRpc, boolean>(playerId, CONTROLLER_RPC.playbackRemoteStop, {}); + this.remoteStopPromises.set(playerId, operation); + const clearPending = () => { + if (this.remoteStopPromises.get(playerId) === operation) this.remoteStopPromises.delete(playerId); + }; + void operation.then(clearPending, clearPending); } + return signal ? this.awaitWithAbort(operation, signal) : operation; } const slot = this.slots.get(playerId); if (!slot) return false; diff --git a/core/src/structures/PlaybackOrchestrator.ts b/core/src/structures/PlaybackOrchestrator.ts index a41f9693..48277b71 100644 --- a/core/src/structures/PlaybackOrchestrator.ts +++ b/core/src/structures/PlaybackOrchestrator.ts @@ -341,25 +341,54 @@ export class PlaybackOrchestrator { } private async stopRemotePlayback(playerId: string, session: PlaybackSession | null, signal: AbortSignal): Promise { + if (signal.aborted) throw this.abortError(); const pending = this.remoteStopOperations.get(playerId); - if (pending) return pending; - const sessionId = session?.id ?? null; - const operation = (async () => { - const stopped = await this.bus.requestRpc(playerId, CONTROLLER_RPC.playbackRemoteStop, {}, { signal }); - if (!stopped) return; - const current = this.sessionController.current(playerId); - if ((current?.id ?? null) !== sessionId) return; - this.bus.requestRpcSync(playerId, PLAYER_RPC.queueClear, undefined); - if (session?.isActive()) session.markStopped(); - this.publishState(playerId); - this.bus.event(playerId, { type: BUS_EVENT.playerStop }); - })(); - this.remoteStopOperations.set(playerId, operation); - try { - await operation; - } finally { - if (this.remoteStopOperations.get(playerId) === operation) this.remoteStopOperations.delete(playerId); + let operation = pending; + if (!operation) { + const sessionId = session?.id ?? null; + operation = this.bus.requestRpc(playerId, CONTROLLER_RPC.playbackRemoteStop, {}).then((stopped) => { + if (!stopped) return; + const current = this.sessionController.current(playerId); + if ((current?.id ?? null) !== sessionId) return; + this.bus.requestRpcSync(playerId, PLAYER_RPC.queueClear, undefined); + if (session?.isActive()) session.markStopped(); + this.publishState(playerId); + this.bus.event(playerId, { type: BUS_EVENT.playerStop }); + }); + this.remoteStopOperations.set(playerId, operation); + const clearPending = () => { + if (this.remoteStopOperations.get(playerId) === operation) this.remoteStopOperations.delete(playerId); + }; + void operation.then(clearPending, clearPending); } + await this.awaitWithAbort(operation, signal); + } + + private async awaitWithAbort(operation: Promise, signal: AbortSignal): Promise { + if (signal.aborted) throw this.abortError(); + return new Promise((resolve, reject) => { + const onAbort = () => { + signal.removeEventListener("abort", onAbort); + reject(this.abortError()); + }; + signal.addEventListener("abort", onAbort, { once: true }); + operation.then( + (value) => { + signal.removeEventListener("abort", onAbort); + resolve(value); + }, + (error) => { + signal.removeEventListener("abort", onAbort); + reject(error); + }, + ); + }); + } + + private abortError(): Error { + const error = new Error("Playback operation was aborted"); + error.name = "AbortError"; + return error; } private reportStreamError(playerId: string, track: Track | null, error: unknown): void { diff --git a/docs/AUDIO_OUTPUT_BACKENDS.md b/docs/AUDIO_OUTPUT_BACKENDS.md index ba661de1..0e4bcc86 100644 --- a/docs/AUDIO_OUTPUT_BACKENDS.md +++ b/docs/AUDIO_OUTPUT_BACKENDS.md @@ -90,7 +90,9 @@ Slot state is cleared only if that same handle is still active, so a late stop c disposal requests share per-handle cleanup. In remote playback mode, stop awaits the remote stop RPC and does not also stop the local output backend. A remote `false` result means the remote endpoint did not stop; the local session and queue remain unchanged and no successful `playerStop` event is emitted. Concurrent remote STOP actions share the in-flight RPC and commit the resulting -state transition at most once. +state transition at most once. The shared remote RPC is not bound to an individual caller's `AbortSignal`: abort rejects only that +caller's wait, while other callers may continue waiting and the eventual remote result is still applied once. The same per-caller +cancellation rule applies to direct `PlaybackController.stop()` calls. Backend start is transactional: readiness and initial volume must succeed before activation is committed, and failed/unactivated handles are disposed; adapters should ensure a rejected `start()` does not leave an active output session behind. Related-track diff --git a/tests/audio_output_backend.test.js b/tests/audio_output_backend.test.js index dcdc7287..5d07f955 100644 --- a/tests/audio_output_backend.test.js +++ b/tests/audio_output_backend.test.js @@ -833,6 +833,27 @@ test("remote stop rejection propagates and does not stop the local backend", asy await harness.dispose(); }); +test("aborting one direct remote STOP caller does not cancel its coalesced peer", async () => { + const harness = createPlaybackHarness({ playerId: "remote-stop-caller-abort" }); + await harness.start(testTrack("remote-stop-caller-abort-track")); + harness.setMode(require("../core/dist").PlaybackMode.REMOTE); + const gate = deferred(); + harness.setRemoteStopGate(gate); + const firstAbort = new AbortController(); + const first = harness.playback.stop(harness.playerId, firstAbort.signal); + const second = harness.playback.stop(harness.playerId, new AbortController().signal); + await harness.remoteStopStarted; + + firstAbort.abort(); + await assert.rejects(first, { name: "AbortError" }); + assert.equal(harness.remoteStopCalls(), 1); + gate.resolve(true); + assert.equal(await second, true); + assert.equal(harness.remoteStopCalls(), 1); + assert.equal(harness.backend.stopCalls, 0); + await harness.dispose(); +}); + test("remote STOP false result preserves session, queue, and stop events", async () => { const harness = createPlaybackHarness({ playerId: "remote-stop-false" }); await harness.start(testTrack("remote-stop-false-track")); @@ -861,14 +882,26 @@ test("overlapping remote STOP requests share one RPC and commit once", async () harness.setMode(require("../core/dist").PlaybackMode.REMOTE); const gate = deferred(); harness.setRemoteStopGate(gate); - const context = { ...playbackContext(harness.playerId), sessionId: session.sessionId }; + const firstAbort = new AbortController(); + const firstContext = { + ...playbackContext(harness.playerId, firstAbort.signal), + sessionId: session.sessionId, + }; + const secondContext = { + ...playbackContext(harness.playerId, new AbortController().signal), + sessionId: session.sessionId, + }; - const first = harness.bus.action(harness.playerId, { type: "STOP" }, context); - const second = harness.bus.action(harness.playerId, { type: "STOP" }, context); + const first = harness.bus.action(harness.playerId, { type: "STOP" }, firstContext); + const second = harness.bus.action(harness.playerId, { type: "STOP" }, secondContext); await harness.remoteStopStarted; assert.equal(harness.remoteStopCalls(), 1); + firstAbort.abort(); + await assert.rejects(first, { name: "AbortError" }); + assert.equal(session.isActive(), true); + assert.equal(harness.queueClearCalls(), 0); gate.resolve(true); - await Promise.all([first, second]); + await second; assert.equal(harness.queueClearCalls(), 1); assert.equal(stopEvents, 1); assert.equal(session.status, "stopped"); From dbda1db393e395ff00ecb9a6ca37ab77d4859bf9 Mon Sep 17 00:00:00 2001 From: Ziji <104454302+zijipia@users.noreply.github.com> Date: Sat, 10 Oct 2026 12:43:01 +0900 Subject: [PATCH 09/55] fix: reconcile remote stop after session replacement Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- core/src/structures/PlaybackOrchestrator.ts | 9 +++---- docs/AUDIO_OUTPUT_BACKENDS.md | 8 +++--- tests/audio_output_backend.test.js | 27 +++++++++++++++++++++ 3 files changed, 36 insertions(+), 8 deletions(-) diff --git a/core/src/structures/PlaybackOrchestrator.ts b/core/src/structures/PlaybackOrchestrator.ts index 48277b71..defbf5ac 100644 --- a/core/src/structures/PlaybackOrchestrator.ts +++ b/core/src/structures/PlaybackOrchestrator.ts @@ -326,7 +326,7 @@ export class PlaybackOrchestrator { const session = this.sessionController.current(playerId); const mode = this.bus.querySync(playerId, PLAYER_QUERY.playbackMode); if (mode === PlaybackMode.REMOTE) { - await this.stopRemotePlayback(playerId, session, context.signal); + await this.stopRemotePlayback(playerId, context.signal); break; } if (session && !this.matchesContext(session, context)) break; @@ -340,18 +340,17 @@ export class PlaybackOrchestrator { } } - private async stopRemotePlayback(playerId: string, session: PlaybackSession | null, signal: AbortSignal): Promise { + private async stopRemotePlayback(playerId: string, signal: AbortSignal): Promise { if (signal.aborted) throw this.abortError(); const pending = this.remoteStopOperations.get(playerId); let operation = pending; if (!operation) { - const sessionId = session?.id ?? null; operation = this.bus.requestRpc(playerId, CONTROLLER_RPC.playbackRemoteStop, {}).then((stopped) => { if (!stopped) return; + if (this.bus.querySync(playerId, PLAYER_QUERY.playbackMode) !== PlaybackMode.REMOTE) return; const current = this.sessionController.current(playerId); - if ((current?.id ?? null) !== sessionId) return; this.bus.requestRpcSync(playerId, PLAYER_RPC.queueClear, undefined); - if (session?.isActive()) session.markStopped(); + if (current?.isActive()) current.markStopped(); this.publishState(playerId); this.bus.event(playerId, { type: BUS_EVENT.playerStop }); }); diff --git a/docs/AUDIO_OUTPUT_BACKENDS.md b/docs/AUDIO_OUTPUT_BACKENDS.md index 0e4bcc86..cad519e8 100644 --- a/docs/AUDIO_OUTPUT_BACKENDS.md +++ b/docs/AUDIO_OUTPUT_BACKENDS.md @@ -90,9 +90,11 @@ Slot state is cleared only if that same handle is still active, so a late stop c disposal requests share per-handle cleanup. In remote playback mode, stop awaits the remote stop RPC and does not also stop the local output backend. A remote `false` result means the remote endpoint did not stop; the local session and queue remain unchanged and no successful `playerStop` event is emitted. Concurrent remote STOP actions share the in-flight RPC and commit the resulting -state transition at most once. The shared remote RPC is not bound to an individual caller's `AbortSignal`: abort rejects only that -caller's wait, while other callers may continue waiting and the eventual remote result is still applied once. The same per-caller -cancellation rule applies to direct `PlaybackController.stop()` calls. +state transition at most once against the session current when the successful RPC completes. Thus, if a replacement session +appears while the RPC is pending and playback mode remains remote, that session is marked stopped to match the endpoint result. +The shared remote RPC is not bound to an individual caller's `AbortSignal`: abort rejects only that caller's wait, while other +callers may continue waiting and the eventual remote result is still applied once. The same per-caller cancellation rule applies +to direct `PlaybackController.stop()` calls. Backend start is transactional: readiness and initial volume must succeed before activation is committed, and failed/unactivated handles are disposed; adapters should ensure a rejected `start()` does not leave an active output session behind. Related-track diff --git a/tests/audio_output_backend.test.js b/tests/audio_output_backend.test.js index 5d07f955..9e3f5714 100644 --- a/tests/audio_output_backend.test.js +++ b/tests/audio_output_backend.test.js @@ -909,6 +909,33 @@ test("overlapping remote STOP requests share one RPC and commit once", async () await harness.dispose(); }); +test("successful remote STOP commits against the current session after a replacement race", async () => { + const harness = createPlaybackHarness({ playerId: "remote-stop-replaced-session" }); + await harness.start(testTrack("remote-stop-session-a")); + const sessionA = harness.sessions.current(harness.playerId); + const stopEvents = []; + harness.bus.subscribe(harness.playerId, "playerStop", (event) => stopEvents.push(event)); + harness.setMode(require("../core/dist").PlaybackMode.REMOTE); + const gate = deferred(); + harness.setRemoteStopGate(gate); + const context = { ...playbackContext(harness.playerId), sessionId: sessionA.sessionId }; + + const stop = harness.bus.action(harness.playerId, { type: "STOP" }, context); + await harness.remoteStopStarted; + const sessionB = harness.sessions.replace(harness.playerId, testTrack("remote-stop-session-b")); + sessionB.markPlaying(); + + gate.resolve(true); + await stop; + + assert.notEqual(sessionA.id, sessionB.id); + assert.equal(sessionB.status, "stopped"); + assert.equal(harness.queueClearCalls(), 1); + assert.equal(stopEvents.length, 1); + assert.equal(harness.backend.stopCalls, 0); + await harness.dispose(); +}); + test("remote STOP action awaits remote completion without entering local stop logic", async () => { const harness = createPlaybackHarness({ playerId: "remote-stop-action" }); const track = testTrack("remote-stop-action-track"); From f6e81680ef34c7a983ab014d6caa2f80ff555bbe Mon Sep 17 00:00:00 2001 From: Ziji <104454302+zijipia@users.noreply.github.com> Date: Sat, 10 Oct 2026 14:47:36 +0900 Subject: [PATCH 10/55] feat: implement WebSocket audio output backend with encoding and decoding support --- core/src/index.ts | 26 + .../src/output/WebSocketAudioOutputBackend.ts | 467 ++++++++++++++++++ docs/AUDIO_OUTPUT_BACKENDS.md | 51 ++ examples/backend/index.js | 0 tests/web_audio_output_backend.test.js | 89 ++++ 5 files changed, 633 insertions(+) create mode 100644 core/src/output/WebSocketAudioOutputBackend.ts create mode 100644 examples/backend/index.js create mode 100644 tests/web_audio_output_backend.test.js diff --git a/core/src/index.ts b/core/src/index.ts index cf7de732..e7f6a9f5 100644 --- a/core/src/index.ts +++ b/core/src/index.ts @@ -33,6 +33,25 @@ export { convertFloat32PcmToS16Le, resolveOutputStreamType, } from "./output/DiscordVoiceOutputBackend"; +export { + WebSocketAudioOutputBackend, + WebAudioOutputBackend, + WebSocketOutputBackend, + WebAudioOutputHandle, + WebSocketAudioOutputHandleImpl, + WEB_AUDIO_PROTOCOL_VERSION, + WEB_AUDIO_SAMPLE_RATE_HZ, + WEB_AUDIO_CHANNELS, + WEB_AUDIO_SAMPLE_BYTES, + WEB_AUDIO_MAX_MESSAGE_BYTES, + webAudioFormatFromPcm, + validateWebAudioOutputFormat, + encodeWebAudioControlMessage, + decodeWebAudioControlMessage, + encodeWebAudioFrame, + decodeWebAudioFrame, + defaultWebAudioSocketFactory, +} from "./output/WebSocketAudioOutputBackend"; export type { AudioFrameFormat, AudioOutputInput, @@ -45,6 +64,13 @@ export type { AudioOutputState, AudioOutputBackend, } from "./output/AudioOutputBackend"; +export type { + WebSocketLike, + WebSocketAudioControlMessage, + WebSocketAudioBackendContext, + WebSocketAudioOutputBackendOptions, + WebSocketAudioSessionResource, +} from "./output/WebSocketAudioOutputBackend"; export { AudioOutputUnsupportedOperationError } from "./output/AudioOutputBackend"; export { TrackLoader } from "./structures/TrackLoader"; export { PlaybackController } from "./controller/PlaybackController"; diff --git a/core/src/output/WebSocketAudioOutputBackend.ts b/core/src/output/WebSocketAudioOutputBackend.ts new file mode 100644 index 00000000..1d2d2ac1 --- /dev/null +++ b/core/src/output/WebSocketAudioOutputBackend.ts @@ -0,0 +1,467 @@ +import type { Readable } from "stream"; +import { AudioOutputUnsupportedOperationError, createAudioAbortError } from "./AudioOutputBackend"; +import type { + AudioFrameFormat, + AudioOutputBackend, + AudioOutputCapabilities, + AudioOutputContext, + AudioOutputEvent, + AudioOutputHandle, + AudioOutputInput, + AudioOutputState, +} from "./AudioOutputBackend"; + +export const WEB_AUDIO_PROTOCOL_VERSION = 1; +export const WEB_AUDIO_SAMPLE_RATE_HZ = 48_000; +export const WEB_AUDIO_CHANNELS = 2; +export const WEB_AUDIO_SAMPLE_BYTES = 2; +export const WEB_AUDIO_MAX_MESSAGE_BYTES = 1024 * 1024; + +export interface WebSocketLike { + readyState: number; + send(data: string | ArrayBuffer | Uint8Array): void; + close(code?: number, reason?: string): void; + addEventListener?(type: string, listener: (event: any) => void): void; + removeEventListener?(type: string, listener: (event: any) => void): void; +} + +export type WebSocketAudioControlMessage = + | { v: number; type: "ready"; sessionId: string; protocolVersion: number } + | { v: number; type: "audio:config"; sessionId: string; protocolVersion: number; sampleRateHz: number; channels: number; sampleFormat: "s16"; endianness: "little"; channelLayout: "interleaved"; } + | { v: number; type: "audio:frame"; sessionId: string; sequence: number; timestampMs: number } + | { v: number; type: "playback:pause"; sessionId: string } + | { v: number; type: "playback:resume"; sessionId: string } + | { v: number; type: "playback:stop"; sessionId: string } + | { v: number; type: "playback:state"; sessionId: string; state: AudioOutputState } + | { v: number; type: "error"; sessionId: string; code: string; message: string } + | { v: number; type: "pong"; sessionId?: string } + | { v: number; type: string; sessionId?: string; [key: string]: unknown }; + +export interface WebSocketAudioOutputBackendOptions { + protocolVersion?: number; + maxBufferedBytes?: number; + socketFactory?: (context: WebSocketAudioBackendContext) => WebSocketLike | Promise; + authorize?: (context: WebSocketAudioBackendContext) => boolean | Promise; +} + +export interface WebSocketAudioBackendContext { + playerId?: string; + sessionId?: string; + metadata?: unknown; + signal?: AbortSignal; +} + +export interface WebSocketAudioSessionResource { + readonly id: string; + readonly sessionId: string; + socket: WebSocketLike | null; + readonly protocolVersion: number; +} + +export function webAudioFormatFromPcm(options: { sampleRateHz?: number; channels?: number; sampleFormat?: "s16" | "f32"; }): AudioFrameFormat { + return { + kind: "pcm", + sampleFormat: options.sampleFormat ?? "s16", + endianness: "little", + sampleRateHz: options.sampleRateHz ?? WEB_AUDIO_SAMPLE_RATE_HZ, + channels: options.channels ?? WEB_AUDIO_CHANNELS, + channelLayout: "interleaved", + chunkAlignmentBytes: (options.channels ?? WEB_AUDIO_CHANNELS) * WEB_AUDIO_SAMPLE_BYTES, + }; +} + +export function validateWebAudioOutputFormat(format: AudioFrameFormat): void { + if (format.kind !== "pcm") { + throw new TypeError("WebSocket audio output backend only supports PCM input streams"); + } + if (format.sampleFormat !== "s16") { + throw new TypeError("WebSocket audio output backend only supports 16-bit little-endian PCM samples"); + } + if (format.endianness !== "little") { + throw new TypeError("WebSocket audio output backend requires little-endian PCM samples"); + } + if (format.sampleRateHz !== WEB_AUDIO_SAMPLE_RATE_HZ) { + throw new TypeError(`WebSocket audio output backend requires ${WEB_AUDIO_SAMPLE_RATE_HZ} Hz PCM output`); + } + if (format.channels !== WEB_AUDIO_CHANNELS) { + throw new TypeError(`WebSocket audio output backend requires ${WEB_AUDIO_CHANNELS} channels`); + } + if (format.channelLayout !== "interleaved") { + throw new TypeError("WebSocket audio output backend requires interleaved stereo PCM"); + } +} + +export function encodeWebAudioControlMessage(message: Record): string { + const payload = { v: WEB_AUDIO_PROTOCOL_VERSION, ...message }; + return JSON.stringify(payload); +} + +export function decodeWebAudioControlMessage(payload: string): Record { + const parsed = JSON.parse(payload) as Record; + if (typeof parsed.v !== "number" || parsed.v !== WEB_AUDIO_PROTOCOL_VERSION) { + throw new Error(`Unsupported Web audio protocol version: ${String(parsed.v ?? "unknown")}`); + } + return parsed; +} + +export function encodeWebAudioFrame(payload: Uint8Array, sequence: number, timestampMs: number): Uint8Array { + if (payload.length > WEB_AUDIO_MAX_MESSAGE_BYTES) { + throw new Error(`Audio frame payload exceeds ${WEB_AUDIO_MAX_MESSAGE_BYTES} bytes`); + } + const header = Buffer.allocUnsafe(16); + header.writeUInt32LE(sequence >>> 0, 0); + header.writeUInt32LE(timestampMs >>> 0, 4); + header.writeUInt16LE(WEB_AUDIO_SAMPLE_RATE_HZ, 8); + header.writeUInt16LE(WEB_AUDIO_CHANNELS, 10); + header.writeUInt16LE(WEB_AUDIO_SAMPLE_BYTES, 12); + header.writeUInt16LE(0, 14); + const output = Buffer.alloc(header.length + payload.length); + output.set(header, 0); + output.set(Buffer.from(payload), header.length); + return new Uint8Array(output.buffer, output.byteOffset, output.byteLength); +} + +export function decodeWebAudioFrame(frame: Uint8Array): { sequence: number; timestampMs: number; payload: Uint8Array } { + if (frame.length < 16) throw new Error("Malformed Web audio frame: missing protocol header"); + const view = Buffer.from(frame); + const sequence = view.readUInt32LE(0); + const timestampMs = view.readUInt32LE(4); + const payload = view.subarray(16); + return { sequence, timestampMs, payload: new Uint8Array(payload) }; +} + +export function defaultWebAudioSocketFactory(_context: WebSocketAudioBackendContext): WebSocketLike { + throw new Error("WebSocketAudioOutputBackend requires a socketFactory or a connected WebSocket to be provided"); +} + +function assertNotAborted(...signals: Array): void { + for (const signal of signals) { + if (signal?.aborted) throw createAudioAbortError(); + } +} + +class WebSocketAudioOutputHandle implements AudioOutputHandle { + private stateValue: AudioOutputState = "ready"; + private disposed = false; + private readonly listeners = new Set<(event: AudioOutputEvent) => void>(); + private readonly cleanupFns = new Set<() => void>(); + private readonly signal?: AbortSignal; + private readonly socketSignal?: AbortSignal; + private socket: WebSocketLike | null = null; + private queuedBytes = 0; + private sequence = 0; + private sendingPromise: Promise | null = null; + private readonly backend: WebSocketAudioOutputBackend; + public readonly resource: WebSocketAudioSessionResource; + public readonly format: AudioFrameFormat; + public readonly ready: Promise; + public readonly input: AudioOutputInput; + public readonly ownership: "transfer" | "borrow"; + + public constructor( + backend: WebSocketAudioOutputBackend, + input: AudioOutputInput, + resource: WebSocketAudioSessionResource, + context: AudioOutputContext = {}, + ) { + this.backend = backend; + this.input = input; + this.resource = resource; + this.format = input.format; + this.ownership = input.ownership; + this.signal = context.signal; + this.socketSignal = context.signal; + this.ready = Promise.resolve(); + if (this.signal) { + const abort = () => { + if (!this.disposed) void this.dispose(); + }; + this.signal.addEventListener("abort", abort, { once: true }); + this.cleanupFns.add(() => this.signal?.removeEventListener("abort", abort)); + } + } + + public get state(): AudioOutputState { + return this.stateValue; + } + + public get bufferedBytes(): number | null { + return this.queuedBytes; + } + + public emit(event: AudioOutputEvent): void { + for (const listener of this.listeners) listener(event); + } + + public async start(signal?: AbortSignal): Promise { + assertNotAborted(this.signal, signal); + if (this.disposed) throw new Error("WebSocket audio session is disposed"); + if (this.format.kind !== "pcm") throw new TypeError("WebSocket audio output backend only supports PCM streams"); + this.stateValue = "buffering"; + this.emit({ type: "state", state: "buffering" }); + this.socket = await this.backend.resolveSocket(this, signal); + if (!this.socket) throw new Error("WebSocket audio output requires a transport socket"); + this.socket.send( + encodeWebAudioControlMessage({ + type: "audio:config", + sessionId: this.resource.sessionId, + protocolVersion: this.resource.protocolVersion, + sampleRateHz: this.format.sampleRateHz, + channels: this.format.channels, + sampleFormat: this.format.sampleFormat, + endianness: this.format.endianness, + channelLayout: this.format.channelLayout, + }), + ); + this.stateValue = "playing"; + this.emit({ type: "state", state: "playing" }); + this.sendingPromise = this.consumeInput(signal); + await this.sendingPromise; + } + + public pause(signal?: AbortSignal): boolean { + assertNotAborted(this.signal, signal); + if (this.stateValue !== "playing") return false; + this.stateValue = "paused"; + this.emit({ type: "state", state: "paused" }); + this.socket?.send( + encodeWebAudioControlMessage({ + type: "playback:pause", + sessionId: this.resource.sessionId, + }), + ); + return true; + } + + public resume(signal?: AbortSignal): boolean { + assertNotAborted(this.signal, signal); + if (this.stateValue !== "paused") return false; + this.stateValue = "playing"; + this.emit({ type: "state", state: "playing" }); + this.socket?.send( + encodeWebAudioControlMessage({ + type: "playback:resume", + sessionId: this.resource.sessionId, + }), + ); + return true; + } + + public stop(signal?: AbortSignal): boolean { + assertNotAborted(this.signal, signal); + if (this.disposed) return false; + this.stateValue = "stopped"; + this.emit({ type: "state", state: "stopped" }); + this.socket?.send( + encodeWebAudioControlMessage({ + type: "playback:stop", + sessionId: this.resource.sessionId, + }), + ); + this.destroyTransferredInput(); + return true; + } + + public seek(_positionMs: number, signal?: AbortSignal): boolean { + assertNotAborted(this.signal, signal); + throw new AudioOutputUnsupportedOperationError("seek"); + } + + public async replace(input: AudioOutputInput, signal?: AbortSignal): Promise> { + assertNotAborted(this.signal, signal); + const replacement = this.backend.createSession(input, { signal, metadata: { sessionId: this.resource.sessionId } }); + await replacement.start(signal); + await this.dispose(); + return replacement; + } + + public setVolume(value: number, signal?: AbortSignal): void { + assertNotAborted(this.signal, signal); + if (this.backend.capabilities.volume !== "backend") { + throw new AudioOutputUnsupportedOperationError("volume control"); + } + this.socket?.send( + encodeWebAudioControlMessage({ + type: "playback:state", + sessionId: this.resource.sessionId, + state: this.stateValue, + volume: value, + }), + ); + } + + public onEvent(listener: (event: AudioOutputEvent) => void): () => void { + if (this.disposed) return () => undefined; + this.listeners.add(listener); + return () => this.listeners.delete(listener); + } + + public async dispose(): Promise { + if (this.disposed) return; + this.disposed = true; + for (const cleanup of [...this.cleanupFns]) cleanup(); + this.discoveryStop(); + this.destroyTransferredInput(); + if (this.socket && typeof this.socket.close === "function") { + try { + this.socket.close(); + } catch { + // no-op: socket teardown is best-effort when the transport is already closing + } + } + this.socket = null; + this.resource.socket = null; + this.listeners.clear(); + } + + public get disposedState(): boolean { + return this.disposed; + } + + private destroyTransferredInput(): void { + if (this.input.ownership === "transfer" && !this.input.stream.destroyed) { + this.input.stream.destroy(); + } + } + + private discoveryStop(): void { + if (this.stateValue !== "stopped" && this.stateValue !== "ended" && this.stateValue !== "failed") { + this.stateValue = "stopped"; + this.emit({ type: "state", state: "stopped" }); + } + } + + private async consumeInput(signal?: AbortSignal): Promise { + const frameBytes = this.calculateFrameBytes(); + this.resource.socket = this.socket; + let remainder: Buffer = Buffer.alloc(0); + try { + for await (const chunk of this.input.stream) { + assertNotAborted(this.signal, signal); + const nextChunk: Buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk as Uint8Array); + const combined: Buffer = remainder.length > 0 ? Buffer.concat([remainder, nextChunk]) : nextChunk; + const completeFrames = Math.floor(combined.length / frameBytes) * frameBytes; + for (let offset = 0; offset < completeFrames; offset += frameBytes) { + const framePayload: Buffer = combined.subarray(offset, offset + frameBytes); + if (this.socket == null) return; + if (this.backend.capabilities.maxBufferedBytes != null) { + this.queuedBytes += framePayload.length; + if (this.queuedBytes > this.backend.capabilities.maxBufferedBytes) { + this.stateValue = "buffering"; + this.emit({ type: "state", state: "buffering" }); + throw new Error(`WebSocket audio output exceeded max buffered bytes: ${this.backend.capabilities.maxBufferedBytes}`); + } + } + this.socket.send(encodeWebAudioFrame(framePayload, this.sequence++, Date.now())); + } + remainder = combined.subarray(completeFrames) as Buffer; + } + if (remainder.length !== 0) { + throw new Error("WebSocket audio stream ended with an incomplete audio frame"); + } + this.stateValue = "ended"; + this.emit({ type: "state", state: "ended" }); + } catch (error) { + if (this.disposed) return; + this.stateValue = "failed"; + this.emit({ type: "error", error: error instanceof Error ? error : new Error(String(error)) }); + this.destroyTransferredInput(); + throw error; + } finally { + this.resource.socket = null; + } + } + + private calculateFrameBytes(): number { + if (this.format.kind !== "pcm") throw new TypeError("WebSocket backend requires PCM stream input"); + return this.format.channels * (this.format.sampleFormat === "s16" ? 2 : 4); + } +} + +export class WebSocketAudioOutputBackend implements AudioOutputBackend { + public readonly capabilities: AudioOutputCapabilities = { + pause: true, + resume: true, + stop: true, + seek: "unsupported", + replacement: "atomic", + ownership: "transfer", + volume: "upstream", + backpressure: "bounded", + maxBufferedBytes: 256 * 1024, + }; + public readonly ready: Promise; + private readonly protocolVersion: number; + private readonly maxBufferedBytes: number; + private readonly socketFactory: (context: WebSocketAudioBackendContext) => WebSocketLike | Promise; + private readonly authorize?: (context: WebSocketAudioBackendContext) => boolean | Promise; + private disposed = false; + private readonly sessions = new Set(); + private readonly abortController = new AbortController(); + + public constructor(options: WebSocketAudioOutputBackendOptions = {}) { + this.protocolVersion = options.protocolVersion ?? WEB_AUDIO_PROTOCOL_VERSION; + this.maxBufferedBytes = options.maxBufferedBytes ?? 256 * 1024; + this.capabilities.maxBufferedBytes = this.maxBufferedBytes; + this.socketFactory = options.socketFactory ?? defaultWebAudioSocketFactory; + this.authorize = options.authorize; + this.ready = Promise.resolve(); + } + + public async initialize(_signal?: AbortSignal): Promise { + if (this.disposed) throw new Error("WebSocket audio backend is disposed"); + this.abortController.signal.throwIfAborted?.(); + } + + public createSession(input: AudioOutputInput, context: AudioOutputContext = {}): AudioOutputHandle { + if (this.disposed) throw new Error("WebSocket audio backend is disposed"); + validateWebAudioOutputFormat(input.format); + if (input.ownership !== "transfer" && input.ownership !== "borrow") { + throw new TypeError(`Unsupported WebSocket audio ownership mode: ${String(input.ownership)}`); + } + const metadata = context.metadata as Record | undefined; + const sessionId = metadata && typeof metadata === "object" && "sessionId" in metadata ? String((metadata as any).sessionId) : undefined; + const resource: WebSocketAudioSessionResource = { + id: `web-audio-${Math.random().toString(16).slice(2)}`, + sessionId: sessionId ?? `session-${Math.random().toString(16).slice(2)}`, + socket: null, + protocolVersion: this.protocolVersion, + }; + const handle = new WebSocketAudioOutputHandle(this, input, resource, context); + this.sessions.add(handle); + return handle; + } + + public async dispose(): Promise { + if (this.disposed) return; + this.disposed = true; + this.abortController.abort(); + for (const session of [...this.sessions]) { + await session.dispose(); + } + this.sessions.clear(); + } + + public async resolveSocket(handle: WebSocketAudioOutputHandle, signal?: AbortSignal): Promise { + if (this.disposed) throw new Error("WebSocket audio backend is disposed"); + if (signal?.aborted) throw createAudioAbortError(); + const context: WebSocketAudioBackendContext = { + playerId: undefined, + sessionId: handle.resource.sessionId, + metadata: { handle }, + signal, + }; + const authorized = this.authorize ? await this.authorize(context) : true; + if (!authorized) throw new Error("WebSocket audio session is not authorized"); + const socket = await this.socketFactory(context); + if (!socket || typeof socket.send !== "function") { + throw new TypeError("WebSocket audio output transport did not provide a valid WebSocket-like object"); + } + return socket; + } +} + +export const WebAudioOutputBackend = WebSocketAudioOutputBackend; +export const WebSocketOutputBackend = WebSocketAudioOutputBackend; +export class WebAudioOutputHandle extends WebSocketAudioOutputHandle {} +export class WebSocketAudioOutputHandleImpl extends WebSocketAudioOutputHandle {} diff --git a/docs/AUDIO_OUTPUT_BACKENDS.md b/docs/AUDIO_OUTPUT_BACKENDS.md index cad519e8..5a898719 100644 --- a/docs/AUDIO_OUTPUT_BACKENDS.md +++ b/docs/AUDIO_OUTPUT_BACKENDS.md @@ -96,6 +96,57 @@ The shared remote RPC is not bound to an individual caller's `AbortSignal`: abor callers may continue waiting and the eventual remote result is still applied once. The same per-caller cancellation rule applies to direct `PlaybackController.stop()` calls. +### Remote STOP examples + +**Session replacement while STOP is pending:** the STOP result describes the remote endpoint, not only the session that existed +when the request began. If session A is replaced by session B before the remote endpoint confirms the stop, a successful result +stops the session that is current when the result is applied (provided playback is still in remote mode). + +```text +time action current session result +t0 remote playback starts A / playing +t1 STOP RPC starts A / playing +t2 a new track replaces A B / playing +t3 STOP RPC resolves true B / stopped + queue cleared; one playerStop event +``` + +For application code, listen for the stop event rather than assuming that the session observed before `stop()` is still current: + +```ts +player.on("playerStop", () => { + console.log("Remote playback has stopped"); +}); + +const stopRequest = player.stop(); +await player.play(nextTrack); // may replace the current session while the remote STOP is pending +await stopRequest; +``` + +The result cases are intentionally different: + +| Remote STOP result | Current session and queue | `playerStop` | +| --------------------------------------------------- | --------------------------------------------------- | ------------ | +| `true`, still in remote mode | Current session is marked stopped; queue is cleared | Emitted once | +| `false` | Left unchanged | Not emitted | +| Rejected RPC | Left unchanged; action reports the failure | Not emitted | +| `true`, playback left remote mode before completion | Left unchanged by the stale remote result | Not emitted | + +**Concurrent callers and cancellation:** overlapping STOP actions share one remote RPC and apply its outcome once, but each caller +waits with its own cancellation signal. Aborting one waiter rejects only that caller; it does not cancel the endpoint request or +another caller's wait. + +```ts +const firstAbort = new AbortController(); +const firstStop = stopRemoteWithSignal(firstAbort.signal); +const secondStop = stopRemoteWithSignal(new AbortController().signal); + +firstAbort.abort(); // firstStop rejects with AbortError +await secondStop; // still observes the shared remote result +``` + +`stopRemoteWithSignal` above is pseudocode for an internal caller; the public `Player.stop()` currently takes no signal. + Backend start is transactional: readiness and initial volume must succeed before activation is committed, and failed/unactivated handles are disposed; adapters should ensure a rejected `start()` does not leave an active output session behind. Related-track generation failure is reported as `streamError`, then the normal queue-end/autoplay fallback proceeds without treating the lookup diff --git a/examples/backend/index.js b/examples/backend/index.js new file mode 100644 index 00000000..e69de29b diff --git a/tests/web_audio_output_backend.test.js b/tests/web_audio_output_backend.test.js new file mode 100644 index 00000000..05695441 --- /dev/null +++ b/tests/web_audio_output_backend.test.js @@ -0,0 +1,89 @@ +const test = require("node:test"); +const assert = require("node:assert/strict"); +const { Readable } = require("node:stream"); +const { + WebSocketAudioOutputBackend, + encodeWebAudioFrame, + decodeWebAudioFrame, + WEB_AUDIO_PROTOCOL_VERSION, +} + = require("../core/dist"); + +const pcmFormat = { + kind: "pcm", + sampleFormat: "s16", + endianness: "little", + sampleRateHz: 48_000, + channels: 2, + channelLayout: "interleaved", +}; + +function makeSocket() { + return { + readyState: 1, + sent: [], + close() { + this.readyState = 3; + this.closed = true; + }, + send(data) { + this.sent.push(data); + }, + }; +} + +test("web protocol frame encoding preserves sequence metadata", () => { + const payload = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); + const encoded = encodeWebAudioFrame(payload, 12, 1234); + const decoded = decodeWebAudioFrame(new Uint8Array(encoded)); + assert.equal(decoded.sequence, 12); + assert.equal(decoded.timestampMs, 1234); + assert.equal(decoded.payload.length, payload.length); + assert.deepEqual([...decoded.payload], [...payload]); + assert.equal(decoded.payload.byteLength, payload.length); +}); + +test("web backend accepts valid PCM sessions and emits config plus payload frames", async () => { + const socket = makeSocket(); + const backend = new WebSocketAudioOutputBackend({ socketFactory: () => socket }); + const handle = backend.createSession({ + stream: Readable.from([Buffer.alloc(8)]), + format: pcmFormat, + ownership: "transfer", + }); + await handle.start(); + const config = socket.sent.find((value) => typeof value === "string"); + assert.ok(config !== undefined); + const parsed = JSON.parse(config); + assert.equal(parsed.v, WEB_AUDIO_PROTOCOL_VERSION); + assert.equal(parsed.type, "audio:config"); + assert.equal(parsed.sessionId, handle.resource.sessionId); + const binary = socket.sent.find((value) => typeof value !== "string"); + assert.ok(binary); + const frame = decodeWebAudioFrame(new Uint8Array(binary)); + assert.equal(frame.payload.length, 4); + assert.equal(frame.sequence, 0); + await handle.dispose(); + assert.equal(socket.closed, true); + await backend.dispose(); +}); + +test("web backend rejects unsupported PCM formats and invalid ownership modes", () => { + const backend = new WebSocketAudioOutputBackend({ socketFactory: () => makeSocket() }); + assert.throws(() => + backend.createSession({ + stream: Readable.from([]), + format: { kind: "encoded", codec: "opus" }, + ownership: "transfer", + }), + /PCM/i, + ); + assert.throws(() => + backend.createSession({ + stream: Readable.from([]), + format: pcmFormat, + ownership: "invalid", + }), + /ownership/i, + ); +}); From 03b12bce5c1d65adef76228e9f380299453e6971 Mon Sep 17 00:00:00 2001 From: Ziji <104454302+zijipia@users.noreply.github.com> Date: Sat, 10 Oct 2026 16:12:14 +0900 Subject: [PATCH 11/55] feat: enhance WebSocket audio output backend with improved session management and error handling --- .../src/output/WebSocketAudioOutputBackend.ts | 257 +++++++++++++++--- docs/AUDIO_OUTPUT_BACKENDS.md | 15 +- tests/web_audio_output_backend.test.js | 202 ++++++++++++-- 3 files changed, 412 insertions(+), 62 deletions(-) diff --git a/core/src/output/WebSocketAudioOutputBackend.ts b/core/src/output/WebSocketAudioOutputBackend.ts index 1d2d2ac1..12b0624a 100644 --- a/core/src/output/WebSocketAudioOutputBackend.ts +++ b/core/src/output/WebSocketAudioOutputBackend.ts @@ -19,6 +19,7 @@ export const WEB_AUDIO_MAX_MESSAGE_BYTES = 1024 * 1024; export interface WebSocketLike { readyState: number; + bufferedAmount: number; send(data: string | ArrayBuffer | Uint8Array): void; close(code?: number, reason?: string): void; addEventListener?(type: string, listener: (event: any) => void): void; @@ -27,7 +28,17 @@ export interface WebSocketLike { export type WebSocketAudioControlMessage = | { v: number; type: "ready"; sessionId: string; protocolVersion: number } - | { v: number; type: "audio:config"; sessionId: string; protocolVersion: number; sampleRateHz: number; channels: number; sampleFormat: "s16"; endianness: "little"; channelLayout: "interleaved"; } + | { + v: number; + type: "audio:config"; + sessionId: string; + protocolVersion: number; + sampleRateHz: number; + channels: number; + sampleFormat: "s16"; + endianness: "little"; + channelLayout: "interleaved"; + } | { v: number; type: "audio:frame"; sessionId: string; sequence: number; timestampMs: number } | { v: number; type: "playback:pause"; sessionId: string } | { v: number; type: "playback:resume"; sessionId: string } @@ -58,7 +69,11 @@ export interface WebSocketAudioSessionResource { readonly protocolVersion: number; } -export function webAudioFormatFromPcm(options: { sampleRateHz?: number; channels?: number; sampleFormat?: "s16" | "f32"; }): AudioFrameFormat { +export function webAudioFormatFromPcm(options: { + sampleRateHz?: number; + channels?: number; + sampleFormat?: "s16"; +}): AudioFrameFormat { return { kind: "pcm", sampleFormat: options.sampleFormat ?? "s16", @@ -146,11 +161,15 @@ class WebSocketAudioOutputHandle implements AudioOutputHandle void>(); private readonly cleanupFns = new Set<() => void>(); private readonly signal?: AbortSignal; - private readonly socketSignal?: AbortSignal; private socket: WebSocketLike | null = null; - private queuedBytes = 0; private sequence = 0; private sendingPromise: Promise | null = null; + private started = false; + private stopped = false; + private transportClosed = false; + private pendingReadCancel: (() => void) | null = null; + private pendingReadRetry: (() => void) | null = null; + private readonly activityWaiters = new Set<(active: boolean) => void>(); private readonly backend: WebSocketAudioOutputBackend; public readonly resource: WebSocketAudioSessionResource; public readonly format: AudioFrameFormat; @@ -170,7 +189,6 @@ class WebSocketAudioOutputHandle implements AudioOutputHandle { @@ -186,7 +204,7 @@ class WebSocketAudioOutputHandle implements AudioOutputHandle { assertNotAborted(this.signal, signal); - if (this.disposed) throw new Error("WebSocket audio session is disposed"); + if (this.disposed || this.stopped) throw new Error("WebSocket audio session is stopped or disposed"); + if (this.started) throw new Error("WebSocket audio session has already started"); if (this.format.kind !== "pcm") throw new TypeError("WebSocket audio output backend only supports PCM streams"); + this.started = true; this.stateValue = "buffering"; this.emit({ type: "state", state: "buffering" }); - this.socket = await this.backend.resolveSocket(this, signal); - if (!this.socket) throw new Error("WebSocket audio output requires a transport socket"); - this.socket.send( - encodeWebAudioControlMessage({ - type: "audio:config", - sessionId: this.resource.sessionId, - protocolVersion: this.resource.protocolVersion, - sampleRateHz: this.format.sampleRateHz, - channels: this.format.channels, - sampleFormat: this.format.sampleFormat, - endianness: this.format.endianness, - channelLayout: this.format.channelLayout, - }), - ); + try { + const socket = await this.backend.resolveSocket(this, signal); + if (this.disposed || this.stopped || this.signal?.aborted || signal?.aborted) { + socket.close(); + assertNotAborted(this.signal, signal); + throw new Error("WebSocket audio session was stopped while connecting"); + } + this.socket = socket; + this.listenForTransportClose(); + this.socket.send( + encodeWebAudioControlMessage({ + type: "audio:config", + sessionId: this.resource.sessionId, + protocolVersion: this.resource.protocolVersion, + sampleRateHz: this.format.sampleRateHz, + channels: this.format.channels, + sampleFormat: this.format.sampleFormat, + endianness: this.format.endianness, + channelLayout: this.format.channelLayout, + }), + ); + } catch (error) { + if (!this.disposed && !this.stopped) { + this.stateValue = "failed"; + this.emit({ type: "error", error: error instanceof Error ? error : new Error(String(error)) }); + await this.dispose(); + } + throw error; + } this.stateValue = "playing"; this.emit({ type: "state", state: "playing" }); this.sendingPromise = this.consumeInput(signal); @@ -238,6 +273,8 @@ class WebSocketAudioOutputHandle implements AudioOutputHandle { if (this.disposed) return; this.disposed = true; + this.stopped = true; for (const cleanup of [...this.cleanupFns]) cleanup(); this.discoveryStop(); + this.pendingReadCancel?.(); + this.wakeActivityWaiters(false); this.destroyTransferredInput(); if (this.socket && typeof this.socket.close === "function") { try { @@ -336,33 +379,33 @@ class WebSocketAudioOutputHandle implements AudioOutputHandle 0 ? Buffer.concat([remainder, nextChunk]) : nextChunk; const completeFrames = Math.floor(combined.length / frameBytes) * frameBytes; for (let offset = 0; offset < completeFrames; offset += frameBytes) { const framePayload: Buffer = combined.subarray(offset, offset + frameBytes); - if (this.socket == null) return; - if (this.backend.capabilities.maxBufferedBytes != null) { - this.queuedBytes += framePayload.length; - if (this.queuedBytes > this.backend.capabilities.maxBufferedBytes) { - this.stateValue = "buffering"; - this.emit({ type: "state", state: "buffering" }); - throw new Error(`WebSocket audio output exceeded max buffered bytes: ${this.backend.capabilities.maxBufferedBytes}`); - } - } - this.socket.send(encodeWebAudioFrame(framePayload, this.sequence++, Date.now())); + if (!(await this.sendFrame(framePayload, signal))) return; } remainder = combined.subarray(completeFrames) as Buffer; } if (remainder.length !== 0) { - throw new Error("WebSocket audio stream ended with an incomplete audio frame"); + const sampleBytes = this.calculateSampleFrameBytes(); + if (remainder.length % sampleBytes !== 0) { + throw new Error("WebSocket audio stream ended with an incomplete PCM sample frame"); + } + if (!(await this.sendFrame(remainder, signal))) return; } + if (this.stopped || this.disposed || this.transportClosed) return; this.stateValue = "ended"; this.emit({ type: "state", state: "ended" }); } catch (error) { - if (this.disposed) return; + if (this.disposed || this.stopped || this.transportClosed) return; this.stateValue = "failed"; this.emit({ type: "error", error: error instanceof Error ? error : new Error(String(error)) }); this.destroyTransferredInput(); @@ -374,7 +417,125 @@ class WebSocketAudioOutputHandle implements AudioOutputHandle maxSamples) { + throw new TypeError(`PCM frame size must be between 1 and ${maxSamples} samples per channel`); + } + return sampleFrameBytes * samplesPerFrame; + } + + private calculateSampleFrameBytes(): number { + if (this.format.kind !== "pcm" || this.format.sampleFormat !== "s16") { + throw new TypeError("WebSocket backend requires interleaved s16 PCM input"); + } + return this.format.channels * WEB_AUDIO_SAMPLE_BYTES; + } + + private async sendFrame(payload: Uint8Array, signal?: AbortSignal): Promise { + const socket = this.socket; + if (!socket || this.stopped || this.disposed || this.transportClosed) return false; + const messageBytes = payload.byteLength + 16; + const maxBufferedBytes = this.backend.capabilities.maxBufferedBytes; + if (maxBufferedBytes !== null && messageBytes > maxBufferedBytes) { + throw new Error(`Audio frame exceeds max buffered bytes: ${maxBufferedBytes}`); + } + while (true) { + assertNotAborted(this.signal, signal); + if (!(await this.waitUntilActive())) return false; + if (socket.readyState !== 1) { + this.transportClosed = true; + return false; + } + if (maxBufferedBytes === null || socket.bufferedAmount + messageBytes <= maxBufferedBytes) break; + await new Promise((resolve) => setTimeout(resolve, 10)); + } + if (this.stopped || this.disposed || this.transportClosed) return false; + socket.send(encodeWebAudioFrame(payload, this.sequence++, Date.now())); + return true; + } + + private waitUntilActive(): Promise { + if (this.stopped || this.disposed || this.transportClosed) return Promise.resolve(false); + if (this.stateValue !== "paused") return Promise.resolve(true); + return new Promise((resolve) => this.activityWaiters.add(resolve)); + } + + private wakeActivityWaiters(active: boolean): void { + for (const resolve of this.activityWaiters) resolve(active); + this.activityWaiters.clear(); + } + + private readNextChunk(): Promise { + const stream = this.input.stream; + const read = (): Buffer | null | undefined => { + const chunk = stream.read() as Buffer | Uint8Array | string | null; + if (chunk !== null) return Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk); + if (stream.readableEnded || stream.destroyed || this.stopped || this.disposed) return null; + return undefined; + }; + const initial = read(); + if (initial !== undefined) return Promise.resolve(initial); + return new Promise((resolve, reject) => { + let settled = false; + const cleanup = () => { + stream.removeListener("readable", onReadable); + stream.removeListener("end", onEnd); + stream.removeListener("close", onClose); + stream.removeListener("error", onError); + this.pendingReadCancel = null; + this.pendingReadRetry = null; + }; + const finish = (chunk: Buffer | null) => { + if (settled) return; + settled = true; + cleanup(); + resolve(chunk); + }; + const onReadable = () => { + if (this.stateValue === "paused") return; + const chunk = read(); + if (chunk !== undefined) finish(chunk); + }; + const onEnd = () => finish(null); + const onClose = () => finish(null); + const onError = (error: Error) => { + if (settled) return; + settled = true; + cleanup(); + reject(error); + }; + this.pendingReadCancel = () => finish(null); + this.pendingReadRetry = onReadable; + stream.on("readable", onReadable); + stream.once("end", onEnd); + stream.once("close", onClose); + stream.once("error", onError); + onReadable(); + }); + } + + private listenForTransportClose(): void { + if (!this.socket?.addEventListener) return; + const socket = this.socket; + const onClose = () => { + this.transportClosed = true; + if (!this.stopped && !this.disposed) { + this.stateValue = "failed"; + this.emit({ type: "error", error: new Error("WebSocket audio transport closed") }); + } + this.destroyTransferredInput(); + this.pendingReadCancel?.(); + this.wakeActivityWaiters(false); + }; + socket.addEventListener?.("close", onClose); + this.cleanupFns.add(() => socket.removeEventListener?.("close", onClose)); } } @@ -385,7 +546,7 @@ export class WebSocketAudioOutputBackend implements AudioOutputBackend { @@ -413,14 +577,18 @@ export class WebSocketAudioOutputBackend implements AudioOutputBackend { + public createSession( + input: AudioOutputInput, + context: AudioOutputContext = {}, + ): AudioOutputHandle { if (this.disposed) throw new Error("WebSocket audio backend is disposed"); validateWebAudioOutputFormat(input.format); if (input.ownership !== "transfer" && input.ownership !== "borrow") { throw new TypeError(`Unsupported WebSocket audio ownership mode: ${String(input.ownership)}`); } const metadata = context.metadata as Record | undefined; - const sessionId = metadata && typeof metadata === "object" && "sessionId" in metadata ? String((metadata as any).sessionId) : undefined; + const sessionId = + metadata && typeof metadata === "object" && "sessionId" in metadata ? String((metadata as any).sessionId) : undefined; const resource: WebSocketAudioSessionResource = { id: `web-audio-${Math.random().toString(16).slice(2)}`, sessionId: sessionId ?? `session-${Math.random().toString(16).slice(2)}`, @@ -454,7 +622,14 @@ export class WebSocketAudioOutputBackend implements AudioOutputBackend socket.sent.filter((value) => typeof value !== "string"); +const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); + test("web protocol frame encoding preserves sequence metadata", () => { const payload = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); const encoded = encodeWebAudioFrame(payload, 12, 1234); @@ -61,7 +74,7 @@ test("web backend accepts valid PCM sessions and emits config plus payload frame const binary = socket.sent.find((value) => typeof value !== "string"); assert.ok(binary); const frame = decodeWebAudioFrame(new Uint8Array(binary)); - assert.equal(frame.payload.length, 4); + assert.equal(frame.payload.length, 8); assert.equal(frame.sequence, 0); await handle.dispose(); assert.equal(socket.closed, true); @@ -70,20 +83,175 @@ test("web backend accepts valid PCM sessions and emits config plus payload frame test("web backend rejects unsupported PCM formats and invalid ownership modes", () => { const backend = new WebSocketAudioOutputBackend({ socketFactory: () => makeSocket() }); - assert.throws(() => - backend.createSession({ - stream: Readable.from([]), - format: { kind: "encoded", codec: "opus" }, - ownership: "transfer", - }), - /PCM/i, + assert.throws( + () => + backend.createSession({ + stream: Readable.from([]), + format: { kind: "encoded", codec: "opus" }, + ownership: "transfer", + }), + /PCM/i, ); - assert.throws(() => - backend.createSession({ - stream: Readable.from([]), - format: pcmFormat, - ownership: "invalid", - }), - /ownership/i, + assert.throws( + () => + backend.createSession({ + stream: Readable.from([]), + format: pcmFormat, + ownership: "invalid", + }), + /ownership/i, + ); +}); + +test("web backend streams beyond its transport buffer limit without a cumulative counter failure", async () => { + const socket = makeSocket(); + const backend = new WebSocketAudioOutputBackend({ socketFactory: () => socket }); + const handle = backend.createSession({ + stream: Readable.from([Buffer.alloc(300 * 1024)]), + format: pcmFormat, + ownership: "transfer", + }); + await handle.start(); + assert.equal(handle.state, "ended"); + assert.ok(binaryMessages(socket).length > 1); + assert.equal(handle.bufferedBytes, 0); + await backend.dispose(); +}); + +test("web backend pauses reading and sending PCM until resumed", async () => { + const socket = makeSocket(); + const stream = new Readable({ read() {} }); + const backend = new WebSocketAudioOutputBackend({ socketFactory: () => socket }); + const handle = backend.createSession({ stream, format: pcmFormat, ownership: "borrow" }); + stream.push(Buffer.alloc(3840)); + const started = handle.start(); + await wait(20); + assert.equal(binaryMessages(socket).length, 1); + assert.equal(handle.pause(), true); + stream.push(Buffer.alloc(3840)); + await wait(20); + assert.equal(binaryMessages(socket).length, 1); + assert.equal(handle.resume(), true); + stream.push(null); + await started; + assert.equal(binaryMessages(socket).length, 2); + await backend.dispose(); +}); + +test("web backend stop cancels a borrowed stream without destroying it or sending later PCM", async () => { + const socket = makeSocket(); + const stream = new Readable({ read() {} }); + const backend = new WebSocketAudioOutputBackend({ socketFactory: () => socket }); + const handle = backend.createSession({ stream, format: pcmFormat, ownership: "borrow" }); + const started = handle.start(); + await wait(20); + assert.equal(handle.stop(), true); + stream.push(Buffer.alloc(3840)); + await started; + await wait(10); + assert.equal(stream.destroyed, false); + assert.equal(binaryMessages(socket).length, 0); + await backend.dispose(); +}); + +test("web backend waits for WebSocket bufferedAmount to fall before sending", async () => { + const socket = makeSocket(); + socket.bufferedAmount = 4096; + const backend = new WebSocketAudioOutputBackend({ + socketFactory: () => socket, + maxBufferedBytes: 4096, + }); + const handle = backend.createSession({ + stream: Readable.from([Buffer.alloc(3840)]), + format: pcmFormat, + ownership: "transfer", + }); + let completed = false; + const started = handle.start().then(() => { + completed = true; + }); + await wait(30); + assert.equal(binaryMessages(socket).length, 0); + assert.equal(completed, false); + socket.bufferedAmount = 0; + await started; + assert.equal(binaryMessages(socket).length, 1); + await backend.dispose(); +}); + +test("web backend rejects float PCM formats", () => { + const backend = new WebSocketAudioOutputBackend({ socketFactory: () => makeSocket() }); + assert.throws( + () => + backend.createSession({ + stream: Readable.from([]), + format: { ...pcmFormat, sampleFormat: "f32" }, + ownership: "transfer", + }), + /16-bit/i, ); }); + +test("web backend abort destroys transferred input and closes the socket", async () => { + const socket = makeSocket(); + const stream = new Readable({ read() {} }); + const controller = new AbortController(); + const backend = new WebSocketAudioOutputBackend({ socketFactory: () => socket }); + const handle = backend.createSession({ stream, format: pcmFormat, ownership: "transfer" }, { signal: controller.signal }); + const started = handle.start(); + await wait(20); + controller.abort(); + await started; + assert.equal(stream.destroyed, true); + assert.equal(socket.closed, true); + await backend.dispose(); +}); + +test("web backend closes a socket that resolves after startup was aborted", async () => { + const socket = makeSocket(); + const stream = new Readable({ read() {} }); + const controller = new AbortController(); + let resolveSocket; + const backend = new WebSocketAudioOutputBackend({ + socketFactory: () => new Promise((resolve) => (resolveSocket = resolve)), + }); + const handle = backend.createSession({ stream, format: pcmFormat, ownership: "transfer" }, { signal: controller.signal }); + const started = handle.start(); + await wait(10); + controller.abort(); + resolveSocket(socket); + await assert.rejects(started, { name: "AbortError" }); + assert.equal(socket.closed, true); + assert.equal(stream.destroyed, true); + await backend.dispose(); +}); + +test("web backend cleans up transferred input when initial configuration send fails", async () => { + const socket = makeSocket(); + socket.send = () => { + throw new Error("socket send failed"); + }; + const stream = new Readable({ read() {} }); + const backend = new WebSocketAudioOutputBackend({ socketFactory: () => socket }); + const handle = backend.createSession({ stream, format: pcmFormat, ownership: "transfer" }); + await assert.rejects(handle.start(), /socket send failed/); + assert.equal(stream.destroyed, true); + assert.equal(socket.closed, true); + assert.equal(handle.state, "failed"); + await backend.dispose(); +}); + +test("web backend stops consuming transferred input after WebSocket disconnect", async () => { + const socket = makeSocket(); + const stream = new Readable({ read() {} }); + const backend = new WebSocketAudioOutputBackend({ socketFactory: () => socket }); + const handle = backend.createSession({ stream, format: pcmFormat, ownership: "transfer" }); + const started = handle.start(); + await wait(20); + socket.close(); + await started; + assert.equal(stream.destroyed, true); + assert.equal(handle.state, "failed"); + assert.equal(binaryMessages(socket).length, 0); + await backend.dispose(); +}); From 26b3638115a3f0a8de551959858adbb81b5cb0d7 Mon Sep 17 00:00:00 2001 From: Ziji <104454302+zijipia@users.noreply.github.com> Date: Sat, 10 Oct 2026 23:03:56 +0900 Subject: [PATCH 12/55] feat: add Web Audio client and backend example for ZiPlayer - Created a new client package for handling WebSocket PCM streams with AudioWorklet. - Implemented tests for audio configuration validation and PCM frame decoding. - Added a backend example with WebSocket support for audio streaming. - Included HTML and JavaScript files for a web client interface to connect to the audio stream. - Established a gateway for managing publisher and listener connections with authentication. - Implemented tests for the gateway to ensure proper handling of audio configuration and PCM frames. --- AGENTS.md | 32 ++ README.md | 21 + client/AGENTS.md | 24 + client/README.md | 84 ++++ client/browser/index.js | 397 ++++++++++++++++ client/index.d.ts | 81 ++++ client/package.json | 26 ++ client/test/protocol.test.js | 55 +++ core/AGENTS.md | 37 +- core/README.md | 43 ++ core/src/index.ts | 1 + .../src/output/WebSocketAudioOutputBackend.ts | 145 +++--- docs/AUDIO_OUTPUT_BACKENDS.md | 46 +- examples/backend/README.md | 77 ++++ examples/backend/client/client.js | 272 +++++++++++ examples/backend/client/index.html | 199 ++++++++ examples/backend/gateway.js | 424 ++++++++++++++++++ examples/backend/index.js | 173 +++++++ examples/backend/package.json | 15 + examples/backend/test/gateway.test.js | 114 +++++ tests/web_audio_output_backend.test.js | 180 +++++++- 21 files changed, 2355 insertions(+), 91 deletions(-) create mode 100644 AGENTS.md create mode 100644 client/AGENTS.md create mode 100644 client/README.md create mode 100644 client/browser/index.js create mode 100644 client/index.d.ts create mode 100644 client/package.json create mode 100644 client/test/protocol.test.js create mode 100644 examples/backend/README.md create mode 100644 examples/backend/client/client.js create mode 100644 examples/backend/client/index.html create mode 100644 examples/backend/gateway.js create mode 100644 examples/backend/package.json create mode 100644 examples/backend/test/gateway.test.js diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 00000000..bc93f36e --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,32 @@ +# ZiPlayer repository guide for coding agents + +Read the root [`README.md`](README.md) for public setup and player workflows. For core API use and internal architecture, read +[`core/AGENTS.md`](core/AGENTS.md). The core package's agent guide is included in the published `ziplayer` package. + +## Repository structure + +- `core/src/` contains the player facade, manager, controllers, stream handling, output backends, and public exports. Edit source + here; `core/dist/` is generated. +- `plugins/`, `extension/`, `infinity/`, and `adapters/` are separate integration packages. +- `client/` is the dependency-free browser PCM receiver package. Keep its browser entry free of Node.js APIs. +- `examples/backend/` is the runnable ZiPlayer + authenticated WebSocket gateway + browser playback example. +- `docs/` contains implementation/API references, including the audio output contract. +- `tests/` contains core regression tests; each package can also provide focused tests. + +## User-facing behavior + +- Normal applications should use `PlayerManager`, `Player`, plugins, and documented player options, not private Bus/controller + internals. +- Discord Voice remains the default output. Custom output is selected per player through `audioOutputBackendFactory`. +- WebSocket output requires 48 kHz stereo s16 LE PCM and an application-owned gateway. The browser client is a separate package; + it does not replace gateway authentication or routing. +- Keep public documentation and the package `AGENTS.md` guides aligned with changes to exported APIs and expected workflows. + +## Validation + +- `npm test` builds core and runs the root unit/regression tests. +- `npm test --prefix examples/backend` checks gateway handoff behavior. +- `npm test --prefix client` checks browser protocol validation and frame decoding. +- `npm run test:integration` runs plugin/extension integration tests when relevant. +- Use `npx prettier --check ` and `git diff --check` for changed source and documentation. +- Do not edit generated `core/dist/` files directly. diff --git a/README.md b/README.md index 6e92460b..afd97cc9 100644 --- a/README.md +++ b/README.md @@ -106,6 +106,27 @@ create → connect → play → stream → events → destroy --- +## 🌐 Browser playback and custom audio output + +ZiPlayer can send processed PCM to a custom output backend as well as the default Discord Voice output. A browser deployment needs +a server-side gateway to authenticate and route WebSocket connections; the browser should not connect directly to a source plugin +or receive provider credentials. + +The reusable browser receiver is [`@ziplayer/client`](client/README.md). It validates ZiPlayer's 48 kHz stereo s16 PCM protocol +and plays it through a bounded AudioWorklet buffer. The complete runnable example combines the client with a WebSocket gateway, +player-stable routing, and normal plugin-backed `PlayerManager` search/play: + +```powershell +npm run build:core +npm install --prefix examples/backend +$env:WEB_AUDIO_TOKEN = "use-a-local-development-token" +npm start --prefix examples/backend +``` + +Open and enter the token. The gateway example is intended for local development, not public deployment. +See [`docs/AUDIO_OUTPUT_BACKENDS.md`](docs/AUDIO_OUTPUT_BACKENDS.md) for the backend API and +[`examples/backend/README.md`](examples/backend/README.md) for setup, operations, and security notes. + ## 🎵 Core Usage ### Play music diff --git a/client/AGENTS.md b/client/AGENTS.md new file mode 100644 index 00000000..7d0e7b59 --- /dev/null +++ b/client/AGENTS.md @@ -0,0 +1,24 @@ +# `@ziplayer/client`: agent guide + +This package is the browser-only receiver for ZiPlayer's version 1 WebSocket audio protocol. Keep it dependency-free and safe to +serve as an ES module; do not import Node.js APIs into `browser/index.js`. + +## Protocol contract + +- The publisher configuration is JSON `audio:config`, protocol version 1, 48 kHz, stereo, interleaved s16 little-endian PCM. +- Binary frames begin with a 16-byte little-endian header: sequence (u32), timestamp milliseconds (u32), sample rate (u16), + channel count (u16), bytes per sample (u16), and reserved bytes (u16). Payload follows as PCM. +- Validate the config and each frame before handing any samples to the AudioWorklet. +- Convert s16 samples to normalized Float32; preserve the original PCM payload in the `pcm` event for recording/capture use. +- Keep the FIFO bounded and reset it when a new `audio:config` arrives. Do not treat network arrival rate as the audio sample + clock; the AudioWorklet consumes exactly one sample frame per output sample frame. + +## API and verification + +- Preserve the `WebAudioClient` lifecycle: connect from a user gesture, surface errors via the `error` event, and release the + WebSocket, AudioWorklet, and AudioContext on disconnect. +- Browser authentication uses the gateway's query-token convention. Explain that this is for browser transport limitations and + that deployments should use WSS and short-lived tokens. +- Keep the public declarations in `index.d.ts` synchronized with `browser/index.js`. +- Run `npm test --prefix client` for protocol validation tests and `npx prettier --check client` for format validation. +- For end-to-end changes, also run `npm test --prefix examples/backend` and the root ZiPlayer test suite. diff --git a/client/README.md b/client/README.md new file mode 100644 index 00000000..6d30c3da --- /dev/null +++ b/client/README.md @@ -0,0 +1,84 @@ +# `@ziplayer/client` + +Small browser client for ZiPlayer's WebSocket PCM protocol. It validates the publisher configuration and binary frame headers, +converts little-endian s16 stereo PCM to Float32, and plays it through an AudioWorklet with a bounded jitter buffer. + +The package is only the receiving/playback client. Your Node.js application still needs an authenticated WebSocket gateway and a +ZiPlayer `WebSocketAudioOutputBackend` publisher. The gateway example in +[`../examples/backend`](https://github.com/ZiProject/ZiPlayer/tree/main/examples/backend) shows a complete local setup with +search, publisher routing, and browser playback. + +## Install and use + +```sh +npm install @ziplayer/client +``` + +Import it from a browser bundle or serve `browser/index.js` as an ES module: + +```js +import { WebAudioClient } from "@ziplayer/client"; + +const client = new WebAudioClient(); +client.addEventListener("config", ({ detail }) => { + console.log(`Listening to player ${detail.sessionId}`); +}); +client.addEventListener("pcm", ({ detail }) => { + console.log(`Frame ${detail.sequence}, peak ${detail.peak.toFixed(3)}`); +}); +client.addEventListener("error", ({ detail }) => { + console.error("Audio client error:", detail.error); +}); + +// Call from a user gesture so the browser permits AudioContext playback. +await client.connect({ + gatewayUrl: "ws://127.0.0.1:8080", + token: tokenFromYourApplication, + sessionId: "my-player", +}); + +// Stop the browser listener and release its AudioContext. +await client.disconnect(); +``` + +For a UI that starts a new player session after the click, connect first with `nextPublisher: true`, then ask the server to start +playback: + +```js +await client.connect({ + gatewayUrl: "ws://127.0.0.1:8080", + token: tokenFromYourApplication, + nextPublisher: true, +}); +await fetch("/play", { method: "POST", body: JSON.stringify({ query }) }); +``` + +The browser fills in `client.sessionId` when the next publisher sends `audio:config`. If a publisher is already active and you +want to join that live stream, pass its `sessionId` instead. Call `disconnect()` to release browser resources. + +## Events + +`WebAudioClient` is an `EventTarget`: + +| Event | `event.detail` | +| ------------- | ------------------------------------------------------------------------------- | +| `connected` | `{ sessionId, nextPublisher }`, emitted when the WebSocket opens | +| `config` | Validated 48 kHz stereo s16 LE PCM publisher configuration | +| `pcm` | `{ sequence, timestampMs, samples, peak, payload, sequenceGap }` for each frame | +| `statechange` | `{ state, previousState }` | +| `sequencegap` | `{ expectedSequence, receivedSequence }` when a frame is lost | +| `control` | An unrecognized, versioned publisher control message | +| `error` | `{ error }` | +| `close` | `{ code, reason }` for a remote WebSocket close | + +`payload` is the original s16 PCM frame payload, excluding its 16-byte protocol header. `samples` is interleaved stereo Float32 +data normalized to `[-1, 1]`. The client transfers that Float32 buffer to its AudioWorklet after dispatching the event; copy the +samples inside the event callback if they must be retained. + +Options default to a 100 ms startup buffer, a two-second maximum AudioWorklet FIFO, and a five-second WebSocket connect timeout. +The AudioContext must support 48 kHz output. Browsers require HTTPS/WSS outside localhost. Because browser WebSocket clients +cannot set authorization headers, the gateway URL carries the listener token in a query parameter; use short-lived credentials. + +## TypeScript + +Declarations are included. The browser APIs require the TypeScript `DOM` library. diff --git a/client/browser/index.js b/client/browser/index.js new file mode 100644 index 00000000..f5682575 --- /dev/null +++ b/client/browser/index.js @@ -0,0 +1,397 @@ +export const WEB_AUDIO_PROTOCOL_VERSION = 1; +export const WEB_AUDIO_SAMPLE_RATE_HZ = 48_000; +export const WEB_AUDIO_CHANNELS = 2; +export const WEB_AUDIO_SAMPLE_BYTES = 2; +export const WEB_AUDIO_FRAME_HEADER_BYTES = 16; +export const WEB_AUDIO_MAX_MESSAGE_BYTES = 1024 * 1024; + +export function parseAudioConfig(message, expectedSessionId) { + const config = typeof message === "string" ? JSON.parse(message) : message; + if ( + !config || + config.v !== WEB_AUDIO_PROTOCOL_VERSION || + config.type !== "audio:config" || + typeof config.sessionId !== "string" || + !config.sessionId || + config.sessionId.length > 128 || + (expectedSessionId && config.sessionId !== expectedSessionId) || + config.protocolVersion !== WEB_AUDIO_PROTOCOL_VERSION || + config.sampleRateHz !== WEB_AUDIO_SAMPLE_RATE_HZ || + config.channels !== WEB_AUDIO_CHANNELS || + config.sampleFormat !== "s16" || + config.endianness !== "little" || + config.channelLayout !== "interleaved" + ) { + throw new Error("Publisher sent an unsupported or mismatched PCM configuration"); + } + return config; +} + +export function decodePcmFrame(data, config, expectedSequence = null) { + if ( + !(data instanceof ArrayBuffer) || + data.byteLength < WEB_AUDIO_FRAME_HEADER_BYTES || + data.byteLength > WEB_AUDIO_MAX_MESSAGE_BYTES + WEB_AUDIO_FRAME_HEADER_BYTES + ) { + throw new Error("Received a malformed PCM frame"); + } + const view = new DataView(data); + const sequence = view.getUint32(0, true); + const timestampMs = view.getUint32(4, true); + const sampleRateHz = view.getUint16(8, true); + const channels = view.getUint16(10, true); + const sampleBytes = view.getUint16(12, true); + const payloadBytes = data.byteLength - WEB_AUDIO_FRAME_HEADER_BYTES; + if ( + sampleRateHz !== config.sampleRateHz || + channels !== config.channels || + sampleBytes !== WEB_AUDIO_SAMPLE_BYTES || + payloadBytes === 0 || + payloadBytes % (channels * sampleBytes) !== 0 + ) { + throw new Error("Received an invalid PCM frame header or payload"); + } + const sampleCount = payloadBytes / sampleBytes; + const samples = new Float32Array(sampleCount); + let peak = 0; + for (let index = 0; index < sampleCount; index++) { + const value = view.getInt16(WEB_AUDIO_FRAME_HEADER_BYTES + index * sampleBytes, true); + const normalized = value < 0 ? value / 32768 : value / 32767; + samples[index] = normalized; + peak = Math.max(peak, Math.abs(normalized)); + } + return { + sequence, + timestampMs, + samples, + peak, + payload: new Uint8Array(data, WEB_AUDIO_FRAME_HEADER_BYTES, payloadBytes), + sequenceGap: expectedSequence !== null && sequence !== expectedSequence, + }; +} + +function createWorkletSource() { + return ` +class ZiPlayerPcmProcessor extends AudioWorkletProcessor { + constructor(options) { + super(); + this.capacityFrames = options.processorOptions.capacityFrames; + this.startupBufferFrames = options.processorOptions.startupBufferFrames; + this.left = new Float32Array(this.capacityFrames); + this.right = new Float32Array(this.capacityFrames); + this.readIndex = 0; + this.writeIndex = 0; + this.availableFrames = 0; + this.primed = false; + this.port.onmessage = ({ data }) => { + if (data.type === "flush") { + this.readIndex = 0; + this.writeIndex = 0; + this.availableFrames = 0; + this.primed = false; + return; + } + if (data.type !== "pcm" || !(data.samples instanceof Float32Array)) return; + this.enqueue(data.samples); + }; + } + + enqueue(samples) { + const incomingFrames = Math.floor(samples.length / 2); + const skipFrames = Math.max(0, incomingFrames - this.capacityFrames); + const framesToWrite = incomingFrames - skipFrames; + const overflow = Math.max(0, this.availableFrames + framesToWrite - this.capacityFrames); + this.readIndex = (this.readIndex + overflow) % this.capacityFrames; + this.availableFrames -= overflow; + for (let frame = 0; frame < framesToWrite; frame++) { + const sourceOffset = (frame + skipFrames) * 2; + this.left[this.writeIndex] = samples[sourceOffset]; + this.right[this.writeIndex] = samples[sourceOffset + 1]; + this.writeIndex = (this.writeIndex + 1) % this.capacityFrames; + } + this.availableFrames += framesToWrite; + } + + process(_inputs, outputs) { + const output = outputs[0]; + const left = output[0]; + const right = output[1]; + if (!this.primed && this.availableFrames >= this.startupBufferFrames) this.primed = true; + if (!this.primed) { + left.fill(0); + right?.fill(0); + return true; + } + for (let frame = 0; frame < left.length; frame++) { + if (this.availableFrames === 0) { + left[frame] = 0; + if (right) right[frame] = 0; + this.primed = false; + continue; + } + left[frame] = this.left[this.readIndex]; + if (right) right[frame] = this.right[this.readIndex]; + this.readIndex = (this.readIndex + 1) % this.capacityFrames; + this.availableFrames--; + } + return true; + } +} + +registerProcessor("ziplayer-pcm-output", ZiPlayerPcmProcessor); +`; +} + +function dispatchDetail(target, type, detail) { + target.dispatchEvent(new CustomEvent(type, { detail })); +} + +export class WebAudioClient extends EventTarget { + constructor({ + audioContextFactory = (options) => new AudioContext(options), + webSocketFactory = (url) => new WebSocket(url), + startupBufferMs = 100, + maxBufferSeconds = 2, + connectTimeoutMs = 5000, + } = {}) { + super(); + if (!Number.isFinite(startupBufferMs) || startupBufferMs < 0) { + throw new TypeError("startupBufferMs must be a non-negative number"); + } + if (!Number.isFinite(maxBufferSeconds) || maxBufferSeconds <= 0) { + throw new TypeError("maxBufferSeconds must be a positive number"); + } + if (startupBufferMs > maxBufferSeconds * 1000) { + throw new TypeError("startupBufferMs cannot exceed the maximum AudioWorklet buffer duration"); + } + if (!Number.isInteger(connectTimeoutMs) || connectTimeoutMs <= 0) { + throw new TypeError("connectTimeoutMs must be a positive integer"); + } + this.audioContextFactory = audioContextFactory; + this.webSocketFactory = webSocketFactory; + this.startupBufferMs = startupBufferMs; + this.maxBufferSeconds = maxBufferSeconds; + this.connectTimeoutMs = connectTimeoutMs; + this.socket = null; + this.audioContext = null; + this.workletNode = null; + this.sessionId = null; + this.config = null; + this.expectedSequence = null; + this.acceptNextSession = false; + this.state = "disconnected"; + } + + async connect({ gatewayUrl, token, sessionId, nextPublisher = false } = {}) { + if (typeof gatewayUrl !== "string" || !gatewayUrl) throw new TypeError("gatewayUrl is required"); + if (typeof token !== "string" || !token) throw new TypeError("token is required"); + if (!nextPublisher && (typeof sessionId !== "string" || !sessionId || sessionId.length > 128)) { + throw new TypeError("sessionId is required unless nextPublisher is enabled"); + } + if (this.socket || this.audioContext) await this.disconnect(); + await this.createAudioOutput(); + + const url = new URL(nextPublisher ? "/listen-next" : "/listen", gatewayUrl); + if (!nextPublisher) url.searchParams.set("sessionId", sessionId); + url.searchParams.set("token", token); + this.sessionId = nextPublisher ? null : sessionId; + this.config = null; + this.expectedSequence = null; + this.acceptNextSession = nextPublisher; + this.setState("connecting"); + + let socket; + try { + socket = this.webSocketFactory(url); + } catch (error) { + this.setState("disconnected"); + throw error; + } + this.socket = socket; + socket.binaryType = "arraybuffer"; + + try { + await new Promise((resolve, reject) => { + let settled = false; + const timeout = setTimeout(() => finish(new Error("WebSocket listener connection timed out")), this.connectTimeoutMs); + const cleanup = () => { + clearTimeout(timeout); + socket.removeEventListener("open", onOpen); + socket.removeEventListener("error", onError); + socket.removeEventListener("close", onClose); + }; + const finish = (error) => { + if (settled) return; + settled = true; + cleanup(); + if (error) reject(error); + else resolve(); + }; + const onOpen = () => finish(); + const onError = () => finish(new Error("WebSocket listener connection failed; check gateway URL and token")); + const onClose = (event) => finish(new Error(`WebSocket listener closed before connecting (${event.code})`)); + socket.addEventListener("open", onOpen, { once: true }); + socket.addEventListener("error", onError, { once: true }); + socket.addEventListener("close", onClose, { once: true }); + }); + } catch (error) { + if (this.socket === socket) { + this.socket = null; + socket.close(); + await this.closeAudioOutput(); + this.setState("disconnected"); + } + throw error; + } + + socket.addEventListener("message", (event) => { + if (this.socket !== socket) return; + try { + if (typeof event.data === "string") this.receiveControlMessage(event.data); + else this.receivePcmFrame(event.data); + } catch (error) { + this.reportError(error); + socket.close(1002, "Invalid audio protocol message"); + } + }); + socket.addEventListener("close", (event) => { + if (this.socket !== socket) return; + this.socket = null; + this.config = null; + this.expectedSequence = null; + this.acceptNextSession = false; + void this.closeAudioOutput() + .catch((error) => this.reportError(error)) + .finally(() => { + this.setState("disconnected"); + dispatchDetail(this, "close", { code: event.code, reason: event.reason }); + }); + }); + socket.addEventListener("error", () => { + if (this.socket === socket) this.reportError(new Error("WebSocket transport error")); + }); + this.setState("connected"); + dispatchDetail(this, "connected", { sessionId: this.sessionId, nextPublisher }); + return this; + } + + async disconnect() { + const socket = this.socket; + this.socket = null; + this.config = null; + this.expectedSequence = null; + this.acceptNextSession = false; + if (socket && socket.readyState < 2) socket.close(1000, "Listener disconnected"); + await this.closeAudioOutput(); + this.setState("disconnected"); + } + + async createAudioOutput() { + if (this.audioContext) return; + const context = this.audioContextFactory({ sampleRate: WEB_AUDIO_SAMPLE_RATE_HZ }); + this.audioContext = context; + if (context.sampleRate !== WEB_AUDIO_SAMPLE_RATE_HZ) { + await this.closeAudioOutput(); + throw new Error(`Browser audio device must support ${WEB_AUDIO_SAMPLE_RATE_HZ} Hz output`); + } + const moduleUrl = URL.createObjectURL(new Blob([createWorkletSource()], { type: "text/javascript" })); + try { + await context.audioWorklet.addModule(moduleUrl); + const startupBufferFrames = Math.round((this.startupBufferMs / 1000) * WEB_AUDIO_SAMPLE_RATE_HZ); + this.workletNode = new AudioWorkletNode(context, "ziplayer-pcm-output", { + numberOfInputs: 0, + numberOfOutputs: 1, + outputChannelCount: [WEB_AUDIO_CHANNELS], + processorOptions: { + capacityFrames: Math.round(this.maxBufferSeconds * WEB_AUDIO_SAMPLE_RATE_HZ), + startupBufferFrames, + }, + }); + this.workletNode.connect(context.destination); + await context.resume(); + } catch (error) { + await this.closeAudioOutput(); + throw error; + } finally { + URL.revokeObjectURL(moduleUrl); + } + } + + async closeAudioOutput() { + this.workletNode?.disconnect(); + this.workletNode = null; + const context = this.audioContext; + this.audioContext = null; + if (context && context.state !== "closed") await context.close(); + } + + receiveControlMessage(payload) { + let message; + try { + message = JSON.parse(payload); + } catch { + throw new Error("Received invalid JSON from audio publisher"); + } + if (!message || message.v !== WEB_AUDIO_PROTOCOL_VERSION || typeof message.type !== "string") { + throw new Error("Received a malformed or unsupported control message"); + } + if (message.type === "audio:config") { + const config = parseAudioConfig(message, this.acceptNextSession ? undefined : this.sessionId); + this.sessionId = config.sessionId; + this.acceptNextSession = false; + this.config = config; + this.expectedSequence = null; + this.workletNode?.port.postMessage({ type: "flush" }); + void this.audioContext?.resume().catch((error) => this.reportError(error)); + this.setState("playing"); + dispatchDetail(this, "config", config); + return; + } + if (message.sessionId !== this.sessionId) throw new Error("Received a control message for another session"); + switch (message.type) { + case "playback:pause": + void this.audioContext?.suspend().catch((error) => this.reportError(error)); + this.setState("paused"); + break; + case "playback:resume": + void this.audioContext?.resume().catch((error) => this.reportError(error)); + this.setState("playing"); + break; + case "playback:stop": + this.workletNode?.port.postMessage({ type: "flush" }); + this.setState("waiting"); + break; + case "error": + throw new Error(message.message || "Publisher reported an audio error"); + case "playback:state": + break; + default: + dispatchDetail(this, "control", message); + } + } + + receivePcmFrame(data) { + if (!this.config || !this.workletNode) throw new Error("Received PCM before its audio configuration"); + const frame = decodePcmFrame(data, this.config, this.expectedSequence); + if (frame.sequenceGap) { + dispatchDetail(this, "sequencegap", { + expectedSequence: this.expectedSequence, + receivedSequence: frame.sequence, + }); + } + this.expectedSequence = (frame.sequence + 1) >>> 0; + dispatchDetail(this, "pcm", frame); + this.workletNode.port.postMessage({ type: "pcm", samples: frame.samples }, [frame.samples.buffer]); + } + + setState(state) { + if (this.state === state) return; + const previousState = this.state; + this.state = state; + dispatchDetail(this, "statechange", { state, previousState }); + } + + reportError(error) { + dispatchDetail(this, "error", { error: error instanceof Error ? error : new Error(String(error)) }); + } +} diff --git a/client/index.d.ts b/client/index.d.ts new file mode 100644 index 00000000..0819d3be --- /dev/null +++ b/client/index.d.ts @@ -0,0 +1,81 @@ +export declare const WEB_AUDIO_PROTOCOL_VERSION: 1; +export declare const WEB_AUDIO_SAMPLE_RATE_HZ: 48000; +export declare const WEB_AUDIO_CHANNELS: 2; +export declare const WEB_AUDIO_SAMPLE_BYTES: 2; +export declare const WEB_AUDIO_FRAME_HEADER_BYTES: 16; +export declare const WEB_AUDIO_MAX_MESSAGE_BYTES: 1048576; + +export interface WebAudioConfig { + v: 1; + type: "audio:config"; + sessionId: string; + protocolVersion: 1; + sampleRateHz: 48000; + channels: 2; + sampleFormat: "s16"; + endianness: "little"; + channelLayout: "interleaved"; +} + +export interface DecodedPcmFrame { + sequence: number; + timestampMs: number; + samples: Float32Array; + peak: number; + payload: Uint8Array; + sequenceGap: boolean; +} + +export declare function parseAudioConfig(message: string | unknown, expectedSessionId?: string): WebAudioConfig; +export declare function decodePcmFrame( + data: ArrayBuffer, + config: WebAudioConfig, + expectedSequence?: number | null, +): DecodedPcmFrame; + +export interface WebAudioClientOptions { + audioContextFactory?: (options: AudioContextOptions) => AudioContext; + webSocketFactory?: (url: URL) => WebSocket; + startupBufferMs?: number; + maxBufferSeconds?: number; + connectTimeoutMs?: number; +} + +export interface WebAudioConnectOptions { + gatewayUrl: string; + token: string; + sessionId?: string; + nextPublisher?: boolean; +} + +export type WebAudioClientState = "disconnected" | "connecting" | "connected" | "waiting" | "playing" | "paused"; + +export interface WebAudioClientEventMap { + connected: CustomEvent<{ sessionId: string | null; nextPublisher: boolean }>; + config: CustomEvent; + pcm: CustomEvent; + statechange: CustomEvent<{ state: WebAudioClientState; previousState: WebAudioClientState }>; + sequencegap: CustomEvent<{ expectedSequence: number; receivedSequence: number }>; + control: CustomEvent>; + error: CustomEvent<{ error: Error }>; + close: CustomEvent<{ code: number; reason: string }>; +} + +export declare class WebAudioClient extends EventTarget { + constructor(options?: WebAudioClientOptions); + readonly sessionId: string | null; + readonly config: WebAudioConfig | null; + readonly state: WebAudioClientState; + connect(options: WebAudioConnectOptions): Promise; + disconnect(): Promise; + addEventListener( + type: K, + callback: (this: WebAudioClient, event: WebAudioClientEventMap[K]) => unknown, + options?: boolean | AddEventListenerOptions, + ): void; + removeEventListener( + type: K, + callback: (this: WebAudioClient, event: WebAudioClientEventMap[K]) => unknown, + options?: boolean | EventListenerOptions, + ): void; +} diff --git a/client/package.json b/client/package.json new file mode 100644 index 00000000..59a5aabb --- /dev/null +++ b/client/package.json @@ -0,0 +1,26 @@ +{ + "name": "@ziplayer/client", + "version": "1.0.0", + "description": "Browser AudioWorklet client for ZiPlayer WebSocket PCM streams", + "license": "MIT", + "type": "module", + "files": [ + "browser", + "index.d.ts", + "README.md", + "AGENTS.md" + ], + "exports": { + ".": { + "types": "./index.d.ts", + "browser": "./browser/index.js", + "import": "./browser/index.js" + } + }, + "scripts": { + "test": "node --test" + }, + "engines": { + "node": ">=20.3.0" + } +} diff --git a/client/test/protocol.test.js b/client/test/protocol.test.js new file mode 100644 index 00000000..24f43ea0 --- /dev/null +++ b/client/test/protocol.test.js @@ -0,0 +1,55 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { decodePcmFrame, parseAudioConfig } from "../browser/index.js"; + +const config = { + v: 1, + type: "audio:config", + sessionId: "player-1", + protocolVersion: 1, + sampleRateHz: 48_000, + channels: 2, + sampleFormat: "s16", + endianness: "little", + channelLayout: "interleaved", +}; + +function frame(sequence, values = [16384, -16384]) { + const payload = Buffer.alloc(values.length * 2); + values.forEach((value, index) => payload.writeInt16LE(value, index * 2)); + const header = Buffer.alloc(16); + header.writeUInt32LE(sequence, 0); + header.writeUInt32LE(1234, 4); + header.writeUInt16LE(48_000, 8); + header.writeUInt16LE(2, 10); + header.writeUInt16LE(2, 12); + const packet = Buffer.concat([header, payload]); + return packet.buffer.slice(packet.byteOffset, packet.byteOffset + packet.byteLength); +} + +test("audio configuration validation enforces the supported wire format", () => { + assert.equal(parseAudioConfig(config, "player-1"), config); + assert.throws(() => parseAudioConfig({ ...config, sampleRateHz: 44_100 }), /unsupported|mismatched/i); + assert.throws(() => parseAudioConfig(config, "another-player"), /unsupported|mismatched/i); +}); + +test("PCM frame decoding converts interleaved s16 and reports sequence gaps", () => { + const decoded = decodePcmFrame(frame(4), config, 3); + assert.equal(decoded.sequence, 4); + assert.equal(decoded.timestampMs, 1234); + assert.equal(decoded.sequenceGap, true); + assert.equal(decoded.samples.length, 2); + assert.ok(Math.abs(decoded.samples[0] - 16384 / 32767) < 1e-7); + assert.equal(decoded.samples[1], -0.5); + assert.ok(Math.abs(decoded.peak - 16384 / 32767) < 1e-7); + assert.equal(decoded.payload.byteLength, 4); +}); + +test("PCM frame decoder rejects invalid headers and unaligned payloads", () => { + const invalidHeader = new Uint8Array(frame(0)); + new DataView(invalidHeader.buffer).setUint16(8, 44_100, true); + assert.throws(() => decodePcmFrame(invalidHeader.buffer, config), /invalid PCM/i); + + const validFrame = new Uint8Array(frame(0)); + assert.throws(() => decodePcmFrame(validFrame.slice(0, validFrame.length - 1).buffer, config), /invalid PCM/i); +}); diff --git a/core/AGENTS.md b/core/AGENTS.md index b0f57368..8795955a 100644 --- a/core/AGENTS.md +++ b/core/AGENTS.md @@ -63,7 +63,9 @@ async function playInGuild(guildId: string, voiceChannel: VoiceChannel, query: s leaveOnEnd: true, leaveOnEmpty: true, volume: 80, - userdata: {/*User store data*/}, + userdata: { + /*User store data*/ + }, }); if (!player.connection) await player.connect(voiceChannel); @@ -174,6 +176,39 @@ The first event argument is the affected `Player`, which is useful when one mana - The canonical option definitions are `PlayerManagerOptions` and `PlayerOptions` in [`src/types/core.ts`](src/types/core.ts). Prefer those definitions over guessing option names or defaults. +### Browser audio output + +Use the public `WebSocketAudioOutputBackend` when a player must publish PCM to a WebSocket gateway rather than Discord Voice. The +backend accepts only 48 kHz, stereo, interleaved s16 little-endian PCM. Configure `audioProcessing` to produce that exact format +and provide a socket factory that resolves only after its publisher WebSocket is connected. + +```ts +import { WebSocketAudioOutputBackend } from "ziplayer"; + +const player = await manager.create("web-player", { + audioProcessing: { + enabled: true, + inputFormat: "encoded", + outputFormat: "pcm16le", + sampleRate: 48_000, + channels: 2, + }, + audioOutputBackendFactory: ({ playerId }) => + new WebSocketAudioOutputBackend({ + sessionId: playerId, + socketFactory: ({ sessionId }) => connectPublisherToYourGateway(sessionId), + }), +}); +``` + +The stable `sessionId: playerId` lets gateway subscribers follow different per-track publisher sockets belonging to the same +player. Do not reuse one session ID for unrelated players. ZiPlayer provides the publisher backend and PCM protocol only: an +application still owns its gateway, authentication/authorization, listener routing, and web server. Use +[`@ziplayer/client`](https://github.com/ZiProject/ZiPlayer/tree/main/client/README.md) for browser-side configuration/frame +validation and AudioWorklet playback, or see +[`examples/backend`](https://github.com/ZiProject/ZiPlayer/tree/main/examples/backend/README.md) for a runnable search-and-play +application. Never expose publisher credentials or a long-lived shared gateway secret in browser code. + ## Common Mistakes to Avoid - Do not treat `play()`, `connect()`, `insert()`, or playback controls as synchronous; await them and handle `false` or rejection. diff --git a/core/README.md b/core/README.md index bbda8818..a1c3039d 100644 --- a/core/README.md +++ b/core/README.md @@ -140,6 +140,49 @@ client.login(process.env.DISCORD_TOKEN); --- +## 🌐 Browser Playback with `@ziplayer/client` + +ZiPlayer can send a player's processed PCM to a browser instead of Discord Voice. The core package provides +`WebSocketAudioOutputBackend`; your application provides an authenticated WebSocket gateway and a `socketFactory` that returns a +connected publisher socket. The backend sends 48 kHz stereo s16 LE PCM and manages playback controls and stream cleanup. It does +not create or host the gateway. + +Install the browser receiver separately: + +```bash +npm install @ziplayer/client +``` + +Configure the output backend when creating a regular player. Keep the player ID as the backend's `sessionId` so browser listeners +can stay subscribed when the player's output socket is replaced for the next track: + +```ts +import { PlayerManager, WebSocketAudioOutputBackend } from "ziplayer"; + +const playerId = "web-player"; +const player = await manager.create(playerId, { + audioOutputBackendFactory: ({ playerId }) => + new WebSocketAudioOutputBackend({ + sessionId: playerId, + socketFactory: ({ sessionId, signal }) => connectPublisherSocket({ sessionId, signal, gatewayUrl, token }), + }), +}); + +await player.play(query, userId); +``` + +`connectPublisherSocket` is application/gateway-specific and must resolve to an open WebSocket; authenticate the publisher on the +server and honor the provided abort signal. In the browser, import `WebAudioClient` from `@ziplayer/client` and call `connect()` +from a user gesture. For a newly starting stream, connect with `nextPublisher: true` before requesting playback so the listener is +ready before the first PCM frames arrive. The client handles protocol validation, s16 conversion, and bounded AudioWorklet +playback. + +For a complete runnable gateway, player session, and browser UI example, see +[`examples/backend`](https://github.com/ZiProject/ZiPlayer/tree/main/examples/backend/README.md). For client events, options, and +browser requirements, see [`@ziplayer/client` documentation](https://github.com/ZiProject/ZiPlayer/tree/main/client/README.md). + +--- + ## Singleton Access ZiPlayer exposes a process-wide manager singleton. Create `PlayerManager` once during application startup so it registers the diff --git a/core/src/index.ts b/core/src/index.ts index e7f6a9f5..2229fc83 100644 --- a/core/src/index.ts +++ b/core/src/index.ts @@ -69,6 +69,7 @@ export type { WebSocketAudioControlMessage, WebSocketAudioBackendContext, WebSocketAudioOutputBackendOptions, + WebSocketAudioOutputHandleContract, WebSocketAudioSessionResource, } from "./output/WebSocketAudioOutputBackend"; export { AudioOutputUnsupportedOperationError } from "./output/AudioOutputBackend"; diff --git a/core/src/output/WebSocketAudioOutputBackend.ts b/core/src/output/WebSocketAudioOutputBackend.ts index 12b0624a..d6750580 100644 --- a/core/src/output/WebSocketAudioOutputBackend.ts +++ b/core/src/output/WebSocketAudioOutputBackend.ts @@ -1,4 +1,4 @@ -import type { Readable } from "stream"; +import { performance } from "node:perf_hooks"; import { AudioOutputUnsupportedOperationError, createAudioAbortError } from "./AudioOutputBackend"; import type { AudioFrameFormat, @@ -51,6 +51,7 @@ export type WebSocketAudioControlMessage = export interface WebSocketAudioOutputBackendOptions { protocolVersion?: number; maxBufferedBytes?: number; + sessionId?: string; socketFactory?: (context: WebSocketAudioBackendContext) => WebSocketLike | Promise; authorize?: (context: WebSocketAudioBackendContext) => boolean | Promise; } @@ -69,6 +70,10 @@ export interface WebSocketAudioSessionResource { readonly protocolVersion: number; } +export interface WebSocketAudioOutputHandleContract extends AudioOutputHandle { + readonly completion: Promise; +} + export function webAudioFormatFromPcm(options: { sampleRateHz?: number; channels?: number; @@ -155,7 +160,7 @@ function assertNotAborted(...signals: Array): void { } } -class WebSocketAudioOutputHandle implements AudioOutputHandle { +class WebSocketAudioOutputHandle implements WebSocketAudioOutputHandleContract { private stateValue: AudioOutputState = "ready"; private disposed = false; private readonly listeners = new Set<(event: AudioOutputEvent) => void>(); @@ -164,9 +169,11 @@ class WebSocketAudioOutputHandle implements AudioOutputHandle | null = null; + public completion: Promise = Promise.resolve(); private started = false; private stopped = false; private transportClosed = false; + private playbackDeadline: number | null = null; private pendingReadCancel: (() => void) | null = null; private pendingReadRetry: (() => void) | null = null; private readonly activityWaiters = new Set<(active: boolean) => void>(); @@ -251,36 +258,28 @@ class WebSocketAudioOutputHandle implements AudioOutputHandle undefined); } public pause(signal?: AbortSignal): boolean { assertNotAborted(this.signal, signal); if (this.stateValue !== "playing") return false; + if (!this.sendControlMessage("playback:pause")) return false; this.stateValue = "paused"; this.emit({ type: "state", state: "paused" }); - this.socket?.send( - encodeWebAudioControlMessage({ - type: "playback:pause", - sessionId: this.resource.sessionId, - }), - ); return true; } public resume(signal?: AbortSignal): boolean { assertNotAborted(this.signal, signal); if (this.stateValue !== "paused") return false; + if (!this.sendControlMessage("playback:resume")) return false; this.stateValue = "playing"; this.emit({ type: "state", state: "playing" }); + this.playbackDeadline = null; this.wakeActivityWaiters(true); this.pendingReadRetry?.(); - this.socket?.send( - encodeWebAudioControlMessage({ - type: "playback:resume", - sessionId: this.resource.sessionId, - }), - ); return true; } @@ -293,13 +292,7 @@ class WebSocketAudioOutputHandle implements AudioOutputHandle> { + public async replace(input: AudioOutputInput, signal?: AbortSignal): Promise { assertNotAborted(this.signal, signal); + this.stop(signal); + await this.dispose(); const replacement = this.backend.createSession(input, { signal, metadata: { sessionId: this.resource.sessionId } }); await replacement.start(signal); - await this.dispose(); return replacement; } public setVolume(value: number, signal?: AbortSignal): void { assertNotAborted(this.signal, signal); - if (this.backend.capabilities.volume !== "backend") { - throw new AudioOutputUnsupportedOperationError("volume control"); - } - this.socket?.send( - encodeWebAudioControlMessage({ - type: "playback:state", - sessionId: this.resource.sessionId, - state: this.stateValue, - volume: value, - }), - ); + throw new AudioOutputUnsupportedOperationError("volume control; apply volume upstream"); } public onEvent(listener: (event: AudioOutputEvent) => void): () => void { @@ -355,6 +339,7 @@ class WebSocketAudioOutputHandle implements AudioOutputHandle((resolve) => setTimeout(resolve, 10)); + if (maxBufferedBytes !== null && socket.bufferedAmount + messageBytes > maxBufferedBytes) { + await new Promise((resolve) => setTimeout(resolve, 10)); + continue; + } + const now = performance.now(); + const deadline = this.playbackDeadline ?? now; + this.playbackDeadline = deadline; + if (deadline > now) { + await new Promise((resolve) => setTimeout(resolve, deadline - now)); + continue; + } + break; } + assertNotAborted(this.signal, signal); if (this.stopped || this.disposed || this.transportClosed) return false; + if (socket.readyState !== 1) { + this.transportClosed = true; + return false; + } + const format = this.format; + if (format.kind !== "pcm") throw new TypeError("WebSocket backend requires PCM stream input"); + const frameDurationMs = (payload.byteLength / (format.sampleRateHz * this.calculateSampleFrameBytes())) * 1000; socket.send(encodeWebAudioFrame(payload, this.sequence++, Date.now())); + this.playbackDeadline = (this.playbackDeadline ?? performance.now()) + frameDurationMs; return true; } + private sendControlMessage(type: "playback:pause" | "playback:resume" | "playback:stop"): boolean { + const socket = this.socket; + if (!socket || socket.readyState !== 1 || this.transportClosed) { + this.failTransport(new Error(`Cannot send ${type}: WebSocket audio transport is not open`)); + return false; + } + try { + socket.send( + encodeWebAudioControlMessage({ + type, + sessionId: this.resource.sessionId, + }), + ); + return true; + } catch (error) { + this.failTransport(error instanceof Error ? error : new Error(String(error))); + return false; + } + } + + private failTransport(error: Error): void { + if (this.transportClosed || this.disposed) return; + this.transportClosed = true; + this.stateValue = "failed"; + this.emit({ type: "error", error }); + this.pendingReadCancel?.(); + this.wakeActivityWaiters(false); + this.destroyTransferredInput(); + try { + this.socket?.close(); + } catch { + // The transport is already unusable; local cleanup must still complete. + } + } + private waitUntilActive(): Promise { if (this.stopped || this.disposed || this.transportClosed) return Promise.resolve(false); if (this.stateValue !== "paused") return Promise.resolve(true); @@ -525,14 +564,7 @@ class WebSocketAudioOutputHandle implements AudioOutputHandle { - this.transportClosed = true; - if (!this.stopped && !this.disposed) { - this.stateValue = "failed"; - this.emit({ type: "error", error: new Error("WebSocket audio transport closed") }); - } - this.destroyTransferredInput(); - this.pendingReadCancel?.(); - this.wakeActivityWaiters(false); + if (!this.stopped && !this.disposed) this.failTransport(new Error("WebSocket audio transport closed")); }; socket.addEventListener?.("close", onClose); this.cleanupFns.add(() => socket.removeEventListener?.("close", onClose)); @@ -545,15 +577,16 @@ export class WebSocketAudioOutputBackend implements AudioOutputBackend; private readonly protocolVersion: number; private readonly maxBufferedBytes: number; + private readonly sessionId?: string; private readonly socketFactory: (context: WebSocketAudioBackendContext) => WebSocketLike | Promise; private readonly authorize?: (context: WebSocketAudioBackendContext) => boolean | Promise; private disposed = false; @@ -563,6 +596,13 @@ export class WebSocketAudioOutputBackend implements AudioOutputBackend 128) + ) { + throw new TypeError("sessionId must be a non-empty string of at most 128 characters"); + } + this.sessionId = options.sessionId; this.capabilities.maxBufferedBytes = this.maxBufferedBytes; this.socketFactory = options.socketFactory ?? defaultWebAudioSocketFactory; this.authorize = options.authorize; @@ -577,10 +617,7 @@ export class WebSocketAudioOutputBackend implements AudioOutputBackend { + public createSession(input: AudioOutputInput, context: AudioOutputContext = {}): WebSocketAudioOutputHandleContract { if (this.disposed) throw new Error("WebSocket audio backend is disposed"); validateWebAudioOutputFormat(input.format); if (input.ownership !== "transfer" && input.ownership !== "borrow") { @@ -591,7 +628,7 @@ export class WebSocketAudioOutputBackend implements AudioOutputBackend { if (this.disposed) return; this.disposed = true; diff --git a/docs/AUDIO_OUTPUT_BACKENDS.md b/docs/AUDIO_OUTPUT_BACKENDS.md index d46694d6..cfdcff79 100644 --- a/docs/AUDIO_OUTPUT_BACKENDS.md +++ b/docs/AUDIO_OUTPUT_BACKENDS.md @@ -172,31 +172,27 @@ s16le before it can be sent down Discord's raw path. ## WebSocket PCM backend status -`WebSocketAudioOutputBackend` implements the output handle contract for one-way PCM s16le sessions. Its socket factory supplies an -already-connected WebSocket-compatible transport; the backend does not create a gateway, browser client, or authentication flow. -The initial protocol is fixed at 48 kHz stereo interleaved PCM. It uses bounded PCM messages and gates source reads on -pause/resume, while transport backpressure is measured through the socket's `bufferedAmount`. A transport that does not expose -that measurement is rejected rather than advertised as bounded. Stop and disconnect prevent further sends; only transfer-owned -input streams are destroyed. - -The backend is not yet a complete browser playback feature. A gateway/client integration will additionally need: - -- A transport frame envelope with codec/configuration and sequence/timestamp data; PCM frames need sample boundaries and format - negotiation. -- Per-client buffering limits, backpressure/drop policy, reconnect behavior, and a bounded queue so slow clients cannot stall or - exhaust shared playback. -- Client join/leave lifecycle, ownership, and synchronization policy (shared live edge versus independently seekable sessions). -- Authentication, authorization, origin policy, TLS/deployment requirements, rate limits, and protection against a client - selecting another user's session. -- A latency budget and clock/drift strategy, especially for synchronized multi-client playback. Decoder and browser buffering - behavior also needs measurement. - -For a first one-way browser listener with ordinary internet reachability and moderate latency tolerance, a WebSocket stream is the -simpler transport to deploy and observe; it handles framing/application messages over a common browser transport but generally has -more jitter/buffering than a media-native transport. WebRTC is a better candidate when interactive controls, low latency, or -synchronized listening dominate, at the cost of signaling, NAT traversal, congestion-control and more involved client lifecycle. -These are transport choices only: the WebSocket PCM protocol/backend exists, but the gateway, authentication, and browser playback -client are not implemented here. +`WebSocketAudioOutputBackend` implements one-way PCM s16le sessions. Its socket factory supplies an already-connected +WebSocket-compatible transport; it does not create a gateway or authentication flow. The protocol is fixed at 48 kHz stereo +interleaved PCM. The backend applies a bounded WebSocket `bufferedAmount` limit and paces output against a monotonic sample +duration clock so source streams cannot flood the browser. A transport without a measurable `bufferedAmount` is rejected. +`start()` resolves after configuration is sent; the handle's `completion` promise tracks stream consumption. Replacement uses +`stop-before-start`; volume is unsupported and must be applied upstream. + +Set `WebSocketAudioOutputBackendOptions.sessionId` to a stable player routing ID when the gateway should keep browser listeners +attached across per-track publisher socket replacement. A backend factory receives `{ playerId }` and can use that value as the +session ID. Without the option, each output session receives an independent random ID. + +Browser playback is available from the dependency-free companion package [`@ziplayer/client`](../client/README.md). It validates +protocol configuration and PCM frame headers, converts s16 LE to Float32, and feeds a bounded AudioWorklet jitter buffer. Browser +clients need a gateway which authenticates publishers and listeners, routes sockets by a stable player ID, enforces listener +buffering bounds, and exposes the application operations (for example search/play) that users need. The runnable +[`examples/backend`](../examples/backend/README.md) demonstrates this pattern with ZiPlayer and its source plugins. + +Browser WebSocket APIs cannot set an Authorization header, so the demo accepts listener tokens in the query string. Use +short-lived, session-scoped tokens, origin policy, rate limits, and HTTPS/WSS in a deployed service; never expose a long-lived +shared secret to browsers. This one-way WebSocket transport targets moderate latency tolerance; choose WebRTC when low latency, +congestion control, or synchronized playback is a primary requirement. ## Verification diff --git a/examples/backend/README.md b/examples/backend/README.md new file mode 100644 index 00000000..b547a4e9 --- /dev/null +++ b/examples/backend/README.md @@ -0,0 +1,77 @@ +# ZiPlayer Web Audio session + +This example starts a regular ZiPlayer playback session with its source plugins, then routes the resulting 48 kHz stereo s16 LE +PCM through the WebSocket output backend to browser listeners. `index.js` wires up ZiPlayer; `gateway.js` handles WebSocket +authentication, publisher/listener routing, and serving the browser client. + +## Run locally + +From the repository root, build the core package and install the example dependencies: + +```sh +npm run build:core +npm install --prefix examples/backend +``` + +Set a local development token and start the session. `TRACK_QUERY` is optional: + +```powershell +$env:WEB_AUDIO_TOKEN = "replace-with-a-local-development-token" +npm start --prefix examples/backend +``` + +You can also provide an initial query through `TRACK_QUERY`: + +```powershell +$env:TRACK_QUERY = "lofi hip hop radio" +npm start --prefix examples/backend +``` + +Or pass a media URL as a command-line argument: + +```powershell +npm start --prefix examples/backend -- "https://www.youtube.com/watch?v=..." +``` + +The example registers YouTube, SoundCloud, Spotify, attachments, and TTS plugins with `PlayerManager`. Enter a search phrase or +media URL on the web page and choose **Search and play**; ZiPlayer resolves it through the registered source plugins, starts it on +the normal player/queue pipeline, and the page subscribes to the next audio publisher before starting playback so the first PCM +frames are not lost. Enter the gateway token in the Listener token field before searching. `audioOutputBackendFactory` sends +processed PCM to the gateway instead of Discord Voice. The browser uses the reusable `@ziplayer/client` package to validate and +play the PCM stream. The backend paces PCM frames at their configured sample rate, and a player-stable session ID lets the gateway +keep listeners attached while the player's publisher socket is replaced for the next track. Open to +search and listen. The session fields remain available for manual connections. + +Run the gateway handoff test from the repository root with `npm test --prefix examples/backend`. + +While connected, choose **Start WAV recording** to record the exact PCM stream while it continues playing. **Download current +WAV** saves a snapshot without stopping the recording; **Stop & download WAV** ends the capture and downloads it. Recordings are +stereo 48 kHz s16 PCM in a WAV container and are capped at 10 minutes per capture to limit browser memory use. This saves the +audio received by the browser; it does not download the provider's original MP3/FLAC file. + +## Troubleshooting + +The `/listen` WebSocket request stays pending while connected; that is normal for a live stream. After the JSON `audio:config` +message, binary PCM frames should follow continuously. The page reports the PCM frame count, whether the PCM has a non-zero +signal, and the browser `AudioContext` state. If no PCM arrives within five seconds, check the server terminal for the +`ZiPlayer stream/output error` or `No PCM frames received` diagnostic. If frames arrive but the PCM is silent, try another track +and check the source stream. The search form opens `/listen-next` before sending its playback request, which prevents the +publisher from sending its first frames before the browser is subscribed. + +Configuration: + +- `WEB_AUDIO_TOKEN` is required by both the gateway and publisher connection. +- `TRACK_QUERY` or a command-line argument optionally starts an initial search query or media URL; otherwise, search from the web + page. +- `HOST` and `PORT` control the HTTP/WebSocket listener (defaults: `127.0.0.1:8080`). +- `GATEWAY_URL` overrides the WebSocket publisher URL if the public address differs from `HOST`. +- `PLAYER_ID`, `REQUESTED_BY`, `TTS_LANGUAGE`, and `EXTRACTOR_TIMEOUT_MS` are optional. + +The page also accepts a session-scoped listener token, allowing a separate browser session to connect to `/listen`. + +## Security + +The shared token and query-string token handling are for local development only. Browser WebSocket APIs cannot set arbitrary +request headers, so the demo uses a query parameter for listener authentication. Do not expose a long-lived shared secret or run +this example on an untrusted network. Production deployments should use HTTPS/WSS, short-lived per-session credentials, and +session-scoped authorization in place of the demo token comparison. diff --git a/examples/backend/client/client.js b/examples/backend/client/client.js new file mode 100644 index 00000000..b89c9ed8 --- /dev/null +++ b/examples/backend/client/client.js @@ -0,0 +1,272 @@ +import { WEB_AUDIO_CHANNELS, WEB_AUDIO_SAMPLE_RATE_HZ, WEB_AUDIO_SAMPLE_BYTES, WebAudioClient } from "/web-audio-client.js"; + +const connectForm = document.querySelector("#connect-form"); +const gatewayUrlInput = document.querySelector("#gateway-url"); +const sessionIdInput = document.querySelector("#session-id"); +const tokenInput = document.querySelector("#token"); +const connectButton = document.querySelector("#connect"); +const disconnectButton = document.querySelector("#disconnect"); +const statusElement = document.querySelector("#status"); +const recordButton = document.querySelector("#record"); +const downloadRecordingButton = document.querySelector("#download-recording"); +const clearRecordingButton = document.querySelector("#clear-recording"); +const recordingStatusElement = document.querySelector("#recording-status"); +const searchForm = document.querySelector("#search-form"); +const searchQueryInput = document.querySelector("#search-query"); +const searchButton = document.querySelector("#search"); +const searchStatusElement = document.querySelector("#search-status"); +const BYTES_PER_SECOND = WEB_AUDIO_SAMPLE_RATE_HZ * WEB_AUDIO_CHANNELS * WEB_AUDIO_SAMPLE_BYTES; +const MAX_RECORDING_BYTES = BYTES_PER_SECOND * 60 * 10; + +gatewayUrlInput.value = `${location.protocol === "https:" ? "wss:" : "ws:"}//${location.host}`; + +const audioClient = new WebAudioClient(); +let followsPublisher = false; +let recordingActive = false; +let recordedChunks = []; +let recordedBytes = 0; +let receivedPcmFrames = 0; +let receivedPcmBytes = 0; +let pcmWatchdog = null; + +function setStatus(message) { + statusElement.textContent = message; +} + +function setSearchStatus(message) { + searchStatusElement.textContent = message; +} + +function updateRecordingControls(message) { + const isConfigured = audioClient.config !== null; + if (message) recordingStatusElement.textContent = message; + else if (recordingActive) { + recordingStatusElement.textContent = `Recording ${formatDuration(recordedBytes / BYTES_PER_SECOND)} · ${(recordedBytes / (1024 * 1024)).toFixed(1)} MiB`; + } else if (recordedBytes > 0) { + recordingStatusElement.textContent = `Captured ${formatDuration(recordedBytes / BYTES_PER_SECOND)} · ${(recordedBytes / (1024 * 1024)).toFixed(1)} MiB`; + } else { + recordingStatusElement.textContent = ""; + } + recordButton.disabled = !isConfigured || (!recordingActive && recordedBytes > 0) || recordedBytes >= MAX_RECORDING_BYTES; + recordButton.textContent = recordingActive ? "Stop & download WAV" : "Start WAV recording"; + downloadRecordingButton.disabled = recordedBytes === 0; + clearRecordingButton.disabled = recordedBytes === 0 || recordingActive; +} + +function formatDuration(seconds) { + const minutes = Math.floor(seconds / 60); + const remainingSeconds = Math.floor(seconds % 60); + return `${minutes}:${String(remainingSeconds).padStart(2, "0")}`; +} + +function armPcmWatchdog() { + clearTimeout(pcmWatchdog); + pcmWatchdog = setTimeout(() => { + if (!audioClient.config) return; + const message = + receivedPcmFrames === 0 ? + "Connected, but no PCM frames arrived. Check the server terminal for stream/decode errors." + : "No PCM received in the last 5s. The source may have stalled or ended."; + setStatus(message); + }, 5000); +} + +function createWavHeader(dataBytes) { + const header = new ArrayBuffer(44); + const view = new DataView(header); + const writeText = (offset, text) => { + for (let index = 0; index < text.length; index++) view.setUint8(offset + index, text.charCodeAt(index)); + }; + writeText(0, "RIFF"); + view.setUint32(4, 36 + dataBytes, true); + writeText(8, "WAVE"); + writeText(12, "fmt "); + view.setUint32(16, 16, true); + view.setUint16(20, 1, true); + view.setUint16(22, WEB_AUDIO_CHANNELS, true); + view.setUint32(24, WEB_AUDIO_SAMPLE_RATE_HZ, true); + view.setUint32(28, BYTES_PER_SECOND, true); + view.setUint16(32, WEB_AUDIO_CHANNELS * WEB_AUDIO_SAMPLE_BYTES, true); + view.setUint16(34, WEB_AUDIO_SAMPLE_BYTES * 8, true); + writeText(36, "data"); + view.setUint32(40, dataBytes, true); + return header; +} + +function downloadWav() { + if (!recordedBytes) return false; + const blob = new Blob([createWavHeader(recordedBytes), ...recordedChunks], { type: "audio/wav" }); + const objectUrl = URL.createObjectURL(blob); + const link = document.createElement("a"); + const sessionName = (audioClient.sessionId || "ziplayer").replace(/[^a-zA-Z0-9_-]/g, "_"); + link.href = objectUrl; + link.download = `${sessionName}-${new Date().toISOString().replace(/[:.]/g, "-")}.wav`; + document.body.append(link); + link.click(); + link.remove(); + setTimeout(() => URL.revokeObjectURL(objectUrl), 60_000); + return true; +} + +function onPcm({ detail }) { + receivedPcmFrames++; + receivedPcmBytes += detail.payload.byteLength; + armPcmWatchdog(); + if (recordingActive) { + const remainingBytes = MAX_RECORDING_BYTES - recordedBytes; + const capturedBytes = Math.min(detail.payload.byteLength, remainingBytes - (remainingBytes % 4)); + if (capturedBytes > 0) { + recordedChunks.push(detail.payload.slice(0, capturedBytes)); + recordedBytes += capturedBytes; + } + if (recordedBytes >= MAX_RECORDING_BYTES) { + recordingActive = false; + updateRecordingControls("Recording reached the 10-minute limit; download or clear it to continue."); + } else { + updateRecordingControls(); + } + } + const signalStatus = detail.peak < 0.0001 ? "PCM is silent" : "PCM has signal"; + setStatus( + `${signalStatus} · ${receivedPcmFrames} frames · ${(receivedPcmBytes / BYTES_PER_SECOND).toFixed(1)}s · AudioContext ${audioClient.state}`, + ); +} + +audioClient.addEventListener("statechange", ({ detail }) => { + if (detail.state === "connected") { + disconnectButton.disabled = false; + setStatus(followsPublisher ? "Ready; waiting for audio from this player" : "Connected; waiting for publisher configuration"); + } + if (detail.state === "disconnected") { + followsPublisher = false; + clearTimeout(pcmWatchdog); + pcmWatchdog = null; + receivedPcmFrames = 0; + receivedPcmBytes = 0; + connectButton.disabled = false; + disconnectButton.disabled = true; + setStatus("Disconnected"); + updateRecordingControls(); + } +}); + +audioClient.addEventListener("connected", ({ detail }) => { + followsPublisher = detail.nextPublisher; +}); + +audioClient.addEventListener("config", ({ detail }) => { + sessionIdInput.value = detail.sessionId; + receivedPcmFrames = 0; + receivedPcmBytes = 0; + clearTimeout(pcmWatchdog); + armPcmWatchdog(); + setStatus(`Connected to ${detail.sessionId}; waiting for PCM frames`); + updateRecordingControls(); +}); + +audioClient.addEventListener("pcm", onPcm); +audioClient.addEventListener("sequencegap", ({ detail }) => { + console.warn(`PCM sequence gap: expected ${detail.expectedSequence}, received ${detail.receivedSequence}`); +}); +audioClient.addEventListener("error", ({ detail }) => { + console.error("Web audio client error:", detail.error); + setStatus(`Web audio error: ${detail.error.message}`); +}); +audioClient.addEventListener("close", ({ detail }) => { + console.warn(`Audio listener closed (${detail.code}${detail.reason ? `: ${detail.reason}` : ""})`); +}); + +async function connectToSession({ nextPublisher = false } = {}) { + connectButton.disabled = true; + setStatus("Starting browser audio output…"); + try { + await audioClient.connect({ + gatewayUrl: gatewayUrlInput.value, + token: tokenInput.value, + sessionId: sessionIdInput.value, + nextPublisher, + }); + return true; + } catch (error) { + console.error("Unable to connect Web audio client:", error); + setStatus(`Unable to start audio: ${error.message}`); + connectButton.disabled = false; + disconnectButton.disabled = true; + return false; + } +} + +async function stopClient() { + recordingActive = false; + await audioClient.disconnect(); + followsPublisher = false; +} + +connectForm.addEventListener("submit", (event) => { + event.preventDefault(); + void connectToSession(); +}); + +disconnectButton.addEventListener("click", () => void stopClient()); +recordButton.addEventListener("click", () => { + if (recordingActive) { + recordingActive = false; + if (!downloadWav()) { + updateRecordingControls("No PCM audio has been captured yet."); + return; + } + recordedChunks = []; + recordedBytes = 0; + updateRecordingControls("Recording downloaded."); + return; + } + if (recordedBytes > 0) return; + recordingActive = true; + updateRecordingControls("Recording stream to WAV; playback continues."); +}); +downloadRecordingButton.addEventListener("click", () => { + if (downloadWav()) + updateRecordingControls(recordingActive ? "Downloaded current snapshot; recording continues." : "WAV downloaded."); +}); +clearRecordingButton.addEventListener("click", () => { + if (recordingActive) return; + recordedChunks = []; + recordedBytes = 0; + updateRecordingControls("Recording cleared."); +}); + +searchForm.addEventListener("submit", async (event) => { + event.preventDefault(); + searchButton.disabled = true; + setSearchStatus("Searching with ZiPlayer plugins…"); + try { + if (!(followsPublisher && audioClient.state === "connected")) { + if (audioClient.state !== "disconnected") await audioClient.disconnect(); + const listenerReady = await connectToSession({ nextPublisher: true }); + if (!listenerReady) throw new Error("Could not connect a listener before starting playback"); + } + const response = await fetch("/play", { + method: "POST", + headers: { + "content-type": "application/json", + authorization: `Bearer ${tokenInput.value}`, + }, + body: JSON.stringify({ query: searchQueryInput.value }), + }); + const result = await response.json(); + if (!response.ok) throw new Error(result.error || `Search failed (${response.status})`); + if (!result.sessionId) throw new Error("Track was queued, but the player session is not available yet"); + if (sessionIdInput.value && sessionIdInput.value !== result.sessionId) { + throw new Error("The audio publisher session did not match the listener session"); + } + setSearchStatus(`Added to playback: ${result.track.title}`); + if (result.track.url) console.info(`Selected track: ${result.track.title} (${result.track.url})`); + } catch (error) { + console.error("Web track search failed:", error); + setSearchStatus(`Search failed: ${error.message}`); + } finally { + searchButton.disabled = false; + } +}); + +window.addEventListener("beforeunload", () => void audioClient.disconnect()); diff --git a/examples/backend/client/index.html b/examples/backend/client/index.html new file mode 100644 index 00000000..6c3b607a --- /dev/null +++ b/examples/backend/client/index.html @@ -0,0 +1,199 @@ + + + + + + ZiPlayer Web Audio + + + +

ZiPlayer Web Audio

+

Search for a track through the configured ZiPlayer source plugins, then connect to its live PCM stream.

+
+ + +
+
+

+ Enter the listener token below before searching. Search and play automatically connects this page to the new audio stream. + You can also use the session fields below to connect manually. +

+
+ + + + + + + + +
+ Disconnected +
+
+
+

+ Recording captures the received 48 kHz stereo PCM into WAV while playback continues. Browser memory is capped at 10 minutes + per recording; use Download current WAV to save a snapshot without stopping capture. +

+

+ For browser connections the example gateway accepts a token in the listener URL. Use a short-lived token and serve this page + over HTTPS/WSS outside local development. +

+ + + diff --git a/examples/backend/gateway.js b/examples/backend/gateway.js new file mode 100644 index 00000000..4f2d8ac6 --- /dev/null +++ b/examples/backend/gateway.js @@ -0,0 +1,424 @@ +"use strict"; + +// Authenticates publisher/listener sockets and relays PCM to browser clients. +// For production, use HTTPS/WSS and short-lived per-session tokens. +const { createServer } = require("node:http"); +const { timingSafeEqual } = require("node:crypto"); +const { readFile } = require("node:fs/promises"); +const path = require("node:path"); +const { WebSocket, WebSocketServer } = require("ws"); + +const PROTOCOL_VERSION = 1; +const SAMPLE_RATE_HZ = 48_000; +const CHANNELS = 2; +const SAMPLE_BYTES = 2; +const FRAME_HEADER_BYTES = 16; +const MAX_MESSAGE_BYTES = 1024 * 1024; +const MAX_LISTENER_BUFFER_BYTES = 256 * 1024; +const MAX_QUERY_LENGTH = 500; +const WS_OPEN = 1; +const STATIC_FILES = new Map([ + ["/", ["client/index.html", "text/html; charset=utf-8"]], + ["/client.js", ["client/client.js", "text/javascript; charset=utf-8"]], + ["/web-audio-client.js", ["../../client/browser/index.js", "text/javascript; charset=utf-8"]], +]); + +function equalSecret(actual, expected) { + if (typeof actual !== "string" || !actual || !expected) return false; + const actualBytes = Buffer.from(actual); + const expectedBytes = Buffer.from(expected); + return actualBytes.length === expectedBytes.length && timingSafeEqual(actualBytes, expectedBytes); +} + +function sendHttpError(socket, status, message) { + socket.end(`HTTP/1.1 ${status} ${message}\r\nConnection: close\r\n\r\n`); +} + +function readRequest(request) { + const url = new URL(request.url ?? "/", "http://localhost"); + const role = + url.pathname === "/publish" ? "publisher" + : url.pathname === "/listen-next" ? "next-listener" + : url.pathname === "/listen" ? "listener" + : null; + const sessionId = url.searchParams.get("sessionId"); + if (!role || (role !== "next-listener" && (!sessionId || sessionId.length > 128))) return null; + + const token = + request.headers.authorization?.startsWith("Bearer ") ? + request.headers.authorization.slice("Bearer ".length) + : url.searchParams.get("token"); + + return { role, sessionId, token }; +} + +function isAudioConfig(message, sessionId) { + return ( + message.v === PROTOCOL_VERSION && + message.type === "audio:config" && + message.sessionId === sessionId && + message.protocolVersion === PROTOCOL_VERSION && + message.sampleRateHz === SAMPLE_RATE_HZ && + message.channels === CHANNELS && + message.sampleFormat === "s16" && + message.endianness === "little" && + message.channelLayout === "interleaved" + ); +} + +function isAudioFrame(data) { + if (data.length < FRAME_HEADER_BYTES || data.length > MAX_MESSAGE_BYTES + FRAME_HEADER_BYTES) return false; + const samplesPerChannel = data.length - FRAME_HEADER_BYTES; + const bytesPerSampleFrame = CHANNELS * SAMPLE_BYTES; + if (samplesPerChannel === 0 || samplesPerChannel % bytesPerSampleFrame !== 0) return false; + + return data.readUInt16LE(8) === SAMPLE_RATE_HZ && data.readUInt16LE(10) === CHANNELS && data.readUInt16LE(12) === SAMPLE_BYTES; +} + +function relayToListeners(session, data, isBinary) { + const byteLength = typeof data === "string" ? Buffer.byteLength(data) : data.byteLength; + for (const listener of session.listeners) { + if (listener.readyState !== WS_OPEN) continue; + if (listener.bufferedAmount + byteLength > MAX_LISTENER_BUFFER_BYTES) { + listener.close(1013, "Listener is too slow"); + continue; + } + listener.send(data, { binary: isBinary }, (error) => { + if (error) { + console.error(`Failed to send audio to listener for ${session.sessionId}:`, error); + listener.close(1011, "Audio forwarding failed"); + } + }); + } +} + +function removeSessionIfUnused(session, sessions) { + if (!session.publisher && session.listeners.size === 0 && sessions.get(session.sessionId) === session) { + sessions.delete(session.sessionId); + } +} + +function sendJson(response, status, body) { + response.writeHead(status, { + "content-type": "application/json; charset=utf-8", + "cache-control": "no-store", + "x-content-type-options": "nosniff", + }); + response.end(JSON.stringify(body)); +} + +async function waitForPublisherSession(sessions, timeoutMs = 5000) { + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + for (const session of sessions.values()) { + if (session.publisher?.readyState === WS_OPEN) return session.sessionId; + } + await new Promise((resolve) => setTimeout(resolve, 50)); + } + return null; +} + +async function readJsonBody(request, maxBytes) { + const chunks = []; + let bytesRead = 0; + let oversized = false; + for await (const chunk of request) { + bytesRead += chunk.length; + if (bytesRead > maxBytes) { + oversized = true; + chunks.length = 0; + } else if (!oversized) { + chunks.push(chunk); + } + } + if (oversized) throw Object.assign(new Error("Request body is too large"), { statusCode: 413 }); + try { + return JSON.parse(Buffer.concat(chunks).toString("utf8")); + } catch { + throw Object.assign(new Error("Request body must be valid JSON"), { statusCode: 400 }); + } +} + +function attachPublisher(session, socket, sessions) { + let configured = false; + let frameCount = 0; + let frameBytes = 0; + let lastStatsAt = Date.now(); + let statsTimer; + session.publisher = socket; + session.config = null; + for (const listener of session.nextListeners) { + session.listeners.add(listener); + listener.once("close", () => { + session.listeners.delete(listener); + removeSessionIfUnused(session, sessions); + }); + } + session.nextListeners.clear(); + + socket.on("message", (data, isBinary) => { + if (isBinary) { + if (!configured || !isAudioFrame(data)) { + socket.close(1003, "Invalid or unexpected PCM audio frame"); + return; + } + frameCount++; + frameBytes += data.length - FRAME_HEADER_BYTES; + if (frameCount === 1) { + console.info(`First PCM frame from ${session.sessionId}: ${data.length - FRAME_HEADER_BYTES} bytes`); + } + if (Date.now() - lastStatsAt >= 5000) { + console.info( + `PCM stream ${session.sessionId}: ${frameCount} frames, ${frameBytes} audio bytes, ${session.listeners.size} listener(s)`, + ); + lastStatsAt = Date.now(); + } + relayToListeners(session, data, true); + return; + } + + let message; + try { + message = JSON.parse(data.toString()); + } catch { + socket.close(1003, "Invalid JSON control message"); + return; + } + if (!message || typeof message !== "object" || message.sessionId !== session.sessionId) { + socket.close(1008, "Control message session mismatch"); + return; + } + if (message.type === "audio:config") { + if (!isAudioConfig(message, session.sessionId)) { + socket.close(1008, "Unsupported audio configuration"); + return; + } + configured = true; + session.config = message; + statsTimer ??= setInterval(() => { + if (session.publisher !== socket) return; + if (frameCount === 0) { + console.warn( + `No PCM frames received for ${session.sessionId} after audio:config; check the ZiPlayer stream/decode errors`, + ); + } else { + console.info( + `PCM stream ${session.sessionId}: ${frameCount} frames, ${frameBytes} audio bytes, ${session.listeners.size} listener(s)`, + ); + } + }, 5000); + statsTimer.unref?.(); + } else if (!configured) { + socket.close(1008, "Audio configuration is required first"); + return; + } else if (message.v !== PROTOCOL_VERSION) { + socket.close(1008, "Unsupported protocol version"); + return; + } + relayToListeners(session, data.toString(), false); + }); + + socket.on("close", () => { + clearInterval(statsTimer); + if (session.publisher !== socket) return; + session.publisher = null; + session.config = null; + removeSessionIfUnused(session, sessions); + }); + + socket.on("error", (error) => { + console.error(`Publisher socket error for ${session.sessionId}:`, error); + }); +} + +function createWebAudioGateway({ host = "127.0.0.1", port = 8080, token = process.env.WEB_AUDIO_TOKEN, onPlayQuery } = {}) { + if (!token) throw new Error("Set WEB_AUDIO_TOKEN to a non-empty secret before starting the gateway"); + if (!Number.isInteger(port) || port < 0 || port > 65535) throw new TypeError("port must be an integer from 0 to 65535"); + + const sessions = new Map(); + const pendingListeners = new Set(); + const httpServer = createServer((request, response) => { + const pathname = new URL(request.url ?? "/", "http://localhost").pathname; + if (request.method === "GET" && pathname === "/health") { + response.writeHead(200, { "content-type": "application/json" }); + response.end(JSON.stringify({ status: "ok", activeSessions: sessions.size })); + return; + } + if (request.method === "POST" && pathname === "/play") { + void (async () => { + const authorization = request.headers.authorization ?? ""; + if (!authorization.startsWith("Bearer ") || !equalSecret(authorization.slice("Bearer ".length), token)) { + sendJson(response, 401, { error: "Unauthorized" }); + request.resume(); + return; + } + if (request.headers["content-type"]?.split(";")[0] !== "application/json") { + sendJson(response, 415, { error: "Content-Type must be application/json" }); + request.resume(); + return; + } + if (typeof onPlayQuery !== "function") { + sendJson(response, 503, { error: "Playback is not available" }); + request.resume(); + return; + } + + try { + const body = await readJsonBody(request, 4096); + if (!body || typeof body.query !== "string" || !body.query.trim() || body.query.length > MAX_QUERY_LENGTH) { + sendJson(response, 400, { error: "query must be a non-empty string of at most 500 characters" }); + return; + } + const result = await onPlayQuery(body.query.trim()); + if (result === null) { + sendJson(response, 503, { error: "Player is not ready" }); + return; + } + if (!result) { + sendJson(response, 422, { error: "No playable track found for this query" }); + return; + } + const sessionId = await waitForPublisherSession(sessions); + sendJson(response, 200, { + sessionId, + track: { + title: result.track?.title ?? body.query.trim(), + url: result.track?.url ?? null, + }, + }); + } catch (error) { + const statusCode = error && typeof error === "object" ? error.statusCode : undefined; + if (statusCode) { + if (!response.destroyed) sendJson(response, statusCode, { error: error.message }); + return; + } + console.error("Web playback search failed:", error); + if (!response.destroyed) sendJson(response, 500, { error: "Playback search failed" }); + } + })(); + return; + } + const file = request.method === "GET" ? STATIC_FILES.get(pathname) : undefined; + if (!file) { + response.writeHead(404, { "content-type": "text/plain; charset=utf-8" }); + response.end("Not found"); + return; + } + void readFile(path.join(__dirname, file[0])) + .then((content) => { + response.writeHead(200, { + "content-type": file[1], + "cache-control": "no-store", + "x-content-type-options": "nosniff", + }); + response.end(content); + }) + .catch((error) => { + console.error(`Failed to serve ${pathname}:`, error); + if (!response.headersSent) response.writeHead(500, { "content-type": "text/plain; charset=utf-8" }); + response.end("Failed to load Web audio client"); + }); + }); + const webSocketServer = new WebSocketServer({ + noServer: true, + maxPayload: MAX_MESSAGE_BYTES + FRAME_HEADER_BYTES, + }); + + httpServer.on("upgrade", (request, socket, head) => { + const parsed = readRequest(request); + if (!parsed) { + sendHttpError(socket, 404, "Not Found"); + return; + } + if (!equalSecret(parsed.token, token)) { + sendHttpError(socket, 401, "Unauthorized"); + return; + } + + const existing = sessions.get(parsed.sessionId); + if (parsed.role === "publisher" && existing?.publisher?.readyState === WS_OPEN) { + sendHttpError(socket, 409, "Session Already Published"); + return; + } + if (parsed.role === "listener" && (!existing || existing.publisher?.readyState !== WS_OPEN)) { + sendHttpError(socket, 404, "Audio Session Not Found"); + return; + } + + webSocketServer.handleUpgrade(request, socket, head, (webSocket) => { + if (parsed.role === "publisher") { + const session = existing ?? { + sessionId: parsed.sessionId, + publisher: null, + listeners: new Set(), + nextListeners: new Set(), + config: null, + }; + for (const listener of pendingListeners) session.nextListeners.add(listener); + pendingListeners.clear(); + sessions.set(parsed.sessionId, session); + attachPublisher(session, webSocket, sessions); + console.info(`Audio publisher connected: ${parsed.sessionId}`); + } else if (parsed.role === "next-listener") { + pendingListeners.add(webSocket); + webSocket.once("close", () => pendingListeners.delete(webSocket)); + webSocket.on("error", (error) => { + console.error("Waiting audio listener socket error:", error); + }); + console.info("Audio listener waiting for next publisher"); + } else { + const session = sessions.get(parsed.sessionId); + if (!session || session.publisher?.readyState !== WS_OPEN) { + webSocket.close(1012, "Publisher disconnected"); + return; + } + session.listeners.add(webSocket); + if (session.config) webSocket.send(JSON.stringify(session.config)); + webSocket.once("close", () => { + session.listeners.delete(webSocket); + removeSessionIfUnused(session, sessions); + }); + webSocket.on("error", (error) => { + console.error(`Listener socket error for ${parsed.sessionId}:`, error); + }); + console.info(`Audio listener connected: ${parsed.sessionId}`); + } + }); + }); + + return { + httpServer, + listen() { + return new Promise((resolve, reject) => { + const onError = (error) => { + httpServer.off("listening", onListening); + reject(error); + }; + const onListening = () => { + httpServer.off("error", onError); + resolve(httpServer.address()); + }; + httpServer.once("error", onError); + httpServer.once("listening", onListening); + httpServer.listen(port, host); + }); + }, + async close() { + for (const listener of pendingListeners) listener.close(1001, "Gateway shutting down"); + pendingListeners.clear(); + for (const session of sessions.values()) { + session.publisher?.close(1001, "Gateway shutting down"); + for (const listener of session.listeners) listener.close(1001, "Gateway shutting down"); + } + sessions.clear(); + webSocketServer.close(); + if (httpServer.listening) { + await new Promise((resolve, reject) => { + httpServer.close((error) => (error ? reject(error) : resolve())); + }); + } + }, + }; +} + +module.exports = { createWebAudioGateway }; diff --git a/examples/backend/index.js b/examples/backend/index.js index e69de29b..b81cdc03 100644 --- a/examples/backend/index.js +++ b/examples/backend/index.js @@ -0,0 +1,173 @@ +"use strict"; + +// Run `npm run build:core` and set WEB_AUDIO_TOKEN before starting the example. +require("dotenv").config(); +const { WebSocket } = require("ws"); +const { PlayerManager, WebSocketAudioOutputBackend } = require("ziplayer"); +const { createWebAudioGateway } = require("./gateway"); + +const SAMPLE_RATE_HZ = 48_000; +const CHANNELS = 2; +function createPublisherSocketFactory({ gatewayUrl, token }) { + if (!gatewayUrl) throw new TypeError("gatewayUrl is required"); + if (!token) throw new TypeError("token is required"); + + return ({ sessionId, signal }) => + new Promise((resolve, reject) => { + if (!sessionId) { + reject(new TypeError("WebSocket audio backend did not provide a sessionId")); + return; + } + if (signal?.aborted) { + const error = new Error("WebSocket connection was aborted"); + error.name = "AbortError"; + reject(error); + return; + } + + const url = new URL("/publish", gatewayUrl); + url.searchParams.set("sessionId", sessionId); + const socket = new WebSocket(url, { headers: { authorization: `Bearer ${token}` } }); + const cleanup = () => { + socket.off("open", onOpen); + socket.off("error", onError); + signal?.removeEventListener("abort", onAbort); + }; + const onOpen = () => { + cleanup(); + socket.on("error", (error) => { + console.error(`WebSocket publisher error for ${sessionId}:`, error); + socket.close(1011, "Publisher transport error"); + }); + resolve(socket); + }; + const onError = (error) => { + cleanup(); + socket.terminate(); + reject(error); + }; + const onAbort = () => { + cleanup(); + socket.terminate(); + const error = new Error("WebSocket connection was aborted"); + error.name = "AbortError"; + reject(error); + }; + + socket.once("open", onOpen); + socket.once("error", onError); + signal?.addEventListener("abort", onAbort, { once: true }); + }); +} + +function createAudioOutputBackendFactory(options) { + const socketFactory = createPublisherSocketFactory(options); + return ({ playerId }) => + new WebSocketAudioOutputBackend({ + socketFactory, + authorize: ({ sessionId }) => Boolean(sessionId), + sessionId: playerId, + }); +} + +async function main() { + const host = process.env.HOST ?? "127.0.0.1"; + const port = Number(process.env.PORT ?? 8080); + const token = process.env.WEB_AUDIO_TOKEN; + const trackQuery = process.env.TRACK_QUERY ?? process.argv.slice(2).join(" ").trim(); + let player; + const gateway = createWebAudioGateway({ + host, + port, + token, + onPlayQuery: (query) => (player ? player.play(query, { requestedBy: "client" }) : null), + }); + let manager; + let shuttingDown = false; + try { + const address = await gateway.listen(); + const gatewayUrl = + process.env.GATEWAY_URL ?? `ws://${host === "0.0.0.0" || host === "::" ? "127.0.0.1" : host}:${address.port}`; + const pluginPackage = await import("@ziplayer/plugin"); + const plugins = [ + new pluginPackage.YouTubePlugin(), + new pluginPackage.SoundCloudPlugin(), + new pluginPackage.SpotifyPlugin(), + new pluginPackage.AttachmentsPlugin(), + new pluginPackage.TTSPlugin({ defaultLang: process.env.TTS_LANGUAGE ?? "vi" }), + ]; + + manager = new PlayerManager({ + plugins, + autoCleanup: false, + extractorTimeout: Number(process.env.EXTRACTOR_TIMEOUT_MS ?? 30_000), + }); + manager.on("trackStart", (_player, track) => { + console.info(`Now playing: ${track.title} (${track.url})`); + }); + manager.on("trackAdd", (_player, track) => { + console.info(`Queued: ${track.title}`); + }); + manager.on("error", (_queue, error) => { + console.error("ZiPlayer playback error:", error); + }); + + const playerId = process.env.PLAYER_ID ?? "web-audio-demo"; + player = await manager.create(playerId, { + audioOutputBackendFactory: createAudioOutputBackendFactory({ gatewayUrl, token }), + audioProcessing: { + enabled: true, + inputFormat: "encoded", + outputFormat: "pcm16le", + sampleRate: SAMPLE_RATE_HZ, + channels: CHANNELS, + }, + preload: { enabled: false }, + crossfade: { enabled: false }, + }); + player.on("streamError", (error, track) => { + console.error(`ZiPlayer stream/output error${track?.title ? ` for "${track.title}"` : ""}:`, error); + }); + player.on("playerError", (error, track) => { + console.error(`ZiPlayer track error${track?.title ? ` for "${track.title}"` : ""}:`, error); + }); + + const requestedBy = process.env.REQUESTED_BY ?? "client"; + console.info(`Web audio gateway and client listening on http://${address.address}:${address.port}`); + console.info(`Starting ZiPlayer session "${playerId}" with ${plugins.length} plugins`); + const shutdown = async (signal) => { + if (shuttingDown) return; + shuttingDown = true; + console.info(`Received ${signal}; stopping ZiPlayer and Web audio gateway`); + try { + await manager?.dispose(); + } finally { + await gateway.close(); + } + }; + process.once("SIGINT", () => void shutdown("SIGINT").catch((error) => console.error("Shutdown failed:", error))); + process.once("SIGTERM", () => void shutdown("SIGTERM").catch((error) => console.error("Shutdown failed:", error))); + console.info("Open the gateway URL in a browser to search and listen."); + if (trackQuery) { + const result = await player.play(trackQuery, { requestedBy }); + if (!result) throw new Error(`ZiPlayer could not start playback for query: ${trackQuery}`); + } + } catch (error) { + await manager?.dispose(); + await gateway.close(); + throw error; + } +} + +if (require.main === module) { + main().catch((error) => { + console.error("Failed to start Web audio gateway:", error); + process.exitCode = 1; + }); +} + +module.exports = { + createAudioOutputBackendFactory, + createPublisherSocketFactory, + createWebAudioGateway, +}; diff --git a/examples/backend/package.json b/examples/backend/package.json new file mode 100644 index 00000000..647bd32b --- /dev/null +++ b/examples/backend/package.json @@ -0,0 +1,15 @@ +{ + "name": "@ziplayer/web-audio-gateway-example", + "private": true, + "scripts": { + "start": "node index.js", + "test": "node --test" + }, + "dependencies": { + "@ziplayer/client": "file:../../client", + "@ziplayer/plugin": "file:../../plugins", + "dotenv": "^18.0.7", + "ws": "^8.19.0", + "ziplayer": "file:../../core" + } +} diff --git a/examples/backend/test/gateway.test.js b/examples/backend/test/gateway.test.js new file mode 100644 index 00000000..47afc19e --- /dev/null +++ b/examples/backend/test/gateway.test.js @@ -0,0 +1,114 @@ +"use strict"; + +const assert = require("node:assert/strict"); +const test = require("node:test"); +const { WebSocket } = require("ws"); +const { encodeWebAudioFrame } = require("ziplayer"); +const { createWebAudioGateway } = require("../gateway"); + +const token = "gateway-test-token"; + +function waitForOpen(socket) { + return new Promise((resolve, reject) => { + socket.once("open", resolve); + socket.once("error", reject); + }); +} + +function waitForMessage(socket) { + return new Promise((resolve, reject) => { + const timeout = setTimeout(() => reject(new Error("Timed out waiting for relayed audio")), 2000); + socket.once("message", (data, isBinary) => { + clearTimeout(timeout); + resolve({ data, isBinary }); + }); + }); +} + +test("a next-track listener receives the publisher config and first PCM frame", async () => { + const gateway = createWebAudioGateway({ host: "127.0.0.1", port: 0, token }); + let listener; + let publisher; + let replacementPublisher; + try { + const address = await gateway.listen(); + const gatewayUrl = `ws://127.0.0.1:${address.port}`; + const origin = `http://127.0.0.1:${address.port}`; + const page = await fetch(origin); + assert.equal(page.status, 200); + assert.match(await page.text(), /src="\/client\.js"/); + + const appScript = await fetch(`${origin}/client.js`); + assert.equal(appScript.status, 200); + assert.match(await appScript.text(), /from "\/web-audio-client\.js"/); + + const audioClient = await fetch(`${origin}/web-audio-client.js`); + assert.equal(audioClient.status, 200); + assert.match(await audioClient.text(), /class WebAudioClient/); + + listener = new WebSocket(`${gatewayUrl}/listen-next?token=${token}`); + await waitForOpen(listener); + + publisher = new WebSocket(`${gatewayUrl}/publish?sessionId=gateway-test-session&token=${token}`); + await waitForOpen(publisher); + + const configMessage = waitForMessage(listener); + publisher.send( + JSON.stringify({ + v: 1, + type: "audio:config", + sessionId: "gateway-test-session", + protocolVersion: 1, + sampleRateHz: 48_000, + channels: 2, + sampleFormat: "s16", + endianness: "little", + channelLayout: "interleaved", + }), + ); + const config = await configMessage; + assert.equal(config.isBinary, false); + assert.equal(JSON.parse(config.data.toString()).type, "audio:config"); + + const frameMessage = waitForMessage(listener); + publisher.send(encodeWebAudioFrame(Buffer.alloc(3840), 0, 0), { binary: true }); + const frame = await frameMessage; + assert.equal(frame.isBinary, true); + assert.deepEqual(Buffer.from(frame.data), Buffer.from(encodeWebAudioFrame(Buffer.alloc(3840), 0, 0))); + + const publisherClosed = new Promise((resolve) => publisher.once("close", resolve)); + publisher.close(); + await publisherClosed; + replacementPublisher = new WebSocket(`${gatewayUrl}/publish?sessionId=gateway-test-session&token=${token}`); + await waitForOpen(replacementPublisher); + + const replacementConfigMessage = waitForMessage(listener); + replacementPublisher.send( + JSON.stringify({ + v: 1, + type: "audio:config", + sessionId: "gateway-test-session", + protocolVersion: 1, + sampleRateHz: 48_000, + channels: 2, + sampleFormat: "s16", + endianness: "little", + channelLayout: "interleaved", + }), + ); + const replacementConfig = await replacementConfigMessage; + assert.equal(replacementConfig.isBinary, false); + assert.equal(JSON.parse(replacementConfig.data.toString()).sessionId, "gateway-test-session"); + + const replacementFrameMessage = waitForMessage(listener); + replacementPublisher.send(encodeWebAudioFrame(Buffer.alloc(3840, 1), 0, 0), { binary: true }); + const replacementFrame = await replacementFrameMessage; + assert.equal(replacementFrame.isBinary, true); + assert.deepEqual(Buffer.from(replacementFrame.data), Buffer.from(encodeWebAudioFrame(Buffer.alloc(3840, 1), 0, 0))); + } finally { + listener?.close(); + publisher?.close(); + replacementPublisher?.close(); + await gateway.close(); + } +}); diff --git a/tests/web_audio_output_backend.test.js b/tests/web_audio_output_backend.test.js index be1fc885..18965512 100644 --- a/tests/web_audio_output_backend.test.js +++ b/tests/web_audio_output_backend.test.js @@ -37,12 +37,13 @@ function makeSocket() { listeners.get(type)?.delete(listener); }, send(data) { - this.sent.push(data); + this.sent.push({ data, sentAt: Date.now() }); }, }; } -const binaryMessages = (socket) => socket.sent.filter((value) => typeof value !== "string"); +const messageData = (message) => message.data; +const binaryMessages = (socket) => socket.sent.map(messageData).filter((value) => typeof value !== "string"); const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); test("web protocol frame encoding preserves sequence metadata", () => { @@ -65,13 +66,14 @@ test("web backend accepts valid PCM sessions and emits config plus payload frame ownership: "transfer", }); await handle.start(); - const config = socket.sent.find((value) => typeof value === "string"); + await handle.completion; + const config = socket.sent.map(messageData).find((value) => typeof value === "string"); assert.ok(config !== undefined); const parsed = JSON.parse(config); assert.equal(parsed.v, WEB_AUDIO_PROTOCOL_VERSION); assert.equal(parsed.type, "audio:config"); assert.equal(parsed.sessionId, handle.resource.sessionId); - const binary = socket.sent.find((value) => typeof value !== "string"); + const binary = socket.sent.map(messageData).find((value) => typeof value !== "string"); assert.ok(binary); const frame = decodeWebAudioFrame(new Uint8Array(binary)); assert.equal(frame.payload.length, 8); @@ -81,6 +83,22 @@ test("web backend accepts valid PCM sessions and emits config plus payload frame await backend.dispose(); }); +test("web backend paces PCM frames at the configured sample rate", async () => { + const socket = makeSocket(); + const backend = new WebSocketAudioOutputBackend({ socketFactory: () => socket }); + const handle = backend.createSession({ + stream: Readable.from([Buffer.alloc(2 * 3840)]), + format: pcmFormat, + ownership: "transfer", + }); + await handle.start(); + await handle.completion; + const binaryMessages = socket.sent.filter((message) => typeof message.data !== "string"); + assert.equal(binaryMessages.length, 2); + assert.ok(binaryMessages[1].sentAt - binaryMessages[0].sentAt >= 15); + await backend.dispose(); +}); + test("web backend rejects unsupported PCM formats and invalid ownership modes", () => { const backend = new WebSocketAudioOutputBackend({ socketFactory: () => makeSocket() }); assert.throws( @@ -103,17 +121,38 @@ test("web backend rejects unsupported PCM formats and invalid ownership modes", ); }); +test("web backend can retain a stable routing session ID across track handles", async () => { + const backend = new WebSocketAudioOutputBackend({ sessionId: "player-1", socketFactory: () => makeSocket() }); + const createTrack = () => + backend.createSession({ + stream: Readable.from([]), + format: pcmFormat, + ownership: "transfer", + }); + const first = createTrack(); + const next = createTrack(); + assert.equal(first.resource.sessionId, "player-1"); + assert.equal(next.resource.sessionId, first.resource.sessionId); + await first.dispose(); + await next.dispose(); + await backend.dispose(); + assert.throws(() => new WebSocketAudioOutputBackend({ sessionId: "" }), /sessionId/i); +}); + test("web backend streams beyond its transport buffer limit without a cumulative counter failure", async () => { const socket = makeSocket(); const backend = new WebSocketAudioOutputBackend({ socketFactory: () => socket }); + const startedAt = performance.now(); const handle = backend.createSession({ stream: Readable.from([Buffer.alloc(300 * 1024)]), format: pcmFormat, ownership: "transfer", }); await handle.start(); + await handle.completion; assert.equal(handle.state, "ended"); assert.ok(binaryMessages(socket).length > 1); + assert.ok(performance.now() - startedAt < 2200, "PCM pacing should not accumulate per-frame timer delays"); assert.equal(handle.bufferedBytes, 0); await backend.dispose(); }); @@ -125,6 +164,7 @@ test("web backend pauses reading and sending PCM until resumed", async () => { const handle = backend.createSession({ stream, format: pcmFormat, ownership: "borrow" }); stream.push(Buffer.alloc(3840)); const started = handle.start(); + await started; await wait(20); assert.equal(binaryMessages(socket).length, 1); assert.equal(handle.pause(), true); @@ -133,7 +173,7 @@ test("web backend pauses reading and sending PCM until resumed", async () => { assert.equal(binaryMessages(socket).length, 1); assert.equal(handle.resume(), true); stream.push(null); - await started; + await handle.completion; assert.equal(binaryMessages(socket).length, 2); await backend.dispose(); }); @@ -143,11 +183,11 @@ test("web backend stop cancels a borrowed stream without destroying it or sendin const stream = new Readable({ read() {} }); const backend = new WebSocketAudioOutputBackend({ socketFactory: () => socket }); const handle = backend.createSession({ stream, format: pcmFormat, ownership: "borrow" }); - const started = handle.start(); + await handle.start(); await wait(20); assert.equal(handle.stop(), true); stream.push(Buffer.alloc(3840)); - await started; + await handle.completion; await wait(10); assert.equal(stream.destroyed, false); assert.equal(binaryMessages(socket).length, 0); @@ -166,19 +206,133 @@ test("web backend waits for WebSocket bufferedAmount to fall before sending", as format: pcmFormat, ownership: "transfer", }); + await handle.start(); let completed = false; - const started = handle.start().then(() => { + const completion = handle.completion.then(() => { completed = true; }); await wait(30); assert.equal(binaryMessages(socket).length, 0); assert.equal(completed, false); socket.bufferedAmount = 0; - await started; + await completion; assert.equal(binaryMessages(socket).length, 1); await backend.dispose(); }); +test("web backend start resolves once a live session is ready", async () => { + const socket = makeSocket(); + const stream = new Readable({ read() {} }); + const backend = new WebSocketAudioOutputBackend({ socketFactory: () => socket }); + const handle = backend.createSession({ stream, format: pcmFormat, ownership: "borrow" }); + await Promise.race([ + handle.start(), + wait(100).then(() => { + throw new Error("start waited for the live stream to finish"); + }), + ]); + assert.equal(handle.state, "playing"); + assert.equal(typeof handle.completion.then, "function"); + handle.stop(); + await handle.completion; + await backend.dispose(); +}); + +test("web backend replacement stops and disposes the old session before starting the new one", async () => { + const sockets = []; + const backend = new WebSocketAudioOutputBackend({ + socketFactory: () => { + const socket = makeSocket(); + sockets.push(socket); + return socket; + }, + }); + const old = backend.createSession({ + stream: new Readable({ read() {} }), + format: pcmFormat, + ownership: "borrow", + }); + await old.start(); + const replacement = await old.replace({ + stream: Readable.from([Buffer.alloc(3840)]), + format: pcmFormat, + ownership: "transfer", + }); + assert.equal(backend.capabilities.replacement, "stop-before-start"); + assert.equal(old.disposedState, true); + assert.equal(sockets[0].closed, true); + assert.notEqual(replacement.resource.id, old.resource.id); + await replacement.completion; + await backend.dispose(); +}); + +test("web backend unregisters disposed sessions exactly once", async () => { + const backend = new WebSocketAudioOutputBackend({ socketFactory: () => makeSocket() }); + const first = backend.createSession({ + stream: Readable.from([]), + format: pcmFormat, + ownership: "transfer", + }); + const second = backend.createSession({ + stream: Readable.from([]), + format: pcmFormat, + ownership: "transfer", + }); + assert.equal(backend.sessions.size, 2); + await first.dispose(); + assert.equal(backend.sessions.size, 1); + await first.dispose(); + assert.equal(backend.sessions.size, 1); + await second.dispose(); + assert.equal(backend.sessions.size, 0); + await backend.dispose(); +}); + +test("web backend declares volume unsupported", async () => { + const backend = new WebSocketAudioOutputBackend({ socketFactory: () => makeSocket() }); + const handle = backend.createSession({ + stream: Readable.from([]), + format: pcmFormat, + ownership: "transfer", + }); + assert.equal(backend.capabilities.volume, "unsupported"); + assert.throws(() => handle.setVolume(0.5), /volume control/i); + await backend.dispose(); +}); + +test("web backend does not report pause success when control send fails", async () => { + const socket = makeSocket(); + const stream = new Readable({ read() {} }); + const backend = new WebSocketAudioOutputBackend({ socketFactory: () => socket }); + const handle = backend.createSession({ stream, format: pcmFormat, ownership: "borrow" }); + await handle.start(); + socket.send = (data) => { + if (typeof data === "string" && JSON.parse(data).type === "playback:pause") { + throw new Error("pause send failed"); + } + socket.sent.push(data); + }; + assert.equal(handle.pause(), false); + assert.equal(handle.state, "failed"); + await handle.completion; + assert.equal(stream.destroyed, false); + await backend.dispose(); +}); + +test("web backend does not report stop success when the transport is closed", async () => { + const socket = makeSocket(); + const stream = new Readable({ read() {} }); + const backend = new WebSocketAudioOutputBackend({ socketFactory: () => socket }); + const handle = backend.createSession({ stream, format: pcmFormat, ownership: "borrow" }); + await handle.start(); + socket.readyState = 3; + assert.equal(handle.stop(), false); + assert.equal(handle.state, "failed"); + assert.equal(stream.destroyed, false); + await handle.completion; + await backend.dispose(); +}); + test("web backend rejects float PCM formats", () => { const backend = new WebSocketAudioOutputBackend({ socketFactory: () => makeSocket() }); assert.throws( @@ -198,10 +352,10 @@ test("web backend abort destroys transferred input and closes the socket", async const controller = new AbortController(); const backend = new WebSocketAudioOutputBackend({ socketFactory: () => socket }); const handle = backend.createSession({ stream, format: pcmFormat, ownership: "transfer" }, { signal: controller.signal }); - const started = handle.start(); + await handle.start(); await wait(20); controller.abort(); - await started; + await handle.completion; assert.equal(stream.destroyed, true); assert.equal(socket.closed, true); await backend.dispose(); @@ -246,10 +400,10 @@ test("web backend stops consuming transferred input after WebSocket disconnect", const stream = new Readable({ read() {} }); const backend = new WebSocketAudioOutputBackend({ socketFactory: () => socket }); const handle = backend.createSession({ stream, format: pcmFormat, ownership: "transfer" }); - const started = handle.start(); + await handle.start(); await wait(20); socket.close(); - await started; + await handle.completion; assert.equal(stream.destroyed, true); assert.equal(handle.state, "failed"); assert.equal(binaryMessages(socket).length, 0); From 2411c36aac1f6dee364c65b382428f1a64040037 Mon Sep 17 00:00:00 2001 From: Ziji <104454302+zijipia@users.noreply.github.com> Date: Sat, 10 Oct 2026 23:28:44 +0900 Subject: [PATCH 13/55] feat: update README and example configurations for improved local setup and session management --- README.md | 41 +++++++++++----- client/browser/index.js | 2 +- examples/backend/.env.example | 5 ++ examples/backend/README.md | 66 ++++++++++++++++---------- examples/backend/gateway.js | 67 ++++++++++++++++++++++----- examples/backend/test/gateway.test.js | 61 ++++++++++++++++++++++++ 6 files changed, 193 insertions(+), 49 deletions(-) create mode 100644 examples/backend/.env.example diff --git a/README.md b/README.md index afd97cc9..c547a3b4 100644 --- a/README.md +++ b/README.md @@ -113,19 +113,36 @@ a server-side gateway to authenticate and route WebSocket connections; the brows or receive provider credentials. The reusable browser receiver is [`@ziplayer/client`](client/README.md). It validates ZiPlayer's 48 kHz stereo s16 PCM protocol -and plays it through a bounded AudioWorklet buffer. The complete runnable example combines the client with a WebSocket gateway, -player-stable routing, and normal plugin-backed `PlayerManager` search/play: - -```powershell -npm run build:core -npm install --prefix examples/backend -$env:WEB_AUDIO_TOKEN = "use-a-local-development-token" -npm start --prefix examples/backend -``` +and plays it through a bounded AudioWorklet buffer. To hear browser audio from a fresh clone, use the complete local example: + +1. Install [Node.js 20.3 or newer](https://nodejs.org/) and Git, then clone this repository. +2. From the repository root, install dependencies and build the core: + + ```sh + npm install + npm run build:core + ``` + +3. Install the runnable example's dependencies: + + ```sh + npm install --prefix examples/backend + ``` + +4. Open `examples/backend/.env.example`, save a local copy as `examples/backend/.env`, and set `WEB_AUDIO_TOKEN` to a + non-empty development-only value. +5. Start the example from the repository root: + + ```sh + npm start --prefix examples/backend + ``` + +6. Open , enter the same token in **Listener token**, type a search phrase or media URL, and choose + **Search and play**. Choose **Disconnect** to stop browser playback; press **Ctrl+C** in the terminal to stop the server. -Open and enter the token. The gateway example is intended for local development, not public deployment. -See [`docs/AUDIO_OUTPUT_BACKENDS.md`](docs/AUDIO_OUTPUT_BACKENDS.md) for the backend API and -[`examples/backend/README.md`](examples/backend/README.md) for setup, operations, and security notes. +This example includes a WebSocket gateway and source plugins; it needs internet access to resolve online media. It is for local +development, not public deployment. See [`examples/backend/README.md`](examples/backend/README.md) for troubleshooting and +configuration, and [`docs/AUDIO_OUTPUT_BACKENDS.md`](docs/AUDIO_OUTPUT_BACKENDS.md) for the backend API. ## 🎵 Core Usage diff --git a/client/browser/index.js b/client/browser/index.js index f5682575..66cc6117 100644 --- a/client/browser/index.js +++ b/client/browser/index.js @@ -192,7 +192,7 @@ export class WebAudioClient extends EventTarget { await this.createAudioOutput(); const url = new URL(nextPublisher ? "/listen-next" : "/listen", gatewayUrl); - if (!nextPublisher) url.searchParams.set("sessionId", sessionId); + if (typeof sessionId === "string" && sessionId) url.searchParams.set("sessionId", sessionId); url.searchParams.set("token", token); this.sessionId = nextPublisher ? null : sessionId; this.config = null; diff --git a/examples/backend/.env.example b/examples/backend/.env.example new file mode 100644 index 00000000..bdbf89b2 --- /dev/null +++ b/examples/backend/.env.example @@ -0,0 +1,5 @@ +# Local development only. Use the same value in the browser's Listener token field. +WEB_AUDIO_TOKEN=change-this-local-token + +# Optional: search for and start a track when the example launches. +# TRACK_QUERY=lofi hip hop radio diff --git a/examples/backend/README.md b/examples/backend/README.md index b547a4e9..ab384226 100644 --- a/examples/backend/README.md +++ b/examples/backend/README.md @@ -1,46 +1,63 @@ -# ZiPlayer Web Audio session +# ZiPlayer Web Audio quick start -This example starts a regular ZiPlayer playback session with its source plugins, then routes the resulting 48 kHz stereo s16 LE -PCM through the WebSocket output backend to browser listeners. `index.js` wires up ZiPlayer; `gateway.js` handles WebSocket -authentication, publisher/listener routing, and serving the browser client. +Hear a ZiPlayer stream in your browser without setting up a Discord bot. This runnable local demo starts ZiPlayer and its source +plugins, routes processed 48 kHz stereo PCM through an authenticated WebSocket gateway, and serves the browser player. -## Run locally +## Requirements -From the repository root, build the core package and install the example dependencies: +- Node.js 20.3 or newer and npm. +- Internet access to install packages and resolve online media. +- A modern browser with AudioWorklet support (for example, current Chrome, Edge, Firefox, or Safari). + +No Discord bot or Discord token is required for this browser example. + +## Start from a fresh clone + +Run these commands from the repository root. If you have not cloned the project yet: ```sh +git clone https://github.com/ZiProject/ZiPlayer.git +cd ZiPlayer +npm install npm run build:core npm install --prefix examples/backend ``` -Set a local development token and start the session. `TRACK_QUERY` is optional: +Create `examples/backend/.env` by copying `examples/backend/.env.example`, then open the new file and set `WEB_AUDIO_TOKEN` to a +non-empty local development value. Keep this value private; `.env` is ignored by Git. -```powershell -$env:WEB_AUDIO_TOKEN = "replace-with-a-local-development-token" +Start the gateway and player from the repository root: + +```sh npm start --prefix examples/backend ``` -You can also provide an initial query through `TRACK_QUERY`: +Open . Enter the same token in the **Listener token** field, enter a track search or media URL, then click +**Search and play**. The page connects to the next audio stream before playback starts, so its first frames are not missed. Click +**Disconnect** to stop listening and release browser audio resources. Press **Ctrl+C** in the terminal to stop the server. -```powershell -$env:TRACK_QUERY = "lofi hip hop radio" -npm start --prefix examples/backend +The browser's first play/search click also unlocks audio playback in browsers that require a user gesture. If the browser reports +that it connected but PCM is silent, check the terminal for source/plugin errors and try a different query. + +You can optionally start a query automatically by adding `TRACK_QUERY` to `examples/backend/.env`: + +```dotenv +TRACK_QUERY=lofi hip hop radio ``` -Or pass a media URL as a command-line argument: +Alternatively, pass a search phrase or URL after `--`: -```powershell +```sh npm start --prefix examples/backend -- "https://www.youtube.com/watch?v=..." ``` -The example registers YouTube, SoundCloud, Spotify, attachments, and TTS plugins with `PlayerManager`. Enter a search phrase or -media URL on the web page and choose **Search and play**; ZiPlayer resolves it through the registered source plugins, starts it on -the normal player/queue pipeline, and the page subscribes to the next audio publisher before starting playback so the first PCM -frames are not lost. Enter the gateway token in the Listener token field before searching. `audioOutputBackendFactory` sends -processed PCM to the gateway instead of Discord Voice. The browser uses the reusable `@ziplayer/client` package to validate and -play the PCM stream. The backend paces PCM frames at their configured sample rate, and a player-stable session ID lets the gateway -keep listeners attached while the player's publisher socket is replaced for the next track. Open to -search and listen. The session fields remain available for manual connections. +## What is running? + +The example registers YouTube, SoundCloud, Spotify, attachments, and TTS source plugins with `PlayerManager`. It uses the regular +ZiPlayer playback pipeline, but sends processed PCM through `WebSocketAudioOutputBackend` to the local gateway instead of Discord +Voice. The gateway authenticates the publisher and browser listener and forwards audio; the browser's reusable +`@ziplayer/client` validates and plays it through an AudioWorklet. The page's session fields are available for manual connections +if you want to listen to an already-running player. Run the gateway handoff test from the repository root with `npm test --prefix examples/backend`. @@ -61,8 +78,7 @@ publisher from sending its first frames before the browser is subscribed. Configuration: - `WEB_AUDIO_TOKEN` is required by both the gateway and publisher connection. -- `TRACK_QUERY` or a command-line argument optionally starts an initial search query or media URL; otherwise, search from the web - page. +- `TRACK_QUERY` or a command-line argument optionally starts an initial search query or media URL; otherwise, use the web page. - `HOST` and `PORT` control the HTTP/WebSocket listener (defaults: `127.0.0.1:8080`). - `GATEWAY_URL` overrides the WebSocket publisher URL if the public address differs from `HOST`. - `PLAYER_ID`, `REQUESTED_BY`, `TTS_LANGUAGE`, and `EXTRACTOR_TIMEOUT_MS` are optional. diff --git a/examples/backend/gateway.js b/examples/backend/gateway.js index 4f2d8ac6..42636c16 100644 --- a/examples/backend/gateway.js +++ b/examples/backend/gateway.js @@ -42,14 +42,15 @@ function readRequest(request) { : url.pathname === "/listen" ? "listener" : null; const sessionId = url.searchParams.get("sessionId"); - if (!role || (role !== "next-listener" && (!sessionId || sessionId.length > 128))) return null; + if (!role || (sessionId !== null && (!sessionId.trim() || sessionId.length > 128))) return null; + if ((role === "publisher" || role === "listener") && (!sessionId || !sessionId.trim())) return null; const token = request.headers.authorization?.startsWith("Bearer ") ? request.headers.authorization.slice("Bearer ".length) - : url.searchParams.get("token"); + : url.searchParams.get("token"); - return { role, sessionId, token }; + return { role, sessionId: sessionId ?? null, token }; } function isAudioConfig(message, sessionId) { @@ -94,10 +95,52 @@ function relayToListeners(session, data, isBinary) { function removeSessionIfUnused(session, sessions) { if (!session.publisher && session.listeners.size === 0 && sessions.get(session.sessionId) === session) { + session.nextListeners.clear(); sessions.delete(session.sessionId); } } +function getPendingListenerSet(pendingListeners, sessionId) { + const key = sessionId ?? "__global__"; + let listeners = pendingListeners.get(key); + if (!listeners) { + listeners = new Set(); + pendingListeners.set(key, listeners); + } + return listeners; +} + +function queuePendingListener(pendingListeners, webSocket, sessionId) { + const listeners = getPendingListenerSet(pendingListeners, sessionId); + listeners.add(webSocket); + webSocket.once("close", () => { + listeners.delete(webSocket); + if (listeners.size === 0) pendingListeners.delete(sessionId ?? "__global__"); + }); + return listeners; +} + +function attachPendingListeners(session, pendingListeners) { + const sessionKey = session.sessionId; + const globalKey = "__global__"; + const queued = new Set([ + ...(pendingListeners.get(sessionKey) ?? []), + ...(pendingListeners.get(globalKey) ?? []), + ]); + for (const listener of queued) { + session.nextListeners.add(listener); + listener.once("close", () => { + session.nextListeners.delete(listener); + }); + } + for (const key of [sessionKey, globalKey]) { + const listeners = pendingListeners.get(key); + if (!listeners) continue; + listeners.clear(); + pendingListeners.delete(key); + } +} + function sendJson(response, status, body) { response.writeHead(status, { "content-type": "application/json; charset=utf-8", @@ -236,7 +279,7 @@ function createWebAudioGateway({ host = "127.0.0.1", port = 8080, token = proces if (!Number.isInteger(port) || port < 0 || port > 65535) throw new TypeError("port must be an integer from 0 to 65535"); const sessions = new Map(); - const pendingListeners = new Set(); + const pendingListeners = new Map(); const httpServer = createServer((request, response) => { const pathname = new URL(request.url ?? "/", "http://localhost").pathname; if (request.method === "GET" && pathname === "/health") { @@ -354,18 +397,17 @@ function createWebAudioGateway({ host = "127.0.0.1", port = 8080, token = proces nextListeners: new Set(), config: null, }; - for (const listener of pendingListeners) session.nextListeners.add(listener); - pendingListeners.clear(); + attachPendingListeners(session, pendingListeners); sessions.set(parsed.sessionId, session); attachPublisher(session, webSocket, sessions); console.info(`Audio publisher connected: ${parsed.sessionId}`); } else if (parsed.role === "next-listener") { - pendingListeners.add(webSocket); - webSocket.once("close", () => pendingListeners.delete(webSocket)); + const queue = queuePendingListener(pendingListeners, webSocket, parsed.sessionId ?? null); webSocket.on("error", (error) => { - console.error("Waiting audio listener socket error:", error); + console.error(`Waiting audio listener socket error for ${parsed.sessionId ?? "next publisher"}:`, error); + queue.delete(webSocket); }); - console.info("Audio listener waiting for next publisher"); + console.info(`Audio listener waiting for ${parsed.sessionId ? `session ${parsed.sessionId}` : "the next publisher"}`); } else { const session = sessions.get(parsed.sessionId); if (!session || session.publisher?.readyState !== WS_OPEN) { @@ -404,11 +446,14 @@ function createWebAudioGateway({ host = "127.0.0.1", port = 8080, token = proces }); }, async close() { - for (const listener of pendingListeners) listener.close(1001, "Gateway shutting down"); + for (const listeners of pendingListeners.values()) { + for (const listener of listeners) listener.close(1001, "Gateway shutting down"); + } pendingListeners.clear(); for (const session of sessions.values()) { session.publisher?.close(1001, "Gateway shutting down"); for (const listener of session.listeners) listener.close(1001, "Gateway shutting down"); + session.nextListeners.clear(); } sessions.clear(); webSocketServer.close(); diff --git a/examples/backend/test/gateway.test.js b/examples/backend/test/gateway.test.js index 47afc19e..3ae64e39 100644 --- a/examples/backend/test/gateway.test.js +++ b/examples/backend/test/gateway.test.js @@ -112,3 +112,64 @@ test("a next-track listener receives the publisher config and first PCM frame", await gateway.close(); } }); + +test("session-scoped next-listener routing keeps concurrent publishers isolated", async () => { + const gateway = createWebAudioGateway({ host: "127.0.0.1", port: 0, token }); + let alphaListener; + let betaListener; + let alphaPublisher; + let betaPublisher; + try { + const address = await gateway.listen(); + const gatewayUrl = `ws://127.0.0.1:${address.port}`; + alphaListener = new WebSocket(`${gatewayUrl}/listen-next?sessionId=alpha-session&token=${token}`); + betaListener = new WebSocket(`${gatewayUrl}/listen-next?sessionId=beta-session&token=${token}`); + await Promise.all([waitForOpen(alphaListener), waitForOpen(betaListener)]); + + alphaPublisher = new WebSocket(`${gatewayUrl}/publish?sessionId=alpha-session&token=${token}`); + await waitForOpen(alphaPublisher); + const alphaConfigMessage = waitForMessage(alphaListener); + alphaPublisher.send( + JSON.stringify({ + v: 1, + type: "audio:config", + sessionId: "alpha-session", + protocolVersion: 1, + sampleRateHz: 48_000, + channels: 2, + sampleFormat: "s16", + endianness: "little", + channelLayout: "interleaved", + }), + ); + const alphaConfig = await alphaConfigMessage; + assert.equal(JSON.parse(alphaConfig.data.toString()).sessionId, "alpha-session"); + + betaPublisher = new WebSocket(`${gatewayUrl}/publish?sessionId=beta-session&token=${token}`); + await waitForOpen(betaPublisher); + const betaConfigMessage = waitForMessage(betaListener); + betaPublisher.send( + JSON.stringify({ + v: 1, + type: "audio:config", + sessionId: "beta-session", + protocolVersion: 1, + sampleRateHz: 48_000, + channels: 2, + sampleFormat: "s16", + endianness: "little", + channelLayout: "interleaved", + }), + ); + const betaConfig = await betaConfigMessage; + assert.equal(JSON.parse(betaConfig.data.toString()).sessionId, "beta-session"); + assert.equal(alphaListener.readyState, 1); + assert.equal(betaListener.readyState, 1); + } finally { + alphaListener?.close(); + betaListener?.close(); + alphaPublisher?.close(); + betaPublisher?.close(); + await gateway.close(); + } +}); From ae86dc9a7b3314944486481465c092c4aed7116c Mon Sep 17 00:00:00 2001 From: Ziji <104454302+zijipia@users.noreply.github.com> Date: Sat, 10 Oct 2026 23:45:31 +0900 Subject: [PATCH 14/55] feat: update README and example configurations for improved setup and session management; enhance gateway and client with session handling --- README.md | 3 +- examples/backend/.env.example | 3 +- examples/backend/README.md | 13 +++++- examples/backend/client/client.js | 20 ++++++++- examples/backend/gateway.js | 58 ++++++++++++++++++++++----- examples/backend/index.js | 3 +- examples/backend/test/gateway.test.js | 53 ++++++++++++++++++++++++ 7 files changed, 137 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index c547a3b4..7d49aa19 100644 --- a/README.md +++ b/README.md @@ -116,10 +116,11 @@ The reusable browser receiver is [`@ziplayer/client`](client/README.md). It vali and plays it through a bounded AudioWorklet buffer. To hear browser audio from a fresh clone, use the complete local example: 1. Install [Node.js 20.3 or newer](https://nodejs.org/) and Git, then clone this repository. -2. From the repository root, install dependencies and build the core: +2. From the repository root, install the project dependencies, install the core package's build tools, and build the core: ```sh npm install + npm install --prefix core npm run build:core ``` diff --git a/examples/backend/.env.example b/examples/backend/.env.example index bdbf89b2..6d48a2a7 100644 --- a/examples/backend/.env.example +++ b/examples/backend/.env.example @@ -1,4 +1,5 @@ -# Local development only. Use the same value in the browser's Listener token field. +# Local loopback development only. The gateway refuses this placeholder on non-loopback hosts. +# Replace it with a unique secret before changing HOST to expose the gateway to a network. WEB_AUDIO_TOKEN=change-this-local-token # Optional: search for and start a track when the example launches. diff --git a/examples/backend/README.md b/examples/backend/README.md index ab384226..dd7a5fd1 100644 --- a/examples/backend/README.md +++ b/examples/backend/README.md @@ -19,12 +19,18 @@ Run these commands from the repository root. If you have not cloned the project git clone https://github.com/ZiProject/ZiPlayer.git cd ZiPlayer npm install +npm install --prefix core npm run build:core npm install --prefix examples/backend ``` +The root install does not install the core package's build tools, so install its dependencies separately before building. + Create `examples/backend/.env` by copying `examples/backend/.env.example`, then open the new file and set `WEB_AUDIO_TOKEN` to a -non-empty local development value. Keep this value private; `.env` is ignored by Git. +non-empty local development value. The checked-in token is only a loopback placeholder: the gateway refuses to start with it +when `HOST` is not a loopback address. Before exposing the gateway to a network, set a unique secret; keep `.env` private (it is +ignored by Git). Network exposure still requires HTTPS/WSS and a production authentication design; a strong shared token alone +does not make this demo production-ready. Start the gateway and player from the repository root: @@ -39,6 +45,11 @@ Open . Enter the same token in the **Listener token** fi The browser's first play/search click also unlocks audio playback in browsers that require a user gesture. If the browser reports that it connected but PCM is silent, check the terminal for source/plugin errors and try a different query. +The page fetches the configured playback session ID from the gateway and uses it both for `/listen-next` and `/play`. These +session-scoped listeners wait for that exact publisher. A listener that manually connects to `/listen-next` without a +`sessionId` explicitly means “attach to whichever publisher connects next”; use a session ID whenever a specific player is +intended. + You can optionally start a query automatically by adding `TRACK_QUERY` to `examples/backend/.env`: ```dotenv diff --git a/examples/backend/client/client.js b/examples/backend/client/client.js index b89c9ed8..a8e182ee 100644 --- a/examples/backend/client/client.js +++ b/examples/backend/client/client.js @@ -20,6 +20,20 @@ const MAX_RECORDING_BYTES = BYTES_PER_SECOND * 60 * 10; gatewayUrlInput.value = `${location.protocol === "https:" ? "wss:" : "ws:"}//${location.host}`; +const playbackConfig = fetch("/config") + .then(async (response) => { + if (!response.ok) throw new Error(`Gateway configuration request failed (${response.status})`); + return response.json(); + }) + .then((config) => { + if (typeof config.defaultSessionId === "string") sessionIdInput.value = config.defaultSessionId; + return config; + }); +void playbackConfig.catch((error) => { + console.error("Unable to load gateway configuration:", error); + setSearchStatus(`Gateway setup unavailable: ${error.message}`); +}); + const audioClient = new WebAudioClient(); let followsPublisher = false; let recordingActive = false; @@ -240,6 +254,10 @@ searchForm.addEventListener("submit", async (event) => { searchButton.disabled = true; setSearchStatus("Searching with ZiPlayer plugins…"); try { + const config = await playbackConfig; + const sessionId = sessionIdInput.value || config.defaultSessionId; + if (!sessionId) throw new Error("Enter the playback session ID before searching"); + sessionIdInput.value = sessionId; if (!(followsPublisher && audioClient.state === "connected")) { if (audioClient.state !== "disconnected") await audioClient.disconnect(); const listenerReady = await connectToSession({ nextPublisher: true }); @@ -251,7 +269,7 @@ searchForm.addEventListener("submit", async (event) => { "content-type": "application/json", authorization: `Bearer ${tokenInput.value}`, }, - body: JSON.stringify({ query: searchQueryInput.value }), + body: JSON.stringify({ query: searchQueryInput.value, sessionId }), }); const result = await response.json(); if (!response.ok) throw new Error(result.error || `Search failed (${response.status})`); diff --git a/examples/backend/gateway.js b/examples/backend/gateway.js index 42636c16..e6fb7610 100644 --- a/examples/backend/gateway.js +++ b/examples/backend/gateway.js @@ -5,6 +5,7 @@ const { createServer } = require("node:http"); const { timingSafeEqual } = require("node:crypto"); const { readFile } = require("node:fs/promises"); +const { isIP } = require("node:net"); const path = require("node:path"); const { WebSocket, WebSocketServer } = require("ws"); @@ -17,6 +18,7 @@ const MAX_MESSAGE_BYTES = 1024 * 1024; const MAX_LISTENER_BUFFER_BYTES = 256 * 1024; const MAX_QUERY_LENGTH = 500; const WS_OPEN = 1; +const INSECURE_DEMO_TOKEN = "change-this-local-token"; const STATIC_FILES = new Map([ ["/", ["client/index.html", "text/html; charset=utf-8"]], ["/client.js", ["client/client.js", "text/javascript; charset=utf-8"]], @@ -101,7 +103,7 @@ function removeSessionIfUnused(session, sessions) { } function getPendingListenerSet(pendingListeners, sessionId) { - const key = sessionId ?? "__global__"; + const key = sessionId; let listeners = pendingListeners.get(key); if (!listeners) { listeners = new Set(); @@ -115,14 +117,14 @@ function queuePendingListener(pendingListeners, webSocket, sessionId) { listeners.add(webSocket); webSocket.once("close", () => { listeners.delete(webSocket); - if (listeners.size === 0) pendingListeners.delete(sessionId ?? "__global__"); + if (listeners.size === 0) pendingListeners.delete(sessionId); }); return listeners; } function attachPendingListeners(session, pendingListeners) { const sessionKey = session.sessionId; - const globalKey = "__global__"; + const globalKey = null; const queued = new Set([ ...(pendingListeners.get(sessionKey) ?? []), ...(pendingListeners.get(globalKey) ?? []), @@ -150,15 +152,21 @@ function sendJson(response, status, body) { response.end(JSON.stringify(body)); } -async function waitForPublisherSession(sessions, timeoutMs = 5000) { +async function waitForPublisher(sessions, sessionId, timeoutMs = 5000) { const deadline = Date.now() + timeoutMs; while (Date.now() < deadline) { - for (const session of sessions.values()) { - if (session.publisher?.readyState === WS_OPEN) return session.sessionId; - } + const session = sessions.get(sessionId); + if (session?.publisher?.readyState === WS_OPEN) return true; await new Promise((resolve) => setTimeout(resolve, 50)); } - return null; + return false; +} + +function isLoopbackHost(host) { + const normalizedHost = String(host).toLowerCase().replace(/^\[|\]$/g, ""); + if (normalizedHost === "localhost" || normalizedHost.endsWith(".localhost") || normalizedHost === "::1") return true; + if (isIP(normalizedHost) === 4) return normalizedHost.startsWith("127."); + return false; } async function readJsonBody(request, maxBytes) { @@ -274,14 +282,30 @@ function attachPublisher(session, socket, sessions) { }); } -function createWebAudioGateway({ host = "127.0.0.1", port = 8080, token = process.env.WEB_AUDIO_TOKEN, onPlayQuery } = {}) { +function createWebAudioGateway({ + host = "127.0.0.1", + port = 8080, + token = process.env.WEB_AUDIO_TOKEN, + defaultSessionId, + onPlayQuery, +} = {}) { if (!token) throw new Error("Set WEB_AUDIO_TOKEN to a non-empty secret before starting the gateway"); if (!Number.isInteger(port) || port < 0 || port > 65535) throw new TypeError("port must be an integer from 0 to 65535"); + if (defaultSessionId !== undefined && (typeof defaultSessionId !== "string" || !defaultSessionId.trim() || defaultSessionId.length > 128)) { + throw new TypeError("defaultSessionId must be a non-empty string of at most 128 characters"); + } + if (!isLoopbackHost(host) && token === INSECURE_DEMO_TOKEN) { + throw new Error(`Refusing to bind to ${host} with the example token; set WEB_AUDIO_TOKEN to a unique secret first`); + } const sessions = new Map(); const pendingListeners = new Map(); const httpServer = createServer((request, response) => { const pathname = new URL(request.url ?? "/", "http://localhost").pathname; + if (request.method === "GET" && pathname === "/config") { + sendJson(response, 200, { defaultSessionId: defaultSessionId ?? null }); + return; + } if (request.method === "GET" && pathname === "/health") { response.writeHead(200, { "content-type": "application/json" }); response.end(JSON.stringify({ status: "ok", activeSessions: sessions.size })); @@ -312,7 +336,16 @@ function createWebAudioGateway({ host = "127.0.0.1", port = 8080, token = proces sendJson(response, 400, { error: "query must be a non-empty string of at most 500 characters" }); return; } - const result = await onPlayQuery(body.query.trim()); + const sessionId = body.sessionId ?? defaultSessionId; + if (typeof sessionId !== "string" || !sessionId.trim() || sessionId.length > 128) { + sendJson(response, 400, { error: "sessionId must identify the player that will handle this request" }); + return; + } + if (defaultSessionId && sessionId !== defaultSessionId) { + sendJson(response, 400, { error: "sessionId does not match the configured playback session" }); + return; + } + const result = await onPlayQuery(body.query.trim(), sessionId); if (result === null) { sendJson(response, 503, { error: "Player is not ready" }); return; @@ -321,7 +354,10 @@ function createWebAudioGateway({ host = "127.0.0.1", port = 8080, token = proces sendJson(response, 422, { error: "No playable track found for this query" }); return; } - const sessionId = await waitForPublisherSession(sessions); + if (!(await waitForPublisher(sessions, sessionId))) { + sendJson(response, 504, { error: `No audio publisher appeared for session ${sessionId}` }); + return; + } sendJson(response, 200, { sessionId, track: { diff --git a/examples/backend/index.js b/examples/backend/index.js index b81cdc03..716f0f6c 100644 --- a/examples/backend/index.js +++ b/examples/backend/index.js @@ -75,11 +75,13 @@ async function main() { const port = Number(process.env.PORT ?? 8080); const token = process.env.WEB_AUDIO_TOKEN; const trackQuery = process.env.TRACK_QUERY ?? process.argv.slice(2).join(" ").trim(); + const playerId = process.env.PLAYER_ID ?? "web-audio-demo"; let player; const gateway = createWebAudioGateway({ host, port, token, + defaultSessionId: playerId, onPlayQuery: (query) => (player ? player.play(query, { requestedBy: "client" }) : null), }); let manager; @@ -112,7 +114,6 @@ async function main() { console.error("ZiPlayer playback error:", error); }); - const playerId = process.env.PLAYER_ID ?? "web-audio-demo"; player = await manager.create(playerId, { audioOutputBackendFactory: createAudioOutputBackendFactory({ gatewayUrl, token }), audioProcessing: { diff --git a/examples/backend/test/gateway.test.js b/examples/backend/test/gateway.test.js index 3ae64e39..4cc89ecd 100644 --- a/examples/backend/test/gateway.test.js +++ b/examples/backend/test/gateway.test.js @@ -173,3 +173,56 @@ test("session-scoped next-listener routing keeps concurrent publishers isolated" await gateway.close(); } }); + +test("play waits for its requested session instead of returning another active publisher", async () => { + const gateway = createWebAudioGateway({ + host: "127.0.0.1", + port: 0, + token, + defaultSessionId: "requested-session", + onPlayQuery: async () => ({ track: { title: "Requested track", url: null } }), + }); + let unrelatedPublisher; + let requestedPublisher; + try { + const address = await gateway.listen(); + const origin = `http://127.0.0.1:${address.port}`; + const configResponse = await fetch(`${origin}/config`); + assert.equal(configResponse.status, 200); + assert.equal((await configResponse.json()).defaultSessionId, "requested-session"); + + unrelatedPublisher = new WebSocket( + `ws://127.0.0.1:${address.port}/publish?sessionId=unrelated-session&token=${token}`, + ); + await waitForOpen(unrelatedPublisher); + + const playResponsePromise = fetch(`${origin}/play`, { + method: "POST", + headers: { + "content-type": "application/json", + authorization: `Bearer ${token}`, + }, + body: JSON.stringify({ query: "requested track", sessionId: "requested-session" }), + }); + await new Promise((resolve) => setTimeout(resolve, 100)); + requestedPublisher = new WebSocket( + `ws://127.0.0.1:${address.port}/publish?sessionId=requested-session&token=${token}`, + ); + await waitForOpen(requestedPublisher); + + const playResponse = await playResponsePromise; + assert.equal(playResponse.status, 200); + assert.equal((await playResponse.json()).sessionId, "requested-session"); + } finally { + unrelatedPublisher?.close(); + requestedPublisher?.close(); + await gateway.close(); + } +}); + +test("the example token is rejected when binding outside loopback", () => { + assert.throws( + () => createWebAudioGateway({ host: "0.0.0.0", token: "change-this-local-token" }), + /refusing to bind.*unique secret/i, + ); +}); From 9ab98404810af49aaff2e4864c81bf03ce8701ef Mon Sep 17 00:00:00 2001 From: Ziji <104454302+zijipia@users.noreply.github.com> Date: Sun, 11 Oct 2026 01:22:06 +0900 Subject: [PATCH 15/55] Support tokenless gateway and player controls This change removes the demo token requirement from the browser WebSocket gateway, makes listener auth optional, and enforces loopback-only local deployment. The example backend now supports per-player session IDs, player-state queries, and playback control routing for pause/resume/seek/volume/filter actions. It also updates the browser client and TypeScript types to allow optional `token` values, adds tests for the new gateway and volume behavior, and implements backend-level PCM volume scaling in `WebSocketAudioOutputBackend` while reporting the capability as supported. --- client/README.md | 14 +- client/browser/index.js | 6 +- client/index.d.ts | 2 +- client/test/protocol.test.js | 47 ++++- .../src/output/WebSocketAudioOutputBackend.ts | 24 ++- examples/backend/.env.example | 4 - examples/backend/README.md | 47 +++-- examples/backend/client/client.js | 180 +++++++++++++++-- examples/backend/client/index.html | 119 +++++++++-- examples/backend/gateway.js | 170 ++++++++++++---- examples/backend/index.js | 143 ++++++++++--- examples/backend/test/gateway.test.js | 191 ++++++++++++++++-- .../backend/test/websocket_output.test.js | 47 +++++ 13 files changed, 834 insertions(+), 160 deletions(-) create mode 100644 examples/backend/test/websocket_output.test.js diff --git a/client/README.md b/client/README.md index 6d30c3da..5a810753 100644 --- a/client/README.md +++ b/client/README.md @@ -3,10 +3,13 @@ Small browser client for ZiPlayer's WebSocket PCM protocol. It validates the publisher configuration and binary frame headers, converts little-endian s16 stereo PCM to Float32, and plays it through an AudioWorklet with a bounded jitter buffer. -The package is only the receiving/playback client. Your Node.js application still needs an authenticated WebSocket gateway and a -ZiPlayer `WebSocketAudioOutputBackend` publisher. The gateway example in +The package is only the receiving/playback client and event source; it does not expose remote `pause`, `stop`, `seek`, or volume +methods. Your Node.js application still needs an authenticated WebSocket gateway and a ZiPlayer +`WebSocketAudioOutputBackend` publisher. Authentication is determined by your gateway; the `token` connect option is optional +for gateways that do not require it. Add playback controls to your own server API and bind them to the intended ZiPlayer player. +The gateway example in [`../examples/backend`](https://github.com/ZiProject/ZiPlayer/tree/main/examples/backend) shows a complete local setup with -search, publisher routing, and browser playback. +search, publisher routing, browser playback, queue display, and multi-player controls. ## Install and use @@ -53,8 +56,9 @@ await client.connect({ await fetch("/play", { method: "POST", body: JSON.stringify({ query }) }); ``` -The browser fills in `client.sessionId` when the next publisher sends `audio:config`. If a publisher is already active and you -want to join that live stream, pass its `sessionId` instead. Call `disconnect()` to release browser resources. +The `token` option is optional for gateways that do not require authentication; provide it when your server uses token-based +authentication. The browser fills in `client.sessionId` when the next publisher sends `audio:config`. If a publisher is already +active and you want to join that live stream, pass its `sessionId` instead. Call `disconnect()` to release browser resources. ## Events diff --git a/client/browser/index.js b/client/browser/index.js index 66cc6117..aaecfc86 100644 --- a/client/browser/index.js +++ b/client/browser/index.js @@ -184,7 +184,7 @@ export class WebAudioClient extends EventTarget { async connect({ gatewayUrl, token, sessionId, nextPublisher = false } = {}) { if (typeof gatewayUrl !== "string" || !gatewayUrl) throw new TypeError("gatewayUrl is required"); - if (typeof token !== "string" || !token) throw new TypeError("token is required"); + if (token !== undefined && typeof token !== "string") throw new TypeError("token must be a string when provided"); if (!nextPublisher && (typeof sessionId !== "string" || !sessionId || sessionId.length > 128)) { throw new TypeError("sessionId is required unless nextPublisher is enabled"); } @@ -193,7 +193,7 @@ export class WebAudioClient extends EventTarget { const url = new URL(nextPublisher ? "/listen-next" : "/listen", gatewayUrl); if (typeof sessionId === "string" && sessionId) url.searchParams.set("sessionId", sessionId); - url.searchParams.set("token", token); + if (token) url.searchParams.set("token", token); this.sessionId = nextPublisher ? null : sessionId; this.config = null; this.expectedSequence = null; @@ -228,7 +228,7 @@ export class WebAudioClient extends EventTarget { else resolve(); }; const onOpen = () => finish(); - const onError = () => finish(new Error("WebSocket listener connection failed; check gateway URL and token")); + const onError = () => finish(new Error("WebSocket listener connection failed; check the gateway URL and access policy")); const onClose = (event) => finish(new Error(`WebSocket listener closed before connecting (${event.code})`)); socket.addEventListener("open", onOpen, { once: true }); socket.addEventListener("error", onError, { once: true }); diff --git a/client/index.d.ts b/client/index.d.ts index 0819d3be..aa4552da 100644 --- a/client/index.d.ts +++ b/client/index.d.ts @@ -43,7 +43,7 @@ export interface WebAudioClientOptions { export interface WebAudioConnectOptions { gatewayUrl: string; - token: string; + token?: string; sessionId?: string; nextPublisher?: boolean; } diff --git a/client/test/protocol.test.js b/client/test/protocol.test.js index 24f43ea0..1fad72f2 100644 --- a/client/test/protocol.test.js +++ b/client/test/protocol.test.js @@ -1,6 +1,6 @@ import assert from "node:assert/strict"; import test from "node:test"; -import { decodePcmFrame, parseAudioConfig } from "../browser/index.js"; +import { decodePcmFrame, parseAudioConfig, WebAudioClient } from "../browser/index.js"; const config = { v: 1, @@ -53,3 +53,48 @@ test("PCM frame decoder rejects invalid headers and unaligned payloads", () => { const validFrame = new Uint8Array(frame(0)); assert.throws(() => decodePcmFrame(validFrame.slice(0, validFrame.length - 1).buffer, config), /invalid PCM/i); }); + +test("WebAudioClient can connect to a gateway that does not require a token", async () => { + const originalAudioWorkletNode = globalThis.AudioWorkletNode; + let socketUrl; + class FakeSocket extends EventTarget { + readyState = 1; + binaryType = ""; + close() { + this.readyState = 3; + } + } + class FakeAudioWorkletNode { + port = { postMessage() {} }; + connect() {} + disconnect() {} + } + globalThis.AudioWorkletNode = FakeAudioWorkletNode; + const client = new WebAudioClient({ + audioContextFactory: () => ({ + sampleRate: 48_000, + state: "running", + destination: {}, + audioWorklet: { async addModule() {} }, + async resume() {}, + async close() { + this.state = "closed"; + }, + }), + webSocketFactory: (url) => { + socketUrl = url; + const socket = new FakeSocket(); + queueMicrotask(() => socket.dispatchEvent(new Event("open"))); + return socket; + }, + }); + try { + await client.connect({ gatewayUrl: "ws://127.0.0.1:8080", sessionId: "player-1" }); + assert.equal(socketUrl.searchParams.get("sessionId"), "player-1"); + assert.equal(socketUrl.searchParams.has("token"), false); + } finally { + await client.disconnect(); + if (originalAudioWorkletNode === undefined) delete globalThis.AudioWorkletNode; + else globalThis.AudioWorkletNode = originalAudioWorkletNode; + } +}); diff --git a/core/src/output/WebSocketAudioOutputBackend.ts b/core/src/output/WebSocketAudioOutputBackend.ts index d6750580..d2f68371 100644 --- a/core/src/output/WebSocketAudioOutputBackend.ts +++ b/core/src/output/WebSocketAudioOutputBackend.ts @@ -168,6 +168,7 @@ class WebSocketAudioOutputHandle implements WebSocketAudioOutputHandleContract { private readonly signal?: AbortSignal; private socket: WebSocketLike | null = null; private sequence = 0; + private volume = 1; private sendingPromise: Promise | null = null; public completion: Promise = Promise.resolve(); private started = false; @@ -311,7 +312,10 @@ class WebSocketAudioOutputHandle implements WebSocketAudioOutputHandleContract { public setVolume(value: number, signal?: AbortSignal): void { assertNotAborted(this.signal, signal); - throw new AudioOutputUnsupportedOperationError("volume control; apply volume upstream"); + if (!Number.isFinite(value) || value < 0) { + throw new TypeError("volume must be a non-negative finite number"); + } + this.volume = value; } public onEvent(listener: (event: AudioOutputEvent) => void): () => void { @@ -374,7 +378,7 @@ class WebSocketAudioOutputHandle implements WebSocketAudioOutputHandleContract { const combined: Buffer = remainder.length > 0 ? Buffer.concat([remainder, nextChunk]) : nextChunk; const completeFrames = Math.floor(combined.length / frameBytes) * frameBytes; for (let offset = 0; offset < completeFrames; offset += frameBytes) { - const framePayload: Buffer = combined.subarray(offset, offset + frameBytes); + const framePayload = this.applyVolume(combined.subarray(offset, offset + frameBytes)); if (!(await this.sendFrame(framePayload, signal))) return; } remainder = combined.subarray(completeFrames) as Buffer; @@ -384,7 +388,7 @@ class WebSocketAudioOutputHandle implements WebSocketAudioOutputHandleContract { if (remainder.length % sampleBytes !== 0) { throw new Error("WebSocket audio stream ended with an incomplete PCM sample frame"); } - if (!(await this.sendFrame(remainder, signal))) return; + if (!(await this.sendFrame(this.applyVolume(remainder), signal))) return; } if (this.stopped || this.disposed || this.transportClosed) return; this.stateValue = "ended"; @@ -423,6 +427,18 @@ class WebSocketAudioOutputHandle implements WebSocketAudioOutputHandleContract { return this.format.channels * WEB_AUDIO_SAMPLE_BYTES; } + private applyVolume(payload: Buffer): Buffer { + const volume = this.volume; + if (volume === 1) return payload; + const output = Buffer.allocUnsafe(payload.length); + for (let offset = 0; offset < payload.length; offset += WEB_AUDIO_SAMPLE_BYTES) { + const sample = payload.readInt16LE(offset); + const amplified = Math.max(-32768, Math.min(32767, Math.round(sample * volume))); + output.writeInt16LE(amplified, offset); + } + return output; + } + private async sendFrame(payload: Uint8Array, signal?: AbortSignal): Promise { const socket = this.socket; if (!socket || this.stopped || this.disposed || this.transportClosed) return false; @@ -579,7 +595,7 @@ export class WebSocketAudioOutputBackend implements AudioOutputBackend. Enter the same token in the **Listener token** field, enter a track search or media URL, then click -**Search and play**. The page connects to the next audio stream before playback starts, so its first frames are not missed. Click +Open . Enter a track search or media URL, then click **Search and play**. The page connects to the next +audio stream before playback starts, so its first frames are not missed. Click **Disconnect** to stop listening and release browser audio resources. Press **Ctrl+C** in the terminal to stop the server. The browser's first play/search click also unlocks audio playback in browsers that require a user gesture. If the browser reports that it connected but PCM is silent, check the terminal for source/plugin errors and try a different query. -The page fetches the configured playback session ID from the gateway and uses it both for `/listen-next` and `/play`. These -session-scoped listeners wait for that exact publisher. A listener that manually connects to `/listen-next` without a -`sessionId` explicitly means “attach to whichever publisher connects next”; use a session ID whenever a specific player is -intended. +The example starts a default ZiPlayer whose ID is `PLAYER_ID` (default `web-audio-demo`). To add another independent player, enter +a different player ID in the browser and use **Search and play**. The gateway creates or reuses exactly one `PlayerManager` player +for that ID; valid IDs contain 1-128 letters, numbers, underscores, or hyphens (ZiPlayer's reserved ID is not allowed). The ID +is also the audio `sessionId`. Reuse that same ID to hear or control the player. The Gateway waits for the publisher for the +requested ID, not for whichever player publishes first. A session-scoped `/listen-next?sessionId=...` listener waits for that +player; omitting `sessionId` explicitly opts into whichever publisher connects next. + +Pause, resume, stop, skip, seek, volume, loop mode, autoplay, and filter requests include the selected player ID and are routed +to the matching `PlayerManager` instance. The `/player-state` endpoint supplies the current track, queue, related tracks, active +filters, and player settings displayed by the page. The reusable `@ziplayer/client` package remains an audio receiver and event +source, not a remote player-control API. Volume is applied to outgoing PCM; seeking requires a current track and a position +within its duration. A control that cannot be applied returns an error rather than a successful-looking response. You can optionally start a query automatically by adding `TRACK_QUERY` to `examples/backend/.env`: @@ -66,7 +73,7 @@ npm start --prefix examples/backend -- "https://www.youtube.com/watch?v=..." The example registers YouTube, SoundCloud, Spotify, attachments, and TTS source plugins with `PlayerManager`. It uses the regular ZiPlayer playback pipeline, but sends processed PCM through `WebSocketAudioOutputBackend` to the local gateway instead of Discord -Voice. The gateway authenticates the publisher and browser listener and forwards audio; the browser's reusable +Voice. The gateway forwards audio to browser listeners; the browser's reusable `@ziplayer/client` validates and plays it through an AudioWorklet. The page's session fields are available for manual connections if you want to listen to an already-running player. @@ -88,17 +95,15 @@ publisher from sending its first frames before the browser is subscribed. Configuration: -- `WEB_AUDIO_TOKEN` is required by both the gateway and publisher connection. - `TRACK_QUERY` or a command-line argument optionally starts an initial search query or media URL; otherwise, use the web page. - `HOST` and `PORT` control the HTTP/WebSocket listener (defaults: `127.0.0.1:8080`). - `GATEWAY_URL` overrides the WebSocket publisher URL if the public address differs from `HOST`. - `PLAYER_ID`, `REQUESTED_BY`, `TTS_LANGUAGE`, and `EXTRACTOR_TIMEOUT_MS` are optional. - -The page also accepts a session-scoped listener token, allowing a separate browser session to connect to `/listen`. +- `PLAYER_ID` selects the default player ID created at startup; additional IDs are created on demand through the browser's + **Search and play** form. ## Security -The shared token and query-string token handling are for local development only. Browser WebSocket APIs cannot set arbitrary -request headers, so the demo uses a query parameter for listener authentication. Do not expose a long-lived shared secret or run -this example on an untrusted network. Production deployments should use HTTPS/WSS, short-lived per-session credentials, and -session-scoped authorization in place of the demo token comparison. +This is an unauthenticated local example. The gateway rejects non-loopback bind addresses, but any local process or browser able +to reach it can control its players. Do not remove the loopback restriction or forward the port to an untrusted network without +adding application-appropriate authentication and authorization. diff --git a/examples/backend/client/client.js b/examples/backend/client/client.js index a8e182ee..262a14b6 100644 --- a/examples/backend/client/client.js +++ b/examples/backend/client/client.js @@ -3,9 +3,16 @@ import { WEB_AUDIO_CHANNELS, WEB_AUDIO_SAMPLE_RATE_HZ, WEB_AUDIO_SAMPLE_BYTES, W const connectForm = document.querySelector("#connect-form"); const gatewayUrlInput = document.querySelector("#gateway-url"); const sessionIdInput = document.querySelector("#session-id"); -const tokenInput = document.querySelector("#token"); const connectButton = document.querySelector("#connect"); const disconnectButton = document.querySelector("#disconnect"); +const pauseButton = document.querySelector("#pause"); +const resumeButton = document.querySelector("#resume"); +const stopPlaybackButton = document.querySelector("#stop-playback"); +const seekForm = document.querySelector("#seek-form"); +const seekPositionInput = document.querySelector("#seek-position"); +const volumeInput = document.querySelector("#volume"); +const volumeValue = document.querySelector("#volume-value"); +const controlStatusElement = document.querySelector("#control-status"); const statusElement = document.querySelector("#status"); const recordButton = document.querySelector("#record"); const downloadRecordingButton = document.querySelector("#download-recording"); @@ -15,6 +22,16 @@ const searchForm = document.querySelector("#search-form"); const searchQueryInput = document.querySelector("#search-query"); const searchButton = document.querySelector("#search"); const searchStatusElement = document.querySelector("#search-status"); +const currentTrackElement = document.querySelector("#current-track"); +const queueListElement = document.querySelector("#queue-list"); +const relatedListElement = document.querySelector("#related-list"); +const skipButton = document.querySelector("#skip"); +const loopModeSelect = document.querySelector("#loop-mode"); +const autoplayInput = document.querySelector("#autoplay"); +const filterSelect = document.querySelector("#filter-select"); +const applyFilterButton = document.querySelector("#apply-filter"); +const clearFiltersButton = document.querySelector("#clear-filters"); +const filterStatusElement = document.querySelector("#filter-status"); const BYTES_PER_SECOND = WEB_AUDIO_SAMPLE_RATE_HZ * WEB_AUDIO_CHANNELS * WEB_AUDIO_SAMPLE_BYTES; const MAX_RECORDING_BYTES = BYTES_PER_SECOND * 60 * 10; @@ -36,12 +53,14 @@ void playbackConfig.catch((error) => { const audioClient = new WebAudioClient(); let followsPublisher = false; +let listeningSessionId = null; let recordingActive = false; let recordedChunks = []; let recordedBytes = 0; let receivedPcmFrames = 0; let receivedPcmBytes = 0; let pcmWatchdog = null; +let currentActiveFilters = new Set(); function setStatus(message) { statusElement.textContent = message; @@ -51,6 +70,94 @@ function setSearchStatus(message) { searchStatusElement.textContent = message; } +function setControlStatus(message) { + controlStatusElement.textContent = message; +} + +async function sendPlaybackControl(action, values = {}) { + const sessionId = sessionIdInput.value.trim(); + if (!sessionId) throw new Error("Enter the player ID to control"); + const response = await fetch("/control", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ sessionId, action, ...values }), + }); + const result = await response.json(); + if (!response.ok) throw new Error(result.error || `Control request failed (${response.status})`); + setControlStatus(`${action} applied to ${result.sessionId}`); + await refreshPlayerState(); +} + +function reportControlError(error) { + console.error("Playback control failed:", error); + setControlStatus(`Control failed: ${error.message}`); +} + +function displayTrack(track) { + if (!track) return "No track"; + const duration = track.isLive ? "LIVE" : formatDuration((track.duration || 0) / 1000); + return `${track.title}${track.author ? ` — ${track.author}` : ""} (${duration})`; +} + +function renderTrackList(element, tracks, emptyMessage) { + element.replaceChildren(); + if (!tracks.length) { + const empty = document.createElement("li"); + empty.textContent = emptyMessage; + element.append(empty); + return; + } + for (const track of tracks) { + const item = document.createElement("li"); + item.textContent = displayTrack(track); + element.append(item); + } +} + +async function refreshPlayerState() { + const sessionId = sessionIdInput.value.trim(); + if (!sessionId) return; + try { + const response = await fetch(`/player-state?sessionId=${encodeURIComponent(sessionId)}`); + const state = await response.json(); + if (response.status === 404) { + currentTrackElement.textContent = "No player created yet"; + renderTrackList(queueListElement, [], "Queue is empty"); + renderTrackList(relatedListElement, [], "No related tracks"); + currentActiveFilters = new Set(); + filterSelect.replaceChildren(new Option("No player selected", "")); + filterStatusElement.textContent = "No player selected"; + loopModeSelect.value = "off"; + autoplayInput.checked = false; + volumeInput.value = "100"; + volumeValue.textContent = "100%"; + return; + } + if (!response.ok) throw new Error(state.error || `Player state request failed (${response.status})`); + currentTrackElement.textContent = displayTrack(state.currentTrack); + renderTrackList(queueListElement, state.tracks, "Queue is empty"); + renderTrackList(relatedListElement, state.related, "No related tracks"); + loopModeSelect.value = state.loopMode; + autoplayInput.checked = state.autoPlay; + volumeInput.value = String(state.volume); + volumeValue.textContent = `${state.volume}%`; + const activeNames = new Set(state.activeFilters.map((filter) => filter.name)); + currentActiveFilters = activeNames; + const selectedFilter = filterSelect.value; + filterSelect.replaceChildren(new Option("Select a filter", "")); + for (const filter of state.filters) { + filterSelect.add( + new Option(`${filter.description}${activeNames.has(filter.name) ? " (active)" : ""}`, filter.name), + ); + } + if (state.filters.some((filter) => filter.name === selectedFilter)) filterSelect.value = selectedFilter; + filterStatusElement.textContent = activeNames.size ? `Active: ${[...activeNames].join(", ")}` : "No active filters"; + } catch (error) { + console.error("Unable to load player state:", error); + filterStatusElement.textContent = `Unable to load player state: ${error.message}`; + } +} + function updateRecordingControls(message) { const isConfigured = audioClient.config !== null; if (message) recordingStatusElement.textContent = message; @@ -153,6 +260,7 @@ audioClient.addEventListener("statechange", ({ detail }) => { } if (detail.state === "disconnected") { followsPublisher = false; + listeningSessionId = null; clearTimeout(pcmWatchdog); pcmWatchdog = null; receivedPcmFrames = 0; @@ -190,16 +298,17 @@ audioClient.addEventListener("close", ({ detail }) => { console.warn(`Audio listener closed (${detail.code}${detail.reason ? `: ${detail.reason}` : ""})`); }); -async function connectToSession({ nextPublisher = false } = {}) { +async function connectToSession({ nextPublisher = false, sessionId = sessionIdInput.value.trim() } = {}) { connectButton.disabled = true; setStatus("Starting browser audio output…"); try { + if (sessionId) sessionIdInput.value = sessionId; await audioClient.connect({ gatewayUrl: gatewayUrlInput.value, - token: tokenInput.value, - sessionId: sessionIdInput.value, + sessionId, nextPublisher, }); + listeningSessionId = sessionId || null; return true; } catch (error) { console.error("Unable to connect Web audio client:", error); @@ -255,20 +364,17 @@ searchForm.addEventListener("submit", async (event) => { setSearchStatus("Searching with ZiPlayer plugins…"); try { const config = await playbackConfig; - const sessionId = sessionIdInput.value || config.defaultSessionId; - if (!sessionId) throw new Error("Enter the playback session ID before searching"); + const sessionId = sessionIdInput.value.trim() || config.defaultSessionId; + if (!sessionId) throw new Error("Enter the player ID for this playback session"); sessionIdInput.value = sessionId; - if (!(followsPublisher && audioClient.state === "connected")) { + if (!(followsPublisher && audioClient.state === "connected" && listeningSessionId === sessionId)) { if (audioClient.state !== "disconnected") await audioClient.disconnect(); - const listenerReady = await connectToSession({ nextPublisher: true }); + const listenerReady = await connectToSession({ nextPublisher: true, sessionId }); if (!listenerReady) throw new Error("Could not connect a listener before starting playback"); } const response = await fetch("/play", { method: "POST", - headers: { - "content-type": "application/json", - authorization: `Bearer ${tokenInput.value}`, - }, + headers: { "content-type": "application/json" }, body: JSON.stringify({ query: searchQueryInput.value, sessionId }), }); const result = await response.json(); @@ -278,6 +384,7 @@ searchForm.addEventListener("submit", async (event) => { throw new Error("The audio publisher session did not match the listener session"); } setSearchStatus(`Added to playback: ${result.track.title}`); + await refreshPlayerState(); if (result.track.url) console.info(`Selected track: ${result.track.title} (${result.track.url})`); } catch (error) { console.error("Web track search failed:", error); @@ -287,4 +394,53 @@ searchForm.addEventListener("submit", async (event) => { } }); +pauseButton.addEventListener("click", () => void sendPlaybackControl("pause").catch(reportControlError)); +resumeButton.addEventListener("click", () => void sendPlaybackControl("resume").catch(reportControlError)); +stopPlaybackButton.addEventListener("click", () => void sendPlaybackControl("stop").catch(reportControlError)); +skipButton.addEventListener("click", () => void sendPlaybackControl("skip").catch(reportControlError)); +seekForm.addEventListener("submit", (event) => { + event.preventDefault(); + const seconds = Number(seekPositionInput.value); + if (!Number.isFinite(seconds) || seconds < 0) { + setControlStatus("Seek position must be a non-negative number of seconds."); + return; + } + void sendPlaybackControl("seek", { positionMs: seconds * 1000 }).catch(reportControlError); +}); +volumeInput.addEventListener("input", () => { + volumeValue.textContent = `${volumeInput.value}%`; +}); +volumeInput.addEventListener("change", () => { + void sendPlaybackControl("volume", { volume: Number(volumeInput.value) }).catch(reportControlError); +}); +loopModeSelect.addEventListener("change", () => { + void sendPlaybackControl("loop", { mode: loopModeSelect.value }).catch(reportControlError); +}); +autoplayInput.addEventListener("change", () => { + void sendPlaybackControl("autoplay", { enabled: autoplayInput.checked }).catch(reportControlError); +}); +applyFilterButton.addEventListener("click", () => { + const filterName = filterSelect.value; + if (!filterName) { + filterStatusElement.textContent = "Choose a filter first."; + return; + } + const isActive = currentActiveFilters.has(filterName); + void sendPlaybackControl("filter", { filterName, enabled: !isActive }) + .then(() => { + filterStatusElement.textContent = `${isActive ? "Removed" : "Applied"} ${filterName}`; + }) + .catch(reportControlError); +}); +clearFiltersButton.addEventListener("click", () => { + void sendPlaybackControl("filter-clear") + .then(() => { + filterStatusElement.textContent = "Cleared all filters"; + }) + .catch(reportControlError); +}); +sessionIdInput.addEventListener("change", () => void refreshPlayerState()); +void refreshPlayerState(); +setInterval(() => void refreshPlayerState(), 3000); + window.addEventListener("beforeunload", () => void audioClient.disconnect()); diff --git a/examples/backend/client/index.html b/examples/backend/client/index.html index 6c3b607a..2ef00551 100644 --- a/examples/backend/client/index.html +++ b/examples/backend/client/index.html @@ -36,6 +36,7 @@ } input, + select, button { box-sizing: border-box; width: 100%; @@ -50,6 +51,15 @@ color: inherit; } + select { + background: #111827; + color: inherit; + } + + input[type="checkbox"] { + width: auto; + } + button { border: 0; background: #2563eb; @@ -67,11 +77,49 @@ background: #4b5563; } + #controls { + display: grid; + gap: 0.75rem; + padding: 1rem; + border: 1px solid #374151; + border-radius: 0.75rem; + background: #1f2937; + } + + #player-state { + display: grid; + gap: 0.75rem; + margin: 1rem 0; + padding: 1rem; + border: 1px solid #374151; + border-radius: 0.75rem; + background: #1f2937; + } + + #player-state ul { + margin: 0.25rem 0; + padding-left: 1.25rem; + } + + #player-state li { + margin: 0.35rem 0; + } + + #controls button, + #controls input { + margin-top: 0.35rem; + } + #download-recording, #clear-recording { background: #4b5563; } + #control-status { + min-height: 1.5em; + color: #fbbf24; + } + #status { min-height: 1.5em; color: #93c5fd; @@ -91,7 +139,10 @@

ZiPlayer Web Audio

-

Search for a track through the configured ZiPlayer source plugins, then connect to its live PCM stream.

+

+ Each player ID is an independent ZiPlayer session. Enter the same ID to play, listen, or control that player's stream; + enter a new ID and choose Search and play to create another player. +