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
-
- 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.
-
+ This example binds to loopback only and does not provide authentication. Do not expose it to a network.
diff --git a/examples/backend/gateway.js b/examples/backend/gateway.js
index e6fb7610..e840ff62 100644
--- a/examples/backend/gateway.js
+++ b/examples/backend/gateway.js
@@ -1,9 +1,7 @@
"use strict";
-// Authenticates publisher/listener sockets and relays PCM to browser clients.
-// For production, use HTTPS/WSS and short-lived per-session tokens.
+// Relays PCM to browser clients; the example intentionally binds to loopback only.
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");
@@ -18,20 +16,14 @@ 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 RESERVED_SESSION_ID = "__ziplayer_search__";
+const SESSION_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/;
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`);
}
@@ -47,12 +39,15 @@ function readRequest(request) {
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");
+ return { role, sessionId: sessionId ?? null };
+}
+
+function isValidSessionId(sessionId) {
+ return typeof sessionId === "string" && sessionId !== RESERVED_SESSION_ID && SESSION_ID_PATTERN.test(sessionId);
+}
- return { role, sessionId: sessionId ?? null, token };
+function invalidSessionIdMessage() {
+ return "sessionId must contain 1-128 letters, numbers, underscores, or hyphens and cannot use ZiPlayer's reserved ID";
}
function isAudioConfig(message, sessionId) {
@@ -285,18 +280,16 @@ function attachPublisher(session, socket, sessions) {
function createWebAudioGateway({
host = "127.0.0.1",
port = 8080,
- token = process.env.WEB_AUDIO_TOKEN,
defaultSessionId,
onPlayQuery,
+ onControl,
+ onGetPlayerState,
} = {}) {
- 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`);
+ if (defaultSessionId !== undefined && !isValidSessionId(defaultSessionId)) {
+ throw new TypeError(invalidSessionIdMessage());
}
+ if (!isLoopbackHost(host)) throw new Error(`The example gateway only supports loopback hosts; refusing to bind to ${host}`);
const sessions = new Map();
const pendingListeners = new Map();
@@ -311,14 +304,124 @@ function createWebAudioGateway({
response.end(JSON.stringify({ status: "ok", activeSessions: sessions.size }));
return;
}
- if (request.method === "POST" && pathname === "/play") {
+ if (request.method === "GET" && pathname === "/player-state") {
void (async () => {
- const authorization = request.headers.authorization ?? "";
- if (!authorization.startsWith("Bearer ") || !equalSecret(authorization.slice("Bearer ".length), token)) {
- sendJson(response, 401, { error: "Unauthorized" });
+ const sessionId = new URL(request.url ?? "/", "http://localhost").searchParams.get("sessionId");
+ if (!isValidSessionId(sessionId)) {
+ sendJson(response, 400, { error: invalidSessionIdMessage() });
+ return;
+ }
+ if (typeof onGetPlayerState !== "function") {
+ sendJson(response, 503, { error: "Player state is not available" });
+ return;
+ }
+ try {
+ const state = await onGetPlayerState(sessionId);
+ if (state === null) {
+ sendJson(response, 404, { error: `No player exists for session ${sessionId}` });
+ return;
+ }
+ sendJson(response, 200, { sessionId, ...state });
+ } catch (error) {
+ const statusCode = error && typeof error === "object" ? error.statusCode : undefined;
+ if (statusCode) {
+ sendJson(response, statusCode, { error: error.message });
+ return;
+ }
+ console.error("Web player state request failed:", error);
+ sendJson(response, 500, { error: "Player state request failed" });
+ }
+ })();
+ return;
+ }
+ if (request.method === "POST" && pathname === "/control") {
+ void (async () => {
+ if (request.headers["content-type"]?.split(";")[0] !== "application/json") {
+ sendJson(response, 415, { error: "Content-Type must be application/json" });
request.resume();
return;
}
+ if (typeof onControl !== "function") {
+ sendJson(response, 503, { error: "Playback controls are not available" });
+ request.resume();
+ return;
+ }
+ try {
+ const body = await readJsonBody(request, 4096);
+ if (!body || typeof body !== "object" || Array.isArray(body) || !isValidSessionId(body.sessionId)) {
+ sendJson(response, 400, { error: invalidSessionIdMessage() });
+ return;
+ }
+ const { action } = body;
+ const supportedActions = [
+ "pause",
+ "resume",
+ "stop",
+ "skip",
+ "seek",
+ "volume",
+ "loop",
+ "autoplay",
+ "filter",
+ "filter-clear",
+ ];
+ if (!supportedActions.includes(action)) {
+ sendJson(response, 400, { error: "Unsupported playback control action" });
+ return;
+ }
+ if (action === "seek" && (!Number.isFinite(body.positionMs) || body.positionMs < 0)) {
+ sendJson(response, 400, { error: "positionMs must be a non-negative number" });
+ return;
+ }
+ if (action === "volume" && (!Number.isFinite(body.volume) || body.volume < 0 || body.volume > 200)) {
+ sendJson(response, 400, { error: "volume must be a number from 0 to 200" });
+ return;
+ }
+ if (action === "loop" && !["off", "track", "queue"].includes(body.mode)) {
+ sendJson(response, 400, { error: "mode must be off, track, or queue" });
+ return;
+ }
+ if (action === "autoplay" && typeof body.enabled !== "boolean") {
+ sendJson(response, 400, { error: "enabled must be a boolean" });
+ return;
+ }
+ if (
+ action === "filter" &&
+ (typeof body.filterName !== "string" || !body.filterName.trim() || body.filterName.length > 100)
+ ) {
+ sendJson(response, 400, { error: "filterName must be a non-empty string of at most 100 characters" });
+ return;
+ }
+ if (action === "filter" && typeof body.enabled !== "boolean") {
+ sendJson(response, 400, { error: "enabled must be a boolean" });
+ return;
+ }
+ const result = await onControl(action, body, body.sessionId);
+ if (result === null) {
+ sendJson(response, 503, { error: "Player is not ready" });
+ return;
+ }
+ if (result === false) {
+ sendJson(response, 409, {
+ error: `${action} was not applied; check that the player has an active track and supports this operation`,
+ });
+ return;
+ }
+ sendJson(response, 200, { sessionId: body.sessionId, action, result: result ?? 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 control failed:", error);
+ if (!response.destroyed) sendJson(response, 500, { error: "Playback control failed" });
+ }
+ })();
+ return;
+ }
+ if (request.method === "POST" && pathname === "/play") {
+ void (async () => {
if (request.headers["content-type"]?.split(";")[0] !== "application/json") {
sendJson(response, 415, { error: "Content-Type must be application/json" });
request.resume();
@@ -337,12 +440,8 @@ function createWebAudioGateway({
return;
}
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" });
+ if (!isValidSessionId(sessionId)) {
+ sendJson(response, 400, { error: invalidSessionIdMessage() });
return;
}
const result = await onPlayQuery(body.query.trim(), sessionId);
@@ -409,11 +508,6 @@ function createWebAudioGateway({
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");
diff --git a/examples/backend/index.js b/examples/backend/index.js
index 716f0f6c..3ffcbee2 100644
--- a/examples/backend/index.js
+++ b/examples/backend/index.js
@@ -1,6 +1,6 @@
"use strict";
-// Run `npm run build:core` and set WEB_AUDIO_TOKEN before starting the example.
+// Run `npm run build:core` before starting the loopback-only example.
require("dotenv").config();
const { WebSocket } = require("ws");
const { PlayerManager, WebSocketAudioOutputBackend } = require("ziplayer");
@@ -8,9 +8,8 @@ const { createWebAudioGateway } = require("./gateway");
const SAMPLE_RATE_HZ = 48_000;
const CHANNELS = 2;
-function createPublisherSocketFactory({ gatewayUrl, token }) {
+function createPublisherSocketFactory({ gatewayUrl }) {
if (!gatewayUrl) throw new TypeError("gatewayUrl is required");
- if (!token) throw new TypeError("token is required");
return ({ sessionId, signal }) =>
new Promise((resolve, reject) => {
@@ -27,7 +26,7 @@ function createPublisherSocketFactory({ gatewayUrl, token }) {
const url = new URL("/publish", gatewayUrl);
url.searchParams.set("sessionId", sessionId);
- const socket = new WebSocket(url, { headers: { authorization: `Bearer ${token}` } });
+ const socket = new WebSocket(url);
const cleanup = () => {
socket.off("open", onOpen);
socket.off("error", onError);
@@ -65,30 +64,126 @@ function createAudioOutputBackendFactory(options) {
return ({ playerId }) =>
new WebSocketAudioOutputBackend({
socketFactory,
- authorize: ({ sessionId }) => Boolean(sessionId),
sessionId: playerId,
});
}
+function serializeTrack(track) {
+ if (!track) return null;
+ return {
+ title: track.title ?? "Untitled",
+ url: track.url ?? null,
+ duration: track.duration ?? 0,
+ thumbnail: track.thumbnail ?? null,
+ author: track.author ?? null,
+ source: track.source ?? null,
+ isLive: Boolean(track.isLive),
+ };
+}
+
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();
const playerId = process.env.PLAYER_ID ?? "web-audio-demo";
- let player;
+ let manager;
+ let gatewayUrl;
const gateway = createWebAudioGateway({
host,
port,
- token,
defaultSessionId: playerId,
- onPlayQuery: (query) => (player ? player.play(query, { requestedBy: "client" }) : null),
+ onPlayQuery: async (query, sessionId) => {
+ if (!manager) return null;
+ const player = await getOrCreatePlayer(sessionId);
+ return player.play(query, { requestedBy: process.env.REQUESTED_BY ?? "client" });
+ },
+ onControl: (action, body, sessionId) => {
+ const player = manager?.getPlayer(sessionId);
+ if (!player) throw Object.assign(new Error(`No player exists for session ${sessionId}`), { statusCode: 404 });
+ switch (action) {
+ case "pause":
+ return player.pause();
+ case "resume":
+ return player.resume();
+ case "stop":
+ return player.stop();
+ case "skip":
+ return player.skip();
+ case "seek":
+ return player.seek(body.positionMs);
+ case "volume":
+ return player.setVolume(body.volume);
+ case "loop":
+ return player.loop(body.mode);
+ case "autoplay":
+ return player.autoPlay(body.enabled);
+ case "filter": {
+ const available = player.filter.getAvailableFilters().some((filter) => filter.name === body.filterName);
+ if (!available) {
+ throw Object.assign(new Error(`Unknown filter: ${body.filterName}`), { statusCode: 400 });
+ }
+ return body.enabled ? player.filter.applyFilter(body.filterName) : player.filter.removeFilter(body.filterName);
+ }
+ case "filter-clear":
+ return player.filter.clearFilters();
+ }
+ },
+ onGetPlayerState: (sessionId) => {
+ const player = manager?.getPlayer(sessionId);
+ if (!player) return null;
+ const toFilterSummary = (filter) => ({
+ name: filter.name,
+ description: filter.description,
+ });
+ return {
+ currentTrack: serializeTrack(player.currentTrack),
+ tracks: player.upcomingTracks.map(serializeTrack),
+ related: player.relatedTracks.map(serializeTrack),
+ loopMode: player.loop(),
+ autoPlay: player.autoPlay(),
+ volume: player.volume,
+ filters: player.filter.getAvailableFilters().map(toFilterSummary),
+ activeFilters: player.filter.getActiveFilters().map(toFilterSummary),
+ };
+ },
});
- let manager;
let shuttingDown = false;
+ async function getOrCreatePlayer(sessionId) {
+ let player = manager.getPlayer(sessionId);
+ if (!player) {
+ player = await manager.create(sessionId, {
+ audioOutputBackendFactory: createAudioOutputBackendFactory({ gatewayUrl }),
+ audioProcessing: {
+ enabled: true,
+ inputFormat: "encoded",
+ outputFormat: "pcm16le",
+ sampleRate: SAMPLE_RATE_HZ,
+ channels: CHANNELS,
+ },
+ preload: { enabled: false },
+ crossfade: { enabled: false },
+ userdata: { webAudioGateway: { sessionId } },
+ });
+ }
+ player.userdata ??= {};
+ const webAudioMetadata = player.userdata.webAudioGateway ?? {};
+ if (webAudioMetadata.listenersAttached) return player;
+ player.userdata.webAudioGateway = { ...webAudioMetadata, sessionId, listenersAttached: true };
+ player.on("streamError", (error, track) => {
+ console.error(
+ `ZiPlayer stream/output error for session ${sessionId}${track?.title ? ` (${track.title})` : ""}:`,
+ error,
+ );
+ });
+ player.on("playerError", (error, track) => {
+ console.error(`ZiPlayer track error for session ${sessionId}${track?.title ? ` (${track.title})` : ""}:`, error);
+ });
+ console.info(`Web Audio configured for session "${sessionId}"`);
+ return player;
+ }
try {
const address = await gateway.listen();
- const gatewayUrl =
+ 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 = [
@@ -114,28 +209,10 @@ async function main() {
console.error("ZiPlayer playback error:", error);
});
- 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 defaultPlayer = await getOrCreatePlayer(playerId);
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`);
+ console.info(`Starting default ZiPlayer session "${playerId}" with ${plugins.length} plugins`);
const shutdown = async (signal) => {
if (shuttingDown) return;
shuttingDown = true;
@@ -148,9 +225,9 @@ async function main() {
};
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.");
+ console.info("Enter any valid player ID in the browser to create or select its independent playback session.");
if (trackQuery) {
- const result = await player.play(trackQuery, { requestedBy });
+ const result = await defaultPlayer.play(trackQuery, { requestedBy });
if (!result) throw new Error(`ZiPlayer could not start playback for query: ${trackQuery}`);
}
} catch (error) {
diff --git a/examples/backend/test/gateway.test.js b/examples/backend/test/gateway.test.js
index 4cc89ecd..a8cb670c 100644
--- a/examples/backend/test/gateway.test.js
+++ b/examples/backend/test/gateway.test.js
@@ -6,8 +6,6 @@ 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);
@@ -26,7 +24,7 @@ function waitForMessage(socket) {
}
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 });
+ const gateway = createWebAudioGateway({ host: "127.0.0.1", port: 0 });
let listener;
let publisher;
let replacementPublisher;
@@ -46,10 +44,10 @@ test("a next-track listener receives the publisher config and first PCM frame",
assert.equal(audioClient.status, 200);
assert.match(await audioClient.text(), /class WebAudioClient/);
- listener = new WebSocket(`${gatewayUrl}/listen-next?token=${token}`);
+ listener = new WebSocket(`${gatewayUrl}/listen-next`);
await waitForOpen(listener);
- publisher = new WebSocket(`${gatewayUrl}/publish?sessionId=gateway-test-session&token=${token}`);
+ publisher = new WebSocket(`${gatewayUrl}/publish?sessionId=gateway-test-session`);
await waitForOpen(publisher);
const configMessage = waitForMessage(listener);
@@ -79,7 +77,7 @@ test("a next-track listener receives the publisher config and first PCM frame",
const publisherClosed = new Promise((resolve) => publisher.once("close", resolve));
publisher.close();
await publisherClosed;
- replacementPublisher = new WebSocket(`${gatewayUrl}/publish?sessionId=gateway-test-session&token=${token}`);
+ replacementPublisher = new WebSocket(`${gatewayUrl}/publish?sessionId=gateway-test-session`);
await waitForOpen(replacementPublisher);
const replacementConfigMessage = waitForMessage(listener);
@@ -114,7 +112,7 @@ test("a next-track listener receives the publisher config and first PCM frame",
});
test("session-scoped next-listener routing keeps concurrent publishers isolated", async () => {
- const gateway = createWebAudioGateway({ host: "127.0.0.1", port: 0, token });
+ const gateway = createWebAudioGateway({ host: "127.0.0.1", port: 0 });
let alphaListener;
let betaListener;
let alphaPublisher;
@@ -122,11 +120,11 @@ test("session-scoped next-listener routing keeps concurrent publishers isolated"
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}`);
+ alphaListener = new WebSocket(`${gatewayUrl}/listen-next?sessionId=alpha-session`);
+ betaListener = new WebSocket(`${gatewayUrl}/listen-next?sessionId=beta-session`);
await Promise.all([waitForOpen(alphaListener), waitForOpen(betaListener)]);
- alphaPublisher = new WebSocket(`${gatewayUrl}/publish?sessionId=alpha-session&token=${token}`);
+ alphaPublisher = new WebSocket(`${gatewayUrl}/publish?sessionId=alpha-session`);
await waitForOpen(alphaPublisher);
const alphaConfigMessage = waitForMessage(alphaListener);
alphaPublisher.send(
@@ -145,7 +143,7 @@ test("session-scoped next-listener routing keeps concurrent publishers isolated"
const alphaConfig = await alphaConfigMessage;
assert.equal(JSON.parse(alphaConfig.data.toString()).sessionId, "alpha-session");
- betaPublisher = new WebSocket(`${gatewayUrl}/publish?sessionId=beta-session&token=${token}`);
+ betaPublisher = new WebSocket(`${gatewayUrl}/publish?sessionId=beta-session`);
await waitForOpen(betaPublisher);
const betaConfigMessage = waitForMessage(betaListener);
betaPublisher.send(
@@ -175,12 +173,15 @@ test("session-scoped next-listener routing keeps concurrent publishers isolated"
});
test("play waits for its requested session instead of returning another active publisher", async () => {
+ const playCalls = [];
const gateway = createWebAudioGateway({
host: "127.0.0.1",
port: 0,
- token,
defaultSessionId: "requested-session",
- onPlayQuery: async () => ({ track: { title: "Requested track", url: null } }),
+ onPlayQuery: async (query, sessionId) => {
+ playCalls.push({ query, sessionId });
+ return { track: { title: "Requested track", url: null } };
+ },
});
let unrelatedPublisher;
let requestedPublisher;
@@ -192,7 +193,7 @@ test("play waits for its requested session instead of returning another active p
assert.equal((await configResponse.json()).defaultSessionId, "requested-session");
unrelatedPublisher = new WebSocket(
- `ws://127.0.0.1:${address.port}/publish?sessionId=unrelated-session&token=${token}`,
+ `ws://127.0.0.1:${address.port}/publish?sessionId=unrelated-session`,
);
await waitForOpen(unrelatedPublisher);
@@ -200,19 +201,19 @@ test("play waits for its requested session instead of returning another active p
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}`,
+ `ws://127.0.0.1:${address.port}/publish?sessionId=requested-session`,
);
await waitForOpen(requestedPublisher);
const playResponse = await playResponsePromise;
assert.equal(playResponse.status, 200);
assert.equal((await playResponse.json()).sessionId, "requested-session");
+ assert.deepEqual(playCalls, [{ query: "requested track", sessionId: "requested-session" }]);
} finally {
unrelatedPublisher?.close();
requestedPublisher?.close();
@@ -220,9 +221,157 @@ test("play waits for its requested session instead of returning another active p
}
});
-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,
- );
+test("the example gateway only binds to loopback", () => {
+ assert.throws(() => createWebAudioGateway({ host: "0.0.0.0" }), /only supports loopback/i);
+});
+
+test("playback controls are routed to the requested player session without a demo token", async () => {
+ const controlCalls = [];
+ const gateway = createWebAudioGateway({
+ host: "127.0.0.1",
+ port: 0,
+ defaultSessionId: "single-player",
+ onControl: (action, body, sessionId) => {
+ controlCalls.push({ action, body, sessionId });
+ return true;
+ },
+ });
+ try {
+ const address = await gateway.listen();
+ const url = `http://127.0.0.1:${address.port}/control`;
+ const sendControl = (body) =>
+ fetch(url, {
+ method: "POST",
+ headers: {
+ "content-type": "application/json",
+ },
+ body: JSON.stringify(body),
+ });
+
+ const pause = await sendControl({ sessionId: "single-player", action: "pause" });
+ assert.equal(pause.status, 200);
+ assert.deepEqual(await pause.json(), { sessionId: "single-player", action: "pause", result: true });
+ assert.equal(controlCalls[0].sessionId, "single-player");
+
+ const seek = await sendControl({ sessionId: "second-player", action: "seek", positionMs: 1250 });
+ assert.equal(seek.status, 200);
+ assert.deepEqual(controlCalls[1], {
+ action: "seek",
+ body: { sessionId: "second-player", action: "seek", positionMs: 1250 },
+ sessionId: "second-player",
+ });
+
+ assert.equal((await sendControl({ sessionId: "single-player", action: "volume", volume: 201 })).status, 400);
+ assert.equal(controlCalls.length, 2);
+ } finally {
+ await gateway.close();
+ }
+});
+
+test("playback controls report unsuccessful operations instead of returning success", async () => {
+ const gateway = createWebAudioGateway({
+ host: "127.0.0.1",
+ port: 0,
+ onControl: () => false,
+ });
+ try {
+ const address = await gateway.listen();
+ const response = await fetch(`http://127.0.0.1:${address.port}/control`, {
+ method: "POST",
+ headers: {
+ "content-type": "application/json",
+ },
+ body: JSON.stringify({ sessionId: "test-player", action: "pause" }),
+ });
+ assert.equal(response.status, 409);
+ assert.match((await response.json()).error, /pause was not applied/);
+ } finally {
+ await gateway.close();
+ }
+});
+
+test("the player-state endpoint returns the requested player's queue and controls", async () => {
+ const gateway = createWebAudioGateway({
+ host: "127.0.0.1",
+ port: 0,
+ onGetPlayerState: (sessionId) => ({
+ currentTrack: { title: `${sessionId} current` },
+ tracks: [{ title: `${sessionId} queued` }],
+ related: [],
+ loopMode: "queue",
+ autoPlay: true,
+ volume: 85,
+ filters: [],
+ activeFilters: [],
+ }),
+ });
+ try {
+ const address = await gateway.listen();
+ const response = await fetch(
+ `http://127.0.0.1:${address.port}/player-state?sessionId=second-player`,
+ );
+ assert.equal(response.status, 200);
+ assert.deepEqual(await response.json(), {
+ sessionId: "second-player",
+ currentTrack: { title: "second-player current" },
+ tracks: [{ title: "second-player queued" }],
+ related: [],
+ loopMode: "queue",
+ autoPlay: true,
+ volume: 85,
+ filters: [],
+ activeFilters: [],
+ });
+ assert.equal(
+ (await fetch(`http://127.0.0.1:${address.port}/player-state?sessionId=bad%2Fid`)).status,
+ 400,
+ );
+ } finally {
+ await gateway.close();
+ }
+});
+
+test("queue, loop, autoplay, and filter controls are validated and routed", async () => {
+ const controlCalls = [];
+ const gateway = createWebAudioGateway({
+ host: "127.0.0.1",
+ port: 0,
+ onControl: (action, body, sessionId) => {
+ controlCalls.push({ action, body, sessionId });
+ return true;
+ },
+ });
+ try {
+ const address = await gateway.listen();
+ const send = (body) =>
+ fetch(`http://127.0.0.1:${address.port}/control`, {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ sessionId: "player-a", ...body }),
+ });
+ for (const body of [
+ { action: "skip" },
+ { action: "loop", mode: "queue" },
+ { action: "autoplay", enabled: true },
+ { action: "filter", filterName: "bassboost", enabled: true },
+ { action: "filter-clear" },
+ ]) {
+ assert.equal((await send(body)).status, 200);
+ }
+ assert.deepEqual(
+ controlCalls.map(({ action, sessionId }) => ({ action, sessionId })),
+ [
+ { action: "skip", sessionId: "player-a" },
+ { action: "loop", sessionId: "player-a" },
+ { action: "autoplay", sessionId: "player-a" },
+ { action: "filter", sessionId: "player-a" },
+ { action: "filter-clear", sessionId: "player-a" },
+ ],
+ );
+ assert.equal((await send({ action: "loop", mode: "invalid" })).status, 400);
+ assert.equal((await send({ action: "autoplay", enabled: "yes" })).status, 400);
+ assert.equal((await send({ action: "filter", filterName: "", enabled: true })).status, 400);
+ } finally {
+ await gateway.close();
+ }
});
diff --git a/examples/backend/test/websocket_output.test.js b/examples/backend/test/websocket_output.test.js
new file mode 100644
index 00000000..63cbb269
--- /dev/null
+++ b/examples/backend/test/websocket_output.test.js
@@ -0,0 +1,47 @@
+"use strict";
+
+const assert = require("node:assert/strict");
+const { Readable } = require("node:stream");
+const test = require("node:test");
+const { WebSocketAudioOutputBackend, decodeWebAudioFrame, webAudioFormatFromPcm } = require("ziplayer");
+
+test("the WebSocket audio output applies dynamic volume to PCM frames", async () => {
+ const messages = [];
+ const socket = {
+ readyState: 1,
+ bufferedAmount: 0,
+ send(message) {
+ messages.push(message);
+ },
+ close() {
+ this.readyState = 3;
+ },
+ };
+ const backend = new WebSocketAudioOutputBackend({
+ sessionId: "volume-test",
+ socketFactory: () => socket,
+ });
+ const handle = backend.createSession({
+ stream: Readable.from([Buffer.from([0x20, 0x4e, 0xe0, 0xb1, 0x00, 0x7d, 0x00, 0x83])]),
+ format: webAudioFormatFromPcm({}),
+ ownership: "borrow",
+ });
+
+ try {
+ assert.equal(backend.capabilities.volume, "backend");
+ handle.setVolume(1.5);
+ await handle.start();
+ await handle.completion;
+
+ const frame = messages.find((message) => typeof message !== "string");
+ assert.ok(frame);
+ const { payload } = decodeWebAudioFrame(frame);
+ const pcm = Buffer.from(payload);
+ assert.deepEqual(
+ [0, 2, 4, 6].map((offset) => pcm.readInt16LE(offset)),
+ [30000, -30000, 32767, -32768],
+ );
+ } finally {
+ await backend.dispose();
+ }
+});
From 429e6c76d703523cdb698b1c6f4e32ba2757e997 Mon Sep 17 00:00:00 2001
From: Ziji <104454302+zijipia@users.noreply.github.com>
Date: Sun, 11 Oct 2026 01:41:47 +0900
Subject: [PATCH 16/55] Fix preload and listener cleanup
This change makes preload requests complete gracefully when no track is ready, adds per-session listener count notifications and idle player cleanup in the backend gateway, and ensures audio pipelines accept Node Readable streams. It also updates websocket backend capability behavior and regression tests covering disabled-preload, listener-count, and volume handling.
---
core/src/audio/AudioProcessingEngine.ts | 10 ++--
core/src/controller/PreloadController.ts | 10 +++-
core/src/structures/PreloadManager.ts | 17 +++---
core/src/structures/TrackLoader.ts | 4 +-
examples/backend/README.md | 4 +-
examples/backend/gateway.js | 16 ++++--
examples/backend/index.js | 41 ++++++++++++++
examples/backend/test/gateway.test.js | 71 ++++++++++++++++++++++++
tests/audio_output_backend.test.js | 29 ++++++++++
tests/audio_processing_engine.test.js | 22 +++++++-
tests/web_audio_output_backend.test.js | 6 +-
11 files changed, 202 insertions(+), 28 deletions(-)
diff --git a/core/src/audio/AudioProcessingEngine.ts b/core/src/audio/AudioProcessingEngine.ts
index 0f69d695..520e1487 100644
--- a/core/src/audio/AudioProcessingEngine.ts
+++ b/core/src/audio/AudioProcessingEngine.ts
@@ -43,11 +43,13 @@ function isFiniteNumber(value: unknown): value is number {
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 instanceof Readable) {
+ return Readable.toWeb(input) as unknown as AsyncIterable;
}
- if ((input as any) instanceof Readable) {
- return Readable.toWeb(input as Readable) as unknown as AsyncIterable;
+ if (typeof (input as AsyncIterable)[Symbol.asyncIterator] === "function") {
+ return (async function* () {
+ yield* input as AsyncIterable;
+ })();
}
if (typeof (input as Iterable)[Symbol.iterator] === "function") {
return (async function* () {
diff --git a/core/src/controller/PreloadController.ts b/core/src/controller/PreloadController.ts
index 180f4acb..2dba5e36 100644
--- a/core/src/controller/PreloadController.ts
+++ b/core/src/controller/PreloadController.ts
@@ -195,9 +195,13 @@ export class PreloadController {
if (this.bus)
this.bus.emitOutput({ type: BUS_OUTPUT.preloadLoading, requestId: event.requestId, playerId, track: event.track });
try {
- await this.loader.preloadNext(playerId);
- const valid = this.loader.hasPreload(playerId, event.track);
- if (!valid) throw new Error(`Preload did not produce the requested track: ${event.track.title}`);
+ const preloaded = await this.loader.preloadNext(playerId);
+ if (!preloaded || !this.loader.hasPreload(playerId, event.track)) {
+ this.debug?.(`[PreloadController] No preload available for ${event.track.title}; playback will resolve it on demand`);
+ if (this.bus)
+ this.bus.emitOutput({ type: BUS_OUTPUT.preloadReady, requestId: event.requestId, playerId, track: event.track });
+ return;
+ }
this.debug?.(`[PreloadController] ${traceBusSignal(BUS_OUTPUT.preloadReady)} guild=${playerId} track=${event.track.title}`);
if (this.bus)
this.bus.emitOutput({ type: BUS_OUTPUT.preloadReady, requestId: event.requestId, playerId, track: event.track });
diff --git a/core/src/structures/PreloadManager.ts b/core/src/structures/PreloadManager.ts
index d06afba3..c819528e 100644
--- a/core/src/structures/PreloadManager.ts
+++ b/core/src/structures/PreloadManager.ts
@@ -149,32 +149,32 @@ export class PreloadManager {
preloadSlot.loadPromise = null;
return { track, stream, streamInfo, streamId };
}
- public async preloadNextTrack(id: string): Promise {
+ public async preloadNextTrack(id: string): Promise {
const slot = this.slots.get(id);
- if (!slot) return;
+ if (!slot) return false;
const { debug, isDestroyed, isEnabled } = slot.deps;
const preloadSlot = slot.preloadSlot;
- if (isDestroyed()) return;
+ if (isDestroyed()) return false;
if (!isEnabled()) {
debug(`[Preload] Disabled by options/runtime profile`);
- return;
+ return false;
}
if (slot.preloadLock) {
debug(`[Preload] Already preloading, skipping`);
- return;
+ return false;
}
const nextTrack = this.getNextTrack(slot);
if (!nextTrack) {
debug(`[Preload] No next track to preload`);
- return;
+ return false;
}
if (this.slotHasValidPreload(slot, nextTrack)) {
debug(`[Preload] Already have valid preload for: ${nextTrack.title}`);
- return;
+ return true;
}
if (preloadSlot.isLoading && this.trackMatches(preloadSlot.track, nextTrack)) {
if (preloadSlot.loadPromise) await preloadSlot.loadPromise;
- return;
+ return this.slotHasValidPreload(slot, nextTrack);
}
if (preloadSlot.isValid && !this.trackMatches(preloadSlot.track, nextTrack)) await this.safeCancelPreload(id);
slot.preloadLock = true;
@@ -211,6 +211,7 @@ export class PreloadManager {
preloadSlot.loadPromise = null;
}
if (slot.preloadNext && !isDestroyed() && isEnabled()) await this.preloadNextTrack(slot.playerId);
+ return this.slotHasValidPreload(slot, nextTrack);
}
public async safeCancelPreload(id: string): Promise {
const slot = this.slots.get(id);
diff --git a/core/src/structures/TrackLoader.ts b/core/src/structures/TrackLoader.ts
index 7ebe0005..b4a83941 100644
--- a/core/src/structures/TrackLoader.ts
+++ b/core/src/structures/TrackLoader.ts
@@ -172,9 +172,9 @@ export class TrackLoader {
return this.loadWithRecoverySlot(this.requireSlot(playerId), track, session);
}
- public async preloadNext(playerId: string): Promise {
+ public async preloadNext(playerId: string): Promise {
this.requireSlot(playerId);
- await this.preloadManager?.preloadNextTrack(playerId);
+ return (await this.preloadManager?.preloadNextTrack(playerId)) ?? false;
}
public async applyMiddleware(playerId: string, track: Track): Promise {
diff --git a/examples/backend/README.md b/examples/backend/README.md
index 008e5c85..5f02d208 100644
--- a/examples/backend/README.md
+++ b/examples/backend/README.md
@@ -55,7 +55,9 @@ Pause, resume, stop, skip, seek, volume, loop mode, autoplay, and filter request
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.
+within its duration. A control that cannot be applied returns an error rather than a successful-looking response. When the last
+browser listener disconnects, that player's instance is destroyed after 100 seconds; reconnecting a listener during that grace
+period cancels cleanup.
You can optionally start a query automatically by adding `TRACK_QUERY` to `examples/backend/.env`:
diff --git a/examples/backend/gateway.js b/examples/backend/gateway.js
index e840ff62..501801c5 100644
--- a/examples/backend/gateway.js
+++ b/examples/backend/gateway.js
@@ -185,7 +185,11 @@ async function readJsonBody(request, maxBytes) {
}
}
-function attachPublisher(session, socket, sessions) {
+function notifyListenerCount(session, onListenerCount) {
+ onListenerCount?.(session.sessionId, session.listeners.size);
+}
+
+function attachPublisher(session, socket, sessions, onListenerCount) {
let configured = false;
let frameCount = 0;
let frameBytes = 0;
@@ -194,13 +198,15 @@ function attachPublisher(session, socket, sessions) {
session.publisher = socket;
session.config = null;
for (const listener of session.nextListeners) {
+ if (listener.readyState !== WS_OPEN) continue;
session.listeners.add(listener);
listener.once("close", () => {
- session.listeners.delete(listener);
+ if (session.listeners.delete(listener)) notifyListenerCount(session, onListenerCount);
removeSessionIfUnused(session, sessions);
});
}
session.nextListeners.clear();
+ notifyListenerCount(session, onListenerCount);
socket.on("message", (data, isBinary) => {
if (isBinary) {
@@ -284,6 +290,7 @@ function createWebAudioGateway({
onPlayQuery,
onControl,
onGetPlayerState,
+ onListenerCount,
} = {}) {
if (!Number.isInteger(port) || port < 0 || port > 65535) throw new TypeError("port must be an integer from 0 to 65535");
if (defaultSessionId !== undefined && !isValidSessionId(defaultSessionId)) {
@@ -529,7 +536,7 @@ function createWebAudioGateway({
};
attachPendingListeners(session, pendingListeners);
sessions.set(parsed.sessionId, session);
- attachPublisher(session, webSocket, sessions);
+ attachPublisher(session, webSocket, sessions, onListenerCount);
console.info(`Audio publisher connected: ${parsed.sessionId}`);
} else if (parsed.role === "next-listener") {
const queue = queuePendingListener(pendingListeners, webSocket, parsed.sessionId ?? null);
@@ -545,9 +552,10 @@ function createWebAudioGateway({
return;
}
session.listeners.add(webSocket);
+ notifyListenerCount(session, onListenerCount);
if (session.config) webSocket.send(JSON.stringify(session.config));
webSocket.once("close", () => {
- session.listeners.delete(webSocket);
+ if (session.listeners.delete(webSocket)) notifyListenerCount(session, onListenerCount);
removeSessionIfUnused(session, sessions);
});
webSocket.on("error", (error) => {
diff --git a/examples/backend/index.js b/examples/backend/index.js
index 3ffcbee2..f909406c 100644
--- a/examples/backend/index.js
+++ b/examples/backend/index.js
@@ -81,6 +81,41 @@ function serializeTrack(track) {
};
}
+function createPlayerIdleCleanup(manager, timeoutMs = 100_000) {
+ const idlePlayers = new Map();
+ let disposed = false;
+
+ return {
+ onListenerCount(sessionId, listenerCount) {
+ const current = idlePlayers.get(sessionId);
+ if (current) {
+ clearTimeout(current.timer);
+ idlePlayers.delete(sessionId);
+ }
+ if (disposed || listenerCount > 0) return;
+ const player = manager.getPlayer(sessionId);
+ if (!player) return;
+
+ const state = { player, listenerCount, timer: null };
+ state.timer = setTimeout(() => {
+ if (idlePlayers.get(sessionId) !== state || state.listenerCount !== 0) return;
+ idlePlayers.delete(sessionId);
+ if (manager.getPlayer(sessionId) !== player) return;
+ void manager.destroy(sessionId).catch((error) => {
+ console.error(`Failed to remove listener-idle player ${sessionId}:`, error);
+ });
+ }, timeoutMs);
+ state.timer.unref?.();
+ idlePlayers.set(sessionId, state);
+ },
+ dispose() {
+ disposed = true;
+ for (const state of idlePlayers.values()) clearTimeout(state.timer);
+ idlePlayers.clear();
+ },
+ };
+}
+
async function main() {
const host = process.env.HOST ?? "127.0.0.1";
const port = Number(process.env.PORT ?? 8080);
@@ -88,6 +123,7 @@ async function main() {
const playerId = process.env.PLAYER_ID ?? "web-audio-demo";
let manager;
let gatewayUrl;
+ let playerIdleCleanup;
const gateway = createWebAudioGateway({
host,
port,
@@ -146,6 +182,7 @@ async function main() {
activeFilters: player.filter.getActiveFilters().map(toFilterSummary),
};
},
+ onListenerCount: (sessionId, listenerCount) => playerIdleCleanup?.onListenerCount(sessionId, listenerCount),
});
let shuttingDown = false;
async function getOrCreatePlayer(sessionId) {
@@ -199,6 +236,7 @@ async function main() {
autoCleanup: false,
extractorTimeout: Number(process.env.EXTRACTOR_TIMEOUT_MS ?? 30_000),
});
+ playerIdleCleanup = createPlayerIdleCleanup(manager);
manager.on("trackStart", (_player, track) => {
console.info(`Now playing: ${track.title} (${track.url})`);
});
@@ -217,6 +255,7 @@ async function main() {
if (shuttingDown) return;
shuttingDown = true;
console.info(`Received ${signal}; stopping ZiPlayer and Web audio gateway`);
+ playerIdleCleanup?.dispose();
try {
await manager?.dispose();
} finally {
@@ -231,6 +270,7 @@ async function main() {
if (!result) throw new Error(`ZiPlayer could not start playback for query: ${trackQuery}`);
}
} catch (error) {
+ playerIdleCleanup?.dispose();
await manager?.dispose();
await gateway.close();
throw error;
@@ -248,4 +288,5 @@ module.exports = {
createAudioOutputBackendFactory,
createPublisherSocketFactory,
createWebAudioGateway,
+ createPlayerIdleCleanup,
};
diff --git a/examples/backend/test/gateway.test.js b/examples/backend/test/gateway.test.js
index a8cb670c..cc4b5ef7 100644
--- a/examples/backend/test/gateway.test.js
+++ b/examples/backend/test/gateway.test.js
@@ -5,6 +5,7 @@ const test = require("node:test");
const { WebSocket } = require("ws");
const { encodeWebAudioFrame } = require("ziplayer");
const { createWebAudioGateway } = require("../gateway");
+const { createPlayerIdleCleanup } = require("../index");
function waitForOpen(socket) {
return new Promise((resolve, reject) => {
@@ -172,6 +173,76 @@ test("session-scoped next-listener routing keeps concurrent publishers isolated"
}
});
+test("gateway reports per-session browser listener counts as listeners connect and disconnect", async () => {
+ const changes = [];
+ let resolveEmpty;
+ let sawListener = false;
+ const empty = new Promise((resolve) => {
+ resolveEmpty = resolve;
+ });
+ const gateway = createWebAudioGateway({
+ host: "127.0.0.1",
+ port: 0,
+ onListenerCount: (sessionId, count) => {
+ changes.push({ sessionId, count });
+ if (count > 0) sawListener = true;
+ else if (sawListener) resolveEmpty();
+ },
+ });
+ let listener;
+ let publisher;
+ try {
+ const address = await gateway.listen();
+ const origin = `ws://127.0.0.1:${address.port}`;
+ publisher = new WebSocket(`${origin}/publish?sessionId=listener-count-player`);
+ await waitForOpen(publisher);
+ listener = new WebSocket(`${origin}/listen?sessionId=listener-count-player`);
+ await waitForOpen(listener);
+ const closed = new Promise((resolve) => listener.once("close", resolve));
+ listener.close();
+ await closed;
+ await empty;
+ assert.deepEqual(changes, [
+ { sessionId: "listener-count-player", count: 0 },
+ { sessionId: "listener-count-player", count: 1 },
+ { sessionId: "listener-count-player", count: 0 },
+ ]);
+ } finally {
+ listener?.close();
+ publisher?.close();
+ await gateway.close();
+ }
+});
+
+test("listener-idle cleanup deletes after the timeout and reconnect cancels deletion", async () => {
+ const players = new Map();
+ const destroyed = [];
+ const player = {};
+ players.set("idle-player", player);
+ const manager = {
+ getPlayer: (id) => players.get(id) ?? null,
+ async destroy(id) {
+ destroyed.push(id);
+ players.delete(id);
+ },
+ };
+ const cleanup = createPlayerIdleCleanup(manager, 30);
+ try {
+ cleanup.onListenerCount("idle-player", 0);
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ cleanup.onListenerCount("idle-player", 1);
+ await new Promise((resolve) => setTimeout(resolve, 40));
+ assert.deepEqual(destroyed, []);
+
+ cleanup.onListenerCount("idle-player", 0);
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ assert.deepEqual(destroyed, ["idle-player"]);
+ assert.equal(players.has("idle-player"), false);
+ } finally {
+ cleanup.dispose();
+ }
+});
+
test("play waits for its requested session instead of returning another active publisher", async () => {
const playCalls = [];
const gateway = createWebAudioGateway({
diff --git a/tests/audio_output_backend.test.js b/tests/audio_output_backend.test.js
index 9e3f5714..6daec967 100644
--- a/tests/audio_output_backend.test.js
+++ b/tests/audio_output_backend.test.js
@@ -1142,6 +1142,35 @@ test("preload promotion reports asynchronous output startup failures", async ()
await harness.dispose();
});
+test("disabled preload requests complete without reporting a stream error", async () => {
+ const { Bus, PreloadController, BUS_REQUEST, BUS_OUTPUT } = require("../core/dist");
+ const bus = new Bus();
+ const preloader = new PreloadController(bus, {
+ loader: {
+ hasPreload: () => false,
+ cancelPreload: () => {},
+ cancelPreloadSafely: async () => {},
+ preloadNext: async () => false,
+ },
+ manager: {
+ takePreloaded: () => null,
+ slotState: () => ({}),
+ clearPreloadSlot: () => {},
+ },
+ });
+ preloader.attach("disabled-preload");
+ const requestId = "disabled-preload-request";
+ const result = await bus.request("disabled-preload", {
+ type: BUS_REQUEST.preloadRequest,
+ requestId,
+ track: testTrack("not-preloaded"),
+ });
+ assert.equal(result.requestId, requestId);
+ assert.equal(result.type, BUS_OUTPUT.preloadReady);
+ preloader.detach("disabled-preload");
+ bus.dispose();
+});
+
test("Discord backend converts float32 PCM at the adapter boundary and controls inline volume", async () => {
const player = new MockAudioPlayer();
const backend = new DiscordVoiceOutputBackend(player);
diff --git a/tests/audio_processing_engine.test.js b/tests/audio_processing_engine.test.js
index b57e3f60..b2701e2e 100644
--- a/tests/audio_processing_engine.test.js
+++ b/tests/audio_processing_engine.test.js
@@ -8,7 +8,7 @@ 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 });
- const audioMod = await import("audio");
+ const audioMod = await import("../core/node_modules/audio/audio.js");
const source = audioMod.default.from((t) => Math.sin(2 * Math.PI * 440 * t), {
duration: 0.05,
sampleRate: 8000,
@@ -53,7 +53,7 @@ test("audio processing engine rejects raw PCM input because the runtime only sup
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 audioMod = await import("../core/node_modules/audio/audio.js");
const source = audioMod.default.from((t) => Math.sin(2 * Math.PI * 440 * t), {
duration: 0.05,
sampleRate: 8000,
@@ -82,9 +82,25 @@ test("audio processing engine emits valid PCM16 bytes for processed output", asy
await pipeline.dispose();
});
+test("audio processing accepts Node readable streams with an attached audio pages field", async () => {
+ const engine = createAudioProcessingEngine({ enabled: true, outputFormat: "pcm16le" });
+ const audioMod = await import("../core/node_modules/audio/audio.js");
+ const wav = await audioMod.default
+ .from((t) => Math.sin(2 * Math.PI * 440 * t), { duration: 0.02, sampleRate: 8000, channels: 1 })
+ .encode("wav");
+ const stream = Readable.from([wav]);
+ stream.pages = [];
+ const pipeline = await engine.createPipeline({ enabled: true, outputFormat: "pcm16le" });
+ const chunks = [];
+ for await (const chunk of pipeline.process(stream, AbortSignal.timeout(3000))) chunks.push(chunk);
+ assert.ok(chunks.length > 0);
+ assert.ok(chunks.some((chunk) => chunk.length > 0));
+ await pipeline.dispose();
+});
+
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 audioMod = await import("../core/node_modules/audio/audio.js");
const wav = await audioMod.default
.from((t) => Math.sin(2 * Math.PI * 440 * t), { duration: 0.02, sampleRate: 8000, channels: 1 })
.encode("wav");
diff --git a/tests/web_audio_output_backend.test.js b/tests/web_audio_output_backend.test.js
index 18965512..f692bbeb 100644
--- a/tests/web_audio_output_backend.test.js
+++ b/tests/web_audio_output_backend.test.js
@@ -288,15 +288,15 @@ test("web backend unregisters disposed sessions exactly once", async () => {
await backend.dispose();
});
-test("web backend declares volume unsupported", async () => {
+test("web backend declares backend-managed volume", 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);
+ assert.equal(backend.capabilities.volume, "backend");
+ assert.doesNotThrow(() => handle.setVolume(0.5));
await backend.dispose();
});
From 37d35aae0aa457d266dae7ce11f8263c94d7c983 Mon Sep 17 00:00:00 2001
From: Ziji <104454302+zijipia@users.noreply.github.com>
Date: Sun, 11 Oct 2026 01:42:27 +0900
Subject: [PATCH 17/55] format
---
CONTRIBUTING.md | 4 +-
README.md | 4 +-
adapters/README.md | 4 +-
client/README.md | 7 +-
core/src/structures/Player.ts | 9 ++-
core/src/types/bus.ts | 19 +++---
examples/backend/README.md | 26 ++++----
examples/backend/client/client.js | 4 +-
examples/backend/client/index.html | 93 +++++++++++++++++++++------
examples/backend/gateway.js | 9 ++-
examples/backend/index.js | 8 +--
examples/backend/test/gateway.test.js | 17 ++---
12 files changed, 121 insertions(+), 83 deletions(-)
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index bacb9203..c9b88363 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -201,7 +201,9 @@ export class MyPlugin extends BasePlugin {
async search(query: string, requestedBy: string): Promise {
// Implement search logic
return {
- tracks: [/* ... */],
+ tracks: [
+ /* ... */
+ ],
};
}
diff --git a/README.md b/README.md
index 7d49aa19..505cf90c 100644
--- a/README.md
+++ b/README.md
@@ -130,8 +130,8 @@ and plays it through a bounded AudioWorklet buffer. To hear browser audio from a
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.
+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
diff --git a/adapters/README.md b/adapters/README.md
index 41639134..0f3f83c8 100644
--- a/adapters/README.md
+++ b/adapters/README.md
@@ -120,7 +120,9 @@ provide(new SoundCloudPlugin());
// Generic object with getInfo() and/or download()
provide({
name: "custom",
- getInfo: async (url) => ({/* ... */}),
+ getInfo: async (url) => ({
+ /* ... */
+ }),
});
// Array of any of the above → MultiAdapter
diff --git a/client/README.md b/client/README.md
index 5a810753..f990950c 100644
--- a/client/README.md
+++ b/client/README.md
@@ -4,10 +4,9 @@ Small browser client for ZiPlayer's WebSocket PCM protocol. It validates the pub
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 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
+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, browser playback, queue display, and multi-player controls.
diff --git a/core/src/structures/Player.ts b/core/src/structures/Player.ts
index 36a1e3de..542c94c8 100644
--- a/core/src/structures/Player.ts
+++ b/core/src/structures/Player.ts
@@ -603,11 +603,10 @@ export class Player extends EventEmitter {
return false;
}
return this.bus
- .requestRpc<{ query: string | Track | Track[]; index: number; requestedBy?: string }, boolean>(
- this.playerId,
- PLAYER_RPC.queueInsert,
- { query, index, requestedBy },
- )
+ .requestRpc<
+ { query: string | Track | Track[]; index: number; requestedBy?: string },
+ boolean
+ >(this.playerId, PLAYER_RPC.queueInsert, { query, index, requestedBy })
.catch(() => false);
}
public remove(index: number): Track | null {
diff --git a/core/src/types/bus.ts b/core/src/types/bus.ts
index 762996ab..1f04cb39 100644
--- a/core/src/types/bus.ts
+++ b/core/src/types/bus.ts
@@ -186,16 +186,15 @@ export type PlayerEventArgsMap = {
) ?
[]
: K extends (
-
- | "TRACK_LOADING"
- | "TRACK_LOADED"
- | "TRACK_STARTED"
- | "TRACK_END"
- | "STREAM_ABORTED"
- | "playbackStateChanged"
- | "playbackSessionCreated"
- | "RECOVERY_STARTED"
- | "RECOVERY_FAILED"
+ | "TRACK_LOADING"
+ | "TRACK_LOADED"
+ | "TRACK_STARTED"
+ | "TRACK_END"
+ | "STREAM_ABORTED"
+ | "playbackStateChanged"
+ | "playbackSessionCreated"
+ | "RECOVERY_STARTED"
+ | "RECOVERY_FAILED"
) ?
[PlaybackSessionSnapshot]
: K extends "TRACK_ERROR" ? [PlaybackSessionSnapshot, Error]
diff --git a/examples/backend/README.md b/examples/backend/README.md
index 5f02d208..f9970162 100644
--- a/examples/backend/README.md
+++ b/examples/backend/README.md
@@ -38,26 +38,26 @@ npm start --prefix examples/backend
```
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.
+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 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
+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
+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. When the last
-browser listener disconnects, that player's instance is destroyed after 100 seconds; reconnecting a listener during that grace
-period cancels cleanup.
+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. When the last browser
+listener disconnects, that player's instance is destroyed after 100 seconds; reconnecting a listener during that grace period
+cancels cleanup.
You can optionally start a query automatically by adding `TRACK_QUERY` to `examples/backend/.env`:
@@ -75,9 +75,9 @@ 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 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.
+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.
Run the gateway handoff test from the repository root with `npm test --prefix examples/backend`.
diff --git a/examples/backend/client/client.js b/examples/backend/client/client.js
index 262a14b6..a011b2e4 100644
--- a/examples/backend/client/client.js
+++ b/examples/backend/client/client.js
@@ -146,9 +146,7 @@ async function refreshPlayerState() {
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),
- );
+ 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";
diff --git a/examples/backend/client/index.html b/examples/backend/client/index.html
index 2ef00551..b4bcf4ee 100644
--- a/examples/backend/client/index.html
+++ b/examples/backend/client/index.html
@@ -140,8 +140,8 @@
ZiPlayer Web Audio
- 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.
+ 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.
-
+
Current track
No track playing
Queue
-
+
Related tracks
-
+
- PLAYER_ID is the default player created when the server starts;
- other valid IDs create separate players the first time you request playback for them.
+ PLAYER_ID is the default player created when the server starts; other valid IDs create separate players the
+ first time you request playback for them.
-