diff --git a/.github/workflows/node.js.yml b/.github/workflows/node.js.yml
index f52d29bd..636355b8 100644
--- a/.github/workflows/node.js.yml
+++ b/.github/workflows/node.js.yml
@@ -94,7 +94,7 @@ jobs:
with:
path: ~/.npm
key:
- npm-${{ runner.os }}-${{ hashFiles('core/package.json', 'plugins/package.json', 'extension/package.json',
+ npm-${{ runner.os }}-${{ hashFiles('core/package.json', 'plugins/package.json', 'extensions/package.json',
'package.json') }}
restore-keys: npm-${{ runner.os }}-
@@ -110,10 +110,10 @@ jobs:
npm -C plugins install --package-lock=false --no-audit --no-fund
npm -C plugins run build
- - name: Bootstrap extension package
+ - name: Bootstrap extensions package
run: |
- npm -C extension install --package-lock=false --no-audit --no-fund
- npm -C extension run build
+ npm -C extensions install --package-lock=false --no-audit --no-fund
+ npm -C extensions run build
- name: Bootstrap root package
run: npm install --no-save --package-lock=false --no-audit --no-fund ./core
diff --git a/AGENTS.md b/AGENTS.md
index 8a32ddbb..3b5b5da7 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -7,10 +7,10 @@ Read the root [`README.md`](README.md) for public setup and player workflows. Fo
- `core/src/` contains the player facade, manager, controllers, stream handling, audio subscribers, and public exports. Edit
source here; `core/dist/` is generated.
-- `plugins/`, `extension/`, `infinity/`, and `adapters/` are separate integration packages.
+- `plugins/`, `extensions/`, `infinity/`, `adapters/`, and `net/` are separate integration packages.
- `client/` is the browser Opus receiver package. Keep its browser entry free of Node.js APIs.
- `examples/backend/` is the runnable ZiPlayer + authenticated WebSocket gateway + browser playback example.
-- `docs/` contains implementation/API references, including the audio output contract.
+- `docs/` contains player event flow and event debugging references (`PLAYER_EVENT_FLOW.md`, `PLAYER_EVENT_DEBUG.md`).
- `tests/` contains core regression tests; each package can also provide focused tests.
## User-facing behavior
@@ -20,6 +20,12 @@ Read the root [`README.md`](README.md) for public setup and player workflows. Fo
- Discord Voice and WebAudio outputs subscribe to the shared `@discordjs/voice` `AudioPlayer`; attach browser output with
`player.connect(webConnection)`. `WebAudioConnection` publishes only Opus packets in Wire Format v1 frames through an
application gateway. The `@ziplayer/client` browser receiver decodes Opus to PCM locally for AudioWorklet playback.
+- `net/` (`@ziplayer/net`) links ZiPlayer processes over MQTT. It is not an output backend: it moves compressed audio (Opus
+ containers and `arbitrary`, never raw PCM) between nodes, and hands a Discord voice session to another node through a relay
+ `voiceAdapterCreator`, so the real `@discordjs/voice` connection still runs on the node that plays. Control data and voice
+ credentials are always end-to-end encrypted; audio is clear by default (`encryptAudio` is opt-in). A node never fetches a URL a
+ peer hands it; a provider resolves peer-requested tracks only through its own plugins (use the `allow` hook). Test with
+ `tests/net_*.test.js` (`npm install --prefix net` once so `npm test` builds and runs them).
- PCM remains internal to DSP/codec processing and browser decoding, not a WebSocket transport. Do not reintroduce server-side PCM
output backends or a custom output backend/factory API. Discord Voice and WebAudio connections subscribe directly to the shared
`AudioPlayer`; attach browser output with `player.connect(webConnection)`.
diff --git a/AUDIO_ENGINE_REVIEW.md b/AUDIO_ENGINE_REVIEW.md
deleted file mode 100644
index 18e6fd85..00000000
--- a/AUDIO_ENGINE_REVIEW.md
+++ /dev/null
@@ -1,75 +0,0 @@
-# Audio engine review: removing `audio` (JS/wasm) in favour of FFmpeg
-
-All numbers below were measured in a sandbox (Node 22.22, FFmpeg 6.1, **1 vCPU**), so use them for ratios and for pass/fail
-behaviour, not as absolute figures for your hardware. Every claim has a test in `tests/` unless marked "not tested".
-
-## Why `audio` was removed
-
-Measured on 5-minute stereo fixtures, gain + highpass, output s16le 48 kHz stereo:
-
-| | `audio` (patched) | FFmpeg child process |
-| --------------------------------- | ------------------------------------------------------- | -------------------------------------------------------- |
-| Total CPU, webm/opus | 3.62 s | 1.52 s |
-| Total CPU, m4a (faststart) | 5.60 s | 0.98 s |
-| Peak RAM, 1 stream | 383-495 MB | 63 MB node + 51 MB child |
-| Peak RAM, 8 concurrent streams | 2234 MB | 495 MB |
-| Longest event-loop stall | 160-229 ms (webm), **4692 ms** (m4a) | 4-7 ms |
-| Backpressure | none: whole source read before the consumer read 0.8 MB | source stalls with the consumer (21% read at 9.3 MB out) |
-| Upstream error / destroyed source | pipeline hangs forever | error is thrown |
-
-`audio` decodes inside the Node.js process: a 230 ms stall breaks Discord's 20 ms voice frame cadence for every guild in the
-process, running it in a `worker_thread` fixed the stall but not the RAM or the missing backpressure. The repo already shipped
-`ffmpeg-static` and `FilterController`, so no dependency was added.
-
-The managed playback path creates an inline-volume `AudioResource` directly in `PlaybackController`. `@discordjs/voice` then
-builds its volume/Opus transformation for that resource; the DSP path emits Opus and bypasses the resource's normal decode path.
-
-## Changes
-
-- `core/src/audio/FFmpegAudioProcessingEngine.ts` (new): the only engine. Backpressure through stdin/stdout, `SIGKILL` on
- abort/early exit/`dispose()`, errors for upstream failure, non-zero exit and "exit 0 but no audio", chunks split to
- `maxBufferBytes` on frame boundaries, loudness presets via `loudnorm`.
-- `core/src/audio/AudioProcessingEngine.ts`: types and factory only; no `audio` import. `AudioJsAudioProcessingEngine` export
- became `FFmpegAudioProcessingEngine`. `normalize` no longer accepts numbers (throws `TypeError`).
-- `core/package.json`: dependency `audio` removed.
-- `tests/`: engine tests rewritten without `audio`; new `helpers/wav.js`, `audio_processing_engine.robustness.test.js`,
- `playback_processing_lifecycle.test.js`, `playback_output_integration.test.js`; `audio_engine_benchmark.js` now compares the
- engine with direct FFmpeg on identical fixtures. Suite: 233 tests, all passing.
-- Docs: `README.md`, `AGENTS.md`, and the audio architecture guide describe the FFmpeg engine and direct AudioPlayer
- subscriptions.
-
-## Bugs found while reviewing the output side, and fixed
-
-1. **Raw PCM after a seek played as loud noise.** `FilterController` returns `StreamType.Raw` after a seek, but the DSP branch
- ignored the input type. FFmpeg cannot probe raw PCM and guessed ADPCM: 1 s of 440 Hz became 3.5 s of full-scale noise (peak
- 1.0, ~10.7 kHz). Fix: `AudioProcessingContext.inputFormat` declares PCM streams (`PlaybackController` sets it for
- `StreamType.Raw`); encoded input is restricted to a demuxer whitelist (`ffmpegInputFormats`, `null` disables) so unknown bytes
- fail instead of being guessed.
-2. **FFmpeg and the source leaked when the player destroyed a stalled stream.** `Readable.from()` only finishes teardown when the
- generator's pending `await` settles, so `AudioPlayer.stop()/replace` left FFmpeg running until the whole player was detached
- (one leaked process per skipped stalled track). Fix: abort the pipeline from `processedStream._destroy`. The new test fails
- without it.
-3. **The source stream leaked when resource creation failed** before playback (the generator never started, so nothing closed the
- plugin's socket). Resource construction now destroys the transferred source on failure.
-4. `audioProcessing` now receives the player's `ffmpegPath`. Checked and found fine: inline-volume Opus handling; WebAudio
- subscriber packet pacing, stop, track replacement, sequence numbers, and frame content (440 Hz, peak 0.500).
-
-## Behaviour differences you should know about
-
-- Mono sources are up-mixed to stereo with FFmpeg's equal-power law (-3 dB); `audio` kept unity gain. Stereo is unaffected.
-- `normalize` is single-pass `loudnorm` (`streaming` -14, `podcast` -16, `broadcast` -23 LUFS); numeric targets are rejected.
- Loudness accuracy against the old normalizer was not compared.
-- MP4/M4A with the `moov` atom at the end cannot be decoded from a pipe: the engine now throws (it used to be a silent empty
- result in a first prototype). Give FFmpeg a seekable URL for such files. `audio` handled them by buffering the whole file.
-- Real-time sources start playing after 0.2-1.4 s of input (FFmpeg probing); not changed.
-- Engine overhead over running FFmpeg directly: about 1.4-1.8x wall time (`npm run bench:audio`).
-- `inlineVolume: true` forces a decode/encode even when volume is never changed. Creating the resource without it when volume is 1
- would restore WebM/Opus passthrough for non-DSP playback. Not changed (behaviour change for volume control).
-
-## Not done / not verified
-
-- Windows (FFmpeg pipes, `SIGKILL`) and real YouTube DASH/Opus streams were not tested; fixtures were produced by FFmpeg.
-- `examples/backend/test/gateway.test.js` needs a built `plugins` package and was not run; `websocket_output.test.js` and the
- client tests pass.
-- `Opus` (raw packets without a container) input is not decodable by FFmpeg and now fails with an explicit error; no bundled
- plugin produces it.
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index c9b88363..bacb9203 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -201,9 +201,7 @@ export class MyPlugin extends BasePlugin {
async search(query: string, requestedBy: string): Promise {
// Implement search logic
return {
- tracks: [
- /* ... */
- ],
+ tracks: [/* ... */],
};
}
diff --git a/adapters/README.md b/adapters/README.md
index 0f3f83c8..41639134 100644
--- a/adapters/README.md
+++ b/adapters/README.md
@@ -120,9 +120,7 @@ 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 1a441ec1..bdc896ed 100644
--- a/client/README.md
+++ b/client/README.md
@@ -63,6 +63,16 @@ The `token` option is optional for gateways that do not require authentication;
authentication. The browser fills in `client.sessionId` when the next publisher sends `audio:config`. If a publisher is already
active and you want to join that live stream, pass its `sessionId` instead. Call `disconnect()` to release browser resources.
+## Control messages
+
+Besides `audio:config` and Opus frames, the publisher may send JSON control messages (all carry `v: 1` and the `sessionId`):
+
+| Message | Effect in `WebAudioClient` |
+| ------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `playback:flush` | Drops audio that is buffered but not yet played (queued Opus frames, decoder state, worklet ring buffer) and keeps the `playing` state. Sent by `WebAudioConnection` when the track changes abruptly (skip, stop, seek, resource reload) so frames of the previous track are never heard before the new one. Older clients ignore it. |
+| `playback:stop` | Same flush, but also moves the client to `waiting`. |
+| `playback:pause` / `playback:resume` | Suspend / resume the `AudioContext`. |
+
## Events
`WebAudioClient` is an `EventTarget`:
diff --git a/client/browser/index.js b/client/browser/index.js
index 58a9b460..afed7eab 100644
--- a/client/browser/index.js
+++ b/client/browser/index.js
@@ -570,10 +570,14 @@ export class WebAudioClient extends EventTarget {
if (this.socket !== socket) return;
try {
if (typeof event.data === "string") this.receiveControlMessage(event.data);
+ else if (!this.config)
+ return; // frame đến trước audio:config: bỏ qua, chờ config
else this.receiveOpusFrame(event.data);
} catch (error) {
this.reportError(error);
- socket.close(1002, "Invalid audio protocol message");
+ try {
+ socket.close(4002, "Invalid audio protocol message"); // 1002 không hợp lệ trên browser
+ } catch {}
}
};
socket.addEventListener("message", onMessage);
@@ -829,6 +833,13 @@ export class WebAudioClient extends EventTarget {
void this.audioContext?.resume().catch((error) => this.reportError(error));
this.setState("playing");
break;
+ case "playback:flush":
+ // Abrupt source change (skip/seek/stop): drop buffered audio of the old source without
+ // leaving the "playing" state, so stale frames never play before the new track.
+ this.pendingOpusFrames = [];
+ this.opusDecoder?.reset();
+ this.workletNode?.port.postMessage({ type: "flush" });
+ break;
case "playback:stop":
this.pendingOpusFrames = [];
this.opusDecoder?.reset();
diff --git a/client/package.json b/client/package.json
index adeaeef3..d3b467a8 100644
--- a/client/package.json
+++ b/client/package.json
@@ -1,6 +1,6 @@
{
"name": "@ziplayer/client",
- "version": "1.0.3",
+ "version": "1.0.5",
"description": "Browser AudioWorklet client for ZiPlayer WebSocket Opus streams",
"license": "MIT",
"type": "module",
diff --git a/client/test/protocol.test.js b/client/test/protocol.test.js
index 93d57dab..6e423090 100644
--- a/client/test/protocol.test.js
+++ b/client/test/protocol.test.js
@@ -772,3 +772,75 @@ test("WebAudioClient getFrequencyBands and getBassEnergy delegates to active Ana
else globalThis.AudioWorkletNode = originalAudioWorkletNode;
}
});
+
+test("WebAudioClient playback:flush drops buffered audio without leaving the playing state", async () => {
+ const originalAudioWorkletNode = globalThis.AudioWorkletNode;
+ const posted = [];
+ class FakeAudioWorkletNode {
+ port = {
+ postMessage(msg) {
+ posted.push(msg);
+ },
+ };
+ connect() {}
+ disconnect() {}
+ }
+ globalThis.AudioWorkletNode = FakeAudioWorkletNode;
+ let resets = 0;
+ class MockOpusDecoder {
+ async initialize() {}
+ decode() {
+ return { samples: new Float32Array(960 * 2), peak: 0.5 };
+ }
+ reset() {
+ resets++;
+ }
+ free() {}
+ }
+ const client = new WebAudioClient({
+ audioContextFactory: () => ({
+ sampleRate: 48_000,
+ state: "running",
+ destination: {},
+ audioWorklet: { async addModule() {} },
+ async resume() {},
+ async close() {
+ this.state = "closed";
+ },
+ }),
+ opusDecoderFactory: () => new MockOpusDecoder(),
+ });
+ try {
+ await client.createAudioOutput();
+ client.receiveControlMessage(
+ JSON.stringify({
+ v: 1,
+ type: "audio:config",
+ sessionId: "flush-session",
+ protocolVersion: 1,
+ codec: "opus",
+ sampleRateHz: 48_000,
+ channels: 2,
+ }),
+ );
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ const flushesBefore = posted.filter((m) => m.type === "flush").length;
+ const resetsBefore = resets;
+
+ client.receiveControlMessage(
+ JSON.stringify({ v: 1, type: "playback:flush", sessionId: "flush-session", reason: "resource-changed" }),
+ );
+
+ assert.equal(posted.filter((m) => m.type === "flush").length, flushesBefore + 1, "worklet ring buffer must be flushed");
+ assert.equal(resets, resetsBefore + 1, "decoder state must be reset");
+ assert.equal(client.state, "playing", "a flush is not a stop: audio keeps flowing afterwards");
+ assert.throws(
+ () => client.receiveControlMessage(JSON.stringify({ v: 1, type: "playback:flush", sessionId: "other" })),
+ /another session/,
+ );
+ } finally {
+ await client.disconnect();
+ if (originalAudioWorkletNode === undefined) delete globalThis.AudioWorkletNode;
+ else globalThis.AudioWorkletNode = originalAudioWorkletNode;
+ }
+});
diff --git a/core/AGENTS.md b/core/AGENTS.md
index 62e16925..6bced248 100644
--- a/core/AGENTS.md
+++ b/core/AGENTS.md
@@ -63,9 +63,7 @@ async function playInGuild(guildId: string, voiceChannel: VoiceChannel, query: s
leaveOnEnd: true,
leaveOnEmpty: true,
volume: 80,
- userdata: {
- /*User store data*/
- },
+ userdata: {/*User store data*/},
});
if (!player.connection) await player.connect(voiceChannel);
@@ -270,7 +268,7 @@ The Bus contract is defined in [`src/structures/BusContract.ts`](src/structures/
3. **Preserve synchronous query contracts.** `querySync()` and `requestRpcSync()` must return immediate, non-Promise values. An
asynchronous handler must use the asynchronous query/RPC path.
4. **Serialize playback mutations.** `PLAY`, `PAUSE`, `RESUME`, `SEEK`, `STOP`, `SKIP`, and `SET_VOLUME` must pass through
- `PlayerActionExecutor` (`this.action()` or `bus.action()`).
+ `PlayerAction` (`this.action()` or `bus.action()`).
5. **Enforce forward-mode guards.** Followers (`playbackMode === PlaybackMode.FORWARD`) must not mutate playback. Existing facade
methods return `false` or return early and log a debug message.
6. **Recover from failed starts.** A failed track start must not leave playback idle indefinitely. Respect
@@ -304,7 +302,7 @@ Use an existing contract before adding another. When adding a contract, update `
| `PlaybackSkipController` | Skip, transition lock, fadeout, and autoplay fallback |
| `PlaybackSeekController` | Seek validation, timeouts, stream recreation, and pipe seeking |
| `PlaybackPreparationController` | Related-track selection, `willNext`, `willPlay`, and preload preparation |
-| `TrackLoader` / `TrackResolverController` | Stream resolution and recovery through plugins, extensions, and stream managers |
+| `TrackLoader` / `TrackResolver` | Stream resolution and recovery through plugins, extensions, and stream managers |
| `PreloadManager` | Upcoming-track preloads, promotion, and broken-stream cleanup |
| `AntiStuckController` | Stalled buffering detection, recovery, and skip fallback |
| `TransitionController` | Transition timing, genre-aware duration, and beat alignment |
@@ -332,8 +330,11 @@ substitute a related track. When autoplay is enabled and the queue is empty, sel
### Forward Mode
-- Subscription validates the follower's voice connection/player, stops independent follower playback, subscribes its voice
- connection to the leader audio player, then sets `PlaybackMode.FORWARD` and emits `forwardModeStart`.
+- Subscription validates the follower's voice connection/player and that the leader has an audio player (the leader needs no
+ Discord voice connection), stops independent follower playback, subscribes its voice connection to the leader audio player, then
+ sets `PlaybackMode.FORWARD` and emits `forwardModeStart`.
+- `Player.subscribeTo()` is asynchronous (`bus.requestRpc`); the `forward.subscribe` handler is async, so never call it through
+ `requestRpcSync`. `unsubscribeForward()` stays synchronous.
- The leader's track and playback events are mirrored to followers.
- Followers cannot call mutating playback methods (`play`, `playNext`, `pause`, `resume`, `stop`, `seek`, `skip`, `previous`,
`insert`, `clearQueue`, `setVolume`). Preserve this guard in facade and controller paths where needed.
@@ -350,6 +351,34 @@ Managed teardown must be idempotent and follow this order:
Do not bypass manager teardown or dispose Bus subscriptions before controller detach.
+### Multi-Node Support (`@ziplayer/net`)
+
+`net/` (`@ziplayer/net`, separate package) connects ZiPlayer processes over MQTT. Core only provides two hooks for it; keep them
+stable:
+
+- `PlayerManager.resolveStream(track, { fresh? })` resolves a normalized `StreamInfo` through the shared plugin manager without
+ creating a player. The caller owns and must destroy the returned stream. Raw PCM is still rejected by `normalizeStreamInfo`.
+- `Player.disconnect({ silent: true })` sends `connectionDisconnect` with `silent`, and `ConnectionController` then calls
+ `connection.destroy(false)` so the Discord channel is **not** left. Plain `disconnect()` still leaves the channel.
+
+Rules when touching connection, stream or extension code:
+
+- A voice hand-off works by giving `player.connect()` a channel whose `guild.voiceAdapterCreator` relays gateway payloads to
+ another node. Do not add a generic stream/output backend for this; `ConnectionController` must keep using
+ `adapterCreator: channel.guild.voiceAdapterCreator`.
+- The owner of a delegated player plays through `StreamInfo.remote` + `handle` (same contract as the Lavalink extension); keep
+ that path free of connection or output checks.
+- `ExtensionManager.provideStream` runs before plugins; `NetExtension` relies on it to pull audio from another node. It caches
+ results by track, so single-use streams must return `cacheable: false` (`RawStreamInfo`); otherwise a replay gets a consumed
+ stream and a later hand-off is bypassed by the cached entry.
+- `StreamController` only forwards `stop()` to a remote handle and stays in REMOTE mode until the remote ends. `@ziplayer/net`
+ therefore calls the public `Player.exitRemoteMode()` after a remote stop, on `reclaimVoice`, and when the executor disappears.
+- Only compressed audio crosses the network: Opus containers (`webm/opus`, `ogg/opus`, `opus`) and `arbitrary` (what the official
+ plugins return, demuxed by the receiver as usual). Raw PCM is refused. Peers cannot make a node fetch a URL.
+- One process holds one `PlayerManager` (singleton), so tests for several nodes use in-memory transports in one process only with
+ fake managers (see `tests/net_voice.test.js`), or separate processes with real managers.
+- Tests: `tests/net_*.test.js` need `net/dist`; run `npm install --prefix net` once, then `npm test` builds it automatically.
+
## Core Development Checks
Follow the owning controller when changing behavior. Keep changes local, update relevant types/contracts when the public or Bus
diff --git a/core/README.md b/core/README.md
index 55e88d0f..f5e4a666 100644
--- a/core/README.md
+++ b/core/README.md
@@ -2,18 +2,41 @@
-# ZiPlayer
-
-> Next-generation, event-driven, controller-architected audio engine for Discord bots, built on top of `@discordjs/voice`.
+> Next-generation, event-driven, controller-architected audio engine for Discord bots / Web, built on top of `@discordjs/voice`.
[](https://www.npmjs.com/package/ziplayer)
[](https://opensource.org/licenses/MIT)
[](https://nodejs.org)
[](https://www.typescriptlang.org)
+[](https://discord.gg/TK9WnFFngu)
+
+ZiPlayer is a powerful and flexible audio engine for Discord bots and web applications. It makes music playback simple to
+integrate while providing everything you need to build a rich audio experience — from smart queues and real-time audio effects to
+crossfade, multi-server playback, and browser streaming.
+
+
+ 💬 Need help or have questions?
+ Join our Discord Community
+ for support, discussions, and updates.
+
+
+---
-ZiPlayer is an enterprise-grade Discord music engine. Built around an asynchronous **Global Bus & Distributed Controller**
-architecture, it separates business logic into decoupled, testable controllers while exposing a clean, intuitive, and
-backwards-compatible `Player` facade.
+## 📚 Table of Contents
+
+- [✨ Key Features](#-key-features)
+- [📦 Installation](#-installation)
+- [🚀 Quick Start](#-quick-start)
+- [🎵 Core Usage & Controls](#-core-usage--controls)
+- [🎛️ Audio Filters](#-audio-filters)
+- [🧠 Smart Transitions & Crossfade](#-smart-transitions--crossfade)
+- [📻 Multi-Guild Forward Mode](#-multi-guild-forward-mode-stream-mirroring)
+- [💾 Session Persistence](#-session-persistence--state-restoration)
+- [🌐 Web Playback & Multi-Node](#-advanced-web-playback--multi-node-ziplayernet)
+- [⚙️ Configuration](#-configuration-reference)
+- [📚 Advanced Developer Guide](#-advanced-developer-guide)
+- [💬 Community & Support](#-community--support)
+- [📄 License](#-license)
---
@@ -21,8 +44,8 @@ backwards-compatible `Player` facade.
- 🚌 **Bus & Controller Architecture** — Fully decoupled internal design with synchronized state queries, ordered actions, and
granular RPC handlers.
-- 🔌 **Extensible Plugin Ecosystem** — First-class support for YouTube, SoundCloud, Spotify, TTS, Apple Music, and custom
- extractors.
+- 🔌 **Extensible Plugin Ecosystem** — Official plugins for YouTube, SoundCloud, Spotify, TTS and file attachments, plus a simple
+ interface for custom extractors.
- 🎛️ **Real-Time FFmpeg Audio Filters** — Live filter switching with zero playback interruption (`bassboost`, `nightcore`, `8D`,
`vaporwave`, `equalizer`, custom chains).
- 🔁 **Smart Autoplay & Queue Management** — Automatic related-track generation based on history, customizable loop modes (`off`,
@@ -31,15 +54,16 @@ backwards-compatible `Player` facade.
protection to prevent infinite loops.
- 🧠 **Smart Transitions & Crossfade** — BPM/genre-aware crossfade (long smooth fades for ambient/chill, punchy fades for
EDM/rock) with beat-alignment capabilities.
-- 🔊 **LUFS Loudness Normalization** — EBU R128 loudness normalization and soft-knee peak limiting to prevent jarring volume jumps
- between tracks.
- 📻 **Playback Mirror / Forward Mode** — Zero-overhead multi-guild broadcasting where follower guilds subscribe directly to a
leader's audio stream without re-downloading or re-encoding.
- 💾 **Session Serialization & State Recovery** — Export and restore full player states across bot restarts (queue, position,
volume, active filters, loop mode).
- ⚡ **High Performance & Auto-Scaling** — Low-performance mode automatically disables memory-heavy features (preload, crossfade)
on constrained host environments.
-- 🎛️ Shared Discord and browser playback through the `AudioPlayer` Opus subscriber path
+- 🌐 **Web / Browser Playback** — Stream the same Opus packets that go to Discord Voice to web listeners with `WebAudioConnection`
+ and the `@ziplayer/client` AudioWorklet receiver (shared server-side volume, no second encode).
+- 🕸️ **Multi-Node Clustering with `@ziplayer/net`** — Connect multiple ZiPlayer instances through MQTT, enabling distributed
+ stream resolution, voice handoff, and intelligent cross-node routing.
---
@@ -47,7 +71,7 @@ backwards-compatible `Player` facade.
```bash
# Using npm
-npm install ziplayer @discordjs/voice discord.js
+npm install ziplayer @discordjs/voice discord.js opusscript
# Recommended audio dependencies
npm install @discordjs/opus ffmpeg-static
@@ -69,7 +93,7 @@ Here is a minimal, production-ready Discord.js bot using ZiPlayer:
import { Client, GatewayIntentBits } from "discord.js";
import { PlayerManager } from "ziplayer";
// Official plugins can be imported from @ziplayer/plugin
-import { YouTubePlugin, SoundCloudPlugin, SpotifyPlugin, TTSPlugin, AttachmentsPlugin } from "@ziplayer/plugin";
+import { YouTubePlugin, SoundCloudPlugin, BilibiliPlugin, SpotifyPlugin, TTSPlugin, AttachmentsPlugin } from "@ziplayer/plugin";
const client = new Client({
intents: [
@@ -86,6 +110,7 @@ const manager = new PlayerManager({
new TTSPlugin({ defaultLang: "en" }),
new YouTubePlugin(),
new SoundCloudPlugin(),
+ new BilibiliPlugin(),
new SpotifyPlugin(),
new AttachmentsPlugin({ maxFileSize: 25 * 1024 * 1024 }), //25mb
],
@@ -141,224 +166,6 @@ client.login(process.env.DISCORD_TOKEN);
---
-## 🌐 Browser Playback with `@ziplayer/client`
-
-Browser playback uses `WebAudioConnection` to subscribe to the shared `AudioPlayer` and publish Opus packets. It can fan out the
-same server-volume-adjusted Opus packets as Discord Voice. The WebSocket gateway is application-provided; ZiPlayer does not create
-or host it.
-
-Install the browser receiver separately:
-
-```bash
-npm install @ziplayer/client
-```
-
-Connect a WebAudio subscriber to a regular player. Keep the player ID as the connection's `sessionId` so listeners can stay
-subscribed across track changes:
-
-```ts
-import { PlayerManager, WebAudioConnection } from "ziplayer";
-
-const manager = new PlayerManager();
-const playerId = "web-player";
-const player = await manager.create(playerId);
-const webConnection = new WebAudioConnection({ sessionId: playerId });
-webConnection.attachSocket(await connectPublisherSocket({ sessionId: playerId, gatewayUrl, token }));
-const browserOutput = await player.connect(webConnection);
-
-await player.play(query, userId);
-// Disconnect only the browser output when it is no longer needed.
-await browserOutput.disconnect();
-```
-
-`connectPublisherSocket` is application/gateway-specific and must resolve to an open WebSocket; authenticate the publisher on the
-server. For the included local gateway, a minimal Node.js helper using `ws` is:
-
-```sh
-npm install ws
-```
-
-```ts
-import { WebSocket } from "ws";
-
-function connectPublisherSocket({ gatewayUrl, sessionId }: { gatewayUrl: string; sessionId: string }): Promise {
- const url = new URL("/publish", gatewayUrl);
- url.searchParams.set("sessionId", sessionId);
- const socket = new WebSocket(url);
-
- return new Promise((resolve, reject) => {
- const onError = (error: Error) => {
- socket.off("open", onOpen);
- socket.terminate();
- reject(error);
- };
- const onOpen = () => {
- socket.off("error", onError);
- socket.on("error", (error: Error) => {
- console.error("Publisher socket error:", error);
- socket.close(1011, "Publisher transport error");
- });
- resolve(socket);
- };
- socket.once("error", onError);
- socket.once("open", onOpen);
- });
-}
-```
-
-This example assumes the gateway's `/publish` endpoint and no authentication; adapt the URL and auth handshake for your gateway.
-In the browser, import `WebAudioClient` from `@ziplayer/client` and call `connect()` from a user gesture. For a newly starting
-stream, connect with `nextPublisher: true` before requesting playback so the listener is ready before the first Opus frames
-arrive. The client validates the protocol, decodes Opus, and plays it through a bounded AudioWorklet buffer.
-
-### Minimal browser client (Vite)
-
-The browser package receives and plays audio; it does not start or control a ZiPlayer. Point it at an application gateway that
-implements the `/listen` WebSocket endpoint and is already publishing the selected player's stream. Start a vanilla Vite app and
-install the client:
-
-```sh
-npm create vite@latest ziplayer-web -- --template vanilla
-cd ziplayer-web
-npm install
-npm install @ziplayer/client
-npm run dev
-```
-
-Replace `index.html` with a small page containing the gateway URL and the exact player ID used by `WebAudioConnection`:
-
-```html
-
-
-
-
-
- ZiPlayer listener
-
-
-
- Gateway WebSocket URL
-
-
-
- Player ID
-
-
-
- Token (if required by your gateway)
-
-
- Listen
-
- Disconnect
-
- Disconnected
-
-
-
-```
-
-Replace `src/main.js` with:
-
-```js
-import { WebAudioClient } from "@ziplayer/client";
-
-const client = new WebAudioClient();
-const connectButton = document.querySelector("#connect");
-const disconnectButton = document.querySelector("#disconnect");
-const status = document.querySelector("#status");
-
-client.addEventListener("config", ({ detail }) => {
- status.textContent = `Receiving audio from: ${detail.sessionId}`;
-});
-client.addEventListener("error", ({ detail }) => {
- status.textContent = `Audio error: ${detail.error.message}`;
- console.error("ZiPlayer client error:", detail.error);
-});
-client.addEventListener("close", ({ detail }) => {
- status.textContent = `Connection closed (${detail.code})`;
-});
-
-connectButton.addEventListener("click", async () => {
- connectButton.disabled = true;
- status.textContent = "Connecting…";
- try {
- const token = document.querySelector("#token").value.trim();
- await client.connect({
- gatewayUrl: document.querySelector("#gateway").value.trim(),
- sessionId: document.querySelector("#session").value.trim(),
- ...(token ? { token } : {}),
- });
- disconnectButton.disabled = false;
- status.textContent = "Connected; waiting for audio…";
- } catch (error) {
- status.textContent = `Could not connect: ${error.message}`;
- connectButton.disabled = false;
- }
-});
-
-disconnectButton.addEventListener("click", async () => {
- await client.disconnect();
- connectButton.disabled = false;
- disconnectButton.disabled = true;
- status.textContent = "Disconnected";
-});
-```
-
-Run the gateway separately and make sure its publisher uses the same player ID. To try the included local gateway and publisher,
-follow the [Web Audio quick start](../examples/backend/README.md), start playback there, and then open the Vite URL and click
-**Listen**. The gateway URL is the WebSocket origin (for example `ws://127.0.0.1:8080`); the client appends `/listen`. To listen
-before a new publisher starts, use `nextPublisher: true` instead of `sessionId`, then start playback through your application API
-after the WebSocket connects. Supply a short-lived token only if the gateway requires one. Serve the page over HTTPS when
-connecting to a non-local `wss://` gateway.
-
-### Shared Discord and browser playback with server-side volume
-
-For simultaneous Discord and browser playback, attach `WebAudioConnection` to the player's `AudioPlayer`:
-
-```ts
-import { WebAudioConnection } from "ziplayer";
-
-const player = await manager.create(guildId);
-const voiceConnection = await player.connect(voiceChannel);
-const webConnection = new WebAudioConnection({ sessionId: player.id });
-webConnection.attachSocket(await connectPublisherSocket({ sessionId: player.id }));
-const webOutput = await player.connect(webConnection);
-
-await player.play(query, { requestedBy: userId });
-player.setVolume(65); // server-side player volume, shared by Discord and browser listeners
-// Call webOutput.disconnect() when the browser output is no longer needed.
-```
-
-The source `Readable` is wrapped in a Discord `AudioResource` with inline volume, then played by the shared Discord `AudioPlayer`.
-The player emits Opus packets to both subscribers: `DiscordVoiceConnection` sends them through the Discord Voice protocol, while
-`WebAudioConnection` adds the ZI v1 frame header and publishes them over WebSocket. The gateway relays those Opus frames to the
-browser for local decoding and playback. `player.setVolume()` changes the shared server-side resource before the fan-out, so the
-updated audio is heard by both outputs. It is not a per-browser volume control.
-
-Inline volume is applied to the shared `AudioResource` before Opus packets are distributed. This in-process codec step does not
-require FFmpeg; both subscribers receive the same post-volume Opus packets. Passing an `AudioResource` created externally may
-bypass ZiPlayer's inline-volume resource setup.
-
-For a complete runnable gateway, player session, and browser UI example, see
-[`examples/backend`](https://github.com/ZiProject/ZiPlayer/tree/main/examples/backend/README.md). For client events, options, and
-browser requirements, see [`@ziplayer/client` documentation](https://github.com/ZiProject/ZiPlayer/tree/main/client/README.md).
-
----
-
## Singleton Access
ZiPlayer exposes a process-wide manager singleton. Create `PlayerManager` once during application startup so it registers the
@@ -518,12 +325,15 @@ const player = await manager.create(guildId, {
Broadcast one stream across multiple guilds simultaneously with **zero duplicate bandwidth or decoding overhead**:
```typescript
-// Guild A is playing music
+// Guild A is playing music; guild B has its own player
const leader = manager.get("guild-A");
const follower = manager.get("guild-B");
+if (!leader || !follower) throw new Error("Create both players first with manager.create(guildId)");
-// Follower subscribes directly to leader's AudioPlayer
-follower.subscribeTo(leader);
+// Follower subscribes directly to leader's AudioPlayer.
+// Async: resolves false if refused (follower not in a voice channel, leader is a follower, ...).
+// The leader only needs an AudioPlayer, so a WebAudio-only leader works too.
+const ok = await follower.subscribeTo(leader);
// Follower automatically mirrors trackStart, trackEnd, pause, resume, and volume!
// Follower mutations are guarded to prevent disrupting the leader.
@@ -562,25 +372,47 @@ if (success) {
Both `PlayerManager` and `Player` emit typed events. `PlayerManager` emits the originating `player` instance as the first
argument.
-| Event | Arguments | Description |
-| ------------------ | -------------------------- | --------------------------------------------------- |
-| `trackStart` | `(player, track)` | Emitted when a track starts playing |
-| `trackEnd` | `(player, track)` | Emitted when a track finishes playing |
-| `queueEnd` | `(player)` | Emitted when the queue is completely exhausted |
-| `queueAdd` | `(player, track)` | A single track was added to the queue |
-| `queueAddList` | `(player, tracks)` | Multiple tracks were appended to the queue |
-| `queueRemove` | `(player, track, index)` | A track was removed from the queue |
-| `playerPause` | `(player, track)` | Playback was paused |
-| `playerResume` | `(player, track)` | Playback was resumed |
-| `playerStop` | `(player)` | Player stopped and queue was cleared |
-| `playerError` | `(player, error, track)` | Playback or stream resolution encountered an error |
-| `volumeChange` | `(player, oldVol, newVol)` | Player volume was modified |
-| `filterApplied` | `(player, filter)` | An audio filter was activated |
-| `filterRemoved` | `(player, filter)` | An audio filter was removed |
-| `filtersCleared` | `(player)` | All active audio filters were cleared |
-| `forwardModeStart` | `(player, leader)` | Player entered forward mode subscribing to a leader |
-| `forwardModeEnd` | `(player, leader, reason)` | Player exited forward mode |
-| `playerDestroy` | `(player)` | Player instance was destroyed and detached |
+| Event | Arguments | Description |
+| ------------------------ | ------------------------------ | ------------------------------------------------------- |
+| `trackStart` | `(player, track)` | Emitted when a track starts playing |
+| `trackEnd` | `(player, track)` | Emitted when a track finishes playing |
+| `queueEnd` | `(player)` | Emitted when the queue is completely exhausted |
+| `queueAdd` | `(player, track)` | A single track was added to the queue |
+| `queueAddList` | `(player, tracks)` | Multiple tracks were appended to the queue |
+| `queueRemove` | `(player, track, index)` | A track was removed from the queue |
+| `playerPause` | `(player, track)` | Playback was paused |
+| `playerResume` | `(player, track)` | Playback was resumed |
+| `playerStop` | `(player)` | Player stopped and queue was cleared |
+| `playerError` | `(player, error, track)` | Playback or stream resolution encountered an error |
+| `volumeChange` | `(player, oldVol, newVol)` | Player volume was modified |
+| `filterApplied` | `(player, filter)` | An audio filter was activated |
+| `filterRemoved` | `(player, filter)` | An audio filter was removed |
+| `filtersCleared` | `(player)` | All active audio filters were cleared |
+| `forwardModeStart` | `(player, leader)` | Player entered forward mode subscribing to a leader |
+| `forwardModeEnd` | `(player, leader, reason)` | Player exited forward mode |
+| `playerDestroy` | `(player)` | Player instance was destroyed and detached |
+| `connectionError` | `(player, error)` | Voice connection or reconnection failed |
+| `seek` | `(player, payload)` | Seek completed; payload contains `track` and `position` |
+| `streamError` | `(player, error, track)` | An audio stream encountered an error |
+| `streamAborted` | `(player, session)` | A stream was aborted |
+| `trackLoading` | `(player, session)` | Track resolution/loading started |
+| `trackLoaded` | `(player, session)` | Track resolution/loading completed |
+| `trackStuck` | `(player, track)` | Playback stalled and recovery was considered |
+| `recoveryStart` | `(player, session)` | Stall or stream recovery started |
+| `recoveryFailed` | `(player)` | Stall or stream recovery failed |
+| `preloadStateChanged` | `(player, state)` | Preload state changed |
+| `preloadPromoted` | `(player, track)` | A preloaded track was promoted for playback |
+| `preloadCancelled` | `(player)` | Preloading was cancelled |
+| `queueChange` | `(player, queue)` | Queue contents changed |
+| `playbackStateChanged` | `(player, session)` | Discord audio player state changed |
+| `playbackSessionCreated` | `(player, session)` | A playback session was created |
+| `trackRequested` | `(player, track, session)` | A track was requested for playback |
+| `stateChanged` | `(player, oldState, newState)` | Internal Discord player state changed |
+| `ttsStart` | `(player, payload)` | TTS playback started; payload contains `text`/`track` |
+| `ttsEnd` | `(player)` | TTS playback ended |
+| `stats` | `(stats)` | Periodic aggregate manager statistics |
+| `playerIdChange` | `(player, newId, oldId)` | A managed player's public ID changed |
+| `debug` | `(...arg)` | A debug message was logged |
---
@@ -593,59 +425,439 @@ Passed to `manager.create(guildId, options)`:
```typescript
interface PlayerOptions {
volume?: number; // Initial volume (0 - 200, default: 100)
- quality?: "low" | "medium" | "high"; // Stream quality preset
+ quality?: "low" | "high"; // Stream quality preset (default: "high")
leaveOnEnd?: boolean; // Leave voice when queue ends (default: true)
- leaveOnEmpty?: boolean; // Leave voice when voice channel is empty
+ leaveOnEmpty?: boolean; // Leave voice when the voice channel is empty (default: true)
pauseOnEmpty?: boolean; // Pause when voice channel is empty and resume when a user returns (default: false)
leaveTimeout?: number; // Inactivity timeout in ms before leave (default: 100000; 0 to disable)
selfDeaf?: boolean; // Join deafened (default: true)
selfMute?: boolean; // Join muted (default: false)
- lowPerformance?: boolean; // Low performance mode (disables preload/crossfade)
- filters?: string[]; // Initial audio filters to apply
+ group?: string; // Optional voice connection group
+ extractorTimeout?: number; // Track extraction timeout in ms (default: 50000)
+ ffmpegPath?: string | null; // Explicit FFmpeg executable for seek/filter processing
+ tts?: {
+ createPlayer?: boolean; // Create a dedicated TTS player (default: false)
+ interrupt?: boolean; // Interrupt current playback for TTS (default: true)
+ volume?: number; // TTS volume (default: 100)
+ maxTimeTts?: number; // Maximum TTS duration in ms (default: 60000)
+ };
+ extensions?: any[] | string[]; // Extensions to attach
+ lowPerformance?: boolean; // Low performance mode
+ filters?: (string | AudioFilter)[]; // Initial audio filters to apply
preload?: {
enabled?: boolean; // Auto-preload upcoming track (default: true)
- autoDisableInLowPerformance?: boolean;
+ autoDisableInLowPerformance?: boolean; // Disable preload in low-performance mode (default: true)
};
crossfade?: {
- enabled?: boolean;
+ enabled?: boolean; // Crossfade enabled (default: true)
durationMs?: number; // Crossfade duration in ms (default: 1000)
autoEnable?: boolean;
- autoDisableInLowPerformance?: boolean;
+ autoDisableInLowPerformance?: boolean; // Disable crossfade in low-performance mode (default: true)
+ };
+ smartTransition?: {
+ enabled?: boolean; // Smart transitions (default: true)
+ genreAware?: boolean; // Use track genre for timing (default: true)
+ beatAlign?: boolean; // Align transitions to beats (default: true)
+ baseDurationMs?: number;
+ minDurationMs?: number; // Default: 600
+ maxDurationMs?: number; // Default: 8000
+ beatAlignMaxWaitMs?: number; // Default: 700
+ genreDurations?: Record;
};
antiStuck?: {
enabled?: boolean; // Enable stall recovery watchdog
+ maxRetries?: number; // Maximum retries (default: 2)
+ retryDelayMs?: number; // Retry delay (default: 90000)
stuckTimeoutMs?: number; // Buffer stall threshold (default: 10000)
+ reusePreloadFirst?: boolean; // Try a preloaded resource first (default: true)
+ reduceQualityOnRetry?: boolean; // Reduce source quality on retry (default: true)
controlledSkipThreshold?: number; // Consecutive error threshold (default: 3)
};
loudnessNormalization?: {
- enabled?: boolean;
+ enabled?: boolean; // Default: false
targetLUFS?: number; // Target LUFS (default: -14)
- maxBoostDb?: number; // Maximum boost in dB (default: 8)
- maxCutDb?: number; // Maximum cut in dB (default: 10)
- limiterCeiling?: number; // Peak ceiling (default: 0.95)
+ maxBoostDb?: number; // Maximum boost in dB (default: 6)
+ maxCutDb?: number; // Maximum cut in dB (default: 12)
+ limiterCeiling?: number; // Peak ceiling (default: 1)
+ autoDisableInLowPerformance?: boolean; // Default: true
};
userdata?: Record; // Arbitrary custom metadata
+ trackMiddleware?: TrackMiddleware | TrackMiddleware[];
+ maxStreamStore?: number; // Maximum concurrent stream slots (default: 4)
+}
+```
+
+### PlayerManagerOptions
+
+Passed to `new PlayerManager(options)`:
+
+```typescript
+interface PlayerManagerOptions {
+ plugins?: SourcePluginLike[];
+ extensions?: any[];
+ extractorTimeout?: number;
+ autoCleanup?: boolean;
+ cleanupInterval?: number;
+ enableSearchCache?: boolean;
+ enableStatsCollection?: boolean;
+ trackMiddleware?: TrackMiddleware | TrackMiddleware[];
+ debugLevel?: "off" | "error" | "warn" | "info" | "debug" | "verbose" | "time";
}
```
---
-## 📚 Advanced Developer Guide
+## 🧩 Advanced: Web Playback & Multi-Node (`@ziplayer/net`)
-For contributors, custom controller authors, and AI agent instructions detailing internal Bus protocols, controller state
-ownership, and teardown lifecycle, see [**AGENTS.md**](./AGENTS.md).
+### Web playback (browser listeners)
+
+Browser playback uses `WebAudioConnection` to subscribe to the shared `AudioPlayer` and publish Opus packets. It can fan out the
+same server-volume-adjusted Opus packets as Discord Voice. The WebSocket gateway is application-provided; ZiPlayer does not create
+or host it.
+
+`WebAudioConnection` watches the shared `AudioPlayer`: when the audio source changes abruptly (skip, stop, seek, resource reload)
+it discards its per-socket backlog and sends a `playback:flush` control message, so listeners never hear leftover frames of the
+previous track. A track that ends by itself is left to play out. You can also call `webConnection.flush()` manually.
+
+Install the browser receiver separately:
+
+```bash
+npm install @ziplayer/client
+```
+
+Connect a WebAudio subscriber to a regular player. Keep the player ID as the connection's `sessionId` so listeners can stay
+subscribed across track changes:
+
+```ts
+import { PlayerManager, WebAudioConnection } from "ziplayer";
+
+const manager = new PlayerManager();
+const playerId = "web-player";
+const player = await manager.create(playerId);
+const webConnection = new WebAudioConnection({ sessionId: playerId });
+webConnection.attachSocket(await connectPublisherSocket({ sessionId: playerId, gatewayUrl, token }));
+const browserOutput = await player.connect(webConnection);
+
+await player.play(query, userId);
+// Disconnect only the browser output when it is no longer needed.
+await browserOutput.disconnect();
+```
+
+`connectPublisherSocket` is application/gateway-specific and must resolve to an open WebSocket; authenticate the publisher on the
+server. For the included local gateway, a minimal Node.js helper using `ws` is:
+
+```sh
+npm install ws
+```
+
+```ts
+import { WebSocket } from "ws";
+
+function connectPublisherSocket({ gatewayUrl, sessionId }: { gatewayUrl: string; sessionId: string }): Promise {
+ const url = new URL("/publish", gatewayUrl);
+ url.searchParams.set("sessionId", sessionId);
+ const socket = new WebSocket(url);
+
+ return new Promise((resolve, reject) => {
+ const onError = (error: Error) => {
+ socket.off("open", onOpen);
+ socket.terminate();
+ reject(error);
+ };
+ const onOpen = () => {
+ socket.off("error", onError);
+ socket.on("error", (error: Error) => {
+ console.error("Publisher socket error:", error);
+ socket.close(1011, "Publisher transport error");
+ });
+ resolve(socket);
+ };
+ socket.once("error", onError);
+ socket.once("open", onOpen);
+ });
+}
+```
+
+This example assumes the gateway's `/publish` endpoint and no authentication; adapt the URL and auth handshake for your gateway.
+In the browser, import `WebAudioClient` from `@ziplayer/client` and call `connect()` from a user gesture. For a newly starting
+stream, connect with `nextPublisher: true` before requesting playback so the listener is ready before the first Opus frames
+arrive. The client validates the protocol, decodes Opus, and plays it through a bounded AudioWorklet buffer.
+
+### Minimal browser client (Vite)
+
+The browser package receives and plays audio; it does not start or control a ZiPlayer. Point it at an application gateway that
+implements the `/listen` WebSocket endpoint and is already publishing the selected player's stream. Start a vanilla Vite app and
+install the client:
+
+```sh
+npm create vite@latest ziplayer-web -- --template vanilla
+cd ziplayer-web
+npm install
+npm install @ziplayer/client
+npm run dev
+```
+
+Replace `index.html` with a small page containing the gateway URL and the exact player ID used by `WebAudioConnection`:
+
+```html
+
+
+
+
+
+ ZiPlayer listener
+
+
+
+ Gateway WebSocket URL
+
+
+
+ Player ID
+
+
+
+ Token (if required by your gateway)
+
+
+ Listen
+
+ Disconnect
+
+ Disconnected
+
+
+
+```
+
+Replace `src/main.js` with:
+
+```js
+import { WebAudioClient } from "@ziplayer/client";
+
+const client = new WebAudioClient();
+const connectButton = document.querySelector("#connect");
+const disconnectButton = document.querySelector("#disconnect");
+const status = document.querySelector("#status");
+
+client.addEventListener("config", ({ detail }) => {
+ status.textContent = `Receiving audio from: ${detail.sessionId}`;
+});
+client.addEventListener("error", ({ detail }) => {
+ status.textContent = `Audio error: ${detail.error.message}`;
+ console.error("ZiPlayer client error:", detail.error);
+});
+client.addEventListener("close", ({ detail }) => {
+ status.textContent = `Connection closed (${detail.code})`;
+});
+
+connectButton.addEventListener("click", async () => {
+ connectButton.disabled = true;
+ status.textContent = "Connecting…";
+ try {
+ const token = document.querySelector("#token").value.trim();
+ await client.connect({
+ gatewayUrl: document.querySelector("#gateway").value.trim(),
+ sessionId: document.querySelector("#session").value.trim(),
+ ...(token ? { token } : {}),
+ });
+ disconnectButton.disabled = false;
+ status.textContent = "Connected; waiting for audio…";
+ } catch (error) {
+ status.textContent = `Could not connect: ${error.message}`;
+ connectButton.disabled = false;
+ }
+});
+
+disconnectButton.addEventListener("click", async () => {
+ await client.disconnect();
+ connectButton.disabled = false;
+ disconnectButton.disabled = true;
+ status.textContent = "Disconnected";
+});
+```
+
+Run the gateway separately and make sure its publisher uses the same player ID. To try the included local gateway and publisher,
+follow the [Web Audio quick start](https://github.com/ZiProject/ZiPlayer/tree/main/examples/backend), start playback there, and
+then open the Vite URL and click **Listen**. The gateway URL is the WebSocket origin (for example `ws://127.0.0.1:8080`); the
+client appends `/listen`. To listen before a new publisher starts, use `nextPublisher: true` instead of `sessionId`, then start
+playback through your application API after the WebSocket connects. Supply a short-lived token only if the gateway requires one.
+Serve the page over HTTPS when connecting to a non-local `wss://` gateway.
+
+### Shared Discord and browser playback with server-side volume
+
+For simultaneous Discord and browser playback, attach `WebAudioConnection` to the player's `AudioPlayer`:
+
+```ts
+import { WebAudioConnection } from "ziplayer";
+
+const player = await manager.create(guildId);
+const voiceConnection = await player.connect(voiceChannel);
+const webConnection = new WebAudioConnection({ sessionId: player.id });
+webConnection.attachSocket(await connectPublisherSocket({ sessionId: player.id }));
+const webOutput = await player.connect(webConnection);
+
+await player.play(query, { requestedBy: userId });
+player.setVolume(65); // server-side player volume, shared by Discord and browser listeners
+// Call webOutput.disconnect() when the browser output is no longer needed.
+```
+
+The source `Readable` is wrapped in a Discord `AudioResource` with inline volume, then played by the shared Discord `AudioPlayer`.
+The player emits Opus packets to both subscribers: `DiscordVoiceConnection` sends them through the Discord Voice protocol, while
+`WebAudioConnection` adds the ZI v1 frame header and publishes them over WebSocket. The gateway relays those Opus frames to the
+browser for local decoding and playback. `player.setVolume()` changes the shared server-side resource before the fan-out, so the
+updated audio is heard by both outputs. It is not a per-browser volume control.
+
+Inline volume is applied to the shared `AudioResource` before Opus packets are distributed. This in-process codec step does not
+require FFmpeg; both subscribers receive the same post-volume Opus packets. Passing an `AudioResource` created externally may
+bypass ZiPlayer's inline-volume resource setup.
+
+For a complete runnable gateway, player session, and browser UI example, see
+[`examples/backend`](https://github.com/ZiProject/ZiPlayer/tree/main/examples/backend/README.md). For client events, options, and
+browser requirements, see [`@ziplayer/client` documentation](https://github.com/ZiProject/ZiPlayer/tree/main/client/README.md).
---
-## 📄 License
+### Multi-node clustering with `@ziplayer/net`
-MIT © [ZiProject](https://github.com/ZiProject)
+Run several ZiPlayer processes ("nodes") and let them cooperate over **MQTT**. This helps when one server can resolve YouTube but
+the bot's gateway lives on another, when you want to spread voice load across machines, or when a source is blocked on one host.
+
+- **Stream transfer** — the node whose plugins resolve a track sends the compressed audio (Opus, or the `arbitrary` containers the
+ official plugins return) to the node that plays it. Raw PCM and peer-supplied URLs are never accepted.
+- **Voice hand-off** — the node that called `player.connect()` keeps the Discord gateway and queue, and hands the voice session to
+ another node (`delegateVoice` / `reclaimVoice`). If that node goes offline the owner takes the voice back.
+- **Automatic routing** — `routeTracks()` keeps the voice and pulls a few foreign tracks (_relay_), or moves the voice to the node
+ that can play most of them (_handoff_).
+- **Security** — Ed25519 node identities pinned per node, a 3-message authenticated key exchange, ChaCha20-Poly1305 for all
+ control data and voice credentials, replay protection. The MQTT broker is untrusted. Audio is sent in clear unless
+ `encryptAudio: true`.
+
+Install the `@ziplayer/net` package .
+
+```bash
+npm install @ziplayer/net mqtt
+```
+
+**1. Create a key for every node** and copy each `.key.pub` file to the other machine (never copy the `.key` file):
+
+```bash
+node -e "require('@ziplayer/net').loadOrCreateIdentity('./yt-1.key')"
+node -e "require('@ziplayer/net').loadOrCreateIdentity('./bot-1.key')"
+```
+
+**2. The node that can resolve YouTube** (`provider.ts`) serves streams:
+
+```ts
+import fs from "node:fs";
+import { PlayerManager } from "ziplayer";
+import { YouTubePlugin } from "@ziplayer/plugin";
+import { ZiNet, MqttTransport } from "@ziplayer/net";
+
+const manager = new PlayerManager({ plugins: [new YouTubePlugin()] });
+
+const net = new ZiNet({
+ nodeId: "yt-1",
+ networkId: "prod",
+ keyFile: "./yt-1.key",
+ // Only bot-1 may ask this node for streams
+ trust: [{ nodeId: "bot-1", publicKey: fs.readFileSync("./bot-1.key.pub", "utf8"), roles: ["provide-stream"] }],
+ transport: new MqttTransport({ url: process.env.MQTT_URL!, username: process.env.MQTT_USER, password: process.env.MQTT_PASS }),
+ manager,
+});
+
+await net.start();
+net.provideStreams(); // optional: { allow: (track) => track.source === "youtube" }
+console.log("yt-1 ready");
+```
+
+**3. The bot node** (`bot.ts`) owns the Discord gateway and plays audio pulled from `yt-1`:
+
+```ts
+import fs from "node:fs";
+import { Client, GatewayIntentBits } from "discord.js";
+import { PlayerManager } from "ziplayer";
+import { YouTubePlugin } from "@ziplayer/plugin";
+import { ZiNet, MqttTransport, discordJsGateway, markTrack } from "@ziplayer/net";
+
+const client = new Client({
+ intents: [
+ GatewayIntentBits.Guilds,
+ GatewayIntentBits.GuildVoiceStates,
+ GatewayIntentBits.GuildMessages,
+ GatewayIntentBits.MessageContent,
+ ],
+});
+// YouTube plugin is still needed here for search/metadata; the audio itself comes from yt-1
+const manager = new PlayerManager({ plugins: [new YouTubePlugin()] });
+
+const net = new ZiNet({
+ nodeId: "bot-1",
+ networkId: "prod",
+ keyFile: "./bot-1.key",
+ trust: [{ nodeId: "yt-1", publicKey: fs.readFileSync("./yt-1.key.pub", "utf8") }],
+ transport: new MqttTransport({ url: process.env.MQTT_URL!, username: process.env.MQTT_USER, password: process.env.MQTT_PASS }),
+ manager,
+ gateway: discordJsGateway(client), // lets this node hand voice off later
+});
+
+client.on("messageCreate", async (message) => {
+ if (message.author.bot || !message.guildId || !message.content.startsWith("!play ")) return;
+ const voiceChannel = message.member?.voice?.channel;
+ if (!voiceChannel) return void message.reply("Join a voice channel first!");
+
+ const player = await manager.create(message.guildId, { extensions: [net.extensionClass()] });
+ if (!player.connection) await player.connect(voiceChannel);
+
+ const result = await manager.search(message.content.slice(6).trim(), message.author.id);
+ const track = result.tracks[0];
+ if (!track) return void message.reply("No results.");
+ await player.play(markTrack(track, "yt-1"), { requestedBy: message.author.id }); // audio streamed from yt-1
+ message.reply(`Playing **${track.title}**`);
+});
+
+await net.start();
+await client.login(process.env.DISCORD_TOKEN);
+```
+
+To move the Discord voice session itself to another node instead (while nothing is playing), accept it there with
+`net.acceptVoice()` and call `await net.delegateVoice(player, "other-node")` on the bot; `await net.reclaimVoice(player)` takes it
+back. `await net.routeTracks(player, result.tracks)` picks between pulling tracks and handing off the voice automatically. Pair
+nodes without copying files by listening to `net.node.on("peerDiscovered", ...)` and calling
+`net.node.acceptPeer(id, fingerprint)` after comparing the fingerprint out-of-band; both sides must accept each other.
+
+To try it with a real Discord bot, real plugins and Mosquitto, see
+[`examples/net`](https://github.com/ZiProject/ZiPlayer/tree/main/examples/net) (commands are driven by `messageCreate`, with an
+automated `!selftest`).
-## Shared Discord and WebAudio playback
+`@ziplayer/net` relies on three core APIs: `manager.resolveStream(track)` (resolve a stream through plugins without a player),
+`player.disconnect({ silent: true })` (release the voice connection without leaving the Discord channel), and the
+`cacheable: false` flag on single-use extension streams. Only one process can own a `PlayerManager`, so run one node per process.
+Web/WebAudio voice and multi-output mirroring across nodes are not available over `@ziplayer/net` yet. See the
+[net README](https://github.com/ZiProject/ZiPlayer/tree/main/net) for the security model.
+
+---
+
+### Connection ownership (reference)
`Player.connect(voiceChannel)` joins Discord Voice. A browser publisher can subscribe to the same `AudioPlayer`:
```ts
+import { WebAudioConnection } from "ziplayer";
+
const webConnection = new WebAudioConnection({ sessionId: player.id });
webConnection.attachSocket(publisherSocket);
const subscription = await player.connect(webConnection);
@@ -659,3 +871,30 @@ backends and output factories are not part of the player API. The shared `Connec
WebAudio connection state; `Player` delegates WebAudio registration, lookup, and teardown through the Bus. `player.connections`
(also exposed through `PLAYER_QUERY.connection`) returns all currently subscribed Voice and WebAudio connections; each WebAudio
connection can be removed through its registration handle or destroyed during player teardown.
+
+## 📚 Advanced Developer Guide
+
+For contributors, custom controller authors, and AI agent instructions detailing internal Bus protocols, controller state
+ownership, and teardown lifecycle, see [**AGENTS.md**](./AGENTS.md).
+
+---
+
+## 💬 Community & Support
+
+Need help with ZiPlayer, have a question, or want to share your ideas?
+
+Join our Discord community!
+
+
+
+
+
+
+
+- 🐛 **Bug Reports:** Open an issue on GitHub.
+- 💡 **Feature Requests:** Share your ideas through GitHub Discussions.
+- 💬 **Community Support:** Ask questions and get help on Discord.
+
+## 📄 License
+
+MIT © [ZiProject](https://github.com/ZiProject)
diff --git a/core/package.json b/core/package.json
index bf41618a..4c90e042 100644
--- a/core/package.json
+++ b/core/package.json
@@ -1,13 +1,23 @@
{
"name": "ziplayer",
- "version": "1.0.5-dev.6",
- "description": "A modular Discord voice player with plugin system",
+ "version": "1.0.5",
+ "description": "Event-driven Discord voice and music player with plugins, FFmpeg filters, browser (WebAudio) playback and multi-node (MQTT) support",
"keywords": [
"ZiPlayer",
"discord",
"music",
"player",
- "@ziplayer/plugin"
+ "@ziplayer/plugin",
+ "discord-bot",
+ "music-bot",
+ "voice",
+ "opus",
+ "audio",
+ "webaudio",
+ "browser-playback",
+ "mqtt",
+ "cluster",
+ "multi-node"
],
"homepage": "https://player.ziji.best",
"bugs": {
diff --git a/core/src/controller/AntiStuckController.ts b/core/src/controller/AntiStuckController.ts
index 4325fd55..eb81c91c 100644
--- a/core/src/controller/AntiStuckController.ts
+++ b/core/src/controller/AntiStuckController.ts
@@ -89,6 +89,7 @@ async function recover(
reason: string,
handlers: AntiStuckRetryHandlers,
requestId?: string,
+ immediate = false,
): Promise {
const track = session.track;
if (state.disposed || !state.enabled || !track || !session.isActive() || generation !== state.generation) return false;
@@ -112,7 +113,8 @@ async function recover(
attempt: retry + 1,
});
}
- if (state.retryDelayMs > 0) await delay(state.retryDelayMs, AbortSignal.any([session.signal, state.lifecycleAbort.signal]));
+ if (!immediate && state.retryDelayMs > 0)
+ await delay(state.retryDelayMs, AbortSignal.any([session.signal, state.lifecycleAbort.signal]));
if (state.disposed || !session.isActive() || generation !== state.generation) return false;
const ok = await handlers.retry({ session, track, retry: retry + 1, reason });
if (ok) {
@@ -164,10 +166,13 @@ export class AntiStuckController {
const state = this.states.get(playerId);
return state ? policy(state) : {};
});
- bus.registerRpc(CONTROLLER_RPC.antiStuckReport, ({ session, reason, handlers }, ctx) => {
- const state = this.states.get(ctx.playerId);
- return state ? this.reportStuck(ctx.playerId, state, session, reason, handlers) : false;
- });
+ bus.registerRpc(
+ CONTROLLER_RPC.antiStuckReport,
+ ({ session, reason, handlers, immediate }, ctx) => {
+ const state = this.states.get(ctx.playerId);
+ return state ? this.reportStuck(ctx.playerId, state, session, reason, handlers, immediate) : false;
+ },
+ );
}
attach(playerId: string, options: Omit = {}): void {
@@ -212,7 +217,8 @@ export class AntiStuckController {
session: PlaybackSession,
reason: string,
handlers: AntiStuckRetryHandlers,
+ immediate = false,
): Promise {
- return recover(this.bus, playerId, state, session, ++state.generation, reason, handlers);
+ return recover(this.bus, playerId, state, session, ++state.generation, reason, handlers, undefined, immediate);
}
}
diff --git a/core/src/controller/ConnectionController.ts b/core/src/controller/ConnectionController.ts
index b904128d..c7b76c72 100644
--- a/core/src/controller/ConnectionController.ts
+++ b/core/src/controller/ConnectionController.ts
@@ -465,7 +465,9 @@ export class ConnectionController {
slot.sessionId = null;
slot.requestId = null;
try {
- connection?.destroy();
+ // `silent` tears the local voice connection down without sending the "leave channel" payload,
+ // so another node can take over the same Discord voice session (see @ziplayer/net).
+ if (connection && connection.state.status !== VoiceConnectionStatus.Destroyed) connection.destroy(!event.silent);
this.trace(playerId, BUS_OUTPUT.connectionDisconnected, event.reason ? `reason=${event.reason}` : undefined);
this.bus?.emitOutput({
type: BUS_OUTPUT.connectionDisconnected,
diff --git a/core/src/controller/FilterController.ts b/core/src/controller/FilterController.ts
index e7055cf0..ccbf9078 100644
--- a/core/src/controller/FilterController.ts
+++ b/core/src/controller/FilterController.ts
@@ -54,7 +54,12 @@ export class FilterEngine {
this.setSourceStreamType(action.streamType);
return;
case "FILTER_APPLY_AND_SEEK":
- this.lastFilteredStream = await this.applyFiltersAndSeek(action.streamInfo, action.position ?? -1);
+ this.lastFilteredStream = await this.applyFiltersAndSeek(action.streamInfo, action.position ?? -1, signal);
+ return;
+ case "STOP":
+ case "SKIP":
+ this.teardownFFmpeg();
+ this.lastFilteredStream = null;
return;
}
}
@@ -97,6 +102,9 @@ export class FilterEngine {
public get lastFilteredStreamValue(): (StreamInfo & { wasRecreated?: boolean }) | null {
return this.lastFilteredStream;
}
+ public clearLastFilteredStream(): void {
+ this.lastFilteredStream = null;
+ }
public getFilterString(): string {
return this.activeFilters.map((filter) => filter.ffmpegFilter).join(",");
}
@@ -208,8 +216,13 @@ export class FilterEngine {
return this.resourcePort.refreshPlayerResource();
}
- public async applyFiltersAndSeek(streamInfo: StreamInfo, position = -1): Promise {
+ public async applyFiltersAndSeek(
+ streamInfo: StreamInfo,
+ position = -1,
+ signal?: AbortSignal,
+ ): Promise {
this.teardownFFmpeg();
+ this.lastFilteredStream = null;
const generation = ++this.ffmpegGeneration;
const hasSeek = position >= 0;
const filterString = this.getFilterString();
@@ -219,7 +232,7 @@ export class FilterEngine {
let needsFfmpegSeek = hasSeek;
if (hasSeek && streamInfo.recreate) {
- const recreated = await streamInfo.recreate(position);
+ const recreated = await streamInfo.recreate(position, signal);
if (!recreated) throw new Error("Stream recreation returned no stream");
if (generation !== this.ffmpegGeneration) {
recreated.destroy();
@@ -423,11 +436,17 @@ export class FilterController {
constructor(private readonly bus: Bus) {
bus.onAction((action, context) => {
- void this.engines.get(context.playerId)?.handleAction(action, context.signal);
+ return this.engines.get(context.playerId)?.handleAction(action, context.signal);
});
bus.registerQuery(PLAYER_QUERY.filterState, (playerId) => this.engines.get(playerId) ?? null);
bus.registerQuery(PLAYER_QUERY.filterString, (playerId) => this.engines.get(playerId)?.getFilterString() ?? "");
- bus.registerQuery(PLAYER_QUERY.filteredStream, (playerId) => this.engines.get(playerId)?.lastFilteredStreamValue ?? null);
+ bus.registerQuery(PLAYER_QUERY.filteredStream, (playerId) => {
+ const engine = this.engines.get(playerId);
+ if (!engine) return null;
+ const stream = engine.lastFilteredStreamValue;
+ engine.clearLastFilteredStream();
+ return stream;
+ });
bus.registerQuery(
PLAYER_QUERY.filterList,
(playerId) =>
diff --git a/core/src/controller/ForwardController.ts b/core/src/controller/ForwardController.ts
index 86bda13f..10f68163 100644
--- a/core/src/controller/ForwardController.ts
+++ b/core/src/controller/ForwardController.ts
@@ -165,9 +165,10 @@ export class ForwardController {
this.bus.querySync(leaderId, PLAYER_QUERY.forwardLeaderId) ?? this.bus.querySync(leaderId, PLAYER_QUERY.forwardLeader);
if (leaderMode === PlaybackMode.FORWARD || leaderLeader) return false;
+ // Only the follower needs a Discord voice connection (it is what plays the leader's audio).
+ // The leader just has to own an AudioPlayer: it may feed WebAudio outputs only.
const myConn = this.bus.querySync(playerId, PLAYER_QUERY.voiceConnection);
- const leaderConn = this.bus.querySync(leaderId, PLAYER_QUERY.voiceConnection);
- if (!myConn || !leaderConn) return false;
+ if (!myConn) return false;
const leaderAudioPlayer = this.bus.querySync(leaderId, PLAYER_QUERY.audioPlayer);
const playerAudioPlayer = this.bus.querySync(playerId, PLAYER_QUERY.audioPlayer);
diff --git a/core/src/controller/PlaybackController.ts b/core/src/controller/PlaybackController.ts
index 2c5d0995..b835bcf0 100644
--- a/core/src/controller/PlaybackController.ts
+++ b/core/src/controller/PlaybackController.ts
@@ -36,6 +36,10 @@ interface PlaybackSlot {
activeResource: AudioResource | null;
readonly volumeValues: Map;
readonly stopPromises: Map>;
+ /** Resources whose stream died with an AudioPlayer error; their Idle transition is a failure, not a track end. */
+ readonly failedResources: WeakSet;
+ /** Resource that must be paused the instant it becomes audible (in-place reload of a paused track). */
+ pauseOnReady: AudioResource | null;
activeSession: PlaybackSession | null;
transitionTimer: ReturnType | null;
transitionStartResolve: (() => void) | null;
@@ -82,10 +86,10 @@ 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 },
+ { resource: AudioResource; session?: PlaybackSession; from?: Track | null; to?: Track; startPaused?: boolean },
void | Promise
- >(CONTROLLER_RPC.playbackPlay, ({ resource, session, from, to }, ctx) =>
- this.play(ctx.playerId, resource, session, from, to, ctx.signal),
+ >(CONTROLLER_RPC.playbackPlay, ({ resource, session, from, to, startPaused }, ctx) =>
+ this.play(ctx.playerId, resource, session, from, to, ctx.signal, startPaused),
);
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));
@@ -135,6 +139,8 @@ export class PlaybackController {
activeResource: null,
volumeValues: new Map(),
stopPromises: new Map(),
+ failedResources: new WeakSet(),
+ pauseOnReady: null,
activeSession: null,
transitionTimer: null,
transitionStartResolve: null,
@@ -149,10 +155,12 @@ export class PlaybackController {
retry: async ({ session }) => {
if (!session.isActive()) return false;
try {
+ // `position()` refreshes from the resource clock; `session.position` is stale while paused.
+ const position = this.position(playerId) ?? session.position ?? 0;
await this.bus.requestRpc(
playerId,
PLAYER_RPC.playbackRefreshResource,
- { position: session.position },
+ { position },
{ signal: session.signal, timeoutMs: 30000 },
);
return session.isActive();
@@ -164,12 +172,32 @@ export class PlaybackController {
this.bus.action(playerId, { type: PLAYER_ACTION.skip }, { signal: session.signal, sessionId: session.sessionId }),
},
onStateChange: (a, b) => {
+ let pauseNow = false;
+ if (slot.pauseOnReady) {
+ const next = "resource" in b ? b.resource : undefined;
+ if (b.status === AudioPlayerStatus.Playing && next === slot.pauseOnReady) {
+ slot.pauseOnReady = null;
+ pauseNow = true;
+ } else if (b.status === AudioPlayerStatus.Idle || (next && next !== slot.pauseOnReady)) {
+ slot.pauseOnReady = null;
+ }
+ }
this.bus.publish(playerId, BUS_EVENT.stateChanged, a, b);
+ // Same synchronous dispatch as the Playing transition: no frame is sent before the pause.
+ if (pauseNow) slot.audioPlayer.pause(false);
if (b.status === AudioPlayerStatus.Buffering) this.armStuckWatchdog(slot);
else this.clearStuckWatchdog(slot);
if (b.status === AudioPlayerStatus.Idle && a.status !== AudioPlayerStatus.Idle) {
const previousResource = "resource" in a ? a.resource : undefined;
if (!slot.stopping && previousResource && previousResource === slot.activeResource) {
+ if (slot.failedResources.has(previousResource)) {
+ // The stream died (expired URL, destroyed while paused, ...). This is not a natural
+ // track end: keep the session alive so anti-stuck can reload it in place.
+ slot.failedResources.delete(previousResource);
+ slot.volumeValues.delete(previousResource);
+ slot.activeResource = null;
+ return;
+ }
const session = slot.activeSession;
if (session?.isActive()) {
this.bus.event(playerId, { type: BUS_EVENT.trackEnd, session: session.snapshot() });
@@ -183,11 +211,20 @@ export class PlaybackController {
onError: (error) => {
const normalized = toError(error);
const session = slot.activeSession;
+ const failedResource = (error as { resource?: AudioResource } | undefined)?.resource;
+ if (failedResource && failedResource === slot.activeResource) slot.failedResources.add(failedResource);
if (session?.isActive()) {
this.bus.event(playerId, { type: BUS_EVENT.trackError, session: session.snapshot(), error: normalized });
- void this.reportStuck(slot, session, `audio player error: ${normalized.message}`).catch((reportError) =>
- this.reportAsyncFailure(slot, reportError, session.track),
- );
+ const reason = `audio player error: ${normalized.message}`;
+ void this.reportStuck(slot, session, reason, true)
+ .then((recovered) => {
+ // Anti-stuck disabled or gave up without skipping: never leave a dead session behind.
+ if (recovered || slot.disposed || !session.isActive() || slot.activeSession !== session || slot.activeResource)
+ return;
+ if (!session.track) return;
+ return slot.recoveryHandlers.skip({ session, track: session.track, retry: 0, reason });
+ })
+ .catch((reportError) => this.reportAsyncFailure(slot, reportError, session.track));
} else {
this.bus.event(playerId, { type: BUS_EVENT.streamError, error: normalized, track: null });
}
@@ -366,12 +403,12 @@ export class PlaybackController {
// Stuck watchdog / resource refresh / filter errors
// ---------------------------------------------------------------------
- private reportStuck(slot: PlaybackSlot, session: PlaybackSession, reason: string): Promise {
+ private reportStuck(slot: PlaybackSlot, session: PlaybackSession, reason: string, immediate = false): Promise {
if (!session.isActive()) return Promise.resolve(false);
return this.bus.requestRpc(
slot.playerId,
CONTROLLER_RPC.antiStuckReport,
- { session, reason, handlers: slot.recoveryHandlers },
+ { session, reason, handlers: slot.recoveryHandlers, immediate },
{ signal: session.signal },
);
}
@@ -489,6 +526,7 @@ export class PlaybackController {
from?: Track | null,
to?: Track,
signal?: AbortSignal,
+ startPaused = false,
): void | Promise {
const slot = this.slots.get(playerId);
if (!slot || (session && !session.isActive())) return;
@@ -511,6 +549,9 @@ export class PlaybackController {
if (session) session.setResource(resource);
slot.activeSession = session ?? null;
slot.activeResource = resource;
+ // Armed before play(): the AudioPlayer pauses it inside the very stateChange that makes it
+ // Playing (see onStateChange), however long the stream takes to become readable.
+ slot.pauseOnReady = startPaused ? resource : null;
slot.audioPlayer.play(resource);
this.retirePendingSession(playerId);
return volumeUpdate;
@@ -706,6 +747,11 @@ export class PlaybackController {
const slot = this.slots.get(playerId);
if (!slot?.activeResource) return false;
if (signal?.aborted) throw this.outputAbortError();
+ if (slot.audioPlayer.state.status === AudioPlayerStatus.Buffering) {
+ // AudioPlayer.pause() is a no-op while buffering: pause as soon as it becomes audible.
+ slot.pauseOnReady = slot.activeResource;
+ return true;
+ }
return slot.audioPlayer.pause();
}
@@ -715,6 +761,11 @@ export class PlaybackController {
const slot = this.slots.get(playerId);
if (!slot?.activeResource) return false;
if (signal?.aborted) throw this.outputAbortError();
+ if (slot.pauseOnReady) {
+ // Resume requested while a paused reload is still buffering: just don't pause it when ready.
+ slot.pauseOnReady = null;
+ return true;
+ }
return slot.audioPlayer.unpause();
}
diff --git a/core/src/controller/PlaybackPreparationController.ts b/core/src/controller/PlaybackPreparationController.ts
index c809ebdf..2a6c7d5c 100644
--- a/core/src/controller/PlaybackPreparationController.ts
+++ b/core/src/controller/PlaybackPreparationController.ts
@@ -17,6 +17,7 @@ export class PlaybackPreparationController {
private readonly playerId: string;
private readonly bus: Bus;
private readonly isCurrentSession: PlaybackPreparationControllerOptions["isCurrentSession"];
+ private readonly isLatestSession: PlaybackPreparationControllerOptions["isLatestSession"];
private readonly queueSnapshot: PlaybackPreparationControllerOptions["queueSnapshot"];
private readonly setQueueRelated: PlaybackPreparationControllerOptions["setQueueRelated"];
private readonly debug: PlaybackPreparationControllerOptions["debug"];
@@ -25,6 +26,7 @@ export class PlaybackPreparationController {
this.playerId = playerId;
this.bus = options.bus;
this.isCurrentSession = options.isCurrentSession;
+ this.isLatestSession = options.isLatestSession;
this.queueSnapshot = options.queueSnapshot;
this.setQueueRelated = options.setQueueRelated;
this.debug = options.debug;
@@ -68,8 +70,21 @@ export class PlaybackPreparationController {
return related.slice();
}
- public async prepareAutoplay(session: PlaybackSession, context: PlayerMessageContext): Promise {
- if (context.signal.aborted || !this.isCurrentSession(session, context)) return null;
+ /**
+ * Picks the next autoplay candidate. With `allowEnded` the session may already be over (the track
+ * ended and nothing was started, e.g. autoplay found no candidate or failed): Next must still be able
+ * to enter autoplay then, so only require that no newer session replaced it.
+ */
+ public async prepareAutoplay(
+ session: PlaybackSession,
+ context: PlayerMessageContext,
+ allowEnded = false,
+ ): Promise {
+ const stillValid = () =>
+ allowEnded && session.status === "ended" ?
+ !context.signal.aborted && (this.isLatestSession?.(session) ?? true)
+ : this.isCurrentSession(session, context);
+ if (context.signal.aborted || !stillValid()) return null;
if (this.bus.querySync(this.playerId, PLAYER_QUERY.queueLoop) === "track") {
this.bus.requestRpcSync(this.playerId, PLAYER_RPC.queueWillNext, { track: null });
return null;
@@ -94,13 +109,13 @@ export class PlaybackPreparationController {
upcomingTracks: this.queueSnapshot(),
relatedTracks: [],
});
- await this.requestPreload(queueNext, context);
+ if (!allowEnded) await this.requestPreload(queueNext, context);
}
return queueNext;
}
const pool = related.slice(0, Math.min(5, related.length));
const next = queueNext ?? pool[Math.floor(Math.random() * pool.length)];
- if (!next || !this.isCurrentSession(session, context)) return null;
+ if (!next || !stillValid()) return null;
this.bus.requestRpcSync(this.playerId, PLAYER_RPC.queueWillNext, { track: next });
this.bus.event(this.playerId, {
type: BUS_EVENT.willPlay,
@@ -109,10 +124,10 @@ export class PlaybackPreparationController {
relatedTracks: related,
});
const autoPlayEnabled = Boolean(this.bus.querySync(this.playerId, PLAYER_QUERY.queueAutoPlay));
- if (queueNext || autoPlayEnabled) {
+ if ((queueNext || autoPlayEnabled) && !allowEnded) {
await this.requestPreload(next, context);
}
- if (context.signal.aborted || !this.isCurrentSession(session, context)) return null;
+ if (context.signal.aborted || !stillValid()) return null;
return next;
}
diff --git a/core/src/controller/PlaybackSkipController.ts b/core/src/controller/PlaybackSkipController.ts
index c24f4e5a..aaab8145 100644
--- a/core/src/controller/PlaybackSkipController.ts
+++ b/core/src/controller/PlaybackSkipController.ts
@@ -91,8 +91,7 @@ export class PlaybackSkipController {
if (context.signal.aborted) return false;
if (oldSession?.isActive()) {
const transition = this.bus.querySync(this.playerId, PLAYER_QUERY.transitionSettings) as
- | { enabled?: boolean }
- | undefined;
+ { enabled?: boolean } | undefined;
if (transition?.enabled) {
try {
await this.bus.requestRpc(this.playerId, PLAYER_RPC.transitionFadeOutCurrent, undefined);
@@ -118,9 +117,12 @@ export class PlaybackSkipController {
if (context.signal.aborted) return false;
if (!next && this.bus.querySync(this.playerId, PLAYER_QUERY.queueAutoPlay) && oldSession) {
+ // After a natural end nothing may be playing (autoplay found nothing / failed): the old session is
+ // "ended" and Next must still reach autoplay instead of silently ending the queue again.
const candidate = await this.bus.requestRpc(this.playerId, CONTROLLER_RPC.playbackPrepareAutoplay, {
session: oldSession,
context,
+ allowEnded: oldSession.status === "ended",
});
if (context.signal.aborted) return false;
diff --git a/core/src/controller/PlaybackStartController.ts b/core/src/controller/PlaybackStartController.ts
index 72fde415..7cede7e1 100644
--- a/core/src/controller/PlaybackStartController.ts
+++ b/core/src/controller/PlaybackStartController.ts
@@ -115,6 +115,7 @@ export class PlaybackStartController {
await this.bus.requestRpc(this.playerId, CONTROLLER_RPC.playbackRemoteAttach, { stream: loaded.stream });
session.markPlaying(0);
this.consecutiveFailures = 0;
+ if (transition) this.sessionController.retirePendingPrevious(this.playerId);
this.bus.event(this.playerId, { type: BUS_EVENT.trackStarted, session: session.snapshot(), track });
await this.prepareTrack(session, context);
return;
diff --git a/core/src/controller/PlaybackTrackEndController.ts b/core/src/controller/PlaybackTrackEndController.ts
index eea7e148..c8d1f827 100644
--- a/core/src/controller/PlaybackTrackEndController.ts
+++ b/core/src/controller/PlaybackTrackEndController.ts
@@ -82,7 +82,9 @@ export class PlaybackTrackEndController {
if (!this.queueSnapshot().length) return;
const generation = ++this.queueStartGeneration;
this.queueStartPromise = this.startQueuedTrackAfterEnd()
- .catch((error) => reportStreamError(this.bus, this.playerId, queryPlaybackSession(this.bus, this.playerId)?.track ?? null, error))
+ .catch((error) =>
+ reportStreamError(this.bus, this.playerId, queryPlaybackSession(this.bus, this.playerId)?.track ?? null, error),
+ )
.finally(() => {
if (generation === this.queueStartGeneration) this.queueStartPromise = null;
});
@@ -138,6 +140,10 @@ export class PlaybackTrackEndController {
}
}
+ // A manual skip may have taken over while related tracks were being fetched: it already started
+ // (or is starting) the next track, so starting another one here would skip twice.
+ if (!current.isActive() || this.lifecycleSignal.aborted) return;
+
// Emit willNext
this.bus.requestRpcSync(this.playerId, PLAYER_RPC.queueWillNext, { track: next });
diff --git a/core/src/controller/QueueController.ts b/core/src/controller/QueueController.ts
index 4c91308c..82dcd935 100644
--- a/core/src/controller/QueueController.ts
+++ b/core/src/controller/QueueController.ts
@@ -442,7 +442,7 @@ export class QueueController {
public constructor(private readonly bus: Bus) {
bus.onAction((action, context) => {
- void this.states.get(context.playerId)?.handleAction(action, context);
+ return this.states.get(context.playerId)?.handleAction(action, context);
});
bus.registerQuery(PLAYER_QUERY.currentTrack, (playerId) => this.states.get(playerId)?.current ?? null);
bus.registerQuery(PLAYER_QUERY.queueCurrent, (playerId) => this.states.get(playerId)?.current ?? null);
diff --git a/core/src/controller/ResourceRefreshController.ts b/core/src/controller/ResourceRefreshController.ts
index bd030879..b21e280b 100644
--- a/core/src/controller/ResourceRefreshController.ts
+++ b/core/src/controller/ResourceRefreshController.ts
@@ -69,6 +69,8 @@ export class ResourceRefreshController {
const session = queryPlaybackSession(this.bus, playerId);
if (!state || !session?.track || !session.isActive()) throw new Error("No active playback session");
const sessionId = session.id;
+ // A reload must not change the user's intent: a paused track stays paused.
+ const wasPaused = session.status === "paused";
const refreshSequence = ++state.refreshSequence;
if (state.refreshAbortController) {
state.refreshAbortController.abort();
@@ -121,8 +123,9 @@ export class ResourceRefreshController {
if (!isCurrentRefresh()) throw new Error("Playback resource refresh superseded");
session.setResource(resource);
session.setPlaybackOffset(Math.max(0, position));
- await this.bus.requestRpc(playerId, CONTROLLER_RPC.playbackPlay, { resource, session }, { signal });
- session.markPlaying(Math.max(0, position));
+ await this.bus.requestRpc(playerId, CONTROLLER_RPC.playbackPlay, { resource, session, startPaused: wasPaused }, { signal });
+ if (wasPaused) session.markPaused(Math.max(0, position));
+ else session.markPlaying(Math.max(0, position));
this.bus.event(playerId, { type: BUS_EVENT.playbackStateChanged, session: session.snapshot() });
return session.snapshot();
} finally {
diff --git a/core/src/controller/SaveController.ts b/core/src/controller/SaveController.ts
index bfc9218f..8a3d458d 100644
--- a/core/src/controller/SaveController.ts
+++ b/core/src/controller/SaveController.ts
@@ -78,11 +78,16 @@ export class SaveController {
track,
options,
signal,
- (exportTrack) => state.resolveStream(exportTrack),
+ (exportTrack, streamSignal) => state.resolveStream(exportTrack, { signal: streamSignal }),
);
if (!saveOptions.filter?.length && (!saveOptions.seek || saveOptions.seek <= 0)) {
- return this.decorateStream(this.bindAbortToStream(streamInfo.stream, operationSignal), saveOptions, streamInfo.metadata);
+ return this.decorateStream(
+ this.bindAbortToStream(streamInfo.stream, operationSignal, streamInfo.destroy),
+ saveOptions,
+ streamInfo.metadata,
+ streamInfo.destroy,
+ );
}
const filterController = new FilterEngine({ refreshPlayerResource: async () => true }, state.debug, undefined, {
@@ -103,7 +108,12 @@ export class SaveController {
this.throwIfAborted(state, operationSignal);
this.disposeFilterOnStreamEnd(state, filterController, output);
cleanupAbort();
- return this.decorateStream(this.bindAbortToStream(output, operationSignal), saveOptions, streamInfo.metadata);
+ return this.decorateStream(
+ this.bindAbortToStream(output, operationSignal, streamInfo.destroy),
+ saveOptions,
+ streamInfo.metadata,
+ streamInfo.destroy,
+ );
} catch (error) {
cleanupAbort();
state.activeFilterEngines.delete(filterController);
@@ -126,9 +136,14 @@ export class SaveController {
track,
options,
signal,
- (exportTrack) => state.resolveVideoStream(exportTrack),
+ (exportTrack, streamSignal) => state.resolveVideoStream(exportTrack, { signal: streamSignal }),
+ );
+ return this.decorateStream(
+ this.bindAbortToStream(streamInfo.stream, operationSignal, streamInfo.destroy),
+ saveOptions,
+ streamInfo.metadata,
+ streamInfo.destroy,
);
- return this.decorateStream(this.bindAbortToStream(streamInfo.stream, operationSignal), saveOptions, streamInfo.metadata);
}
/**
@@ -140,15 +155,23 @@ export class SaveController {
track: Track,
options: O | string | undefined,
signal: AbortSignal | undefined,
- resolver: (exportTrack: Track) => ReturnType,
+ resolver: (exportTrack: Track, signal?: AbortSignal) => ReturnType,
) {
const saveOptions = (typeof options === "string" ? { filename: options } : (options ?? {})) as O;
- const operationSignal = signal ?? saveOptions.signal;
+ const operationSignal =
+ signal && saveOptions.signal && signal !== saveOptions.signal ?
+ AbortSignal.any([signal, saveOptions.signal])
+ : (signal ?? saveOptions.signal);
state.debug(`[SaveController] save called for track: ${track.title}`);
const exportTrack = this.prepareExportTrack(track, saveOptions);
await this.applyMiddleware(state, exportTrack, operationSignal);
- const streamInfo = await this.resolveWithTimeout(state, () => resolver(exportTrack), saveOptions.timeout, operationSignal);
+ const streamInfo = await this.resolveWithTimeout(
+ state,
+ () => resolver(exportTrack, operationSignal),
+ saveOptions.timeout,
+ operationSignal,
+ );
if (!streamInfo?.stream) throw new Error(`No save stream available for track: ${track.title}`);
state.debug(`[SaveController] Save stream obtained for track: ${track.title}`);
@@ -193,19 +216,46 @@ export class SaveController {
timer = setTimeout(() => reject(new Error(`Save operation timed out after ${timeoutMs}ms`)), timeoutMs);
})
: null;
+ let settled = false;
+ const resolvePromise = resolve().then(
+ (res) => {
+ if (settled && res && typeof (res as any).stream?.destroy === "function") {
+ try {
+ (res as any).stream.destroy();
+ } catch {}
+ }
+ return res;
+ },
+ (err) => {
+ if (!settled) throw err;
+ return undefined as unknown as T;
+ },
+ );
try {
- return await Promise.race(timeout ? [resolve(), timeout, aborted] : [resolve(), aborted]);
+ return await Promise.race(timeout ? [resolvePromise, timeout, aborted] : [resolvePromise, aborted]);
} finally {
+ settled = true;
if (timer) clearTimeout(timer);
if (onAbort) operationSignal.removeEventListener("abort", onAbort);
}
}
- private decorateStream(stream: T, options: SaveOptions, streamInfoMetadata?: Record): T {
- const exportStream = stream as T & { filename?: string; metadata?: Record; quality?: SaveOptions["quality"] };
+ private decorateStream(
+ stream: T,
+ options: SaveOptions,
+ streamInfoMetadata?: Record,
+ destroyHook?: () => void | Promise,
+ ): T {
+ const exportStream = stream as T & {
+ filename?: string;
+ metadata?: Record;
+ quality?: SaveOptions["quality"];
+ destroyStream?: () => void | Promise;
+ };
if (options.filename) exportStream.filename = options.filename;
exportStream.metadata = { ...(streamInfoMetadata ?? {}), ...(options.metadata ?? {}) };
if (options.quality) exportStream.quality = options.quality;
+ if (destroyHook) exportStream.destroyStream = destroyHook;
return exportStream;
}
@@ -229,9 +279,21 @@ export class SaveController {
};
}
- private bindAbortToStream(stream: T, signal?: AbortSignal): T {
+ private bindAbortToStream(stream: T, signal?: AbortSignal, destroyHook?: () => void | Promise): T {
+ const runDestroy = () => {
+ if (destroyHook) {
+ try {
+ void destroyHook();
+ } catch {}
+ }
+ };
+ stream.once("close", runDestroy);
+ stream.once("error", runDestroy);
if (!signal) return stream;
- const onAbort = () => stream.destroy(this.abortError());
+ const onAbort = () => {
+ runDestroy();
+ stream.destroy(this.abortError());
+ };
if (signal.aborted) onAbort();
else signal.addEventListener("abort", onAbort, { once: true });
const cleanup = () => signal.removeEventListener("abort", onAbort);
diff --git a/core/src/controller/StreamController.ts b/core/src/controller/StreamController.ts
index d9c33655..334a778f 100644
--- a/core/src/controller/StreamController.ts
+++ b/core/src/controller/StreamController.ts
@@ -153,7 +153,13 @@ export class StreamController {
state: StreamState,
stream: { handle?: NonNullable },
): Promise {
- state.remoteHandle = stream?.handle ?? null;
+ const nextHandle = stream?.handle ?? null;
+ const previousHandle = state.remoteHandle;
+ if (previousHandle && previousHandle !== nextHandle) {
+ if (previousHandle.destroy) await previousHandle.destroy();
+ else if (previousHandle.stop) await previousHandle.stop();
+ }
+ state.remoteHandle = nextHandle;
state.remotePaused = false;
if (this.bus.hasRpc(CONTROLLER_RPC.playbackModeSet)) {
this.bus.requestRpcSync(playerId, CONTROLLER_RPC.playbackModeSet, { mode: PlaybackMode.REMOTE });
diff --git a/core/src/extensions/index.ts b/core/src/extensions/index.ts
index d1b6e701..2d783be9 100644
--- a/core/src/extensions/index.ts
+++ b/core/src/extensions/index.ts
@@ -437,8 +437,8 @@ export class ExtensionManager {
);
if (hasStream || hasHandle) {
- // Only cache if it's a reusable stream (not remote with handle)
- if (!isRemote) {
+ // Only cache reusable streams (not remote handles, not streams that opt out with cacheable: false)
+ if (!isRemote && (result as StreamInfo).cacheable !== false) {
this.setCachedStream(track, result as StreamInfo);
}
return result as StreamInfo;
diff --git a/core/src/output/WebAudioConnection.ts b/core/src/output/WebAudioConnection.ts
index 426cc7db..1723a89d 100644
--- a/core/src/output/WebAudioConnection.ts
+++ b/core/src/output/WebAudioConnection.ts
@@ -1,5 +1,11 @@
import { EventEmitter } from "node:events";
-import { VoiceConnectionStatus, type AudioPlayer, type PlayerSubscription } from "@discordjs/voice";
+import {
+ AudioPlayerStatus,
+ VoiceConnectionStatus,
+ type AudioPlayer,
+ type AudioPlayerState,
+ type PlayerSubscription,
+} from "@discordjs/voice";
import { validateOpusPacketDuration, validateOpusPacketFraming } from "../audio/OpusSourceAdapter";
import type { DebugLogger } from "../types";
@@ -175,6 +181,10 @@ export class WebAudioConnection extends EventEmitter {
private speaking = false;
private destroyed = false;
private manuallyDisconnected = false;
+ private playerStateListener: {
+ player: AudioPlayer;
+ listener: (oldState: AudioPlayerState, newState: AudioPlayerState) => void;
+ } | null = null;
// Metrics
private dispatchedPackets = 0;
@@ -344,6 +354,7 @@ export class WebAudioConnection extends EventEmitter {
this.state.subscription = subscription;
this.updateState();
this.reset();
+ this.watchPlayer(targetPlayer);
return subscription;
}
@@ -356,10 +367,61 @@ export class WebAudioConnection extends EventEmitter {
this.pendingPacket = null;
}
+ /**
+ * Drops every audio frame that is queued but not yet delivered (pending packet and per-socket
+ * backlog) and tells listeners to discard what they already buffered. Call it whenever the audio
+ * source changes abruptly (skip, stop, seek, resource reload) so stale frames of the previous
+ * track are never heard before the new one. Sequence/timestamps keep counting, so there is no gap.
+ */
+ public flush(reason = "manual"): void {
+ if (this.destroyed) return;
+ this.pendingPacket = null;
+ for (const queue of this.socketQueues.values()) queue.length = 0;
+ const message = JSON.stringify({ v: 1, type: "playback:flush", sessionId: this.sessionId, reason });
+ for (const socket of [...this.sockets]) {
+ if (socket.readyState !== 1 /* OPEN */) continue;
+ try {
+ socket.send(message);
+ } catch (err: any) {
+ this.debugLogger?.(`[WebAudioConnection] Error sending flush: ${err?.message}`);
+ this.detachSocket(socket);
+ }
+ }
+ this.emit("flush", reason);
+ }
+
+ /** Flushes on every abrupt source change observed on the subscribed AudioPlayer. */
+ private watchPlayer(player: AudioPlayer): void {
+ this.unwatchPlayer();
+ const listener = (oldState: AudioPlayerState, newState: AudioPlayerState) => {
+ // Coming from Idle there is no previous audio to discard: either nothing played, the track
+ // ended by itself (its tail must still be heard) or an abrupt stop already flushed below.
+ if (oldState.status === AudioPlayerStatus.Idle) return;
+ const oldResource = "resource" in oldState ? oldState.resource : undefined;
+ if (newState.status === AudioPlayerStatus.Idle) {
+ // readableEnded === true: the stream was consumed to EOF (natural end). Anything else
+ // (stop, skip, destroyed stream) is an abrupt cut and must not leave frames behind.
+ if (oldResource && !oldResource.playStream?.readableEnded) this.flush("stopped");
+ return;
+ }
+ const newResource = "resource" in newState ? newState.resource : undefined;
+ if (newResource && newResource !== oldResource) this.flush("resource-changed");
+ };
+ player.on("stateChange", listener);
+ this.playerStateListener = { player, listener };
+ }
+
+ private unwatchPlayer(): void {
+ if (!this.playerStateListener) return;
+ this.playerStateListener.player.off("stateChange", this.playerStateListener.listener);
+ this.playerStateListener = null;
+ }
+
/**
* Unsubscribes from the active AudioPlayer subscription.
*/
public unsubscribe(): boolean {
+ this.unwatchPlayer();
const sub = this.state.subscription;
if (!sub) return false;
this.state.subscription = undefined;
@@ -551,6 +613,7 @@ export class WebAudioConnection extends EventEmitter {
public destroy(): void {
if (this.destroyed) return;
this.destroyed = true;
+ this.unwatchPlayer();
this.unsubscribe();
this.state.status = VoiceConnectionStatus.Destroyed;
diff --git a/core/src/plugins/index.ts b/core/src/plugins/index.ts
index 348e474f..139c0b28 100644
--- a/core/src/plugins/index.ts
+++ b/core/src/plugins/index.ts
@@ -844,7 +844,7 @@ export class PluginManager {
if (cached && Date.now() < cached.expiresAt) {
const s = cached.streamInfo?.stream;
- if (!s || s.destroyed || (s as any).readable === false) {
+ if (!s || s.destroyed || (s as any).readable === false || (s as any).readableEnded || (s as any)._readableState?.ended) {
this.debug(`[StreamCache] Dead stream detected, evicting: ${track.title}`);
runtime.streamCache.delete(key);
return null;
diff --git a/core/src/structures/PlaybackOrchestrator.ts b/core/src/structures/PlaybackOrchestrator.ts
index a17b0924..3ada1708 100644
--- a/core/src/structures/PlaybackOrchestrator.ts
+++ b/core/src/structures/PlaybackOrchestrator.ts
@@ -100,11 +100,11 @@ export class PlaybackOrchestrator {
return state.start.startResource(resource, track, context);
},
);
- bus.registerRpc<{ session: PlaybackSession; context: PlayerMessageContext }, Promise>(
+ bus.registerRpc<{ session: PlaybackSession; context: PlayerMessageContext; allowEnded?: boolean }, Promise>(
CONTROLLER_RPC.playbackPrepareAutoplay,
- ({ session, context }, ctx) => {
+ ({ session, context, allowEnded }, ctx) => {
const state = this.states.get(ctx.playerId);
- return state ? state.prepare.prepareAutoplay(session, context) : Promise.resolve(null);
+ return state ? state.prepare.prepareAutoplay(session, context, allowEnded) : Promise.resolve(null);
},
);
bus.registerRpc<{ track?: Track | null }, Promise>(CONTROLLER_RPC.playbackCreateRelatedTracks, ({ track }, ctx) => {
@@ -150,6 +150,7 @@ export class PlaybackOrchestrator {
const prepare = new PlaybackPreparationController(playerId, {
bus: this.bus,
isCurrentSession: callbacks.matchesContext,
+ isLatestSession: (session) => this.sessionController.current(playerId) === session,
queueSnapshot: () => callbacks.queueSnapshot(playerId),
setQueueRelated: (tracks) => callbacks.setQueueRelated(playerId, tracks),
debug,
diff --git a/core/src/structures/Player.ts b/core/src/structures/Player.ts
index 25370bd4..5b3bdb56 100644
--- a/core/src/structures/Player.ts
+++ b/core/src/structures/Player.ts
@@ -358,9 +358,17 @@ export class Player extends EventEmitter {
public getWebAudioSubscribers() {
return this.bus.requestRpcSync(this.playerId, PLAYER_RPC.connectionWebAudioList, undefined);
}
- public async disconnect(): Promise {
+ /**
+ * Disconnects the voice connection. With `{ silent: true }` the local connection is destroyed
+ * without leaving the Discord voice channel (used when handing the voice session to another node).
+ */
+ public async disconnect(options?: { silent?: boolean }): Promise {
return this.bus
- .request(this.playerId, { type: BUS_REQUEST.connectionDisconnect, requestId: createPlayerRequestId() })
+ .request(this.playerId, {
+ type: BUS_REQUEST.connectionDisconnect,
+ requestId: createPlayerRequestId(),
+ silent: options?.silent === true ? true : undefined,
+ })
.then(() => undefined);
}
@@ -719,8 +727,9 @@ export class Player extends EventEmitter {
.catch(() => false);
}
async save(track: Track, options?: SaveOptions | string): Promise {
+ const signal = typeof options === "object" ? options?.signal : undefined;
try {
- return await this.bus.requestRpc(this.playerId, PLAYER_RPC.save, { track, options });
+ return await this.bus.requestRpc(this.playerId, PLAYER_RPC.save, { track, options }, { signal });
} catch (error) {
this.debug("[Player] save error:", error);
this.emit("playerError", error as Error, track);
@@ -729,8 +738,9 @@ export class Player extends EventEmitter {
}
async saveVideo(track: Track, options?: SaveVideoOptions | string): Promise {
if (!track) throw new TypeError("A track is required to save video");
+ const signal = typeof options === "object" ? options?.signal : undefined;
try {
- return await this.bus.requestRpc(this.playerId, PLAYER_RPC.saveVideo, { track, options });
+ return await this.bus.requestRpc(this.playerId, PLAYER_RPC.saveVideo, { track, options }, { signal });
} catch (error) {
this.debug("[Player] saveVideo error:", error);
this.emit("playerError", error as Error, track);
@@ -778,10 +788,11 @@ export class Player extends EventEmitter {
return false;
}
return this.bus
- .requestRpc<
- { query: string | Track | Track[]; index: number; requestedBy?: TrackRequester },
- boolean
- >(this.playerId, PLAYER_RPC.queueInsert, { query, index, requestedBy })
+ .requestRpc<{ query: string | Track | Track[]; index: number; requestedBy?: TrackRequester }, boolean>(
+ this.playerId,
+ PLAYER_RPC.queueInsert,
+ { query, index, requestedBy },
+ )
.catch(() => false);
}
public remove(index: number): Track | null {
@@ -968,8 +979,9 @@ export class Player extends EventEmitter {
extension,
});
}
- public subscribeTo(leader: Player | string, options?: { forwardMode?: boolean }): boolean {
- return this.bus.requestRpcSync(this.playerId, PLAYER_RPC.forwardSubscribe, { leader, options });
+
+ public subscribeTo(leader: Player | string, options?: { forwardMode?: boolean }): Promise {
+ return this.bus.requestRpc(this.playerId, PLAYER_RPC.forwardSubscribe, { leader, options });
}
public unsubscribeForward(reason?: string): boolean {
return this.bus.requestRpcSync(this.playerId, PLAYER_RPC.forwardUnsubscribe, { reason });
diff --git a/core/src/structures/PlayerManager.ts b/core/src/structures/PlayerManager.ts
index 70eb9c27..9423a19f 100644
--- a/core/src/structures/PlayerManager.ts
+++ b/core/src/structures/PlayerManager.ts
@@ -18,6 +18,9 @@ import {
SharedControllerSet,
SourcePluginLike,
type TrackRequester,
+ type Track,
+ type StreamInfo,
+ normalizeStreamInfo,
} from "../types";
import type { BaseExtension } from "../extensions";
import { PlayerEventDebug } from "../controller/PlayerEventDebug";
@@ -558,8 +561,8 @@ export class PlayerManager extends EventEmitter {
this.controllers.save?.attach(playerId, {
middleware: [async (track) => this.controllers.trackLoader.applyMiddleware(playerId, track)],
middlewareContext: { playerId, manager: this } as any,
- resolveStream: (track) => pluginManager.getStream(track, { context: { playerId } }),
- resolveVideoStream: (track) => pluginManager.getVideo(track, { playerId }),
+ resolveStream: (track, options) => pluginManager.getStream(track, { context: { playerId, signal: options?.signal } }),
+ resolveVideoStream: (track, options) => pluginManager.getVideo(track, { playerId, signal: options?.signal }),
debug: channel("SaveController"),
});
this.controllers.filter?.attach(playerId, undefined, channel("FilterController"), {
@@ -1006,7 +1009,11 @@ export class PlayerManager extends EventEmitter {
*
* ## Requirements
* - All guilds must already have active players.
- * - All players must already be connected to voice channels.
+ * - Every follower must already be connected to a voice channel.
+ * - The leader only needs an AudioPlayer (it may be a WebAudio-only player).
+ *
+ * Subscription is asynchronous; failures are reported through the manager debug log.
+ * Calling the returned cleanup also cancels subscriptions that have not finished yet.
*
* @param {PlaybackMirrorOptions} options Playback mirror configuration.
*
@@ -1030,10 +1037,11 @@ export class PlayerManager extends EventEmitter {
if (!leader) {
throw new Error(`subscribeForwardMirror: no player for leader guild ${options.leaderGuildId}`);
}
- if (!leader.connection) {
- throw new Error(`Leader player ${options.leaderGuildId} is not connected to a voice channel`);
+ if (!leader.audioPlayer) {
+ throw new Error(`Leader player ${options.leaderGuildId} has no AudioPlayer`);
}
const followers = [...new Set(options.followerGuildIds)].filter((id) => id !== options.leaderGuildId);
+ let stopped = false;
for (const gid of followers) {
const fp = this.get(gid);
@@ -1048,12 +1056,20 @@ export class PlayerManager extends EventEmitter {
continue;
}
- fp.subscribeTo(leader, {
- forwardMode: options.forwardMode,
- });
+ void fp
+ .subscribeTo(leader, {
+ forwardMode: options.forwardMode,
+ })
+ .then((subscribed) => {
+ if (!subscribed) this.debug(`Playback mirror: follower ${gid} could not subscribe to ${options.leaderGuildId}`);
+ // Cleanup ran while the subscription was still in flight: undo it now.
+ else if (stopped) fp.unsubscribeForward();
+ })
+ .catch((error) => this.debug(`Playback mirror: follower ${gid} subscribe failed: ${error?.message ?? error}`));
}
return () => {
+ stopped = true;
for (const gid of followers) {
const fp = this.get(gid);
@@ -1358,6 +1374,18 @@ export class PlayerManager extends EventEmitter {
}
}
+ /**
+ * Resolves a playable stream for `track` through the manager's plugins without needing a player.
+ * The caller owns the returned stream and must destroy it. Used by `@ziplayer/net` stream providers.
+ */
+ async resolveStream(track: Track, options?: { fresh?: boolean }): Promise {
+ this.assertNotDisposed();
+ const pluginManager = this.controllers.plugin?.getSharedManager();
+ if (!pluginManager) throw new Error("PluginController is unavailable");
+ const info = await pluginManager.getStream(track, { fresh: options?.fresh });
+ return info ? normalizeStreamInfo(track, info) : null;
+ }
+
/**
* Clear search cache
*/
diff --git a/core/src/structures/StreamManager.ts b/core/src/structures/StreamManager.ts
index 12cdd40c..e106fc10 100644
--- a/core/src/structures/StreamManager.ts
+++ b/core/src/structures/StreamManager.ts
@@ -231,7 +231,14 @@ export class StreamManager extends EventEmitter {
if ((managed.stream as any)._readableState?.flowing === true) {
attach();
} else {
- managed.stream.once("pipe", attach);
+ const attachBeforeFlowing = (event: string) => {
+ if (event !== "data") return;
+ managed.stream.off("newListener", attachBeforeFlowing);
+ attach();
+ };
+ // Install the counter before a pipe's first data listener starts flowing the source.
+ managed.stream.on("newListener", attachBeforeFlowing);
+ managed.stream.once("close", () => managed.stream.off("newListener", attachBeforeFlowing));
}
}
diff --git a/core/src/types/bus.ts b/core/src/types/bus.ts
index 8325e5ab..5ad5334a 100644
--- a/core/src/types/bus.ts
+++ b/core/src/types/bus.ts
@@ -78,7 +78,7 @@ export type PlayerConnectionInput =
channel: VoiceChannel;
options?: { deaf?: boolean; mute?: boolean; group?: string };
}
- | { type: typeof BUS_REQUEST.connectionDisconnect; requestId: PlayerRequestId; reason?: string }
+ | { type: typeof BUS_REQUEST.connectionDisconnect; requestId: PlayerRequestId; reason?: string; silent?: boolean }
| { type: typeof BUS_REQUEST.connectionReconnect; requestId: PlayerRequestId; channel: VoiceChannel };
export type PlayerPreloadInput = { type: typeof BUS_REQUEST.preloadRequest; requestId: PlayerRequestId; track: Track };
export type PlayerRecoveryInput = {
@@ -188,15 +188,16 @@ 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]
@@ -324,7 +325,10 @@ export interface PlayerRpcMap {
"playback.loadFreshCurrent": { request: { track: Track }; response: TrackLoadResult | null };
"playback.promotePreload": { request: { track: Track }; response: AudioResource | null };
"playback.transitionLock": { request: { active: boolean }; response: void };
- "playback.prepareAutoplay": { request: { session: PlaybackSession; context: PlayerMessageContext }; response: Track | null };
+ "playback.prepareAutoplay": {
+ request: { session: PlaybackSession; context: PlayerMessageContext; allowEnded?: boolean };
+ response: Track | null;
+ };
"playback.start": { request: { track: Track; context: PlayerMessageContext; from: Track | null }; response: void };
"playback.startResource": { request: { resource: AudioResource; track: Track }; response: boolean };
"forward.health": { request: undefined; response: ForwardHealthStatus };
diff --git a/core/src/types/controller.ts b/core/src/types/controller.ts
index c773388f..d021e5e9 100644
--- a/core/src/types/controller.ts
+++ b/core/src/types/controller.ts
@@ -85,15 +85,7 @@ 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;
@@ -162,6 +154,8 @@ export interface AntiStuckReportRequest {
session: PlaybackSession;
reason: string;
handlers: AntiStuckRetryHandlers;
+ /** Hard failure (stream already dead): retry right away instead of waiting `retryDelayMs`. */
+ immediate?: boolean;
}
export interface TrackLoadRequest {
track: Track;
diff --git a/core/src/types/core.ts b/core/src/types/core.ts
index 32940ce3..efd2404d 100644
--- a/core/src/types/core.ts
+++ b/core/src/types/core.ts
@@ -65,7 +65,14 @@ export interface RawStreamInfo {
inputType?: StreamType;
metadata?: Record;
position?: number;
- recreate?: (position: number) => Promise;
+ recreate?: (position: number, signal?: AbortSignal) => Promise;
+ /** Custom cleanup hook to cancel/abort upstream resources (e.g. SABR stream, network readers). */
+ destroy?: () => void | Promise;
+ /**
+ * Set to `false` when the stream is single-use (for example data pulled from another node) so the extension
+ * manager does not cache it and hand the same, already consumed stream to the next play of this track.
+ */
+ cacheable?: boolean;
remote?: boolean;
handle?: {
play(): Promise;
@@ -80,7 +87,7 @@ export interface RawStreamInfo {
/**
* Normalized streaming information for audio playback.
- * Guaranteed to have `track` and `streamType`.
+ * Guaranteed to have `track`, `streamType`, and `destroy`.
*/
export interface StreamInfo extends RawStreamInfo {
stream?: Readable;
@@ -90,6 +97,7 @@ export interface StreamInfo extends RawStreamInfo {
inputType?: StreamType;
/** @deprecated Use streamType */
type?: "webm/opus" | "ogg/opus" | "arbitrary" | "url" | string;
+ destroy?: () => void | Promise;
}
export function inferStreamType(info: Partial): StreamType {
@@ -108,12 +116,34 @@ export function normalizeStreamInfo(requestedTrack: Track, info: RawStreamInfo):
if (String(streamType).toLowerCase() === "raw") {
throw new TypeError("Raw audio input is unsupported; provide encoded audio");
}
+ const defaultDestroy = () => {
+ if (info.stream && !info.stream.destroyed && typeof info.stream.destroy === "function") {
+ try {
+ info.stream.destroy();
+ } catch {}
+ }
+ if (info.handle && typeof (info.handle as any).destroy === "function") {
+ try {
+ void (info.handle as any).destroy();
+ } catch {}
+ }
+ };
+ const destroy =
+ typeof info.destroy === "function" ?
+ () => {
+ try {
+ void info.destroy!();
+ } catch {}
+ defaultDestroy();
+ }
+ : defaultDestroy;
return {
...info,
track: info.track ?? requestedTrack,
streamType,
inputType: info.inputType ?? streamType,
type: info.type ?? (streamType as string),
+ destroy,
};
}
diff --git a/core/src/types/options.ts b/core/src/types/options.ts
index b4060944..35ba5cf7 100644
--- a/core/src/types/options.ts
+++ b/core/src/types/options.ts
@@ -20,6 +20,8 @@ export interface PlaybackStartControllerOptions {
export interface PlaybackPreparationControllerOptions {
bus: Bus;
isCurrentSession: (session: PlaybackSession, context: import("./bus").PlayerMessageContext) => boolean;
+ /** True while `session` is still the player's latest session, even after it ended or stopped. */
+ isLatestSession?: (session: PlaybackSession) => boolean;
queueSnapshot: () => Track[];
setQueueRelated: (tracks: Track[]) => void;
debug?: DebugLogger;
@@ -49,8 +51,8 @@ export interface PlaybackPlayControllerOptions {
export interface SaveControllerOptions {
middleware?: TrackMiddleware[];
middlewareContext: import("./core").TrackMiddlewareContext;
- resolveStream: (track: Track) => Promise;
- resolveVideoStream: (track: Track) => Promise;
+ resolveStream: (track: Track, options?: { signal?: AbortSignal }) => Promise;
+ resolveVideoStream: (track: Track, options?: { signal?: AbortSignal }) => Promise;
ffmpegPath?: string | null;
debug?: DebugLogger;
bus?: Bus;
diff --git a/examples/backend/package.json b/examples/backend/package.json
index 016e74e1..5ea6ba35 100644
--- a/examples/backend/package.json
+++ b/examples/backend/package.json
@@ -9,6 +9,7 @@
"@ziplayer/client": "file:../../client",
"@ziplayer/plugin": "file:../../plugins",
"dotenv": "^18.0.7",
+ "opus-decoder": "^0.7.12",
"ws": "^8.19.0",
"ziplayer": "file:../../core"
},
diff --git a/examples/bilibili-example.ts b/examples/bilibili-example.ts
new file mode 100644
index 00000000..aec871ad
--- /dev/null
+++ b/examples/bilibili-example.ts
@@ -0,0 +1,31 @@
+import { PlayerManager } from "ziplayer";
+import { BilibiliPlugin } from "../plugins";
+
+const manager = new PlayerManager({
+ plugins: [
+ new BilibiliPlugin({
+ // sessdata: process.env.BILIBILI_SESSDATA, // tuỳ chọn: video hạn chế / Hi-Res
+ quality: "super",
+ preferHiRes: false,
+ multiPartAsPlaylist: true,
+ maxPlaylistItems: 100,
+ }),
+ ],
+});
+
+async function demo(guildId: string, userId: string, channel: any) {
+ const player = await manager.create(guildId, { userdata: { channel } });
+ await player.connect(channel);
+
+ // Từ khoá (tiền tố "bilibili:" giúp ép dùng plugin này)
+ await player.play("bilibili: 周杰伦 青花瓷", userId);
+
+ // Link video, BV, av, link rút gọn b23.tv
+ await player.play("https://www.bilibili.com/video/BV1r7411p7R4", userId);
+ await player.play("BV1r7411p7R4", userId);
+
+ // Playlist: favorites (fid / ml…) hoặc kênh UP
+ // const tracks = await manager.getAll?.(); // tuỳ API của bạn
+}
+
+export { demo };
diff --git a/examples/lavalink/package.json b/examples/lavalink/package.json
index 1f0c8149..8a1227e4 100644
--- a/examples/lavalink/package.json
+++ b/examples/lavalink/package.json
@@ -17,7 +17,7 @@
"dependencies": {
"@discordjs/opus": "^0.10.0",
"@discordjs/voice": "^0.19.0",
- "@ziplayer/extension": "file:../../extension",
+ "@ziplayer/extension": "file:../../extensions",
"@ziplayer/plugin": "file:../../plugins",
"lodash": "^4.17.21",
"discord.js": "^14.22.1",
diff --git a/examples/lyrics ext/package.json b/examples/lyrics ext/package.json
index 677fbab7..c6506e52 100644
--- a/examples/lyrics ext/package.json
+++ b/examples/lyrics ext/package.json
@@ -12,7 +12,7 @@
"dependencies": {
"@discordjs/opus": "^0.10.0",
"@discordjs/voice": "^0.19.0",
- "@ziplayer/extension": "file:../../extension",
+ "@ziplayer/extension": "file:../../extensions",
"@ziplayer/plugin": "file:../../plugins",
"lodash": "^4.17.21",
"discord.js": "^14.22.1",
diff --git a/examples/net/.env.example b/examples/net/.env.example
new file mode 100644
index 00000000..953eb1d2
--- /dev/null
+++ b/examples/net/.env.example
@@ -0,0 +1,50 @@
+# Copy to ".env" and fill in. Real environment variables override this file.
+# Use another file with: node test-cluster.js --env=./staging.env
+
+# ── Discord (only the bot node uses it) ─────────────────────────────────────
+DISCORD_TOKEN=
+COMMAND_PREFIX=!
+# Optional allow-lists (comma separated). Empty = anyone / any guild.
+ALLOWED_GUILD_ID=
+ALLOWED_USER_IDS=
+
+# ── MQTT (Mosquitto) ────────────────────────────────────────────────────────
+MQTT_URL=mqtt://127.0.0.1:1883
+# "{node}" is replaced by the node id, so every node can log in as itself (pairs with mosquitto.acl.example).
+MQTT_USERNAME={node}
+MQTT_PASSWORD=
+# 5 (default) or 4 for brokers without MQTT v5
+MQTT_PROTOCOL=5
+
+# ── Cluster ─────────────────────────────────────────────────────────────────
+NET_ID=ziplayer-test
+# id:plugin+plugin, ... The Discord bot node is DISCORD_NODE (default: the first one).
+# Plugin names: youtube, soundcloud, spotify, tts, attachments. Give nodes DIFFERENT plugins to force relay/handoff.
+NODES=bot-1:soundcloud,yt-1:youtube,tts-1:tts+attachments
+DISCORD_NODE=
+# Let the bot node serve streams to the others too (0/1)
+BOT_SERVES=0
+# Where node keys live (.key private, .key.pub public). Copy only the .pub files between machines.
+KEY_DIR=./.keys
+ENCRYPT_AUDIO=0
+
+# ── Test behaviour ──────────────────────────────────────────────────────────
+# Search text for youtube / soundcloud / spotify when the command or selftest needs a track
+TEST_QUERY=lofi hip hop
+# Share of tracks the bot cannot resolve at or above which routeTracks() hands the voice off
+HANDOFF_THRESHOLD=0.5
+# Lets "!kill " make a node crash (SIGKILL) to test failover. Never enable this outside tests.
+ALLOW_REMOTE_KILL=0
+DEBUG=0
+# Print what each node sends to / receives from MQTT: 0 | msg (decoded messages) | wire (raw MQTT) | 1 (both)
+# Can also be toggled in Discord with "!trace on|off|msg|wire|audio".
+NET_DEBUG=1
+# Also print every audio frame (very chatty)
+NET_DEBUG_AUDIO=0
+# Optional append-only file for formatted, redacted MQTT debug events.
+NET_DEBUG_FILE=./mqtt-debug.log
+
+# Optional one-shot voice-transfer test, started after the Discord bot logs in.
+# Use a voice channel ID, then set the YouTube URL/query to play on the remote YouTube node.
+VOICE_TEST_CHANNEL_ID=
+VOICE_TEST_QUERY=
diff --git a/examples/net/.gitignore b/examples/net/.gitignore
new file mode 100644
index 00000000..1b82e42d
--- /dev/null
+++ b/examples/net/.gitignore
@@ -0,0 +1,5 @@
+.env
+.keys/
+node_modules/
+mqtt-debug.log
+voice-transfer-mqtt-debug.log
diff --git a/examples/net/README.md b/examples/net/README.md
new file mode 100644
index 00000000..d51159aa
--- /dev/null
+++ b/examples/net/README.md
@@ -0,0 +1,112 @@
+# @ziplayer/net cluster test (real Discord bot + Mosquitto)
+
+A real `discord.js` bot (commands arrive through `messageCreate`) plus provider nodes, each in its own process with its **own real
+plugins**, linked over an MQTT broker. Use it to try stream transfer, relay, voice hand-off and failover with real audio.
+
+```
+Discord ── messageCreate ──► bot-1 (soundcloud) ◄──── MQTT (Mosquitto) ────► yt-1 (youtube)
+ owns the gateway tts-1 (tts, attachments)
+```
+
+## 1. Install and build
+
+```bash
+npm install --prefix core && npm run build --prefix core
+npm install --prefix plugins && npm run build --prefix plugins
+npm install --prefix net && npm run build --prefix net
+npm install --prefix examples/net # discord.js
+```
+
+## 2. Mosquitto
+
+```bash
+cd examples/net
+mosquitto_passwd -c ./passwd bot-1 && mosquitto_passwd ./passwd yt-1 && mosquitto_passwd ./passwd tts-1
+chown mosquitto passwd mosquitto.acl.example && chmod 600 passwd mosquitto.acl.example # Mosquitto 2.x requirement
+mosquitto -c ./mosquitto.conf.example
+```
+
+`mosquitto.acl.example` gives every node its own presence topic and inbox. The broker is **not trusted** (payloads are
+authenticated and control data is encrypted end to end); the ACL only stops nodes from impersonating each other. For a quick local
+try you can skip auth with `listener 1883` + `allow_anonymous true` and leave `MQTT_USERNAME` empty.
+
+## 3. Configure
+
+```bash
+cp .env.example .env # set DISCORD_TOKEN, MQTT_URL, MQTT_PASSWORD, NODES ...
+```
+
+Every variable is documented in `.env.example`. Real environment variables override the file; `--env=./other.env` picks another
+file. Enable the **Message Content Intent** for the bot in the Discord developer portal (the commands are plain messages).
+
+## 4. Run
+
+```bash
+node test-cluster.js # keys are created on first run, all nodes start as separate processes
+node test-cluster.js --keys # only create keys and print fingerprints
+node test-cluster.js --node=yt-1 # one node only (another machine): copy the other nodes' *.key.pub into KEY_DIR first
+```
+
+## 5. Try one case at a time
+
+The cluster runner wires the Discord bot and shared helpers together; each user-facing network scenario lives in its own module:
+
+1. **Search and play** — start with `!search yt:`, then `!play yt:` to find a track on a provider and stream it to
+ the bot: [`cases/search-and-play.js`](./cases/search-and-play.js).
+2. **Relay or route** — use `!route yt: 10` to see the router choose local playback, audio relay, or voice hand-off based
+ on track ownership: [`cases/routing.js`](./cases/routing.js).
+3. **Voice hand-off** — move a connected voice session with `!handoff ` and return it with `!reclaim`:
+ [`cases/voice-handoff.js`](./cases/voice-handoff.js).
+4. **Full self-test** — run `!selftest` for pairing, stream transfer, routing, hand-off, and reclaim; `!selftest failover`
+ additionally crashes the remote executor and checks recovery (requires `ALLOW_REMOTE_KILL=1`):
+ [`cases/selftest.js`](./cases/selftest.js).
+
+The `!nodes`, `!status`, `!trace`, `!stop`, `!skip`, `!leave`, and guarded `!kill` commands remain in
+[`test-cluster.js`](./test-cluster.js) as cluster controls and diagnostics.
+
+### One-shot voice transfer
+
+To connect a specific voice channel and play a YouTube URL on the YouTube provider automatically after login, set
+`VOICE_TEST_CHANNEL_ID` and `VOICE_TEST_QUERY` in the env file. Make sure `NODES` includes a non-Discord node with the `youtube`
+plugin. The test searches on that node, transfers the voice connection, starts playback, and reports success only after the
+provider emits `trackStart`.
+
+For an isolated extra cluster, copy `.env` to `.env.voice-transfer`, set a unique `NET_ID`, `NODES` (for example
+`transfer-client:soundcloud,transfer-yt:youtube`), and `KEY_DIR=./.keys/voice-transfer`, then set the channel and query:
+
+```env
+VOICE_TEST_CHANNEL_ID=1563498330582032529
+VOICE_TEST_QUERY=https://www.youtube.com/watch?v=oc7FhDaO5c4
+NET_DEBUG=1
+DEBUG=1
+NET_DEBUG_FILE=./voice-transfer-mqtt-debug.log
+```
+
+Run the separate processes with `node test-cluster.js --env=./.env.voice-transfer`. The formatted MQTT trace is appended to
+`NET_DEBUG_FILE`; player-manager debug messages are printed in the process console. Debug message bodies remain redacted by
+default. The log file is ignored by git.
+
+## 6. Discord commands
+
+| Command | What it tests |
+| ------------------------------------ | ---------------------------------------------------------------------------------------------- |
+| `!nodes` / `!status` | Authenticated request to every node, their plugins, who owns the voice |
+| `!play ` | Bot plugins first; if nothing is found (e.g. a YouTube URL) the other nodes are asked |
+| `!play yt:` | Search and audio on the node with the youtube plugin, streamed to the bot (`sc:` `sp:` `tts:`) |
+| `!search ` | Only show the results and which node found them |
+| `!trace [on\|off\|msg\|wire\|audio]` | Print what this node sends to / receives from MQTT (or `NET_DEBUG=1` in `.env`) |
+| `!route yt: [n]` | Router: relay a few foreign tracks, or hand the voice off when most tracks are foreign |
+| `!handoff ` / `!reclaim` | Move the Discord voice session to another node and take it back |
+| `!selftest [failover]` | Automated: pairing, plugins, stream, relay, handoff, executor playback, reclaim (+ node crash) |
+| `!kill ` | Crash a node (`ALLOW_REMOTE_KILL=1`) and watch the bot take the voice back |
+| `!stop` `!skip` `!leave` | Housekeeping |
+
+Change `NODES` to give nodes different plugins and see the router choose differently, for example
+`NODES=bot-1:soundcloud+youtube,yt-1:youtube,tts-1:tts` makes YouTube local to the bot.
+
+## Notes
+
+- Voice hand-off needs a real voice session: the bot joins your channel, then `yt-1` takes over through the relay adapter. If the
+ executor never gets audio out, check that `yt-1` can reach Discord's voice servers (UDP) from where it runs.
+- Search for `yt:`/`sc:` needs internet from the node that owns the plugin; `tts:` uses the TTS plugin.
+- Keys live in `KEY_DIR` (default `.keys/`, git-ignored). Never copy a `.key` file, only `.key.pub`.
diff --git a/examples/net/cases/routing.js b/examples/net/cases/routing.js
new file mode 100644
index 00000000..a0a0a8fc
--- /dev/null
+++ b/examples/net/cases/routing.js
@@ -0,0 +1,34 @@
+"use strict";
+
+function formatOwners(owners, localNodeId) {
+ return Object.entries(
+ owners.reduce((counts, owner) => ((counts[owner ?? localNodeId] = (counts[owner ?? localNodeId] || 0) + 1), counts), {}),
+ )
+ .map(([nodeId, count]) => `${nodeId}×${count}`)
+ .join(", ");
+}
+
+module.exports = function createRoutingCase({ id, cfg, zi, getPlayer, findTracks, waitStart }) {
+ return async function route(message, argument) {
+ const parts = argument.split(/\s+/);
+ const count = /^\d+$/.test(parts[parts.length - 1] ?? "") ? Number(parts.pop()) : 20;
+ const query = parts.join(" ");
+ if (!query) return void (await message.reply("Usage: `route yt: [count]`"));
+ const player = await getPlayer(message);
+ const { tracks: found, node } = await findTracks(query, Math.min(count, 25));
+ const tracks = Array.from({ length: count }, (_, index) => ({
+ ...found[index % found.length],
+ id: `${found[index % found.length].id}#${index}`,
+ }));
+ const plan = await zi.routeTracks(player, tracks, { handoffThreshold: cfg.handoffThreshold });
+ let reply = `**${plan.mode}**${plan.executor ? ` → ${plan.executor}` : ""} · tracks resolved on: ${formatOwners(plan.owners, id)} · applied: ${plan.applied}${plan.error ? ` (${plan.error.message})` : ""}`;
+ if (plan.applied || plan.mode === "local") {
+ const since = Date.now();
+ await player.play(tracks[0], { requestedBy: message.author.id });
+ player.queue.addMultiple(tracks.slice(1));
+ const started = await waitStart(message.guildId, since).catch((error) => error.message);
+ reply += ` · ${started === true ? "▶️ started" : `⚠️ ${started === false ? "no trackStart" : started}`} (source node: ${node})`;
+ }
+ await message.reply(reply);
+ };
+};
diff --git a/examples/net/cases/search-and-play.js b/examples/net/cases/search-and-play.js
new file mode 100644
index 00000000..00962aee
--- /dev/null
+++ b/examples/net/cases/search-and-play.js
@@ -0,0 +1,48 @@
+"use strict";
+
+module.exports = function createSearchAndPlayCases({ id, net, zi, st, findTracks, getPlayer, waitStart }) {
+ return {
+ async search(message, query) {
+ if (!query) return void (await message.reply("Usage: `search ` or `search yt:`"));
+ const { tracks, node, result } = await findTracks(query, 5);
+ const lines = tracks.map(
+ (track, index) =>
+ `${index + 1}. **${track.title}** (${track.source}) · found on **${track.metadata?.net?.owner ?? id}**${track.duration ? ` · ${track.duration}s` : ""}`,
+ );
+ await message.reply(
+ `${result.playlist ? `📃 playlist **${result.playlist.name}**\n` : ""}${lines.join("\n")}\n_(answered by ${node === id ? "this bot" : node})_`.slice(
+ 0,
+ 1990,
+ ),
+ );
+ },
+
+ async play(message, query) {
+ if (!query) return void (await message.reply("Usage: `play ` or `play yt:`"));
+ const player = await getPlayer(message);
+ const { tracks, node } = await findTracks(query, 1);
+ const track = tracks[0];
+ if (node !== id) net.markTrack(track, node);
+ const alreadyActive = player.isPlaying || player.isPaused || player.isBuffering;
+ const since = Date.now();
+ const bytes0 = st.bytesIn;
+ const result = await player.play(track, { requestedBy: message.author.id });
+ if (!result) throw new Error(`Could not queue or play "${track.title}"`);
+ const delegation = zi.delegationFor(message.guildId);
+ if (alreadyActive) {
+ const destination = delegation ? ` · will play on **${delegation.executor}**` : "";
+ await message.reply(`➕ queued **${track.title}** (${track.source})${destination}`);
+ return;
+ }
+ const started = await waitStart(message.guildId, since).catch((error) => error.message);
+ const where = delegation ? `played by **${delegation.executor}**` : "played here";
+ const from =
+ node === id ? "found and resolved locally" : (
+ `audio streamed from **${node}**${st.bytesIn > bytes0 ? ` (${st.bytesIn - bytes0} bytes)` : ""}`
+ );
+ await message.reply(
+ `${started === true ? "▶️" : "⚠️"} **${track.title}** (${track.source}) · ${from} · ${where}${started === true ? "" : ` · not confirmed: ${started === false ? "no trackStart in 25s" : started}`}`,
+ );
+ },
+ };
+};
diff --git a/examples/net/cases/selftest.js b/examples/net/cases/selftest.js
new file mode 100644
index 00000000..caae4e84
--- /dev/null
+++ b/examples/net/cases/selftest.js
@@ -0,0 +1,143 @@
+"use strict";
+
+module.exports = function createSelfTestCase({
+ id,
+ cfg,
+ zi,
+ manager,
+ net,
+ st,
+ peers,
+ ask,
+ getPlayer,
+ findTracks,
+ waitStart,
+ peerStatus,
+ specFor,
+ sleep,
+ searchableSources,
+}) {
+ return async function selftest(message, argument) {
+ const player = await getPlayer(message);
+ // Start from a clean slate so prior playback cannot hide new stream pulls.
+ await player.stop().catch(() => {});
+ player.queue.clear?.();
+ await sleep(1500);
+ const lines = [];
+ let failures = 0;
+ const response = await message.reply("🧪 selftest running…");
+ const flush = () => response.edit(lines.join("\n").slice(0, 1990) || "…").catch(() => {});
+ const check = (name, passed, detail = "") => {
+ if (!passed) failures++;
+ lines.push(`${passed ? "✅" : "❌"} ${name}${detail ? ` — ${detail}` : ""}`);
+ return flush();
+ };
+ const searchable = (node) => node.sources.filter((source) => searchableSources.includes(source));
+ const localSource = searchable({ sources: zi.localSources() })[0];
+ const foreignNode = peers.find((node) => searchable(node).some((source) => !zi.localSources().includes(source)));
+ const foreignSource = foreignNode && searchable(foreignNode).find((source) => !zi.localSources().includes(source));
+
+ try {
+ for (const peer of peers) {
+ const status = await peerStatus(peer.id).catch((error) => ({ error: error.message }));
+ const expected = peer.sources.slice().sort().join(",");
+ await check(
+ `${peer.id} authenticated, plugins [${expected}]`,
+ !status.error && status.sources.slice().sort().join(",") === expected,
+ status.error || `got [${status.sources?.join(",")}]`,
+ );
+ }
+ if (!foreignNode || !localSource) {
+ await check("needs a searchable plugin on the bot and a different one on a provider", false, "adjust NODES");
+ } else {
+ const found = (await findTracks(`${foreignSource}:${specFor(foreignSource)}`, 3)).tracks;
+ const foreignTrack = found[0];
+ const resolvedBefore = (await peerStatus(foreignNode.id)).resolved;
+ const bytesBefore = st.bytesIn;
+ const since = Date.now();
+ await player.play(net.markTrack({ ...foreignTrack }, foreignNode.id), { requestedBy: message.author.id });
+ const started = await waitStart(message.guildId, since).catch(() => false);
+ await sleep(500);
+ await check(`stream: audio pulled from ${foreignNode.id}`, st.bytesIn > bytesBefore, `${st.bytesIn - bytesBefore} bytes`);
+ await check(
+ `stream: ${foreignNode.id} resolved it with its own ${foreignSource} plugin`,
+ (await peerStatus(foreignNode.id)).resolved === resolvedBefore + 1,
+ );
+ await check("stream: trackStart on the bot", started === true);
+ await player.stop();
+
+ const localTrack = (await findTracks(`${localSource}:${specFor(localSource)}`, 1)).tracks[0];
+ const list = (track, count, tag) =>
+ Array.from({ length: count }, (_, index) => ({ ...track, id: `${track.id}#${tag}${index}` }));
+ let plan = await zi.routeTracks(player, list(localTrack, 6, "a"), { handoffThreshold: cfg.handoffThreshold });
+ await check("route: all local → local", plan.mode === "local", plan.mode);
+
+ const mixed = [...list(localTrack, 9, "b"), ...list(foreignTrack, 1, "bf")];
+ plan = await zi.routeTracks(player, mixed, { handoffThreshold: cfg.handoffThreshold });
+ await check(
+ "route: 1 foreign of 10 → relay",
+ plan.mode === "relay" && mixed[9].metadata?.net?.owner === foreignNode.id,
+ `${plan.mode}, owner ${mixed[9].metadata?.net?.owner}`,
+ );
+
+ plan = await zi.routeTracks(player, [...list(foreignTrack, 20, "c"), ...list(localTrack, 1, "cl")], {
+ handoffThreshold: cfg.handoffThreshold,
+ });
+ await check(
+ `route: 20 foreign of 21 → handoff to ${foreignNode.id}`,
+ plan.mode === "handoff" && plan.applied,
+ plan.error?.message || plan.mode,
+ );
+ if (plan.applied) {
+ const executorStatus = await peerStatus(foreignNode.id);
+ await check(`${foreignNode.id} executes this guild's voice`, executorStatus.executing.includes(message.guildId));
+ const startedAt = Date.now();
+ await player.play({ ...foreignTrack }, { requestedBy: message.author.id });
+ const executorStarted = await (async () => {
+ const end = Date.now() + 25_000;
+ while (Date.now() < end) {
+ if (
+ (await peerStatus(foreignNode.id)).events.some(
+ (event) => event.at >= startedAt && event.type === "trackStart" && event.guildId === message.guildId,
+ )
+ )
+ return true;
+ await sleep(500);
+ }
+ return false;
+ })();
+ await check(`track started on the executor ${foreignNode.id}, driven by the bot`, executorStarted);
+ await player.stop().catch(() => {});
+ await zi.reclaimVoice(player);
+ await check("reclaim: voice is back on the bot", Boolean(player.connection) && !zi.delegationFor(message.guildId));
+ }
+
+ if (argument === "failover") {
+ if (!cfg.allowRemoteKill) await check("failover needs ALLOW_REMOTE_KILL=1", false);
+ else {
+ await player.stop().catch(() => {});
+ const failoverPlan = await zi.routeTracks(player, [...list(foreignTrack, 20, "f"), ...list(localTrack, 1, "fl")], {
+ handoffThreshold: cfg.handoffThreshold,
+ });
+ if (!failoverPlan.applied) await check("failover: handoff established", false, failoverPlan.error?.message);
+ else {
+ await ask(foreignNode.id, "test.kill", undefined, 5000).catch(() => {});
+ const end = Date.now() + 20_000;
+ while (Date.now() < end && (zi.delegationFor(message.guildId) || !player.connection)) await sleep(250);
+ await check(
+ `failover: bot reclaimed the voice after ${foreignNode.id} crashed`,
+ !zi.delegationFor(message.guildId) && Boolean(player.connection),
+ `restart ${foreignNode.id} afterwards`,
+ );
+ }
+ }
+ }
+ }
+ } catch (error) {
+ await check("selftest aborted", false, error.message);
+ }
+
+ lines.push(failures ? `\n**${failures} check(s) failed**` : "\n**all checks passed**");
+ await flush();
+ };
+};
diff --git a/examples/net/cases/voice-handoff.js b/examples/net/cases/voice-handoff.js
new file mode 100644
index 00000000..12cc1ac6
--- /dev/null
+++ b/examples/net/cases/voice-handoff.js
@@ -0,0 +1,20 @@
+"use strict";
+
+module.exports = function createVoiceHandoffCases({ zi, getPlayer }) {
+ return {
+ async handoff(message, nodeId) {
+ if (!nodeId) return void (await message.reply("Usage: `handoff `"));
+ const player = await getPlayer(message);
+ if (player.isPlaying) await player.stop();
+ await zi.delegateVoice(player, nodeId.trim());
+ await message.reply(`🔀 voice handed to **${nodeId.trim()}** (this bot keeps the gateway and the queue)`);
+ },
+
+ async reclaim(message) {
+ const player = await getPlayer(message, { connect: false });
+ if (!zi.delegationFor(message.guildId)) return void (await message.reply("Voice is not delegated."));
+ await zi.reclaimVoice(player);
+ await message.reply("🔙 voice is back on this bot");
+ },
+ };
+};
diff --git a/examples/net/mosquitto.acl.example b/examples/net/mosquitto.acl.example
new file mode 100644
index 00000000..ecf244b2
--- /dev/null
+++ b/examples/net/mosquitto.acl.example
@@ -0,0 +1,33 @@
+# ACL for the cluster test. The username of each client is its node id (MQTT_USERNAME={node}).
+# Payloads are ciphertext / authenticated end to end, so the broker is not trusted; these rules only stop a node from
+# impersonating another node's presence or reading someone else's inbox.
+#
+# Mosquitto applies `topic` lines that appear BEFORE the first `user` line to anonymous clients only, so every node gets
+# its own block. Copy a block for each node id in NODES (and keep NET_ID as the "+" level, or replace it with the id).
+#
+# read presence of everyone (retained + last-will) write only its own presence
+# read only its own inbox / audio write into any peer's inbox / audio
+
+user bot-1
+topic read zi/v1/+/presence/+
+topic write zi/v1/+/presence/bot-1
+topic read zi/v1/+/node/bot-1/in
+topic read zi/v1/+/node/bot-1/au
+topic write zi/v1/+/node/+/in
+topic write zi/v1/+/node/+/au
+
+user yt-1
+topic read zi/v1/+/presence/+
+topic write zi/v1/+/presence/yt-1
+topic read zi/v1/+/node/yt-1/in
+topic read zi/v1/+/node/yt-1/au
+topic write zi/v1/+/node/+/in
+topic write zi/v1/+/node/+/au
+
+user tts-1
+topic read zi/v1/+/presence/+
+topic write zi/v1/+/presence/tts-1
+topic read zi/v1/+/node/tts-1/in
+topic read zi/v1/+/node/tts-1/au
+topic write zi/v1/+/node/+/in
+topic write zi/v1/+/node/+/au
diff --git a/examples/net/mosquitto.conf.example b/examples/net/mosquitto.conf.example
new file mode 100644
index 00000000..4ae40fcf
--- /dev/null
+++ b/examples/net/mosquitto.conf.example
@@ -0,0 +1,10 @@
+# Minimal Mosquitto 2.x config for the cluster test.
+# mosquitto_passwd -c ./passwd bot-1 # then: mosquitto_passwd ./passwd yt-1 ; mosquitto_passwd ./passwd tts-1
+# mosquitto -c ./mosquitto.conf.example
+listener 1883
+allow_anonymous false
+password_file ./passwd
+acl_file ./mosquitto.acl.example
+# Mosquitto 2.x wants these files to be owned by the mosquitto user and not world-readable:
+# chown mosquitto passwd mosquitto.acl.example && chmod 600 passwd mosquitto.acl.example
+# For TLS, add: cafile / certfile / keyfile and use mqtts://host:8883 in MQTT_URL.
diff --git a/examples/net/package.json b/examples/net/package.json
new file mode 100644
index 00000000..51ecf899
--- /dev/null
+++ b/examples/net/package.json
@@ -0,0 +1,12 @@
+{
+ "name": "@ziplayer/net-cluster-example",
+ "private": true,
+ "description": "Real Discord bot + provider nodes talking over MQTT (Mosquitto) with @ziplayer/net",
+ "scripts": {
+ "start": "node test-cluster.js",
+ "keys": "node test-cluster.js --keys"
+ },
+ "dependencies": {
+ "discord.js": "^14.16.0"
+ }
+}
diff --git a/examples/net/test-cluster.js b/examples/net/test-cluster.js
new file mode 100644
index 00000000..ed3c66d0
--- /dev/null
+++ b/examples/net/test-cluster.js
@@ -0,0 +1,621 @@
+#!/usr/bin/env node
+/**
+ * @ziplayer/net cluster test: a REAL Discord bot (discord.js, driven by `messageCreate`) plus provider nodes, all REAL plugins,
+ * linked over an MQTT broker (Mosquitto). Everything is configured through `.env` (see .env.example).
+ *
+ * node test-cluster.js start every node of NODES as its own process (Ctrl+C stops them all)
+ * node test-cluster.js --node=yt-1 start only one node (e.g. on another machine; copy the *.key.pub files first)
+ * node test-cluster.js --keys create missing node keys, print fingerprints, exit
+ * node test-cluster.js --env=./x.env use another env file
+ *
+ * In Discord (prefix from COMMAND_PREFIX), from inside a voice channel:
+ * !help | !nodes | !status
+ * !play search on the bot's own plugins; if nothing is found, ask the other nodes (e.g. a YouTube URL)
+ * !play yt: search AND audio on the node that has the youtube plugin, streamed to the bot (also sc: sp: tts:)
+ * !search only show the search results (and which node found them); nothing is played
+ * !trace [on|off|msg|wire|audio] print what this node sends to / receives from MQTT (also: NET_DEBUG=1 in .env)
+ * !route yt: [n] plan relay/handoff for n tracks (default 20), apply it and start playing
+ * !handoff | !reclaim | !stop | !skip | !leave
+ * !selftest [failover] automated checks of pairing, stream transfer, relay, handoff, reclaim (and failover)
+ * !kill crash a node (needs ALLOW_REMOTE_KILL=1)
+ */
+"use strict";
+const path = require("node:path");
+const fs = require("node:fs");
+const { fork } = require("node:child_process");
+const createSearchAndPlayCases = require("./cases/search-and-play");
+const createRoutingCase = require("./cases/routing");
+const createVoiceHandoffCases = require("./cases/voice-handoff");
+const createSelfTestCase = require("./cases/selftest");
+
+const ROOT = path.resolve(__dirname, "..", "..");
+function load(name, rel) {
+ try {
+ return require(path.join(ROOT, rel));
+ } catch (e) {
+ throw new Error(
+ `Cannot load ${name}: build it first (npm install --prefix ${rel.split("/")[0]} && npm run build --prefix ${rel.split("/")[0]}).\n${e.message}`,
+ );
+ }
+}
+
+/* ───────────────────────────── configuration ───────────────────────────── */
+
+function parseEnv(text) {
+ const out = {};
+ for (const raw of text.split(/\r?\n/)) {
+ const line = raw.trim();
+ if (!line || line.startsWith("#")) continue;
+ const eq = line.indexOf("=");
+ if (eq < 1) continue;
+ let value = line.slice(eq + 1).trim();
+ if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'")))
+ value = value.slice(1, -1);
+ else value = value.replace(/\s+#.*$/, "");
+ out[line.slice(0, eq).trim()] = value;
+ }
+ return out;
+}
+
+function loadConfig(argv = process.argv.slice(2), env = process.env) {
+ const args = Object.fromEntries(
+ argv.map((a) => {
+ const m = a.match(/^--([^=]+)(?:=(.*))?$/);
+ return m ? [m[1], m[2] ?? true] : [a, true];
+ }),
+ );
+ const envFile = path.resolve(typeof args.env === "string" ? args.env : path.join(__dirname, ".env"));
+ const fileVars = fs.existsSync(envFile) ? parseEnv(fs.readFileSync(envFile, "utf8")) : {};
+ const get = (k, d = "") => (env[k] !== undefined && env[k] !== "" ? env[k] : (fileVars[k] ?? d));
+ const flag = (k) => ["1", "true", "yes", "on"].includes(String(get(k, "0")).toLowerCase());
+
+ const nodes = get("NODES", "bot-1:soundcloud,yt-1:youtube,tts-1:tts+attachments")
+ .split(",")
+ .map((s) => s.trim())
+ .filter(Boolean)
+ .map((s) => {
+ const [id, list = ""] = s.split(":");
+ return {
+ id: id.trim(),
+ sources: list
+ .split("+")
+ .map((x) => x.trim())
+ .filter(Boolean),
+ };
+ });
+ if (nodes.length < 2) throw new Error("NODES needs at least two nodes");
+ return {
+ args,
+ envFile,
+ envFileFound: fs.existsSync(envFile),
+ discordToken: get("DISCORD_TOKEN"),
+ prefix: get("COMMAND_PREFIX", "!"),
+ allowedGuild: get("ALLOWED_GUILD_ID"),
+ allowedUsers: new Set(
+ get("ALLOWED_USER_IDS")
+ .split(",")
+ .map((s) => s.trim())
+ .filter(Boolean),
+ ),
+ mqttUrl: get("MQTT_URL", "mqtt://127.0.0.1:1883"),
+ mqttUsername: get("MQTT_USERNAME"),
+ mqttPassword: get("MQTT_PASSWORD"),
+ mqttProtocol: Number(get("MQTT_PROTOCOL", "5")),
+ netId: get("NET_ID", "ziplayer-test"),
+ nodes,
+ discordNode: get("DISCORD_NODE") || nodes[0].id,
+ botServes: flag("BOT_SERVES"),
+ keyDir: path.resolve(__dirname, get("KEY_DIR", "./.keys")),
+ encryptAudio: flag("ENCRYPT_AUDIO"),
+ query: get("TEST_QUERY", "lofi hip hop"),
+ handoffThreshold: Number(get("HANDOFF_THRESHOLD", "0.5")),
+ allowRemoteKill: flag("ALLOW_REMOTE_KILL"),
+ debug: flag("DEBUG"),
+ netDebugFile: get("NET_DEBUG_FILE") ? path.resolve(__dirname, get("NET_DEBUG_FILE")) : undefined,
+ voiceTestChannelId: get("VOICE_TEST_CHANNEL_ID"),
+ voiceTestQuery: get("VOICE_TEST_QUERY"),
+ // what the net layer prints: 0 | msg | wire | 1/all (+ NET_DEBUG_AUDIO=1 for every audio frame)
+ netDebug:
+ ["1", "true", "yes", "on"].includes(get("NET_DEBUG", "0").toLowerCase()) ? "all" : get("NET_DEBUG", "0").toLowerCase(),
+ netDebugAudio: flag("NET_DEBUG_AUDIO"),
+ };
+}
+
+const keyFile = (cfg, id) => path.join(cfg.keyDir, `${id}.key`);
+const pubFile = (cfg, id) => `${keyFile(cfg, id)}.pub`;
+
+function ensureKeys(cfg, ids) {
+ const net = load("@ziplayer/net", "net/dist");
+ fs.mkdirSync(cfg.keyDir, { recursive: true });
+ for (const id of ids) {
+ const r = net.loadOrCreateIdentity(keyFile(cfg, id));
+ console.log(
+ `key ${id}: ${r.created ? "created" : "exists "} fingerprint ${net.fingerprint(r.identity.publicKey).slice(0, 32)}…`,
+ );
+ }
+}
+
+function trustFor(cfg, id) {
+ const trust = [];
+ for (const n of cfg.nodes) {
+ if (n.id === id) continue;
+ if (!fs.existsSync(pubFile(cfg, n.id))) {
+ console.warn(`[${id}] missing ${pubFile(cfg, n.id)}: node "${n.id}" will not be trusted (copy its .pub file here)`);
+ continue;
+ }
+ trust.push({ nodeId: n.id, publicKey: fs.readFileSync(pubFile(cfg, n.id), "utf8") });
+ }
+ return trust;
+}
+
+/* ───────────────────────────── a node ───────────────────────────── */
+
+const SEARCHABLE = ["youtube", "soundcloud", "spotify", "tts"];
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+
+/**
+ * Prints the net layer's `debug` events. `mode`: "all" (wire + message + info), "msg" (decoded messages + info),
+ * "wire" (raw MQTT only), anything else = off. Returns a function to change the mode at runtime.
+ */
+function makeTracer(node, formatNetDebug, initial, out = console.log) {
+ let mode = initial;
+ const layers = () =>
+ mode === "all" ? ["wire", "message", "info"]
+ : mode === "msg" ? ["message", "info"]
+ : mode === "wire" ? ["wire"]
+ : [];
+ const listener = (e) => layers().includes(e.layer) && out(formatNetDebug(e));
+ const apply = (next) => {
+ mode = next;
+ node.off("debug", listener);
+ if (layers().length) node.on("debug", listener);
+ return mode;
+ };
+ apply(initial);
+ return apply;
+}
+
+/**
+ * Starts one node. `hooks` exists for automated tests of this file (inject discord.js, plugins, simulated voice); normal runs
+ * pass nothing and get the real discord.js client and the real plugins.
+ */
+async function startNode(id, cfg, hooks = {}) {
+ const spec = cfg.nodes.find((n) => n.id === id);
+ if (!spec) throw new Error(`"${id}" is not in NODES`);
+ const isBot = id === cfg.discordNode;
+ const { PlayerManager } = load("ziplayer", "core/dist");
+ const net = load("@ziplayer/net", "net/dist");
+
+ const log = (...a) => console.log(`[${id}]`, ...a);
+ const st = { resolved: 0, bytesIn: 0 };
+ const events = [];
+ process.on("uncaughtException", (e) => log("uncaughtException:", e.message));
+ process.on("unhandledRejection", (e) => log("unhandledRejection:", e?.message ?? e));
+
+ // real plugins
+ let plugins = hooks.plugins;
+ if (!plugins) {
+ const p = load("@ziplayer/plugin", "plugins/dist");
+ const classes = {
+ youtube: p.YouTubePlugin,
+ soundcloud: p.SoundCloudPlugin,
+ spotify: p.SpotifyPlugin,
+ tts: p.TTSPlugin,
+ attachments: p.AttachmentsPlugin,
+ };
+ plugins = spec.sources.map((s) => {
+ if (!classes[s]) throw new Error(`Unknown plugin "${s}" for ${id}`);
+ return new classes[s]();
+ });
+ }
+ const manager = new PlayerManager({ autoCleanup: false, plugins });
+ if (cfg.debug) {
+ manager.debugLevel = "debug";
+ manager.on("debug", (message, ...args) => log("[PlayerManager]", message, ...args));
+ }
+ const origResolve = manager.resolveStream.bind(manager);
+ manager.resolveStream = async (...a) => (st.resolved++, origResolve(...a));
+ const origCreate = manager.create.bind(manager);
+ manager.create = async (...a) => {
+ const p = await origCreate(...a);
+ hooks.onPlayerCreated?.(p);
+ return p;
+ };
+ manager.on("trackStart", (player, track) =>
+ events.push({ at: Date.now(), type: "trackStart", guildId: player.guildId, title: track?.title, source: track?.source }),
+ );
+ manager.on("playerError", (player, err) =>
+ events.push({ at: Date.now(), type: "error", guildId: player.guildId, message: err?.message }),
+ );
+
+ // real Discord client (bot node only)
+ let client = null;
+ if (isBot) {
+ let discord = hooks.discord;
+ if (!discord) {
+ try {
+ discord = require(require.resolve("discord.js", { paths: [__dirname, ROOT] }));
+ } catch {
+ throw new Error("discord.js is not installed: run `npm install --prefix examples/net`");
+ }
+ }
+ client = new discord.Client({
+ intents: [
+ discord.GatewayIntentBits.Guilds,
+ discord.GatewayIntentBits.GuildVoiceStates,
+ discord.GatewayIntentBits.GuildMessages,
+ discord.GatewayIntentBits.MessageContent,
+ ],
+ });
+ }
+
+ const subst = (s) => s.replace(/\{node\}/g, id);
+ const zi = new net.ZiNet({
+ nodeId: id,
+ networkId: cfg.netId,
+ identity: hooks.identity ?? net.loadOrCreateIdentity(keyFile(cfg, id)).privateKeyPem,
+ trust: hooks.trust ?? trustFor(cfg, id),
+ transport:
+ hooks.transport ??
+ new net.MqttTransport({
+ url: cfg.mqttUrl,
+ clientId: `zi-${id}-${process.pid}`,
+ username: cfg.mqttUsername ? subst(cfg.mqttUsername) : undefined,
+ password: cfg.mqttPassword ? subst(cfg.mqttPassword) : undefined,
+ protocolVersion: cfg.mqttProtocol,
+ }),
+ manager,
+ gateway: client ? net.discordJsGateway(client) : undefined,
+ encryptAudio: cfg.encryptAudio,
+ debugAudio: cfg.netDebugAudio,
+ requestTimeoutMs: 30_000,
+ debug: cfg.debug ? (m, ...a) => console.log(m, ...a) : undefined,
+ });
+ const origFrame = zi.importer.onFrame.bind(zi.importer);
+ zi.importer.onFrame = (peer, frame) => ((st.bytesIn += frame.payload.length), origFrame(peer, frame));
+
+ const status = ({ guildId } = {}) => {
+ const player = typeof guildId === "string" ? manager.get(guildId) : undefined;
+ return {
+ id,
+ sources: zi.localSources(),
+ online: zi.node.onlinePeers(),
+ resolved: st.resolved,
+ bytesIn: st.bytesIn,
+ executing: [...zi.executions.keys()],
+ delegated: [...zi.delegations.keys()],
+ playback:
+ player ?
+ {
+ isPlaying: player.isPlaying,
+ isPaused: player.isPaused,
+ trackId: player.currentTrack?.id ?? null,
+ }
+ : null,
+ events: events.slice(-20),
+ };
+ };
+ zi.node.handle("test.status", status);
+ const setTrace = makeTracer(zi.node, net.formatNetDebug, cfg.netDebug, (line) => {
+ log(line);
+ if (cfg.netDebugFile) {
+ fs.mkdirSync(path.dirname(cfg.netDebugFile), { recursive: true });
+ fs.appendFileSync(cfg.netDebugFile, `${new Date().toISOString()} ${line}\n`);
+ }
+ });
+ if (cfg.allowRemoteKill) {
+ zi.node.handle("test.kill", () => {
+ log("test.kill received: crashing on purpose");
+ setTimeout(() => process.kill(process.pid, "SIGKILL"), 100);
+ return "killing";
+ });
+ }
+
+ await zi.start();
+ zi.acceptVoice();
+ if (!isBot || cfg.botServes) {
+ zi.provideStreams({ allow: (track) => spec.sources.includes(track.source) });
+ zi.provideSearch();
+ }
+ log(
+ `ready · plugins: ${spec.sources.join(", ") || "-"} · mqtt ${cfg.mqttUrl} · net ${cfg.netId}${isBot ? " · discord bot" : ""}`,
+ );
+
+ if (isBot) attachDiscordCommands({ id, cfg, zi, manager, net, client, events, st, log, hooks, setTrace });
+ if (isBot && !hooks.noLogin) {
+ if (!cfg.discordToken) throw new Error("DISCORD_TOKEN is empty (set it in .env)");
+ await client.login(cfg.discordToken);
+ log(`logged in as ${client.user?.tag}`);
+ if (cfg.voiceTestChannelId) {
+ if (!client.isReady()) await new Promise((resolve) => client.once("ready", resolve));
+ runVoiceTransferTest({ id, cfg, zi, manager, net, client, log }).catch((e) =>
+ log("[voice-test] FAILED:", e.stack || e.message),
+ );
+ }
+ }
+ return { id, zi, manager, client, status, stop: () => zi.stop() };
+}
+
+async function runVoiceTransferTest({ id, cfg, zi, manager, net, client, log }) {
+ const provider = cfg.nodes.find((node) => node.id !== id && node.sources.includes("youtube"));
+ if (!provider) throw new Error("NODES must include a non-Discord node with the youtube plugin");
+ if (!cfg.voiceTestQuery) throw new Error("VOICE_TEST_QUERY is required when VOICE_TEST_CHANNEL_ID is set");
+
+ const channel = await client.channels.fetch(cfg.voiceTestChannelId);
+ if (!channel?.isVoiceBased?.() || !channel.guildId) {
+ throw new Error(`VOICE_TEST_CHANNEL_ID ${cfg.voiceTestChannelId} is not an accessible voice channel`);
+ }
+ const existing = manager.get(channel.guildId);
+ if (existing?.connection || zi.delegationFor(channel.guildId)) {
+ throw new Error(`A player or voice hand-off already exists for guild ${channel.guildId}`);
+ }
+
+ const result = await zi.searchOn(provider.id, cfg.voiceTestQuery, {
+ source: "youtube",
+ limit: 1,
+ requestedBy: "voice-transfer-test",
+ });
+ const track = net.markTrack(result.tracks[0], provider.id);
+ const player = existing ?? (await manager.create(channel.guildId, { extensions: [zi.extensionClass()] }));
+ await player.connect(channel);
+ log(`[voice-test] connected to channel ${channel.id} in guild ${channel.guildId}`);
+
+ const plan = await zi.routeTracks(player, [track], { handoffThreshold: cfg.handoffThreshold });
+ if (plan.mode !== "handoff" || plan.executor !== provider.id || !plan.applied) {
+ throw new Error(
+ `Expected voice hand-off to ${provider.id}; got mode=${plan.mode}, executor=${plan.executor || "-"}, applied=${plan.applied}`,
+ );
+ }
+ log(`[voice-test] voice handed off to ${provider.id}; playing "${track.title}" (${track.source})`);
+
+ const startedAt = Date.now();
+ await player.play(track, { requestedBy: "voice-transfer-test" });
+ let trackStartedAt;
+ const end = Date.now() + 90_000;
+ while (Date.now() < end) {
+ const remote = await zi.node.request(provider.id, "test.status", { guildId: channel.guildId }, { timeoutMs: 8_000 });
+ const error = remote.events.find((e) => e.at >= startedAt && e.guildId === channel.guildId && e.type === "error");
+ if (error) throw new Error(`executor player error: ${error.message}`);
+ const started = remote.events.find((e) => e.at >= startedAt && e.guildId === channel.guildId && e.type === "trackStart");
+ if (started && trackStartedAt === undefined) trackStartedAt = started.at;
+ if (trackStartedAt !== undefined && Date.now() - trackStartedAt >= 10_000) {
+ if (!remote.playback?.isPlaying || remote.playback.trackId !== track.id) {
+ throw new Error(
+ `executor playback is not stable after 10 seconds (playing=${remote.playback?.isPlaying ?? "unknown"}, track=${remote.playback?.trackId ?? "unknown"})`,
+ );
+ }
+ log(
+ `[voice-test] SUCCESS: ${provider.id} played "${started.title}" (${started.source}) for 10 seconds in guild ${channel.guildId}`,
+ );
+ return;
+ }
+ await sleep(1000);
+ }
+ throw new Error(`No trackStart reported by ${provider.id} within 90 seconds`);
+}
+
+/* ───────────────────────── Discord command handling ───────────────────────── */
+
+function attachDiscordCommands({ id, cfg, zi, manager, net, client, events, st, log, setTrace = () => "off" }) {
+ const peers = cfg.nodes.filter((n) => n.id !== id);
+ const ask = (peer, type, body, timeoutMs = 30_000) => zi.node.request(peer, type, body, { timeoutMs });
+ const specFor = (source) => (source === "tts" ? "tts:Hello from the ZiPlayer net test" : cfg.query);
+
+ /**
+ * Cluster-wide search. `yt:lofi` goes to the node that has the youtube plugin; a plain query or a URL is tried on this
+ * bot's plugins first and then on every node that serves search. Tracks come back marked with the node that found them.
+ */
+ async function findTracks(text, limit = 5) {
+ const result = await zi.search(text, { limit, requestedBy: "net-test" });
+ return { tracks: result.tracks, node: result.node, result };
+ }
+
+ async function getPlayer(message, { connect = true } = {}) {
+ const guildId = message.guildId;
+ let p = manager.get(guildId);
+ if (!p) p = await manager.create(guildId, { extensions: [zi.extensionClass()] });
+ if (connect && !p.connection && !zi.delegationFor(guildId)) {
+ const vc = message.member?.voice?.channel;
+ if (!vc) throw new Error("Join a voice channel first");
+ await p.connect(vc);
+ }
+ return p;
+ }
+
+ async function waitStart(guildId, since, ms = 25_000) {
+ const end = Date.now() + ms;
+ while (Date.now() < end) {
+ if (events.some((e) => e.at >= since && e.guildId === guildId && e.type === "trackStart")) return true;
+ const err = events.find((e) => e.at >= since && e.guildId === guildId && e.type === "error");
+ if (err) throw new Error(`player error: ${err.message}`);
+ await sleep(150);
+ }
+ return false;
+ }
+
+ const peerStatus = (peer) => ask(peer, "test.status", undefined, 8000);
+ const caseContext = {
+ id,
+ cfg,
+ zi,
+ manager,
+ net,
+ client,
+ events,
+ st,
+ log,
+ peers,
+ ask,
+ specFor,
+ findTracks,
+ getPlayer,
+ waitStart,
+ peerStatus,
+ sleep,
+ searchableSources: SEARCHABLE,
+ };
+
+ const commands = {
+ ...createSearchAndPlayCases(caseContext),
+ route: createRoutingCase(caseContext),
+ ...createVoiceHandoffCases(caseContext),
+ selftest: createSelfTestCase(caseContext),
+
+ async help(m) {
+ await m.reply(
+ [
+ "**ZiPlayer net test**",
+ "`play ` bot plugins first, then the other nodes · `play yt:` / `sc:` / `sp:` / `tts:` search + audio on the node with that plugin",
+ "`search ` show results and which node found them · `trace [on|off|msg|wire|audio]` print MQTT traffic of this node",
+ "`route yt: [n]` plan relay/handoff for n tracks and play · `handoff ` · `reclaim` · `stop` · `skip` · `leave`",
+ "`nodes` · `status` · `selftest [failover]` · `kill ` (ALLOW_REMOTE_KILL=1)",
+ ].join("\n"),
+ );
+ },
+
+ async nodes(m) {
+ const lines = [];
+ for (const p of peers) {
+ try {
+ const s = await peerStatus(p.id);
+ lines.push(
+ `✅ **${p.id}** plugins: ${s.sources.join(", ") || "-"} · resolved ${s.resolved} · executing ${s.executing.join(",") || "-"}`,
+ );
+ } catch (e) {
+ lines.push(`❌ **${p.id}** ${zi.node.isOnline(p.id) ? "online but " : "offline: "}${e.message}`);
+ }
+ }
+ await m.reply(`**${id}** (bot) plugins: ${zi.localSources().join(", ") || "-"}\n${lines.join("\n")}`);
+ },
+
+ async status(m) {
+ const p = manager.get(m.guildId);
+ const d = zi.delegationFor(m.guildId);
+ await m.reply(
+ [
+ `voice: ${
+ d ? `delegated to **${d.executor}**`
+ : p?.connection ? "on this bot"
+ : "not connected"
+ }`,
+ `playing: ${p?.isPlaying ? `**${p.currentTrack?.title}**` : "no"} · queue ${p?.queueSize ?? 0}`,
+ `bytes pulled from other nodes so far: ${st.bytesIn}`,
+ ].join("\n"),
+ );
+ },
+
+ async trace(m, arg) {
+ const a = (arg || "").trim().toLowerCase();
+ if (a === "audio") {
+ zi.node.options.debugAudio = !zi.node.options.debugAudio;
+ return void (await m.reply(`audio frames in trace: ${zi.node.options.debugAudio ? "on" : "off"}`));
+ }
+ const mode =
+ a === "off" || a === "0" ? "off"
+ : a === "msg" || a === "wire" ? a
+ : "all";
+ await m.reply(`net trace: **${setTrace(mode)}** (printed in the console of ${id})`);
+ },
+
+ async stop(m) {
+ await (await getPlayer(m, { connect: false })).stop();
+ await m.reply("⏹️ stopped");
+ },
+ async skip(m) {
+ await (await getPlayer(m, { connect: false })).playNext();
+ await m.reply("⏭️ skipped");
+ },
+ async leave(m) {
+ const player = manager.get(m.guildId);
+ if (player && zi.delegationFor(m.guildId)) await zi.reclaimVoice(player).catch(() => {});
+ await manager.destroy(m.guildId);
+ await m.reply("👋 left");
+ },
+
+ async kill(m, arg) {
+ if (!cfg.allowRemoteKill) return void (await m.reply("Set ALLOW_REMOTE_KILL=1 to use this."));
+ await ask(arg.trim(), "test.kill", undefined, 5000);
+ await m.reply(`💥 ${arg.trim()} is crashing; watch the failover with \`status\``);
+ },
+ };
+
+ client.on("messageCreate", async (message) => {
+ if (message.author?.bot || !message.guild || !message.content?.startsWith(cfg.prefix)) return;
+ if (cfg.allowedGuild && message.guildId !== cfg.allowedGuild) return;
+ if (cfg.allowedUsers.size && !cfg.allowedUsers.has(message.author.id)) return;
+ const [name, ...rest] = message.content.slice(cfg.prefix.length).trim().split(/\s+/);
+ const handler = commands[(name || "").toLowerCase()];
+ if (!handler) return;
+ log(`messageCreate ${message.author.tag ?? message.author.id}: ${message.content}`);
+ try {
+ await handler(message, rest.join(" "));
+ } catch (e) {
+ log("command failed:", e.stack || e.message);
+ await message.reply(`❌ ${e.message}`).catch(() => {});
+ }
+ });
+ return commands;
+}
+
+/* ───────────────────────────── launcher / entry ───────────────────────────── */
+
+async function main() {
+ const cfg = loadConfig();
+ if (!cfg.envFileFound) console.warn(`(no env file at ${cfg.envFile}; copy .env.example to .env)`);
+
+ if (cfg.args.keys)
+ return void ensureKeys(
+ cfg,
+ cfg.nodes.map((n) => n.id),
+ );
+
+ if (typeof cfg.args.node === "string") {
+ ensureKeys(cfg, [cfg.args.node]);
+ const node = await startNode(cfg.args.node, cfg);
+ const bye = async () => (await node.stop().catch(() => {}), process.exit(0));
+ process.on("SIGINT", bye);
+ process.on("SIGTERM", bye);
+ return;
+ }
+
+ // launcher: all nodes as separate processes
+ if (!cfg.discordToken) {
+ console.error(
+ `DISCORD_TOKEN is empty. Put it in ${cfg.envFile} (or run the provider nodes only: node test-cluster.js --node=yt-1).`,
+ );
+ process.exit(2);
+ }
+ ensureKeys(
+ cfg,
+ cfg.nodes.map((n) => n.id),
+ );
+ const order = [...cfg.nodes.filter((n) => n.id !== cfg.discordNode), ...cfg.nodes.filter((n) => n.id === cfg.discordNode)];
+ const children = [];
+ const passEnv = typeof cfg.args.env === "string" ? [`--env=${cfg.args.env}`] : [];
+ for (const n of order) {
+ const child = fork(__filename, [`--node=${n.id}`, ...passEnv], { silent: true });
+ const pipe = (stream, out) => {
+ let buf = "";
+ stream.on("data", (d) => {
+ buf += d;
+ let i;
+ while ((i = buf.indexOf("\n")) >= 0) (out.write(`${buf.slice(0, i)}\n`), (buf = buf.slice(i + 1)));
+ });
+ };
+ pipe(child.stdout, process.stdout);
+ pipe(child.stderr, process.stderr);
+ child.on("exit", (code, sig) => console.log(`[launcher] ${n.id} exited (${sig || code})`));
+ children.push(child);
+ await sleep(n.id === cfg.discordNode ? 0 : 1200);
+ }
+ const stopAll = () => {
+ for (const c of children) c.kill("SIGTERM");
+ setTimeout(() => process.exit(0), 1500).unref();
+ };
+ process.on("SIGINT", stopAll);
+ process.on("SIGTERM", stopAll);
+ console.log(`[launcher] ${children.length} nodes started. Use the commands in Discord (${cfg.prefix}help). Ctrl+C to stop.`);
+}
+
+module.exports = { parseEnv, loadConfig, startNode, attachDiscordCommands };
+if (require.main === module) main().catch((e) => (console.error(e.message), process.exit(1)));
diff --git a/examples/save/package.json b/examples/save/package.json
index 1f0c8149..8a1227e4 100644
--- a/examples/save/package.json
+++ b/examples/save/package.json
@@ -17,7 +17,7 @@
"dependencies": {
"@discordjs/opus": "^0.10.0",
"@discordjs/voice": "^0.19.0",
- "@ziplayer/extension": "file:../../extension",
+ "@ziplayer/extension": "file:../../extensions",
"@ziplayer/plugin": "file:../../plugins",
"lodash": "^4.17.21",
"discord.js": "^14.22.1",
diff --git a/examples/search/package.json b/examples/search/package.json
index bcae02d6..da103cc4 100644
--- a/examples/search/package.json
+++ b/examples/search/package.json
@@ -10,7 +10,7 @@
"test": "echo \"Error: no test specified\" && exit 1"
},
"dependencies": {
- "@ziplayer/extension": "file:../../extension",
+ "@ziplayer/extension": "file:../../extensions",
"@ziplayer/plugin": "file:../../plugins",
"ziplayer": "file:../../core"
}
diff --git a/examples/voice/package.json b/examples/voice/package.json
index 6aa2fcd9..5cc72473 100644
--- a/examples/voice/package.json
+++ b/examples/voice/package.json
@@ -12,7 +12,7 @@
"dependencies": {
"@discordjs/opus": "^0.10.0",
"@discordjs/voice": "^0.19.0",
- "@ziplayer/extension": "file:../../extension",
+ "@ziplayer/extension": "file:../../extensions",
"@ziplayer/plugin": "file:../../plugins",
"discord.js": "^14.22.1",
"dotenv": "^17.2.2",
diff --git a/extension/README.md b/extensions/README.md
similarity index 92%
rename from extension/README.md
rename to extensions/README.md
index 39c594e4..3c9cad3a 100644
--- a/extension/README.md
+++ b/extensions/README.md
@@ -213,6 +213,27 @@ new voiceExt(null, {
If you pass a Discord.js `client`, the payload will include resolved `user` and `channel` objects when possible.
+### Discord Rich Presence Extension
+
+Use `richPresenceExt` to broadcast currently playing track information directly to the local Discord desktop client via IPC. It
+displays song titles, artist/author, interactive timeline progress bar, thumbnail artwork, and maintains status even when idle.
+
+```ts
+import { richPresenceExt } from "@ziplayer/extension";
+
+const rpc = new richPresenceExt({
+ clientId: "YOUR_DISCORD_APPLICATION_ID", // optional override
+ activityType: "Listening", // "Listening" | "Playing"
+ showTimeline: true, // displays start/end time bar
+ showThumbnail: true, // displays track thumbnail
+ showIdle: true, // displays idle presence when not playing
+ idleDetails: "Chờ phát nhạc",
+ idleState: "Zimusix",
+});
+
+await player.attachExtension(rpc);
+```
+
## Requirements & Tips
- Your bot needs the `GuildVoiceStates` intent.
diff --git a/extension/package.json b/extensions/package.json
similarity index 100%
rename from extension/package.json
rename to extensions/package.json
diff --git a/extension/src/AiAutoplayExtension.ts b/extensions/src/AiAutoplayExtension.ts
similarity index 100%
rename from extension/src/AiAutoplayExtension.ts
rename to extensions/src/AiAutoplayExtension.ts
diff --git a/extension/src/index.ts b/extensions/src/index.ts
similarity index 86%
rename from extension/src/index.ts
rename to extensions/src/index.ts
index aa42ce6c..ebc130db 100644
--- a/extension/src/index.ts
+++ b/extensions/src/index.ts
@@ -109,3 +109,21 @@ export * from "./types/lavalink";
* ```
*/
export * from "./AiAutoplayExtension";
+
+/**
+ * Discord Rich Presence extension for live now-playing status, timeline progress bar, and thumbnail artwork.
+ *
+ * @example
+ * ```typescript
+ * import { richPresenceExt } from "@ziplayer/extension";
+ *
+ * const rpc = new richPresenceExt({
+ * clientId: "383226320970055681",
+ * activityType: "Listening",
+ * showTimeline: true,
+ * showThumbnail: true
+ * });
+ * await player.attachExtension(rpc);
+ * ```
+ */
+export * from "./richPresenceExt";
diff --git a/extension/src/lavalinkExt.ts b/extensions/src/lavalinkExt.ts
similarity index 100%
rename from extension/src/lavalinkExt.ts
rename to extensions/src/lavalinkExt.ts
diff --git a/extension/src/lyricsExt.ts b/extensions/src/lyricsExt.ts
similarity index 100%
rename from extension/src/lyricsExt.ts
rename to extensions/src/lyricsExt.ts
diff --git a/extensions/src/richPresenceExt.ts b/extensions/src/richPresenceExt.ts
new file mode 100644
index 00000000..78d6a448
--- /dev/null
+++ b/extensions/src/richPresenceExt.ts
@@ -0,0 +1,555 @@
+import { BaseExtension, Player, Track } from "ziplayer";
+import type { ExtensionContext } from "ziplayer";
+import net from "node:net";
+import path from "node:path";
+import os from "node:os";
+import crypto from "node:crypto";
+
+export interface RichPresenceOptions {
+ /** Discord Application (Client) ID. Defaults to standard Discord RPC application. */
+ clientId?: string;
+ /** Activity type: "Listening" (type 2) or "Playing" (type 0). Defaults to "Listening". */
+ activityType?: "Listening" | "Playing";
+ /** Whether to display start/end timeline bar. Defaults to true. */
+ showTimeline?: boolean;
+ /** Whether to display track thumbnail as large image. Defaults to true. */
+ showThumbnail?: boolean;
+ /** Whether to display Rich Presence when idle (no track playing). Defaults to true. */
+ showIdle?: boolean;
+ /** Details text displayed when idle. Defaults to "Chờ phát nhạc". */
+ idleDetails?: string;
+ /** State text displayed when idle. Defaults to "Zimusix". */
+ idleState?: string;
+ /** Fallback large image asset key or HTTPS URL when track has no thumbnail. */
+ largeImageFallback?: string;
+}
+
+export interface DiscordRpcUser {
+ id: string;
+ username: string;
+ discriminator?: string;
+ global_name?: string;
+ avatar?: string | null;
+}
+
+const OPCODES = {
+ HANDSHAKE: 0,
+ FRAME: 1,
+ CLOSE: 2,
+ PING: 3,
+ PONG: 4,
+} as const;
+
+function sanitizeString(str: unknown, minLen = 2, maxLen = 128): string | undefined {
+ if (typeof str !== "string") return undefined;
+ const trimmed = str.trim();
+ if (!trimmed) return undefined;
+ if (trimmed.length < minLen) return trimmed.padEnd(minLen, " ");
+ return trimmed.slice(0, maxLen);
+}
+
+function isValidHttpUrl(url: unknown): boolean {
+ if (typeof url !== "string") return false;
+ try {
+ const parsed = new URL(url);
+ return (
+ (parsed.protocol === "http:" || parsed.protocol === "https:") &&
+ !parsed.hostname.includes("127.0.0.1") &&
+ parsed.hostname !== "localhost"
+ );
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * richPresenceExt - Discord Rich Presence extension for ZiPlayer.
+ *
+ * Connects directly to the local Discord desktop client via IPC pipe/socket,
+ * displaying the currently playing track with live timeline progress bar and thumbnail artwork,
+ * as well as an idle status when no music is playing.
+ */
+export class richPresenceExt extends BaseExtension {
+ public name = "richPresenceExt";
+ public version = "1.0.0";
+ public priority = 80;
+ public player: Player | null = null;
+
+ private options: Required;
+ private socket: net.Socket | null = null;
+ private rxBuffer: Buffer = Buffer.alloc(0);
+ private isConnected = false;
+ private isDestroyed = false;
+ private reconnectTimer: NodeJS.Timeout | null = null;
+ private currentUser: DiscordRpcUser | null = null;
+ private currentActivity: Record | null = null;
+ private attachedPlayer: Player | null = null;
+ private busUnsubs: Array<() => void> = [];
+ private idleStartedAt: number = Date.now();
+
+ constructor(playerOrOptions?: Player | RichPresenceOptions | null, options?: RichPresenceOptions) {
+ super();
+ const opts: RichPresenceOptions = playerOrOptions && !(playerOrOptions instanceof Player) ? playerOrOptions : (options ?? {});
+ if (playerOrOptions instanceof Player) {
+ this.player = playerOrOptions;
+ }
+
+ this.options = {
+ clientId: opts.clientId ?? "383226320970055681",
+ activityType: opts.activityType ?? "Listening",
+ showTimeline: opts.showTimeline ?? true,
+ showThumbnail: opts.showThumbnail ?? true,
+ showIdle: opts.showIdle ?? true,
+ idleDetails: opts.idleDetails ?? "Chờ phát nhạc",
+ idleState: opts.idleState ?? "Zimusix",
+ largeImageFallback: opts.largeImageFallback ?? "",
+ };
+
+ this.connect();
+ }
+
+ public get connected(): boolean {
+ return this.isConnected;
+ }
+
+ public get user(): DiscordRpcUser | null {
+ return this.currentUser;
+ }
+
+ public setClientId(clientId: string): void {
+ if (!clientId || clientId === this.options.clientId) return;
+ this.options.clientId = clientId;
+ this.disconnect();
+ this.connect();
+ }
+
+ public setOptions(options: Partial): void {
+ const oldClientId = this.options.clientId;
+ this.options = { ...this.options, ...options };
+ if (options.clientId && options.clientId !== oldClientId) {
+ this.setClientId(options.clientId);
+ } else if (this.attachedPlayer && this.attachedPlayer.currentTrack) {
+ this.syncPlayerState(this.attachedPlayer);
+ } else if (this.options.showIdle) {
+ this.setIdleActivity();
+ }
+ }
+
+ public active(context: ExtensionContext): boolean {
+ const player = context.player ?? this.player;
+ if (!player) return false;
+ this.attachedPlayer = player;
+ this.player = player;
+
+ this.busUnsubs.push(
+ player.bus.subscribe(player.playerId, "TRACK_STARTED", ({ track }) => {
+ this.onTrackStart(track, player);
+ }),
+ );
+ this.busUnsubs.push(
+ player.bus.subscribe(player.playerId, "playerPause", () => {
+ this.onPlayerPause(player);
+ }),
+ );
+ this.busUnsubs.push(
+ player.bus.subscribe(player.playerId, "playerResume", () => {
+ this.onPlayerResume(player);
+ }),
+ );
+ this.busUnsubs.push(
+ player.bus.subscribe(player.playerId, "seek", ({ position }) => {
+ this.onSeek(position, player);
+ }),
+ );
+ this.busUnsubs.push(
+ player.bus.subscribe(player.playerId, "TRACK_END", () => {
+ this.onTrackEnd(player);
+ }),
+ );
+ this.busUnsubs.push(
+ player.bus.subscribe(player.playerId, "playerStop", () => {
+ this.setIdleActivity();
+ }),
+ );
+ this.busUnsubs.push(
+ player.bus.subscribe(player.playerId, "destroyed", () => {
+ this.onDestroy();
+ }),
+ );
+
+ if (player.currentTrack) {
+ this.syncPlayerState(player);
+ } else {
+ this.setIdleActivity();
+ }
+
+ return true;
+ }
+
+ public onDestroy(): void {
+ this.isDestroyed = true;
+ for (const unsub of this.busUnsubs) {
+ try {
+ unsub();
+ } catch {}
+ }
+ this.busUnsubs = [];
+ this.clearActivity();
+ this.disconnect();
+ }
+
+ public clearActivity(): void {
+ this.currentActivity = null;
+ if (!this.isConnected || !this.socket) return;
+ this.sendPacket(OPCODES.FRAME, {
+ cmd: "SET_ACTIVITY",
+ args: {
+ pid: process.pid,
+ activity: null,
+ },
+ nonce: crypto.randomUUID(),
+ });
+ }
+
+ public setIdleActivity(): void {
+ if (!this.options.showIdle) {
+ this.clearActivity();
+ return;
+ }
+
+ if (!this.idleStartedAt) {
+ this.idleStartedAt = Date.now();
+ }
+
+ const details = sanitizeString(this.options.idleDetails || "Chờ phát nhạc");
+ const state = sanitizeString(this.options.idleState || "Zimusix");
+
+ let largeImage: string | undefined;
+ if (this.options.largeImageFallback && isValidHttpUrl(this.options.largeImageFallback)) {
+ largeImage = this.options.largeImageFallback;
+ }
+
+ const assets: Record = {
+ large_image: largeImage,
+ large_text: sanitizeString(this.options.idleState || "Zimusix"),
+ };
+
+ const activity: Record = {
+ details,
+ state,
+ assets,
+ timestamps: { start: this.idleStartedAt },
+ type: this.options.activityType === "Playing" ? 0 : 2,
+ };
+
+ this.setActivity(activity);
+ }
+
+ public setActivity(activity: Record | null): void {
+ this.currentActivity = activity;
+ if (!this.isConnected || !this.socket) return;
+ this.sendPacket(OPCODES.FRAME, {
+ cmd: "SET_ACTIVITY",
+ args: {
+ pid: process.pid,
+ activity,
+ },
+ nonce: crypto.randomUUID(),
+ });
+ }
+
+ public syncPlayerState(player: Player): void {
+ const track = player.currentTrack;
+ if (!track) {
+ this.setIdleActivity();
+ return;
+ }
+
+ const time = player.getTime();
+ const positionMs = time.current;
+ const durationMs = time.total;
+ const isPaused = player.isPaused;
+
+ this.formatAndSendActivity({
+ track,
+ positionMs,
+ durationMs,
+ isPaused,
+ isLive: Boolean(track.isLive),
+ });
+ }
+
+ private onTrackStart(track: Track | null, player: Player): void {
+ if (!track) {
+ this.setIdleActivity();
+ return;
+ }
+ this.idleStartedAt = 0;
+ const d = Number(track.duration) || 0;
+ const durationMs = d > 1000 ? d : d * 1000;
+ this.formatAndSendActivity({
+ track,
+ positionMs: 0,
+ durationMs,
+ isPaused: false,
+ isLive: Boolean(track.isLive),
+ });
+ }
+
+ private onPlayerPause(player: Player): void {
+ const track = player.currentTrack;
+ if (!track) return;
+ const time = player.getTime();
+ this.formatAndSendActivity({
+ track,
+ positionMs: time.current,
+ durationMs: time.total,
+ isPaused: true,
+ isLive: Boolean(track.isLive),
+ });
+ }
+
+ private onPlayerResume(player: Player): void {
+ const track = player.currentTrack;
+ if (!track) return;
+ const time = player.getTime();
+ this.formatAndSendActivity({
+ track,
+ positionMs: time.current,
+ durationMs: time.total,
+ isPaused: false,
+ isLive: Boolean(track.isLive),
+ });
+ }
+
+ private onSeek(positionMs: number, player: Player): void {
+ const track = player.currentTrack;
+ if (!track) return;
+ const time = player.getTime();
+ this.formatAndSendActivity({
+ track,
+ positionMs,
+ durationMs: time.total,
+ isPaused: player.isPaused,
+ isLive: Boolean(track.isLive),
+ });
+ }
+
+ private onTrackEnd(player: Player): void {
+ if (player.upcomingTracks.length === 0 && !player.isPlaying) {
+ this.setIdleActivity();
+ }
+ }
+
+ private formatAndSendActivity(params: {
+ track: Track;
+ positionMs: number;
+ durationMs: number;
+ isPaused: boolean;
+ isLive: boolean;
+ }): void {
+ const { track, positionMs, durationMs, isPaused, isLive } = params;
+ const details = sanitizeString(track.title || "Untitled track");
+ const authorText = track.author ? `by ${track.author}` : "ZiPlayer";
+ const stateText = isPaused ? `${authorText} (Paused)` : authorText;
+ const state = sanitizeString(stateText);
+
+ let timestamps: { start?: number; end?: number } | undefined;
+ if (this.options.showTimeline && !isPaused) {
+ const start = Math.floor(Date.now() - Math.max(0, positionMs));
+ timestamps = { start };
+ if (durationMs > 0 && !isLive) {
+ timestamps.end = Math.floor(start + durationMs);
+ }
+ }
+
+ let largeImage: string | undefined;
+ if (this.options.showThumbnail) {
+ if (isValidHttpUrl(track.thumbnail)) {
+ largeImage = track.thumbnail;
+ } else if (this.options.largeImageFallback && isValidHttpUrl(this.options.largeImageFallback)) {
+ largeImage = this.options.largeImageFallback;
+ }
+ }
+
+ const assets: Record = {
+ large_image: largeImage,
+ large_text: sanitizeString(track.title || "ZiPlayer"),
+ small_image: isPaused ? "pause" : "play",
+ small_text: isPaused ? "Paused" : "Playing",
+ };
+
+ const activity: Record = {
+ details,
+ state,
+ assets,
+ type: this.options.activityType === "Playing" ? 0 : 2,
+ };
+ if (timestamps) activity.timestamps = timestamps;
+
+ this.setActivity(activity);
+ }
+
+ /* ------------------------------------------------------------- IPC Protocol */
+
+ private getIpcPaths(): string[] {
+ const paths: string[] = [];
+ if (process.platform === "win32") {
+ for (let i = 0; i < 10; i++) {
+ paths.push(`\\\\?\\pipe\\discord-ipc-${i}`);
+ paths.push(`\\\\.\\pipe\\discord-ipc-${i}`);
+ }
+ } else {
+ const envDirs = [process.env.XDG_RUNTIME_DIR, process.env.TMPDIR, process.env.TMP, process.env.TEMP, "/tmp"].filter(
+ Boolean,
+ ) as string[];
+
+ for (const dir of envDirs) {
+ for (let i = 0; i < 10; i++) {
+ paths.push(path.join(dir, `discord-ipc-${i}`));
+ }
+ }
+ }
+ return paths;
+ }
+
+ private connect(): void {
+ if (this.isDestroyed || this.socket || this.isConnected) return;
+
+ const candidatePaths = this.getIpcPaths();
+ let index = 0;
+
+ const tryNext = () => {
+ if (this.isDestroyed || this.socket) return;
+ if (index >= candidatePaths.length) {
+ this.scheduleReconnect();
+ return;
+ }
+
+ const ipcPath = candidatePaths[index++];
+ const sock = net.connect(ipcPath);
+
+ sock.once("connect", () => {
+ this.socket = sock;
+ this.rxBuffer = Buffer.alloc(0);
+ this.setupSocket(sock);
+ this.sendHandshake();
+ });
+
+ sock.once("error", () => {
+ sock.destroy();
+ tryNext();
+ });
+ };
+
+ tryNext();
+ }
+
+ private setupSocket(sock: net.Socket): void {
+ sock.on("data", (chunk: Buffer) => {
+ this.rxBuffer = Buffer.concat([this.rxBuffer, chunk]);
+ while (this.rxBuffer.length >= 8) {
+ const opcode = this.rxBuffer.readInt32LE(0);
+ const length = this.rxBuffer.readInt32LE(4);
+ if (this.rxBuffer.length < 8 + length) break;
+
+ const payloadBytes = this.rxBuffer.subarray(8, 8 + length);
+ this.rxBuffer = this.rxBuffer.subarray(8 + length);
+
+ try {
+ const text = payloadBytes.toString("utf8");
+ const message = JSON.parse(text);
+ this.handleMessage(opcode, message);
+ } catch (err) {
+ console.error("[richPresenceExt] Failed to parse frame:", err);
+ }
+ }
+ });
+
+ sock.on("close", () => {
+ this.onSocketDisconnected();
+ });
+
+ sock.on("error", () => {
+ this.onSocketDisconnected();
+ });
+ }
+
+ private handleMessage(opcode: number, message: any): void {
+ if (opcode === OPCODES.FRAME) {
+ if (message.evt === "READY") {
+ this.isConnected = true;
+ this.currentUser = message.data?.user ?? null;
+ this.emit("ready", this.currentUser);
+ if (this.currentActivity) {
+ this.setActivity(this.currentActivity);
+ } else if (this.attachedPlayer?.currentTrack) {
+ this.syncPlayerState(this.attachedPlayer);
+ } else {
+ this.setIdleActivity();
+ }
+ } else if (message.evt === "ERROR") {
+ console.warn("[richPresenceExt] Discord error event:", message.data);
+ }
+ } else if (opcode === OPCODES.PING) {
+ this.sendPacket(OPCODES.PONG, message);
+ } else if (opcode === OPCODES.CLOSE) {
+ this.disconnect();
+ this.scheduleReconnect();
+ }
+ }
+
+ private sendHandshake(): void {
+ this.sendPacket(OPCODES.HANDSHAKE, {
+ v: 1,
+ client_id: this.options.clientId,
+ });
+ }
+
+ private sendPacket(opcode: number, payload: unknown): void {
+ if (!this.socket || this.socket.destroyed) return;
+ try {
+ const json = JSON.stringify(payload);
+ const jsonBuf = Buffer.from(json, "utf8");
+ const header = Buffer.alloc(8);
+ header.writeInt32LE(opcode, 0);
+ header.writeInt32LE(jsonBuf.length, 4);
+ this.socket.write(Buffer.concat([header, jsonBuf]));
+ } catch (err) {
+ console.error("[richPresenceExt] Failed to send packet:", err);
+ }
+ }
+
+ private onSocketDisconnected(): void {
+ this.isConnected = false;
+ this.currentUser = null;
+ if (this.socket) {
+ this.socket.removeAllListeners();
+ this.socket.destroy();
+ this.socket = null;
+ }
+ this.scheduleReconnect();
+ }
+
+ private disconnect(): void {
+ this.isConnected = false;
+ this.currentUser = null;
+ if (this.socket) {
+ this.socket.removeAllListeners();
+ this.socket.destroy();
+ this.socket = null;
+ }
+ if (this.reconnectTimer) {
+ clearTimeout(this.reconnectTimer);
+ this.reconnectTimer = null;
+ }
+ }
+
+ private scheduleReconnect(): void {
+ if (this.isDestroyed || !this.socket || this.reconnectTimer) return;
+ this.reconnectTimer = setTimeout(() => {
+ this.reconnectTimer = null;
+ this.connect();
+ }, 10_000).unref();
+ }
+}
diff --git a/extension/src/types/lavalink.ts b/extensions/src/types/lavalink.ts
similarity index 100%
rename from extension/src/types/lavalink.ts
rename to extensions/src/types/lavalink.ts
diff --git a/extension/src/voiceExt.ts b/extensions/src/voiceExt.ts
similarity index 100%
rename from extension/src/voiceExt.ts
rename to extensions/src/voiceExt.ts
diff --git a/extension/tsconfig.json b/extensions/tsconfig.json
similarity index 100%
rename from extension/tsconfig.json
rename to extensions/tsconfig.json
diff --git a/implementation-notes.md b/implementation-notes.md
deleted file mode 100644
index 80cda3db..00000000
--- a/implementation-notes.md
+++ /dev/null
@@ -1,301 +0,0 @@
-# ZiPlayer AudioEngine Implementation Notes
-
-## A. Confirmed Findings
-
-### 1. Silent Dropping and Concurrency Race in `TTSController`
-
-- **Component**: `core/src/controller/TTSController.ts`
-- **Defect**: When multiple TTS requests were received sequentially or concurrently, the existing implementation did
- `if (state.running) return state.running;`.
-- **Reproduction**: When request A started playing, and request B arrived, request B immediately returned request A's Promise.
- Request B was never queued, never resolved, and never spoken.
-- **Coverage**: Existing tests in `tests/tts_playback_routing.test.js` only checked that a single TTS track routed to `ttsPlay`
- RPC, but failed to assert queue behavior for concurrent or sequential requests.
-
-### 2. Music Skipping During Active TTS Playback
-
-- **Component**: `core/src/controller/PlaybackSkipController.ts`, `core/src/structures/Player.ts`
-- **Defect**: In `PlaybackSkipController.doSkip()`, invoking the public `skip()` API operated unconditionally on the underlying
- music session (`this.currentSession()`). When TTS was actively playing over a ducked/paused music track, calling `player.skip()`
- did not cancel the TTS utterance, but instead skipped and ended the underlying music session.
-- **Defect**: In `Player.ts`, `skip()` unconditionally called `this.invalidatePlay()`, aborting `this.playAbortController`. This
- aborted in-flight TTS calls and would cancel queued TTS utterances instead of skipping only the active utterance.
-- **Reproduction**: Start music track, invoke `player.play("tts:hello")`, invoke `player.skip()`. The music track advanced in the
- queue while the TTS utterance kept playing.
-
-### 3. Stale Session Resurrection on TTS Finish
-
-- **Component**: `core/src/controller/TTSController.ts`
-- **Defect**: `TTSController` blindly unpaused `state.audioPlayer` in its `finally` block if `wasPlaying` was true when TTS
- started, without checking whether the underlying playback session was replaced, ended, or stopped during TTS playback.
-- **Reproduction**: Start music track A, play TTS track, replace or stop music track A with track B, wait for TTS to finish. Track
- A was unpaused in `audioPlayer` despite having been replaced.
-
-### 4. Browser Client Autoplay Rejection and Lack of Resume/Unlock
-
-- **Component**: `client/browser/index.js`
-- **Defect**: In `createAudioOutput()`, `await context.resume()` unconditionally rejected `connect()` if invoked without prior
- user gesture in environments enforcing browser Autoplay policies (including Electron and Tauri WebViews).
-- **Defect**: `WebAudioClient` lacked explicit `resume()` and `unlockAudio()` methods, preventing applications from recovering
- from audio suspension upon user click without tearing down and reconnecting the entire WebSocket connection.
-- **Defect**: Unreachable dead code in `receiveOpusFrame()` (dispatch after return).
-
-### 5. `Player.play()` False-Negative Return on Concurrent TTS Requests
-
-- **Component**: `core/src/structures/Player.ts`
-- **Defect**: `Player.play()` incremented `this.playGeneration` unconditionally (`const generation = ++this.playGeneration;`) and
- checked `if (generation !== this.playGeneration || combinedSignal.aborted) return false;` after RPC completion.
-- **Reproduction**: Calling `player.play("tts:A")` immediately followed by `player.play("tts:B")` caused request B to increment
- `this.playGeneration`. When request A completed playing via the FIFO queue, its `generation` no longer matched
- `this.playGeneration`, causing `player.play("tts:A")` to return `false` despite audio having played successfully.
-
-### 6. `WebAudioClient` TypeScript Declaration Incompatibility with `EventTarget`
-
-- **Component**: `client/index.d.ts`
-- **Defect**: `WebAudioClient` declared generic `addEventListener` and `removeEventListener` signatures without overload
- declarations matching base `EventTarget` (`(type: string, callback: EventListenerOrEventListenerObject | null, ...)`).
-- **Reproduction**: Compiling TypeScript projects importing `WebAudioClient` with strict types triggered `error TS2416` and
- `error TS2322`.
-
-### 7. `unlockAudio()` Ineffective When Called Prior to `connect()`
-
-- **Component**: `client/browser/index.js`
-- **Defect**: `unlockAudio()` only checked `if (this.audioContext)` and was a no-op if called before `connect()`. Furthermore,
- `connect()` unconditionally ran `if (this.socket || this.audioContext) await this.disconnect();`, closing any existing unlocked
- `AudioContext` and creating a new one outside the synchronous user interaction gesture.
-
----
-
-## B. Implementation Decisions
-
-### 1. Per-Player Sequential FIFO TTS Queue
-
-- Implemented an isolated FIFO queue in `TTSController` (`queue: TTSQueueItem[]`).
-- Each queued utterance receives an independent lifecycle token, independent `AbortController`, and dedicated completion Promise
- (`resolve`, `reject`).
-- Sequential queue processor `runWorker()` executes utterances in strict `A -> B -> C` order with a single worker promise per
- player.
-- If an utterance fails (e.g. stream resolution error), the rejection settles that utterance's promise while the worker safely
- advances to the next queued utterance.
-
-### 2. Integrated TTS Skip Architecture
-
-- Added `CONTROLLER_RPC.ttsSkip` (`"controller.tts.skip"`) and `PLAYER_QUERY.ttsIsActive` (`"tts.isActive"`).
-- In `PlaybackSkipController.doSkip()`:
- - Skip checks whether TTS is active via `CONTROLLER_RPC.ttsSkip`.
- - If TTS is active (in preparation phase, playing audio, or pending in queue), `ttsSkip` aborts the current utterance and
- returns `{ skipped: true }`.
- - If another utterance is queued, playback immediately advances to the next utterance.
- - If no more utterances are queued, TTS terminates cleanly and restores the underlying playback state.
- - Underlying music is untouched (`doSkip` returns `true` without touching the music queue).
- - If TTS is not active, standard music track skipping proceeds unaffected.
-- Preparation race condition: If a skip arrives while an utterance is resolving its stream (status `"preparing"`), the utterance's
- `AbortController` triggers, aborting the resolver and rejecting the utterance promise with an `AbortError`, returning
- `{ skipped: true }` so music is never skipped.
-
-### 3. Playback Restoration and Session Ownership
-
-- When the first TTS utterance begins in an empty queue, `TTSController` records:
- - `wasMusicPlaying`: boolean flag from `audioPlayer.state.status === AudioPlayerStatus.Playing`.
- - `interruptedSessionId`: string identifier of the active `PlaybackSession`.
- - It pauses music and redirects the voice connection to `ttsPlayer`.
-- During transitions between consecutive queued TTS utterances, music is not unpaused, preventing audio glitching/flicker.
-- When the queue drains completely:
- - Voice connection is restored to the player's `audioPlayer`.
- - Only if `wasMusicPlaying` was true, the player is not disposed, AND the current music session's `sessionId` matches
- `interruptedSessionId`, `audioPlayer.unpause()` is called.
- - If the music session ended or was replaced while TTS played, the obsolete track is never resumed.
-
-### 4. Player Facade (`Player.ts`) Concurrency Isolation
-
-- In `Player.play()`:
- - Queries are inspected with `isTTSQuery()`.
- - For music queries, `this.playAbortController` is aborted to cancel superseded track loads, and `this.playGeneration` is
- incremented.
- - For TTS queries:
- - `this.playAbortController` is NOT aborted, allowing sequential and concurrent `player.play("tts:...")` requests to enter the
- `TTSController` queue without mutual cancellation.
- - `this.playGeneration` is NOT incremented (`const generation = isTTS ? 0 : ++this.playGeneration;`), and completion checks
- skip generation matching (`if ((!isTTS && generation !== this.playGeneration) || combinedSignal.aborted) return false;`),
- ensuring that all queued TTS requests return their valid `PlayResult` once spoken.
-- In `Player.skip()`:
- - Skip checks `PLAYER_QUERY.ttsIsActive`. If active, `this.invalidatePlay()` is skipped so subsequent queued TTS utterances are
- preserved.
-
-### 5. Desktop Audio Support (Electron & Tauri)
-
-- Added `workletUrl` option to `WebAudioClient` to allow loading AudioWorklet processor files directly in strict CSP environments
- where `blob:` is disallowed.
-- Added `resume()` and `unlockAudio()` methods on `WebAudioClient` to recover from `suspended` state following user gesture.
-- `unlockAudio()` initializes and resumes the `AudioContext` and plays a silent buffer if called prior to `connect()`.
-- `connect()` reuses any existing, active `AudioContext` instead of tearing it down, flushing pending worklet frames and ensuring
- pre-unlocked audio state remains intact.
-- In `createAudioOutput()`, catch Autoplay `NotAllowedError` / suspended state during initial connect, dispatching a `"suspended"`
- event rather than terminating `connect()`.
-- Implemented socket listener cleanup on `disconnect()` and socket closure to prevent listener accumulation on repeated
- connect/disconnect cycles.
-- Added base `EventTarget` overloads to `addEventListener` and `removeEventListener` in `client/index.d.ts` for strict TypeScript
- compilation.
-
----
-
-## C. Trade-offs
-
-1. **Internal RPC vs Direct Controller State Access**:
- - _Choice_: Used `CONTROLLER_RPC.ttsSkip` and `PLAYER_QUERY.ttsIsActive` on the `Bus`.
- - _Rationale_: Preserves controller isolation and complies with ZiPlayer architecture rules ("sibling controllers talk only
- through Bus queries/RPCs — never by holding a direct reference").
- - _Alternative Considered_: Directly referencing `TTSController` inside `PlaybackSkipController` was rejected because it
- violates repository conventions and tightly couples controllers.
-
-2. **FIFO Worker vs Pipeline Buffering**:
- - _Choice_: Sequential single-worker execution with stream resolution right before playback.
- - _Rationale_: Guarantees that cancelled or skipped pending utterances do not leak active audio streams or decode resources.
-
-3. **Autoplay Handling in Desktop WebViews**:
- - _Choice_: Establish the WebSocket and Web Audio graph on `connect()`, dispatching `"suspended"` if the platform requires a
- user gesture.
- - _Rationale_: Allows applications to connect early (e.g. at app launch) and unlock audio on the first user click via
- `client.unlockAudio()`.
-
----
-
-## D. Compatibility
-
-### 1. Browser Requirements
-
-- Web Audio API (`AudioContext`, `AudioWorkletNode`).
-- WebAssembly (`WebAssembly.instantiate` / `WebAssembly.compile`).
-- Sample rate: 48 kHz.
-
-### 2. Electron Requirements
-
-- Runs directly inside Chromium Renderer process.
-- Compatible with `contextIsolation: true` and `nodeIntegration: false`.
-- Preload script does not need to expose private audio internals.
-
-### 3. Tauri Requirements
-
-- Compatible with Wry (WebView2 on Windows, WebKitGTK on Linux, WKWebView on macOS).
-- Required CSP directives in `tauri.conf.json`:
- - `connect-src 'self' ws: wss:;`
- - `script-src 'self' 'wasm-unsafe-eval' blob:;` (or supply custom `workletUrl` if `blob:` is omitted).
- - `worker-src 'self' blob:;`
-
----
-
-## E. Validation
-
-### 1. Commands Executed
-
-- `npm run build:core:fast`: Built core TypeScript into `dist/` (passed, 180ms).
-- `node --test tests/tts_queue_skip_lifecycle.test.js`: Ran all 9 new TTS queue, skip, and lifecycle regression tests (passed,
- 10.8s).
-- `npm test --prefix client`: Ran all 29 browser and desktop compatibility tests in client package (passed, 241ms).
-- `npm run test:integration`: Ran all 13 plugin and extension integration tests (passed, 4.3s).
-- `node --test tests/*.test.js`: Ran all root test suites (236 passed, 0 failed, 2 skipped across 44 test files).
-- `git diff --check`: Verified no whitespace errors or leftover markers.
-
-### 2. Real-Runtime Desktop Checks Not Performed
-
-- Unit and integration tests validate the browser client using mock Web Audio and WebSocket environments.
-- Real-runtime end-to-end testing with a live GUI window in Electron binary packaging or compiled `cargo tauri dev` was not
- executed in this headless CLI environment; verification procedures are documented in `examples/desktop/README.md`.
-
----
-
-## F. Removal of FFmpegAudioProcessingEngine and Architectural Simplification
-
-### 1. Reason for Removal
-
-`FFmpegAudioProcessingEngine` previously introduced an intermediate child-process FFmpeg pipeline in `PlaybackController` for
-every track played when enabled. This had several architectural issues:
-
-- **Redundant transcoding**: Even when tracks were already encoded Opus or were already processed by `FilterController`, they were
- piped through a second FFmpeg child process before reaching `createAudioResource`.
-- **Process overhead and latency**: Normal playback required spawning child processes, setting up IPC pipes, and managing process
- concurrency limits.
-- **Architectural duplication**: `FilterController` already owns the FFmpeg-based audio filtering capabilities and real-time
- filter chains, making a second general-purpose FFmpeg processing engine redundant.
-- **Complexity and failure modes**: Stalled stdin/stdout pipes, orphan process tracking, and generator abort races added
- significant operational fragility.
-
-### 2. Ownership of Filtering and Resource Creation
-
-- **Normal Playback (No Filter)**: `Track / StreamInfo` → `TrackLoader / Plugin` → `PlaybackStartController` → `StreamController`
- → `PlaybackController.createResource()` → `@discordjs/voice` `createAudioResource()` → `AudioPlayer` → Subscribers (Discord
- Voice, `WebAudioConnection`).
- - No FFmpeg process is spawned solely for audio playback.
- - The original stream feeds directly into the resource pipeline.
- - Inline volume handling is managed by `@discordjs/voice` via its native Opus / PCM transformation.
-- **Filtered Playback (Filter Active or Non-Seekable Stream Seek)**: `PlaybackStartController` detects active filters
- (`filterString` query) and routes the stream through `FilterController` (`FilterEngine.applyFiltersAndSeek()`).
- - `FilterController` spawns a single FFmpeg process executing the requested filter graph (`-af `).
- - Output is encoded to Opus in an Ogg container (`-c:a libopus -f opus -ar 48000 -ac 2`) with `inputType: StreamType.OggOpus`.
- - When seeking on a stream providing `streamInfo.recreate(position)`:
- - If no filters are active, the recreated stream is passed directly without spawning FFmpeg (`wasRecreated: true`).
- - If filters are active, the recreated stream is processed through FFmpeg with `-af ` but omitting redundant `-ss`
- (since `recreate` already starts at the target offset).
- - Initial filters (`PlayerOptions.filters`) are registered synchronously at player creation without requiring an active audio
- resource, ensuring filters persist before the first track plays.
- - The filtered stream enters `StreamController` and is handed to `PlaybackController.createResource()`, which creates an
- `AudioResource` without any second FFmpeg stage.
-- **Save / Export Operations**:
- - `SaveController` maintains its own isolated `FilterEngine` instance for offline stream filtering and export, completely
- independent of the live playback resource path.
-
-### 3. Removed Public Configuration Options and APIs
-
-- **Removed Public APIs**:
- - `createAudioProcessingEngine`
- - `defaultAudioProcessingEngine`
- - `FFmpegAudioProcessingEngine`
- - `resolveAudioProcessingOptions`
- - `getFfmpegProcessStats`
- - `configureFfmpegConcurrency`
- - `AudioFrameFormat`
- - Types: `AudioProcessingEngine`, `AudioProcessingPipeline`, `AudioProcessingOptions`, `AudioProcessingContext`,
- `AudioProcessingFormat`, `AudioProcessingInputFormat`, `AudioProcessingOutputFormat`, `AudioProcessingHint`
-- **Removed Configuration Options**:
- - `PlayerOptions.audioProcessing` (and `PlaybackControllerOptions.audioProcessing`)
- - Sub-options: `audioProcessing.enabled`, `audioProcessing.inputFormat`, `audioProcessing.outputFormat`,
- `audioProcessing.sampleRate`, `audioProcessing.channels`, `audioProcessing.gainDb`, `audioProcessing.gainLinear`,
- `audioProcessing.highpassHz`, `audioProcessing.lowpassHz`, `audioProcessing.normalize`, `audioProcessing.resampleRate`,
- `audioProcessing.maxBufferBytes`, `audioProcessing.ffmpegInputFormats`, `audioProcessing.encodedBitrate`,
- `audioProcessing.encodedApplication`, `audioProcessing.maxInputBytes`, `audioProcessing.maxDurationMs`,
- `audioProcessing.stallTimeoutMs`, `audioProcessing.ffmpegThreads`, `audioProcessing.maxConcurrentProcesses`.
-- **Preserved Options**:
- - `PlayerOptions.ffmpegPath`: Shared setting used by `FilterController` and `SaveController` to locate the FFmpeg executable.
- - `PlayerOptions.loudnessNormalization`: High-level volume leveling managed entirely in software by `VolumeController` (inline
- volume target scaling), independent of FFmpeg.
- - `PlayerOptions.volume`: Shared player volume.
-
-### 4. DSP Features and Behavior Changes
-
-- Static DSP flags on the removed engine (`gainDb`, `gainLinear`, `highpassHz`, `lowpassHz`, `normalize`) are no longer configured
- via `audioProcessing`.
-- Equivalent filtering is available dynamically through `player.filter.applyFilter()` / `player.filter.applyFilters()` (e.g.
- `bassboost`, `loudnorm`, `highpass`, `equalizer`, custom filter graphs validated by `isSafeCustomFilter`).
-
-### 5. When FFmpeg Starts
-
-FFmpeg processes are started **only** in the following circumstances:
-
-1. When active filters are applied to a player (`player.filter.applyFilter()` or initial filters specified in
- `PlayerOptions.filters`).
-2. When seeking on a non-seekable Readable stream where the plugin does not provide `recreate(position)`.
-3. When saving/exporting audio with active filters via `SaveController`.
-4. When `@discordjs/voice` internally transcodes an arbitrary non-Opus stream (e.g. raw MP3) to PCM via `prism-media` during
- inline-volume resource creation.
-
-FFmpeg is **never** started for standard playback of Opus streams without filters.
-
-### 6. Format Compatibility and Resource Contract
-
-- Direct encoded streams (`StreamType.Opus`, `StreamType.WebmOpus`, `StreamType.OggOpus`, `StreamType.Arbitrary`) retain their
- source type.
-- Raw audio inputs (`StreamType.Raw`) are explicitly rejected before resource creation with
- `TypeError("Raw audio input is unsupported; provide encoded audio")`, destroying the input stream.
-- Filter output is consistently formatted as `StreamType.OggOpus` (48 kHz, stereo) via FFmpeg `libopus`, allowing downstream
- `@discordjs/voice` demuxing and inline volume transformation without further conversion.
-- Both Discord Voice and `WebAudioConnection` subscribe directly to `@discordjs/voice` `AudioPlayer` and receive Opus packets.
diff --git a/net/README.md b/net/README.md
new file mode 100644
index 00000000..73986d75
--- /dev/null
+++ b/net/README.md
@@ -0,0 +1,315 @@
+
+
+Connect several ZiPlayer processes ("nodes") over MQTT.
+
+- **Stream transfer** – the node whose plugins resolve a track (the _owner streamInfo_) sends the compressed audio (Opus, or the
+ `arbitrary` containers official plugins return) to the node that plays it.
+- **Voice hand-off** – the node that called `player.connect()` (the _owner connection_) can hand the Discord voice session to
+ another node, which plays instead. The owner keeps the gateway and the queue; the gateway adapter replays the latest cached
+ voice-server update when a hand-off starts after the initial join.
+- **Auto routing** – `routeTracks()` decides per batch of tracks: keep the voice and pull a few foreign tracks (_relay_), or move
+ the voice to the node that can play most of them (_handoff_).
+
+## Quick start
+
+`@ziplayer/net` connects separate ZiPlayer processes. Each process needs a unique `nodeId`, the same `networkId`, an MQTT
+connection, and a pinned public key for every peer it trusts. Use Node.js 20.3 or newer.
+
+Install the packages used by the examples:
+
+```bash
+npm install ziplayer @ziplayer/net @ziplayer/plugin @discordjs/voice discord.js mqtt
+```
+
+On the provider node, create a manager with the source plugin and opt in to search, stream, and voice requests:
+
+```js
+import { PlayerManager } from "ziplayer";
+import { YouTubePlugin } from "@ziplayer/plugin";
+import { MqttTransport, ZiNet } from "@ziplayer/net";
+
+const manager = new PlayerManager({ plugins: [new YouTubePlugin()] });
+const net = new ZiNet({
+ nodeId: "yt-1",
+ networkId: "music-prod",
+ keyFile: "./keys/yt-1.key",
+ trust: [{ nodeId: "bot-1", publicKey: botPublicKey }],
+ transport: new MqttTransport({
+ url: process.env.MQTT_URL, // Prefer mqtts://
+ username: process.env.MQTT_USERNAME,
+ password: process.env.MQTT_PASSWORD,
+ }),
+ manager,
+});
+
+await net.start();
+net.provideStreams({ allow: (track) => track.source === "youtube" });
+net.provideSearch();
+net.acceptVoice({ allow: (_guildId, peerId) => peerId === "bot-1" });
+```
+
+On the Discord owner node, pass `discordJsGateway(client)` and the pinned provider key when constructing `ZiNet`. Attach the
+network extension to players. Search results from another node are marked with their owner automatically:
+
+```js
+import { PlayerManager } from "ziplayer";
+import { discordJsGateway, MqttTransport, ZiNet } from "@ziplayer/net";
+
+const manager = new PlayerManager();
+const net = new ZiNet({
+ nodeId: "bot-1",
+ networkId: "music-prod",
+ keyFile: "./keys/bot-1.key",
+ trust: [{ nodeId: "yt-1", publicKey: ytPublicKey }],
+ transport: new MqttTransport({ url: process.env.MQTT_URL }),
+ manager,
+ gateway: discordJsGateway(client),
+});
+
+await net.start();
+const player = await manager.create(guildId, { extensions: [net.extensionClass()] });
+await player.connect(voiceChannel);
+
+const { tracks } = await net.search("yt:lofi hip hop");
+const route = await net.routeTracks(player, tracks);
+if (!route.applied) throw route.error ?? new Error(`Routing failed: ${route.mode}`);
+await player.play(tracks[0]);
+```
+
+See [Detailed guide](#detailed-guide) for peer-key setup, role permissions, relay vs hand-off, and lifecycle details. For a
+complete runnable cluster, see [`examples/net`](../examples/net).
+
+## Detailed guide
+
+### How the nodes work together
+
+Each process owns its own `PlayerManager`, plugins, and `ZiNet` instance. The Discord owner has the Discord client and gateway;
+provider nodes run the plugins that supply search results or streams; a voice executor accepts a delegated connection. These roles
+can be combined in one process. Run each node in a separate process because `PlayerManager` is process-scoped.
+
+- **Relay:** the Discord owner stays connected and imports a provider's compressed stream over MQTT. The player's net extension is
+ required on the owner.
+- **Hand-off:** the owner releases the voice connection and a selected executor joins voice and plays there. The owner keeps the
+ gateway and queue; `discordJsGateway(client)` is required on the owner and `acceptVoice()` on the executor.
+
+### Install and configure MQTT
+
+`@ziplayer/net` has peer dependencies on `ziplayer` and `@discordjs/voice`; `mqtt` is optional unless using `MqttTransport`.
+Install `mqtt` explicitly for MQTT transport. `MqttTransport` defaults to MQTT protocol version 5; set `protocolVersion: 4` for a
+broker that only supports MQTT 3.1.1.
+
+```js
+const transport = new MqttTransport({
+ url: process.env.MQTT_URL, // mqtts://broker.example.com:8883
+ username: process.env.MQTT_USERNAME,
+ password: process.env.MQTT_PASSWORD,
+ clientId: `ziplayer-${nodeId}`,
+ protocolVersion: 5,
+});
+```
+
+Use the same `networkId` on nodes in one cluster and a different value for independent clusters sharing the broker. Every `nodeId`
+must be unique and must not contain `/`, `+`, or `#`. Use TLS (`mqtts://`) and broker authentication; the broker is not a trust
+authority for peers.
+
+### Create a node and pin peers
+
+Create one `ZiNet` instance per process. `keyFile` loads an existing Ed25519 private key or creates one, along with a
+`.pub` public-key file. Keep the private `.key` file private and distribute only `.key.pub`.
+
+```js
+const net = new ZiNet({
+ nodeId,
+ networkId,
+ keyFile: `./keys/${nodeId}.key`,
+ trust: [{ nodeId: peerId, publicKey: fs.readFileSync(peerPublicKeyPath, "utf8"), roles: ["*"] }],
+ transport,
+ manager, // Required to serve streams/search or accept voice
+ gateway: isDiscordOwner ? discordJsGateway(client) : undefined,
+});
+
+await net.start();
+```
+
+For manual pairing, listen for `peerDiscovered`, compare its fingerprint with the peer over a trusted channel, then call
+`net.node.acceptPeer(peerId, verifiedFingerprint, roles)` on **both** nodes. This adds the peer to the in-memory trust store;
+persist approved keys in configuration if they must survive a restart. Static `trust` entries pin public keys at startup and are
+preferable for production.
+
+```js
+net.node.on("peerDiscovered", ({ nodeId, fingerprint }) => {
+ console.log(`Verify ${nodeId} out of band: ${fingerprint}`);
+});
+
+// On the provider, after verifying the bot's fingerprint:
+net.node.acceptPeer("bot-1", verifiedBotFingerprint, ["provide-search", "provide-stream", "delegate-voice"]);
+
+// On the bot, after verifying the provider's fingerprint:
+net.node.acceptPeer("yt-1", verifiedYtFingerprint, ["accept-voice"]);
+```
+
+`roles` describe what the peer is allowed to ask **this node** to do. The default `["*"]` is convenient for a trusted private
+cluster; use only the needed roles for least privilege:
+
+| Role | Grants the peer permission to ask this node to… |
+| ---------------- | -------------------------------------------------------------- |
+| `provide-search` | Search this node's plugins |
+| `provide-stream` | Open streams resolved by this node |
+| `delegate-voice` | Ask this node to accept/execute a voice hand-off |
+| `accept-voice` | Send delegated voice gateway events/player events to this node |
+
+For example, the provider's trust entry for the bot should include `provide-search`, `provide-stream`, and `delegate-voice`. The
+bot's trust entry for the provider should include `accept-voice` when using hand-off.
+
+### Provide search and streams
+
+Only enable capabilities a node should expose. Search and stream requests are independently opt-in:
+
+```js
+net.provideSearch({
+ allow: (query, peerId) => peerId === "bot-1" && query.length <= 200,
+ maxResults: 25,
+});
+
+net.provideStreams({
+ allow: (track, peerId) => peerId === "bot-1" && track.source === "youtube",
+});
+```
+
+`provideSearch()` uses the node's `PlayerManager` plugins. `provideStreams()` resolves each requested track through the local
+manager/plugins; an `allow` callback can enforce source or peer allowlists. A remote node never fetches a URL supplied by a peer.
+Only compressed audio is transferable: Opus streams/containers and supported `arbitrary` containers, never raw PCM.
+
+On the Discord owner, attach the network extension to every player that may relay or hand off playback:
+
+```js
+const player = await manager.create(guildId, { extensions: [net.extensionClass()] });
+```
+
+`net.extensionClass()` handles remote stream resolution for relay and remote playback commands for hand-off. Without it, a player
+will not use `@ziplayer/net` for playback.
+
+### Search the cluster
+
+```js
+const result = await net.search("yt:lofi hip hop", { requestedBy: userId });
+console.log(result.node, result.nodes, result.tracks);
+await player.play(result.tracks[0]);
+```
+
+`yt:`, `sc:`, `sp:`, and `tts:` target the corresponding plugin source. Unknown prefixes are treated as part of the query. Without
+a source prefix, `search()` tries local plugins first, then trusted online nodes that opted into `provideSearch()`. Tracks
+returned by a peer are stamped with that peer as `metadata.net.owner`; applications should not set a peer owner from untrusted
+input. If your application already has a trusted `Track` from a specific node, `markTrack()` sets its stream owner:
+
+```js
+import { markTrack } from "@ziplayer/net";
+
+await player.play(markTrack(track, "yt-1"));
+```
+
+Useful options:
+
+```js
+await net.search("lofi", { local: "last", merge: true, limit: 20 });
+await net.searchOn("yt-1", "lofi", { timeoutMs: 10_000 });
+```
+
+`NetSearchOptions` supports `source`, `peers`, `local` (`first`, `last`, `only`, or `never`), `merge`, `limit`, `timeoutMs`,
+`signal`, and `requestedBy`. `net.search()` returns the first successful result by default. With `merge: true`, it asks all
+eligible nodes and de-duplicates the combined tracks. `searchOn()` targets one specific peer.
+
+Use `searchAliases` in `ZiNetOptions` to add or override prefixes, for example `{ ytm: "youtube" }`.
+
+### Relay streams or hand off voice
+
+To keep playback on the connected Discord owner, play a marked track from `net.search()`; the extension pulls its stream from the
+provider. To let the router choose relay or hand-off for a batch:
+
+```js
+const route = await net.routeTracks(player, tracks, {
+ handoffThreshold: 0.5,
+ apply: true, // Default; marks owners and applies voice hand-off/reclaim when needed
+});
+if (!route.applied) throw route.error ?? new Error(`Could not apply route: ${route.mode}`);
+
+for (const track of tracks) await player.play(track);
+```
+
+`routeTracks()` returns a plan with `mode`, `executor`, per-track `owners`, and `applied`. With `apply: false`, it only plans. In
+`relay` mode, the Discord connection stays on this node and foreign tracks are streamed from their owners. In `handoff` mode, the
+router delegates voice to the best executor and marks tracks the executor cannot resolve for stream transfer.
+
+For explicit voice control, first connect the owner player and make sure it is idle:
+
+```js
+await net.delegateVoice(player, "yt-1"); // Requires gateway on this node; voice must not be playing
+await player.play(track);
+
+await net.reclaimVoice(player); // Return voice to the owner
+```
+
+Reclaim stops the remote current track, preserves queued tracks, and refreshes the gateway voice state before reconnecting the
+owner to the channel. This avoids leaving a stale remote playback session behind or reusing an unchanged Discord voice session.
+
+The executor must call `net.acceptVoice()` and pass an authorization check if configured. By default, the executor resolves the
+track with its own plugins. Set `{ streamFrom: "owner" }` in `delegateVoice()` when the owner should provide the audio stream. The
+owner reconnects locally if delegation fails or the executor goes offline, provided its gateway adapter can resolve the original
+channel.
+
+### Lifecycle and errors
+
+- Call `await net.start()` once before making network requests or accepting traffic.
+- Use `await net.stop()` during shutdown. It closes provided/imported streams, ends delegations, and closes the transport.
+- Catch rejected `search()`, `player.play()`, and delegation operations at the application boundary. `NetError.code` can be used
+ to distinguish cases such as `NO_RESULTS`, `NOT_CONNECTED`, `NO_GATEWAY`, `FORBIDDEN`, and `TIMEOUT`.
+- If a peer disappears, presence/last-will detection closes sessions. A delegated owner attempts to reclaim voice locally.
+
+## Security model
+
+| What | Protection |
+| ----------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Control messages, voice credentials | Always encrypted end-to-end (ChaCha20-Poly1305), authenticated, replay-protected |
+| Audio (Opus) | Clear by default, `encryptAudio: true` to encrypt |
+| Node identity | Ed25519 keys, **pinned per node**; unknown nodes are rejected |
+| Broker | Untrusted: it only sees ciphertext, audio, node ids and sizes (use TLS to hide those) |
+| Peer input | Only compressed audio is accepted (raw PCM is refused; `allowedStreamTypes` can narrow it to Opus containers); a node never fetches a URL a peer gives it (a provider resolves requested tracks through its own plugins: use `allow`); relayed gateway payloads are limited to op 4 for the delegated guild |
+
+The 3-message handshake (`hs1` → `hs2` → `hs3`) is a SIGMA-style exchange built from `node:crypto` (ephemeral X25519 + Ed25519
+signatures over the transcript + HKDF). It is a small custom protocol: **get it reviewed before protecting anything valuable.**
+
+## Debugging what goes over MQTT
+
+Every `NetNode` (also `net.node`) emits a `debug` event. Without listeners it costs nothing.
+
+```js
+const { formatNetDebug } = require("@ziplayer/net");
+net.node.on("debug", (e) => console.log(formatNetDebug(e)));
+```
+
+```
+[net:bot-1] → MQTT PUBLISH zi/v1/ziplayer-test/node/yt-1/in qos1 188B control(encrypted) [02a1b2c3…]
+[net:bot-1] → control to yt-1 net.search #3 188B {"query":"https://www.youtube.com/watch?v=PqpCRSOUuIE","limit":1}
+[net:bot-1] ← control from yt-1 reply re#3 3120B {"tracks":[{"id":"PqpCRSOUuIE","title":"…"}],…}
+```
+
+- `layer: "wire"`: the exact MQTT message the broker sees (topic, qos, retain, size, first bytes). Control frames are ciphertext.
+- `layer: "message"`: the same traffic decoded: `type`, request `id` / `re`, `body`, `peer`. Handshakes, requests, notifications
+ and replies.
+- `layer: "info"`: routing notes such as `search "lofi" → yt-1`.
+- Audio frames are only reported with `debugAudio: true` (very chatty). Bodies are redacted (`token`, `session_id`, `password`, …)
+ unless `debugRedact: false`; treat logs with raw bodies as secrets because voice tokens pass through here.
+
+## Try it for real
+
+[`examples/net`](../examples/net) runs a real Discord bot (commands via `messageCreate`) with provider nodes that have different
+real plugins, over Mosquitto, including an automated `!selftest` for stream transfer, relay, hand-off and failover.
+
+## Notes and limits
+
+- `PlayerManager` is a process singleton, so one process = one node (test with several processes).
+- Delegate voice while nothing is playing; the next `play()` is driven on the executor.
+- MQTT is fine for control; for audio it adds broker hops and has no back-pressure, so streaming uses credit-based flow control
+ and QoS 1. The `Transport` interface lets other carriers (WebSocket, TCP, ...) replace it later.
+- Web/WebAudio voice and multi-output fan-out (mirroring one queue to several remote outputs) are not implemented yet.
+- Core changes this package relies on: `manager.resolveStream()` and `player.disconnect({ silent: true })`.
diff --git a/net/package.json b/net/package.json
new file mode 100644
index 00000000..a03d1ecd
--- /dev/null
+++ b/net/package.json
@@ -0,0 +1,54 @@
+{
+ "name": "@ziplayer/net",
+ "version": "0.0.2",
+ "description": "Connect multiple ZiPlayer nodes over MQTT: stream resources and hand off voice connections",
+ "keywords": [
+ "ZiPlayer",
+ "@ziplayer/net",
+ "mqtt",
+ "discord",
+ "voice",
+ "cluster"
+ ],
+ "homepage": "https://player.ziji.best",
+ "bugs": {
+ "url": "https://github.com/ZiProject/ZiPlayer/issues"
+ },
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/ZiProject/ZiPlayer.git"
+ },
+ "license": "MIT",
+ "engines": {
+ "node": ">=20.3.0"
+ },
+ "main": "dist/index.js",
+ "types": "dist/index.d.ts",
+ "files": [
+ "dist",
+ "README.md"
+ ],
+ "scripts": {
+ "build": "tsc",
+ "dev": "tsc --watch",
+ "prepare": "npm run build"
+ },
+ "peerDependencies": {
+ "@discordjs/voice": "^0.19.2",
+ "mqtt": "^5.0.0",
+ "ziplayer": "^1.0.5"
+ },
+ "peerDependenciesMeta": {
+ "mqtt": {
+ "optional": true
+ }
+ },
+ "devDependencies": {
+ "@discordjs/voice": "^0.19.2",
+ "@types/node": "^20.0.0",
+ "aedes": "^0.51.3",
+ "mqtt": "^5.16.1",
+ "typescript": "^5.0.0",
+ "ziplayer": "^1.0.5"
+ }
+}
diff --git a/net/src/NetNode.ts b/net/src/NetNode.ts
new file mode 100644
index 00000000..aa5e7e3f
--- /dev/null
+++ b/net/src/NetNode.ts
@@ -0,0 +1,670 @@
+import { EventEmitter } from "node:events";
+import { HandshakeError, HandshakeInitiator, HandshakeResponder, type Hs1, type Hs2, type Hs3 } from "./crypto/handshake";
+import {
+ fingerprint,
+ loadIdentity,
+ loadOrCreateIdentity,
+ parsePublicKey,
+ TrustStore,
+ type NetRole,
+ type NodeIdentity,
+ type TrustedPeer,
+} from "./crypto/identity";
+import { KIND, SecureChannel, SessionError } from "./crypto/session";
+import { hexPreview, redact, type NetDebugEvent, type NetDebugKind } from "./debug";
+import { decodePlainAudio, encodePlainAudio, sessionIdOf, topics, type AudioFrame } from "./protocol/frames";
+import type { PublishOptions, Transport } from "./transport/Transport";
+
+export interface NetNodeOptions {
+ /** Unique id of this node. No `/`, `+` or `#`. */
+ nodeId: string;
+ /** Isolates independent clusters sharing one broker. */
+ networkId?: string;
+ /** Ed25519 identity: PEM private key or a loaded identity. Omit it and give `keyFile` to load-or-create one. */
+ identity?: string | NodeIdentity;
+ /** Where to keep the node's private key. If the file does not exist a new key is created there. */
+ keyFile?: string;
+ /** Pinned peers. Anyone not listed is rejected during the handshake. */
+ trust?: TrustStore | TrustedPeer[];
+ transport: Transport;
+ /** Encrypt audio frames too. Default `false`: Opus/WebM audio is sent in clear, control data is always encrypted. */
+ encryptAudio?: boolean;
+ /** MQTT QoS for audio frames (default 1 so container streams never lose bytes). */
+ audioQos?: 0 | 1;
+ requestTimeoutMs?: number;
+ handshakeTimeoutMs?: number;
+ sessionMaxAgeMs?: number;
+ debug?: (message: string, ...args: unknown[]) => void;
+ /** Also emit `debug` events for every audio frame (very chatty). Default `false`. */
+ debugAudio?: boolean;
+ /** Hide tokens / session ids in the `body` of `debug` message events. Default `true`. */
+ debugRedact?: boolean;
+}
+
+export interface RequestContext {
+ from: string;
+ session: SecureChannel;
+}
+
+export type RequestHandler = (body: any, context: RequestContext) => unknown | Promise;
+
+interface Pending {
+ peerId: string;
+ resolve: (value: any) => void;
+ reject: (error: Error) => void;
+ timer: NodeJS.Timeout;
+}
+
+export class NetError extends Error {
+ constructor(
+ message: string,
+ readonly code: string = "NET_ERROR",
+ ) {
+ super(message);
+ this.name = "NetError";
+ }
+}
+
+const ID_RE = /^[A-Za-z0-9._:-]{1,64}$/;
+
+/**
+ * One ZiPlayer process on the network. Owns the transport, authenticates peers with the 3-message
+ * handshake, and exposes encrypted request/notify messaging plus (optionally encrypted) audio frames.
+ *
+ * Events: `peerOnline(id)`, `peerOffline(id)`, `sessionOpen(id)`, `sessionClose(id)`, `peerDiscovered(info)` and
+ * `debug(event: NetDebugEvent)`, which shows exactly what is published to / received from the broker (see `debug.ts`).
+ */
+export class NetNode extends EventEmitter {
+ readonly nodeId: string;
+ readonly networkId: string;
+ readonly trust: TrustStore;
+ /** This node's public key, announced in its presence message so operators can pair nodes. */
+ readonly publicKeyPem: string;
+ readonly fingerprint: string;
+ private readonly discovered = new Map();
+ private readonly identity: NodeIdentity;
+ /** The transport as given (kept untouched: tests and tooling reach into it, e.g. `MemoryTransport.kill()`). */
+ private readonly transport: Transport;
+ /** What this node really talks through: the same transport, observed for `debug` events. */
+ private readonly wire: Transport;
+ /** @internal */
+ readonly options: NetNodeOptions;
+ private readonly bySid = new Map();
+ private readonly byPeer = new Map();
+ private readonly initiating = new Map>();
+ private readonly initiators = new Map<
+ string,
+ { hs: HandshakeInitiator; resolve: (c: SecureChannel) => void; reject: (e: Error) => void; timer: NodeJS.Timeout }
+ >();
+ private readonly responders = new Map();
+ private readonly handlers = new Map();
+ private readonly pending = new Map();
+ private readonly online = new Set();
+ private audioHandler?: (peerId: string, frame: AudioFrame) => void;
+ private nextId = 1;
+ private unsubs: Array<() => void> = [];
+ private started = false;
+
+ constructor(options: NetNodeOptions) {
+ super();
+ if (!ID_RE.test(options.nodeId)) throw new TypeError("nodeId must match [A-Za-z0-9._:-]{1,64}");
+ this.options = options;
+ this.nodeId = options.nodeId;
+ this.networkId = options.networkId ?? "default";
+ if (!ID_RE.test(this.networkId)) throw new TypeError("networkId must match [A-Za-z0-9._:-]{1,64}");
+ if (options.identity)
+ this.identity = typeof options.identity === "string" ? loadIdentity(options.identity) : options.identity;
+ else if (options.keyFile) this.identity = loadOrCreateIdentity(options.keyFile).identity;
+ else throw new TypeError("NetNode needs an `identity` or a `keyFile`");
+ this.publicKeyPem = this.identity.publicKey.export({ type: "spki", format: "pem" }).toString();
+ this.fingerprint = fingerprint(this.identity.publicKey);
+ this.trust = options.trust instanceof TrustStore ? options.trust : new TrustStore(options.trust ?? []);
+ this.transport = options.transport;
+ this.wire = new TracedTransport(options.transport, this);
+ }
+
+ /** True while somebody listens to `debug`: tracing costs nothing otherwise. */
+ get tracing(): boolean {
+ return this.listenerCount("debug") > 0;
+ }
+
+ /** Emits a `debug` event. Cheap no-op without listeners. */
+ trace(event: Omit): void {
+ if (!this.tracing) return;
+ try {
+ this.emit("debug", { at: Date.now(), node: this.nodeId, ...event } satisfies NetDebugEvent);
+ } catch {}
+ }
+
+ /** Free-form `info` debug note (used by routing code such as `ZiNet.search`). */
+ traceNote(note: string, extra: Partial = {}): void {
+ this.trace({ layer: "info", dir: "info", note, ...extra });
+ }
+
+ private traceMessage(
+ dir: "out" | "in",
+ peer: string | undefined,
+ kind: NetDebugKind,
+ message: Record,
+ bytes: number,
+ sessionId?: string,
+ ) {
+ if (!this.tracing) return;
+ const type =
+ typeof message.type === "string" ? message.type
+ : message.re !== undefined ?
+ message.err ?
+ "reply:error"
+ : "reply"
+ : undefined;
+ const raw = message.body !== undefined ? message.body : message.err;
+ this.trace({
+ layer: "message",
+ dir,
+ kind,
+ peer,
+ type,
+ id: message.id,
+ re: message.re,
+ bytes,
+ sessionId,
+ body:
+ raw === undefined ? undefined
+ : this.options.debugRedact === false ? raw
+ : redact(raw),
+ });
+ }
+
+ private traceAudio(dir: "out" | "in", peer: string, frame: AudioFrame, encrypted: boolean) {
+ if (!this.tracing || !this.options.debugAudio) return;
+ this.trace({
+ layer: "message",
+ dir,
+ kind: encrypted ? "audio-encrypted" : "audio",
+ peer,
+ encrypted,
+ streamId: frame.streamId,
+ seq: frame.seq,
+ flags: frame.flags,
+ bytes: frame.payload.length,
+ });
+ }
+
+ private debug(message: string, ...args: unknown[]) {
+ this.options.debug?.(`[net:${this.nodeId}] ${message}`, ...args);
+ }
+
+ // ── lifecycle ────────────────────────────────────────────────────────────
+
+ async start(): Promise {
+ if (this.started) return;
+ const enc = (v: unknown) => Buffer.from(JSON.stringify(v));
+ const presenceTopic = topics.presence(this.networkId, this.nodeId);
+ this.wire.setLastWill?.(presenceTopic, enc({ online: false, nodeId: this.nodeId }), { qos: 1, retain: true });
+ await this.wire.connect();
+ this.started = true;
+ this.unsubs.push(
+ await this.wire.subscribe(topics.inbox(this.networkId, this.nodeId), (_t, p) => this.onInbox(Buffer.from(p))),
+ await this.wire.subscribe(topics.audio(this.networkId, this.nodeId), (_t, p) => this.onAudioFrame(Buffer.from(p))),
+ await this.wire.subscribe(topics.presenceAll(this.networkId), (t, p) => this.onPresence(t, Buffer.from(p))),
+ );
+ await this.wire.publish(presenceTopic, enc({ online: true, nodeId: this.nodeId, ts: Date.now(), pub: this.publicKeyPem }), {
+ qos: 1,
+ retain: true,
+ });
+ }
+
+ async stop(): Promise {
+ if (!this.started) return;
+ this.started = false;
+ try {
+ await this.wire.publish(
+ topics.presence(this.networkId, this.nodeId),
+ Buffer.from(JSON.stringify({ online: false, nodeId: this.nodeId })),
+ { qos: 1, retain: true },
+ );
+ } catch {}
+ for (const u of this.unsubs.splice(0)) u();
+ for (const peerId of [...this.byPeer.keys()]) this.closeSessions(peerId, "node stopped");
+ for (const s of this.initiators.values()) {
+ clearTimeout(s.timer);
+ s.reject(new NetError("node stopped", "STOPPED"));
+ }
+ this.initiators.clear();
+ this.initiating.clear();
+ for (const r of this.responders.values()) clearTimeout(r.timer);
+ this.responders.clear();
+ await this.wire.close();
+ }
+
+ /** Nodes seen on the network that are not trusted yet. Compare `fingerprint` out-of-band before accepting. */
+ discoveredPeers(): Array<{ nodeId: string; fingerprint: string; publicKey: string }> {
+ return [...this.discovered.values()];
+ }
+
+ /**
+ * Trusts a discovered node. `expectedFingerprint` must match the key it announced, so a swapped key is refused.
+ * Both sides have to accept each other before they can talk.
+ */
+ acceptPeer(nodeId: string, expectedFingerprint: string, roles?: NetRole[]): void {
+ const found = this.discovered.get(nodeId);
+ if (!found) throw new NetError(`Node "${nodeId}" has not been discovered`, "UNKNOWN_PEER");
+ if (found.fingerprint !== expectedFingerprint.toLowerCase().replace(/[^0-9a-f]/g, "")) {
+ throw new NetError("Fingerprint mismatch", "FINGERPRINT_MISMATCH");
+ }
+ this.trust.add({ nodeId, publicKey: found.publicKey, roles });
+ this.discovered.delete(nodeId);
+ this.online.add(nodeId);
+ this.emit("peerOnline", nodeId);
+ }
+
+ isOnline(peerId: string): boolean {
+ return this.online.has(peerId);
+ }
+
+ onlinePeers(): string[] {
+ return [...this.online];
+ }
+
+ // ── messaging API ────────────────────────────────────────────────────────
+
+ /** Registers a handler for a message type. `role` is checked against the caller's trust entry. */
+ handle(type: string, handler: RequestHandler, options?: { role?: NetRole }): () => void {
+ this.handlers.set(type, { handler, role: options?.role });
+ return () => this.handlers.delete(type);
+ }
+
+ async request(
+ peerId: string,
+ type: string,
+ body?: unknown,
+ options?: { timeoutMs?: number; signal?: AbortSignal },
+ ): Promise {
+ const session = await this.ensureSession(peerId);
+ const id = this.nextId++;
+ const timeoutMs = options?.timeoutMs ?? this.options.requestTimeoutMs ?? 15_000;
+ return new Promise((resolve, reject) => {
+ const timer = setTimeout(() => {
+ this.pending.delete(id);
+ reject(new NetError(`Request "${type}" to ${peerId} timed out`, "TIMEOUT"));
+ }, timeoutMs);
+ const onAbort = () => {
+ clearTimeout(timer);
+ this.pending.delete(id);
+ reject(new NetError("Request aborted", "ABORTED"));
+ };
+ if (options?.signal) {
+ if (options.signal.aborted) return onAbort();
+ options.signal.addEventListener("abort", onAbort, { once: true });
+ }
+ this.pending.set(id, { peerId, resolve, reject, timer });
+ this.sendControl(session, { id, type, body }).catch((error) => {
+ clearTimeout(timer);
+ this.pending.delete(id);
+ reject(error);
+ });
+ });
+ }
+
+ async notify(peerId: string, type: string, body?: unknown): Promise {
+ const session = await this.ensureSession(peerId);
+ await this.sendControl(session, { type, body });
+ }
+
+ onAudio(handler: (peerId: string, frame: AudioFrame) => void): void {
+ this.audioHandler = handler;
+ }
+
+ async sendAudio(peerId: string, frame: AudioFrame): Promise {
+ const session = await this.ensureSession(peerId);
+ const data =
+ this.options.encryptAudio ?
+ session.sealAudio(frame.streamId, frame.seq, frame.flags, frame.payload)
+ : encodePlainAudio(session.sessionId, frame);
+ this.traceAudio("out", peerId, frame, Boolean(this.options.encryptAudio));
+ await this.wire.publish(topics.audio(this.networkId, peerId), data, { qos: this.options.audioQos ?? 1 });
+ }
+
+ // ── sessions ─────────────────────────────────────────────────────────────
+
+ async ensureSession(peerId: string): Promise {
+ if (!this.started) throw new NetError("node not started", "NOT_STARTED");
+ const existing = this.byPeer.get(peerId);
+ if (existing && !existing.expired) return existing;
+ const inflight = this.initiating.get(peerId);
+ if (inflight) return inflight;
+ const promise = this.startHandshake(peerId).finally(() => this.initiating.delete(peerId));
+ this.initiating.set(peerId, promise);
+ return promise;
+ }
+
+ hasSession(peerId: string): boolean {
+ const s = this.byPeer.get(peerId);
+ return Boolean(s && !s.expired);
+ }
+
+ private startHandshake(peerId: string): Promise {
+ return new Promise((resolve, reject) => {
+ let hs: HandshakeInitiator;
+ try {
+ hs = new HandshakeInitiator(this.ctx(), peerId);
+ } catch (error) {
+ return reject(error);
+ }
+ const sid = hs.sessionId;
+ const timer = setTimeout(() => {
+ this.initiators.delete(sid);
+ reject(new NetError(`Handshake with ${peerId} timed out`, "HANDSHAKE_TIMEOUT"));
+ }, this.options.handshakeTimeoutMs ?? 10_000);
+ this.initiators.set(sid, { hs, resolve, reject, timer });
+ this.publishHandshake(peerId, hs.hello()).catch((error) => {
+ clearTimeout(timer);
+ this.initiators.delete(sid);
+ reject(error);
+ });
+ });
+ }
+
+ private ctx() {
+ return { networkId: this.networkId, selfId: this.nodeId, identity: this.identity, trust: this.trust };
+ }
+
+ private publishHandshake(peerId: string, message: Hs1 | Hs2 | Hs3) {
+ const data = Buffer.concat([Buffer.from([KIND.HANDSHAKE]), Buffer.from(JSON.stringify(message))]);
+ this.trace({
+ layer: "message",
+ dir: "out",
+ kind: "handshake",
+ peer: peerId,
+ type: message.t,
+ sessionId: message.sid,
+ bytes: data.length,
+ });
+ return this.wire.publish(topics.inbox(this.networkId, peerId), data, { qos: 1 });
+ }
+
+ private install(channel: SecureChannel) {
+ const old = this.byPeer.get(channel.peerId);
+ this.bySid.set(channel.sessionId, channel);
+ this.byPeer.set(channel.peerId, channel);
+ if (old && old !== channel) {
+ // Keep the old one receivable briefly: in-flight frames may still use it.
+ setTimeout(() => {
+ this.bySid.delete(old.sessionId);
+ old.closed = true;
+ }, 5_000).unref?.();
+ }
+ this.debug(`session ${channel.sessionId} open with ${channel.peerId}`);
+ this.emit("sessionOpen", channel.peerId);
+ }
+
+ private closeSessions(peerId: string, reason: string) {
+ for (const [sid, s] of this.bySid) {
+ if (s.peerId !== peerId) continue;
+ s.closed = true;
+ this.bySid.delete(sid);
+ }
+ if (this.byPeer.delete(peerId)) this.emit("sessionClose", peerId);
+ for (const [id, p] of this.pending) {
+ if (p.peerId !== peerId) continue;
+ clearTimeout(p.timer);
+ this.pending.delete(id);
+ p.reject(new NetError(`Session with ${peerId} closed: ${reason}`, "SESSION_CLOSED"));
+ }
+ }
+
+ // ── inbound ──────────────────────────────────────────────────────────────
+
+ private onPresence(topic: string, payload: Buffer) {
+ const peerId = topic.split("/").pop()!;
+ if (peerId === this.nodeId) return;
+ let online = false;
+ let pub: unknown;
+ try {
+ const parsed = JSON.parse(payload.toString("utf8"));
+ online = parsed.online === true;
+ pub = parsed.pub;
+ } catch {
+ return;
+ }
+ if (!this.trust.has(peerId)) {
+ // Unknown node: remember its announced key so an operator can verify the fingerprint and accept it.
+ if (online && typeof pub === "string" && pub.length < 2048 && !this.discovered.has(peerId)) {
+ try {
+ const fp = fingerprint(parsePublicKey(pub));
+ this.discovered.set(peerId, { nodeId: peerId, publicKey: pub, fingerprint: fp });
+ this.emit("peerDiscovered", { nodeId: peerId, fingerprint: fp, publicKey: pub });
+ } catch {}
+ }
+ return;
+ }
+ if (online) {
+ if (!this.online.has(peerId)) {
+ this.online.add(peerId);
+ this.emit("peerOnline", peerId);
+ }
+ } else if (this.online.delete(peerId)) {
+ this.closeSessions(peerId, "peer offline");
+ this.emit("peerOffline", peerId);
+ }
+ }
+
+ private onInbox(buf: Buffer) {
+ if (buf.length < 2) return;
+ try {
+ if (buf[0] === KIND.HANDSHAKE) this.onHandshake(JSON.parse(buf.subarray(1).toString("utf8")));
+ else if (buf[0] === KIND.CONTROL) void this.onControl(buf);
+ } catch (error) {
+ this.debug(`dropped inbound message: ${(error as Error).message}`);
+ }
+ }
+
+ private onHandshake(message: Hs1 | Hs2 | Hs3) {
+ if (!message || typeof message !== "object") return;
+ this.trace({ layer: "message", dir: "in", kind: "handshake", type: message.t, sessionId: message.sid });
+ if (message.t === "hs1") {
+ if (this.responders.size >= 64) return;
+ let responder: HandshakeResponder;
+ try {
+ responder = new HandshakeResponder(this.ctx(), message);
+ } catch (error) {
+ this.debug(`rejected handshake: ${(error as Error).message}`);
+ return;
+ }
+ const sid = message.sid;
+ const timer = setTimeout(() => this.responders.delete(sid), this.options.handshakeTimeoutMs ?? 10_000);
+ timer.unref?.();
+ this.responders.set(sid, { hs: responder, timer });
+ this.publishHandshake(responder.peerId, responder.hs2).catch((e) => this.debug(`hs2 publish failed: ${e.message}`));
+ } else if (message.t === "hs2") {
+ const entry = this.initiators.get(message.sid);
+ if (!entry) return;
+ this.initiators.delete(message.sid);
+ clearTimeout(entry.timer);
+ try {
+ const { hs3, result } = entry.hs.finish(message);
+ const channel = new SecureChannel(result.sessionId, result.peerId, true, result.sendKey, result.recvKey, {
+ maxAgeMs: this.options.sessionMaxAgeMs,
+ });
+ // Install before sending hs3 so a fast reply is not dropped.
+ this.install(channel);
+ this.publishHandshake(result.peerId, hs3).then(
+ () => entry.resolve(channel),
+ (e) => entry.reject(e),
+ );
+ } catch (error) {
+ entry.reject(error instanceof Error ? error : new HandshakeError(String(error)));
+ }
+ } else if (message.t === "hs3") {
+ const entry = this.responders.get(message.sid);
+ if (!entry) return;
+ this.responders.delete(message.sid);
+ clearTimeout(entry.timer);
+ try {
+ const result = entry.hs.finish(message);
+ this.install(
+ new SecureChannel(result.sessionId, result.peerId, false, result.sendKey, result.recvKey, {
+ maxAgeMs: this.options.sessionMaxAgeMs,
+ }),
+ );
+ } catch (error) {
+ this.debug(`handshake failed: ${(error as Error).message}`);
+ }
+ }
+ }
+
+ private async sendControl(session: SecureChannel, message: Record) {
+ const frame = session.seal(Buffer.from(JSON.stringify(message)));
+ this.traceMessage("out", session.peerId, "control", message, frame.length, session.sessionId);
+ await this.wire.publish(topics.inbox(this.networkId, session.peerId), frame, { qos: 1 });
+ }
+
+ private async onControl(buf: Buffer) {
+ const sid = sessionIdOf(buf);
+ const session = sid ? this.bySid.get(sid) : undefined;
+ if (!session) return;
+ let message: { id?: number; re?: number; type?: string; body?: any; err?: { message: string; code?: string } };
+ try {
+ message = JSON.parse(session.open(buf).toString("utf8"));
+ } catch (error) {
+ if (error instanceof SessionError) this.debug(`dropped control frame: ${error.message}`);
+ return;
+ }
+ this.traceMessage("in", session.peerId, "control", message, buf.length, session.sessionId);
+ if (message.re !== undefined) {
+ const p = this.pending.get(message.re);
+ if (!p || p.peerId !== session.peerId) return;
+ clearTimeout(p.timer);
+ this.pending.delete(message.re);
+ if (message.err) p.reject(new NetError(message.err.message, message.err.code ?? "REMOTE_ERROR"));
+ else p.resolve(message.body);
+ return;
+ }
+ if (typeof message.type !== "string") return;
+ const entry = this.handlers.get(message.type);
+ const reply = (payload: Record) => {
+ if (message.id === undefined) return;
+ this.sendControl(session, { re: message.id, ...payload }).catch(() => {});
+ };
+ if (!entry) return reply({ err: { message: `No handler for "${message.type}"`, code: "NO_HANDLER" } });
+ if (entry.role && !this.trust.hasRole(session.peerId, entry.role)) {
+ return reply({ err: { message: `Peer lacks role "${entry.role}"`, code: "FORBIDDEN" } });
+ }
+ try {
+ reply({ body: await entry.handler(message.body, { from: session.peerId, session }) });
+ } catch (error) {
+ reply({ err: { message: (error as Error).message, code: (error as any).code } });
+ }
+ }
+
+ private onAudioFrame(buf: Buffer) {
+ try {
+ const sid = sessionIdOf(buf);
+ const session = sid ? this.bySid.get(sid) : undefined;
+ if (!session || !this.audioHandler) return;
+ if (buf[0] === KIND.AUDIO_ENCRYPTED) {
+ const frame = session.openAudio(buf);
+ this.traceAudio("in", session.peerId, frame, true);
+ this.audioHandler(session.peerId, frame);
+ } else if (buf[0] === KIND.AUDIO) {
+ if (this.options.encryptAudio) return; // refuse downgrade
+ const frame = decodePlainAudio(buf).frame;
+ this.traceAudio("in", session.peerId, frame, false);
+ this.audioHandler(session.peerId, frame);
+ }
+ } catch (error) {
+ this.debug(`dropped audio frame: ${(error as Error).message}`);
+ }
+ }
+}
+
+/**
+ * Wraps the real transport and reports every publish / delivery as a `wire` debug event: this is the exact
+ * MQTT traffic (topic, qos, size, first bytes). Audio frames are only reported with `debugAudio`.
+ */
+class TracedTransport implements Transport {
+ constructor(
+ private readonly inner: Transport,
+ private readonly node: NetNode,
+ ) {}
+
+ setLastWill(topic: string, payload: Uint8Array, options?: PublishOptions): void {
+ this.inner.setLastWill?.(topic, payload, options);
+ this.report("out", topic, payload, options, "last-will registered (the broker publishes it if this node disappears)");
+ }
+
+ connect(): Promise {
+ return this.inner.connect();
+ }
+
+ close(): Promise {
+ return this.inner.close();
+ }
+
+ async publish(topic: string, payload: Uint8Array, options?: PublishOptions): Promise {
+ this.report("out", topic, payload, options);
+ try {
+ await this.inner.publish(topic, payload, options);
+ } catch (error) {
+ this.report("out", topic, payload, options, undefined, (error as Error)?.message ?? String(error));
+ throw error;
+ }
+ }
+
+ subscribe(filter: string, handler: (topic: string, payload: Uint8Array) => void): Promise<() => void> {
+ return this.inner.subscribe(filter, (topic, payload) => {
+ this.report("in", topic, payload);
+ handler(topic, payload);
+ });
+ }
+
+ private report(dir: "out" | "in", topic: string, payload: Uint8Array, options?: PublishOptions, note?: string, error?: string) {
+ if (!this.node.tracing) return;
+ const buf = Buffer.from(payload.buffer, payload.byteOffset, payload.byteLength);
+ const presence = topic.includes("/presence/");
+ let kind: NetDebugKind = "unknown";
+ let encrypted = false;
+ let type: string | undefined = note;
+ let body: unknown;
+ if (presence) {
+ kind = "presence";
+ try {
+ const { pub, ...rest } = JSON.parse(buf.toString("utf8"));
+ body = pub ? { ...rest, pub: "" } : rest;
+ } catch {}
+ } else if (buf[0] === KIND.HANDSHAKE) {
+ kind = "handshake";
+ try {
+ type = JSON.parse(buf.subarray(1).toString("utf8")).t;
+ } catch {}
+ } else if (buf[0] === KIND.CONTROL) {
+ kind = "control";
+ encrypted = true;
+ } else if (buf[0] === KIND.AUDIO) kind = "audio";
+ else if (buf[0] === KIND.AUDIO_ENCRYPTED) {
+ kind = "audio-encrypted";
+ encrypted = true;
+ }
+ if ((kind === "audio" || kind === "audio-encrypted") && !this.node.options.debugAudio) return;
+ const parts = topic.split("/");
+ const peer =
+ presence ? parts[parts.length - 1]
+ : dir === "out" && parts[parts.length - 3] === "node" ? parts[parts.length - 2]
+ : undefined;
+ this.node.trace({
+ layer: "wire",
+ dir,
+ kind,
+ topic,
+ peer,
+ qos: options?.qos,
+ retain: options?.retain,
+ bytes: buf.length,
+ hex: hexPreview(buf),
+ encrypted,
+ type,
+ body,
+ error,
+ });
+ }
+}
diff --git a/net/src/ZiNet.ts b/net/src/ZiNet.ts
new file mode 100644
index 00000000..0b5c54d4
--- /dev/null
+++ b/net/src/ZiNet.ts
@@ -0,0 +1,719 @@
+import { PassThrough } from "node:stream";
+import { NetError, NetNode, type NetNodeOptions } from "./NetNode";
+import { NetExtension } from "./ext/NetExtension";
+import { StreamImporter, type StreamImporterOptions } from "./stream/StreamImporter";
+import { StreamProvider, type ProvidedStreamInfo } from "./stream/StreamProvider";
+import { RemoteVoiceHub, serializeTrack } from "./voice/RemoteVoice";
+import { planRoute, type RoutePlan } from "./router";
+import {
+ dedupeNetTracks,
+ DEFAULT_SEARCH_ALIASES,
+ importWireResult,
+ MAX_QUERY_CHARS,
+ parseSearchQuery,
+ toWireResult,
+ type NetSearchOptions,
+ type NetSearchResult,
+ type ServeSearchOptions,
+} from "./search";
+import type { GatewayLike } from "./voice/Gateway";
+
+export interface ZiNetOptions extends NetNodeOptions {
+ /** The local PlayerManager (needed to provide streams and to accept voice). */
+ manager?: any;
+ /** Required on a node that hands voice off (it owns the Discord gateway). */
+ gateway?: GatewayLike;
+ importer?: StreamImporterOptions;
+ /** Source (plugin) names this node can resolve. Defaults to the manager's registered plugin names. */
+ sources?: string[];
+ /** Extra / overriding query prefixes for `search()`: `{ ytm: "youtube" }` makes `ytm:lofi` search the youtube plugin. */
+ searchAliases?: Record;
+}
+
+export interface DelegateVoiceOptions {
+ /** Channel object to reconnect locally if the hand-off fails or is reclaimed. Defaults to `gateway.resolveChannel`. */
+ channel?: any;
+ /**
+ * Where the executor gets audio: `"executor"` (default) resolves with its own plugins; `"owner"` pulls
+ * from this node, which must call `provideStreams()`. Tracks already marked with `markTrack` keep their owner.
+ */
+ streamFrom?: "executor" | "owner";
+}
+
+interface Delegation {
+ executor: string;
+ channelId: string;
+ channel: any;
+ selfDeaf: boolean;
+ selfMute: boolean;
+ streamFrom: "executor" | "owner";
+ stopRelay: () => void;
+}
+
+interface Execution {
+ owner: string;
+ cleanup: () => void;
+}
+
+export function markTrack }>(track: T, ownerNodeId: string): T {
+ track.metadata = { ...(track.metadata ?? {}), net: { ...(track.metadata?.net ?? {}), owner: ownerNodeId } };
+ return track;
+}
+
+/**
+ * High level entry point: wires a {@link NetNode} to a PlayerManager.
+ *
+ * - Owner streamInfo: `provideStreams()`; consumers just play tracks marked with `markTrack(track, nodeId)`.
+ * - Owner connection: `player.connect()` as usual; `delegateVoice()` hands the voice session to another node.
+ */
+export class ZiNet {
+ readonly node: NetNode;
+ readonly importer: StreamImporter;
+ readonly hub: RemoteVoiceHub;
+ private provider?: StreamProvider;
+ private readonly delegations = new Map();
+ private readonly executions = new Map();
+ private readonly manager: any;
+ private readonly gateway?: GatewayLike;
+ private voiceAccepting = false;
+ private searchProvider?: { allow?: ServeSearchOptions["allow"]; maxResults: number; maxResponseBytes: number };
+ private readonly aliases: Record;
+ private allowVoice?: (guildId: string, from: string) => boolean | Promise;
+
+ constructor(private readonly options: ZiNetOptions) {
+ this.node = new NetNode(options);
+ this.aliases = { ...DEFAULT_SEARCH_ALIASES, ...(options.searchAliases ?? {}) };
+ this.manager = options.manager;
+ this.gateway = options.gateway;
+ this.importer = new StreamImporter(this.node, options.importer);
+ this.hub = new RemoteVoiceHub(this.node);
+ this.node.onAudio((peerId, frame) => this.importer.onFrame(peerId, frame));
+ this.node.on("peerOffline", (peerId: string) => this.onPeerGone(peerId));
+
+ // Owner side: relayed gateway payloads from the executor.
+ this.node.handle(
+ "voice.payload",
+ (body, ctx) => {
+ const guildId = String(body?.guildId);
+ const delegation = this.delegations.get(guildId);
+ if (!delegation || delegation.executor !== ctx.from) throw new NetError("No delegation for this guild", "FORBIDDEN");
+ const p = body?.payload;
+ // Only a voice-state update for this very guild may reach the gateway.
+ if (!p || p.op !== 4 || String(p.d?.guild_id) !== guildId) throw new NetError("Payload not allowed", "FORBIDDEN");
+ this.gateway?.send(guildId, { op: 4, d: p.d });
+ },
+ { role: "accept-voice" },
+ );
+ this.node.handle("player.event", (body, ctx) => this.onExecutorEvent(body, ctx.from), { role: "accept-voice" });
+ this.node.handle("net.capabilities", () => ({
+ sources: this.localSources(),
+ players: this.manager?.getStats?.().players ?? 0,
+ search: Boolean(this.searchProvider),
+ }));
+ this.node.handle("net.search", (body, ctx) => this.onSearch(body, ctx.from), { role: "provide-search" });
+ }
+
+ // ── capabilities & routing ───────────────────────────────────────────────
+
+ private readonly capsCache = new Map();
+
+ localSources(): string[] {
+ if (this.options.sources) return this.options.sources;
+ const plugins = this.manager?.controllers?.plugin?.getPlugins?.() ?? [];
+ return plugins.map((p: any) => String(p.name));
+ }
+
+ async peerCapabilities(peerId: string, maxAgeMs = 30_000) {
+ const hit = this.capsCache.get(peerId);
+ if (hit && Date.now() - hit.at < maxAgeMs) return hit;
+ const caps = await this.node.request<{ sources: string[]; players: number; search?: boolean }>(
+ peerId,
+ "net.capabilities",
+ undefined,
+ { timeoutMs: 5000 },
+ );
+ const entry = { at: Date.now(), sources: caps.sources ?? [], players: caps.players ?? 0, search: caps.search };
+ this.capsCache.set(peerId, entry);
+ return entry;
+ }
+
+ /**
+ * Plans where each track should be resolved and, with `apply` (default), marks tracks with their owner node
+ * and moves or reclaims the voice when the plan calls for it.
+ *
+ * - `relay`: voice stays here; foreign tracks are pulled from the node that can resolve them.
+ * - `handoff`: voice moves to the node that can play most tracks; others are pulled from their owners.
+ */
+ async routeTracks(
+ player: any,
+ tracks: any[],
+ options: { handoffThreshold?: number; apply?: boolean; peers?: string[]; delegate?: DelegateVoiceOptions } = {},
+ ): Promise {
+ const candidates = (options.peers ?? this.node.onlinePeers()).filter((id) => this.node.isOnline(id) || options.peers);
+ const peers = (
+ await Promise.all(
+ candidates.map((id) =>
+ this.peerCapabilities(id)
+ .then((c) => ({ id, sources: c.sources, load: c.players }))
+ .catch(() => null),
+ ),
+ )
+ ).filter((p): p is { id: string; sources: string[]; load: number } => p !== null);
+
+ const plan = planRoute({
+ selfId: this.nodeId,
+ selfSources: this.localSources(),
+ peers,
+ tracks,
+ handoffThreshold: options.handoffThreshold,
+ });
+ if (options.apply === false) return { ...plan, applied: false };
+
+ const resolvesItself = plan.mode === "handoff" ? plan.executor : this.nodeId;
+ tracks.forEach((track, i) => {
+ const owner = plan.owners[i];
+ if (owner !== resolvesItself) markTrack(track, owner);
+ });
+ try {
+ const delegated = Boolean(this.delegations.get(player.guildId));
+ if (plan.mode === "handoff" && !delegated) await this.delegateVoice(player, plan.executor!, options.delegate);
+ else if (plan.mode !== "handoff" && delegated) await this.reclaimVoice(player);
+ return { ...plan, applied: true };
+ } catch (error) {
+ return { ...plan, applied: false, error: error as Error };
+ }
+ }
+
+ get nodeId(): string {
+ return this.node.nodeId;
+ }
+
+ start(): Promise {
+ return this.node.start();
+ }
+
+ async stop(): Promise {
+ this.provider?.closeAll();
+ this.importer.closeAll();
+ for (const g of [...this.delegations.keys()]) this.dropDelegation(g);
+ for (const e of this.executions.values()) e.cleanup();
+ this.executions.clear();
+ await this.node.stop();
+ }
+
+ /** Extension class to pass in `manager.create(guild, { extensions: [net.extensionClass()] })`. */
+ extensionClass(): new (player?: any) => NetExtension {
+ const net = this;
+ return class extends NetExtension {
+ constructor(player?: any) {
+ super(net, player ?? null);
+ }
+ };
+ }
+
+ // ── search ───────────────────────────────────────────────────────────────
+
+ /**
+ * Serve search results from this node's plugins to trusted peers that hold the `provide-search` role
+ * (the default `*` role includes it). Opt-in, like `provideStreams()`.
+ */
+ provideSearch(options: ServeSearchOptions = {}): void {
+ if (!this.manager?.search) throw new Error("provideSearch() needs a PlayerManager with search()");
+ this.searchProvider = {
+ allow: options.allow,
+ maxResults: Math.min(Math.max(Math.floor(options.maxResults ?? 25), 1), 100),
+ maxResponseBytes: Math.max(Math.floor(options.maxResponseBytes ?? 200_000), 1_000),
+ };
+ }
+
+ /**
+ * Searches across the cluster. Tracks found by another node come back already marked with that node as owner
+ * (`track.metadata.net.owner`), so `player.play(track)` pulls the audio from it.
+ *
+ * `yt:lofi`, `sc:…`, `sp:…`, `tts:…` target the node that has that plugin; anything else (a plain query or a URL)
+ * is tried on this node first and, if nothing is found, on every node that serves search.
+ */
+ async search(text: string, options: NetSearchOptions = {}): Promise {
+ const raw = typeof text === "string" ? text.trim() : "";
+ if (!raw) throw new NetError("Empty search query", "BAD_REQUEST");
+ const { source, query } = parseSearchQuery(raw, this.aliases, options.source);
+ const limit = Math.min(Math.max(Math.floor(options.limit ?? 10) || 10, 1), 100);
+ const mode = options.local ?? "first";
+ const canLocal = mode !== "never" && Boolean(this.manager?.search) && (!source || this.localSources().includes(source));
+ const errors: Error[] = [];
+ const fail = () => {
+ const detail = [...new Set(errors.map((e) => e.message))].join("; ");
+ return new NetError(`No results found for: ${raw}${detail ? ` (${detail})` : ""}`, "NO_RESULTS");
+ };
+
+ const local = async (): Promise => {
+ const r = await this.searchLocal(query, source, options.requestedBy);
+ if (!r?.tracks?.length) throw new NetError(`No results found locally for: ${query}`, "NO_RESULTS");
+ this.node.traceNote(`search "${query}": ${r.tracks.length} result(s) from local plugins`);
+ return {
+ tracks: r.tracks.slice(0, limit),
+ playlist: r.playlist ?? null,
+ query: r.query,
+ source: r.source,
+ node: this.nodeId,
+ nodes: [this.nodeId],
+ };
+ };
+ const peerIds = async () => (mode === "only" ? [] : await this.searchCandidates(source, options.peers));
+
+ if (options.merge) {
+ const ids = await peerIds();
+ const jobs = [...(canLocal ? [local()] : []), ...ids.map((id) => this.searchOn(id, raw, options))];
+ const settled = await Promise.allSettled(jobs);
+ const ok: NetSearchResult[] = [];
+ for (const r of settled) r.status === "fulfilled" ? ok.push(r.value) : errors.push(r.reason as Error);
+ if (!ok.length) throw fail();
+ const withPlaylist = ok.find((r) => r.playlist);
+ if (withPlaylist) return withPlaylist;
+ return {
+ tracks: dedupeNetTracks(ok.flatMap((r) => r.tracks)).slice(0, limit),
+ playlist: null,
+ query: ok[0].query,
+ source: ok[0].source,
+ node: ok[0].node,
+ nodes: [...new Set(ok.flatMap((r) => r.nodes))],
+ };
+ }
+
+ const tryLocal = async () => {
+ if (!canLocal) return null;
+ try {
+ return await local();
+ } catch (error) {
+ errors.push(error as Error);
+ this.node.traceNote(`search "${query}": nothing from local plugins (${(error as Error).message})`);
+ return null;
+ }
+ };
+ const tryPeers = async () => {
+ const ids = await peerIds();
+ if (!ids.length) return null;
+ const stop = new AbortController();
+ const onAbort = () => stop.abort();
+ if (options.signal?.aborted) stop.abort();
+ options.signal?.addEventListener("abort", onAbort, { once: true });
+ try {
+ return await Promise.any(ids.map((id) => this.searchOn(id, raw, { ...options, signal: stop.signal })));
+ } catch (error) {
+ errors.push(...(error instanceof AggregateError ? (error.errors as Error[]) : [error as Error]));
+ return null;
+ } finally {
+ stop.abort(); // cancel the requests that lost the race
+ options.signal?.removeEventListener("abort", onAbort);
+ }
+ };
+ for (const step of mode === "last" ? [tryPeers, tryLocal] : [tryLocal, tryPeers]) {
+ const result = await step();
+ if (result) return result;
+ }
+ throw fail();
+ }
+
+ /** Searches on one specific node (it must run `provideSearch()` and trust this node). */
+ async searchOn(peerId: string, text: string, options: NetSearchOptions = {}): Promise {
+ const { source, query } = parseSearchQuery(String(text ?? ""), this.aliases, options.source);
+ if (!query) throw new NetError("Empty search query", "BAD_REQUEST");
+ const limit = Math.min(Math.max(Math.floor(options.limit ?? 10) || 10, 1), 100);
+ this.node.traceNote(`search "${query}" → ${peerId}${source ? ` (plugin ${source})` : ""}`, { peer: peerId });
+ const raw = await this.node.request(
+ peerId,
+ "net.search",
+ { query, limit, plugins: source ? [source] : undefined },
+ { timeoutMs: options.timeoutMs, signal: options.signal },
+ );
+ const result = importWireResult(raw, peerId, options.requestedBy, limit);
+ if (!result.tracks.length) throw new NetError(`No results found on ${peerId} for: ${query}`, "NO_RESULTS");
+ this.node.traceNote(`search "${query}": ${result.tracks.length} result(s) from ${peerId}`, { peer: peerId });
+ return { ...result, node: peerId, nodes: [peerId] };
+ }
+
+ private async searchCandidates(source: string | undefined, explicit?: string[]): Promise {
+ const ids = (explicit ?? this.node.onlinePeers()).filter((id) => id !== this.nodeId && (explicit || this.node.isOnline(id)));
+ const caps = await Promise.all(
+ ids.map((id) =>
+ this.peerCapabilities(id)
+ .then((c) => ({ id, ...c }))
+ .catch(() => null),
+ ),
+ );
+ return caps
+ .filter((c): c is NonNullable => c !== null)
+ .filter((c) => c.search !== false && (!source || c.sources.includes(source)))
+ .sort((a, b) => a.players - b.players)
+ .map((c) => c.id);
+ }
+
+ /** Runs the query on this node's plugins. With a `plugins` filter it goes straight to the shared plugin manager. */
+ private async searchLocal(query: string, source: string | undefined, requestedBy: unknown): Promise {
+ const who = typeof requestedBy === "string" ? requestedBy : ((requestedBy as any)?.id ?? "net");
+ const pluginManager = source ? this.manager?.controllers?.plugin?.getSharedManager?.() : undefined;
+ if (pluginManager?.search) {
+ const result = await pluginManager.search(query, { requestedBy: String(who), plugins: [source] });
+ if (!result?.tracks?.length) throw new NetError(`No results found for: ${query}`, "NO_RESULTS");
+ return result;
+ }
+ return this.manager.search(query, requestedBy ?? "net");
+ }
+
+ private async onSearch(body: any, from: string) {
+ const provider = this.searchProvider;
+ if (!provider) throw new NetError("This node does not serve search", "NOT_PROVIDED");
+ const query = typeof body?.query === "string" ? body.query.trim() : "";
+ if (!query || query.length > MAX_QUERY_CHARS) throw new NetError("Invalid search query", "BAD_REQUEST");
+ const plugins: string[] | undefined =
+ Array.isArray(body?.plugins) ?
+ body.plugins.filter((p: unknown): p is string => typeof p === "string" && p.length > 0 && p.length <= 64).slice(0, 8)
+ : undefined;
+ const limit = Math.min(Math.max(Math.floor(Number(body?.limit)) || 10, 1), provider.maxResults);
+ if (provider.allow && !(await provider.allow(query, from))) throw new NetError("Search refused", "FORBIDDEN");
+ const source = plugins?.length === 1 ? plugins[0] : undefined;
+ const result = await this.searchLocal(query, source, `net:${from}`);
+ const wire = toWireResult(result, limit, provider.maxResponseBytes);
+ this.node.traceNote(`search "${query}" from ${from}: answering ${wire.tracks.length} track(s)`, { peer: from });
+ return wire;
+ }
+
+ // ── owner streamInfo ─────────────────────────────────────────────────────
+
+ /** Serve streams resolved by this node's plugins to trusted peers that hold the `provide-stream` role. */
+ provideStreams(options?: {
+ allow?: (track: any, peerId: string) => boolean | Promise;
+ chunkBytes?: number;
+ }): StreamProvider {
+ if (!this.manager?.resolveStream) throw new Error("provideStreams() needs a PlayerManager with resolveStream()");
+ this.provider = new StreamProvider(this.node, {
+ resolveStream: (track, opts) => this.manager.resolveStream(track, opts) as Promise,
+ allow: options?.allow,
+ chunkBytes: options?.chunkBytes,
+ debug: this.options.debug,
+ });
+ return this.provider;
+ }
+
+ /** Open a remote stream as a ziplayer `StreamInfo`. */
+ async openRemoteStream(ownerId: string, track: any, position = 0, signal?: AbortSignal) {
+ const remote = await this.importer.open(ownerId, serializeTrack(track), { position, signal });
+ return {
+ stream: remote.stream,
+ track,
+ streamType: remote.streamType,
+ type: remote.streamType,
+ recreate: remote.recreate,
+ // A network stream is single-use: never let the extension manager replay a consumed Readable.
+ cacheable: false,
+ metadata: { net: { owner: ownerId } },
+ };
+ }
+
+ // ── owner connection → executor ──────────────────────────────────────────
+
+ delegationFor(guildId: string): Delegation | undefined {
+ return this.delegations.get(guildId);
+ }
+
+ /**
+ * Hands the player's Discord voice session to `executorId`. This node keeps the gateway and the queue; the
+ * executor joins voice (through a relay adapter) and plays. Call it while nothing is playing.
+ */
+ async delegateVoice(player: any, executorId: string, options: DelegateVoiceOptions = {}): Promise {
+ const gateway = this.gateway;
+ if (!gateway) throw new NetError("delegateVoice() needs a gateway (see discordJsGateway)", "NO_GATEWAY");
+ const guildId: string = player.guildId;
+ if (this.delegations.has(guildId)) throw new NetError("Voice already delegated for this guild", "ALREADY_DELEGATED");
+ const connection = player.connection;
+ if (!connection) throw new NetError("Player is not connected; call player.connect() first", "NOT_CONNECTED");
+ if (player.isPlaying) throw new NetError("Stop playback before delegating voice", "BUSY");
+ const channelId: string = connection.joinConfig.channelId;
+ const channel = options.channel ?? gateway.resolveChannel?.(guildId, channelId);
+
+ await this.node.ensureSession(executorId);
+ const stopRelay = gateway.onVoiceUpdate((gid, kind, data) => {
+ if (gid !== guildId) return;
+ this.node.notify(executorId, "voice.event", { guildId, kind, data }).catch(() => {});
+ });
+ // Registered BEFORE the request: the executor's first gateway payload (join) arrives while it is still connecting.
+ this.delegations.set(guildId, {
+ executor: executorId,
+ channelId,
+ channel,
+ selfDeaf: connection.joinConfig.selfDeaf,
+ selfMute: connection.joinConfig.selfMute,
+ streamFrom: options.streamFrom ?? "executor",
+ stopRelay,
+ });
+ // Release our UDP connection WITHOUT leaving the Discord channel so the executor can take over.
+ await player.disconnect({ silent: true });
+ try {
+ await this.node.request(
+ executorId,
+ "voice.delegate",
+ {
+ guildId,
+ channelId,
+ selfDeaf: connection.joinConfig.selfDeaf,
+ selfMute: connection.joinConfig.selfMute,
+ volume: player.volume,
+ },
+ { timeoutMs: 30_000 },
+ );
+ } catch (error) {
+ this.dropDelegation(guildId);
+ if (channel) await player.connect(channel).catch(() => {});
+ throw error;
+ }
+ }
+
+ /** Takes the voice session back and reconnects locally. */
+ async reclaimVoice(player: any, options: { channel?: any } = {}): Promise {
+ const guildId: string = player.guildId;
+ const d = this.delegations.get(guildId);
+ if (!d) return;
+ const queuedTracks = player.queue?.getTracks?.() ?? [];
+ const hadCurrentTrack = player.currentTrack != null;
+ await this.node.request(d.executor, "voice.release", { guildId }, { timeoutMs: 10_000 }).catch(() => {});
+ this.dropDelegation(guildId);
+ try {
+ player.exitRemoteMode?.();
+ } catch {}
+ if (hadCurrentTrack) {
+ if (!(await player.stop())) throw new NetError("Could not clear remote playback while reclaiming voice", "STOP_FAILED");
+ if (queuedTracks.length) player.queue.addMultiple(queuedTracks);
+ }
+ const channel = options.channel ?? d.channel;
+ if (channel) {
+ await this.leaveGatewayVoice(guildId, d);
+ await player.connect(channel);
+ }
+ }
+
+ private async leaveGatewayVoice(guildId: string, delegation: Delegation): Promise {
+ const gateway = this.gateway;
+ if (!gateway) return;
+ await new Promise((resolve, reject) => {
+ let settled = false;
+ let unsubscribe = () => {};
+ const finish = (error?: unknown) => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timeout);
+ unsubscribe();
+ if (error) reject(error);
+ else resolve();
+ };
+ const timeout = setTimeout(
+ () => finish(new NetError(`Timed out waiting for guild ${guildId} to leave voice before reclaim`, "VOICE_LEAVE_TIMEOUT")),
+ 5_000,
+ );
+ unsubscribe = gateway.onVoiceUpdate((eventGuildId, kind, data) => {
+ if (eventGuildId === guildId && kind === "state" && data?.channel_id == null) finish();
+ });
+ try {
+ gateway.send(guildId, {
+ op: 4,
+ d: {
+ guild_id: guildId,
+ channel_id: null,
+ self_deaf: delegation.selfDeaf,
+ self_mute: delegation.selfMute,
+ },
+ });
+ } catch (error) {
+ finish(error);
+ }
+ });
+ }
+
+ private dropDelegation(guildId: string) {
+ const d = this.delegations.get(guildId);
+ if (!d) return;
+ d.stopRelay();
+ this.delegations.delete(guildId);
+ }
+
+ /** Remote playback handle for a delegated player (same contract Lavalink uses). */
+ buildRemoteStream(player: any, track: any) {
+ const guildId: string = player.guildId;
+ const d = this.delegations.get(guildId);
+ if (!d) return null;
+ const wire = serializeTrack(track);
+ if (!wire.metadata?.net?.owner && d.streamFrom === "owner") markTrack(wire, this.nodeId);
+ const cmd = (name: string, value?: unknown) =>
+ this.node.request(d.executor, "player.cmd", { guildId, cmd: name, value }, { timeoutMs: 30_000 });
+ const handle = {
+ play: async () => void (await cmd("play", { track: wire, position: 0 })),
+ pause: async () => void (await cmd("pause")),
+ resume: async () => void (await cmd("resume")),
+ stop: async () => {
+ await cmd("stop");
+ // Core only forwards stop() to the handle; leave REMOTE mode afterwards so the player is not left "playing".
+ setImmediate(() => {
+ try {
+ if (this.delegations.has(guildId)) player.exitRemoteMode?.();
+ } catch {}
+ });
+ },
+ seek: async (position: number) => void (await cmd("seek", position)),
+ setVolume: async (volume: number) => void (await cmd("volume", volume)),
+ destroy: async () => void (await cmd("stop").catch(() => {})),
+ };
+ const dummy = new PassThrough();
+ dummy.end();
+ return { stream: dummy, track, streamType: "arbitrary", type: "arbitrary", remote: true, handle };
+ }
+
+ private onExecutorEvent(body: any, from: string) {
+ const guildId = String(body?.guildId);
+ const d = this.delegations.get(guildId);
+ if (!d || d.executor !== from) return;
+ const player = this.manager?.get?.(guildId);
+ if (!player || player.destroyed) return;
+ switch (body.type) {
+ case "trackEnd": {
+ const track = player.currentTrack;
+ if (track) player.emit("trackEnd", track);
+ if (body.reason === "finished" || body.reason === "error") void player.playNext?.().catch(() => {});
+ break;
+ }
+ case "error":
+ player.emit("playerError", new Error(String(body.message ?? "Remote playback error")), player.currentTrack);
+ break;
+ }
+ }
+
+ private onPeerGone(peerId: string) {
+ // Executor vanished: take voice back so the guild is not left silent.
+ for (const [guildId, d] of [...this.delegations]) {
+ if (d.executor !== peerId) continue;
+ const player = this.manager?.get?.(guildId);
+ this.dropDelegation(guildId);
+ try {
+ player?.exitRemoteMode?.();
+ } catch {}
+ if (player && !player.destroyed && d.channel) void player.connect(d.channel).catch(() => {});
+ player?.emit?.("debug", `[net] executor ${peerId} went offline; reclaimed voice for ${guildId}`);
+ }
+ for (const [guildId, e] of [...this.executions]) {
+ if (e.owner !== peerId) continue;
+ e.cleanup();
+ this.executions.delete(guildId);
+ }
+ }
+
+ // ── executor ─────────────────────────────────────────────────────────────
+
+ /** Accept voice hand-offs from trusted owners that hold the `delegate-voice` role. */
+ acceptVoice(options?: { allow?: (guildId: string, from: string) => boolean | Promise }): void {
+ if (!this.manager) throw new Error("acceptVoice() needs a PlayerManager");
+ if (this.voiceAccepting) return;
+ this.voiceAccepting = true;
+ this.allowVoice = options?.allow;
+
+ this.node.handle(
+ "voice.event",
+ (body, ctx) => {
+ if (body?.kind !== "state" && body?.kind !== "server") return;
+ this.hub.feed(String(body.guildId), ctx.from, body.kind, body.data);
+ },
+ { role: "delegate-voice" },
+ );
+
+ this.node.handle("voice.delegate", (body, ctx) => this.onDelegate(body, ctx.from), { role: "delegate-voice" });
+
+ this.node.handle(
+ "voice.release",
+ async (body, ctx) => {
+ const guildId = String(body?.guildId);
+ const e = this.executions.get(guildId);
+ if (!e || e.owner !== ctx.from) return;
+ await this.endExecution(guildId, true);
+ },
+ { role: "delegate-voice" },
+ );
+
+ this.node.handle(
+ "player.cmd",
+ async (body, ctx) => {
+ const guildId = String(body?.guildId);
+ const e = this.executions.get(guildId);
+ if (!e || e.owner !== ctx.from) throw new NetError("No execution for this guild", "FORBIDDEN");
+ const player = this.manager.get(guildId);
+ if (!player) throw new NetError("Player missing", "NO_PLAYER");
+ switch (body.cmd) {
+ case "play": {
+ const track = body.value?.track;
+ if (!track) throw new Error("Missing track");
+ if (!(await player.play(track, { requestedBy: track.requestedBy ?? "net" })))
+ throw new Error("Playback failed to start");
+ return;
+ }
+ case "pause":
+ return void (await player.pause());
+ case "resume":
+ return void (await player.resume());
+ case "stop":
+ return void (await player.stop());
+ case "seek":
+ return void (await player.seek(Number(body.value) || 0));
+ case "volume":
+ return void player.setVolume(Number(body.value));
+ default:
+ throw new Error(`Unknown command "${body.cmd}"`);
+ }
+ },
+ { role: "delegate-voice" },
+ );
+ }
+
+ private async onDelegate(body: any, owner: string) {
+ const guildId = String(body?.guildId);
+ const channelId = String(body?.channelId);
+ if (!guildId || !channelId) throw new Error("Missing guildId/channelId");
+ if (this.allowVoice && !(await this.allowVoice(guildId, owner))) throw new NetError("Delegation refused", "FORBIDDEN");
+ if (this.executions.has(guildId)) await this.endExecution(guildId, true);
+
+ const player = await this.manager.create(guildId, {
+ extensions: [this.extensionClass()],
+ selfDeaf: body.selfDeaf,
+ selfMute: body.selfMute,
+ });
+ const channel = this.hub.createChannel(guildId, channelId, owner);
+ await player.connect(channel);
+ if (typeof body.volume === "number") player.setVolume(body.volume);
+
+ const report = (payload: Record) =>
+ this.node.notify(owner, "player.event", { guildId, ...payload }).catch(() => {});
+ const onEnd = () => void report({ type: "trackEnd", reason: "finished" });
+ const onError = (error: Error) => void report({ type: "error", message: error?.message });
+ player.on("queueEnd", onEnd);
+ player.on("trackEnd", onEnd);
+ player.on("playerError", onError);
+ this.executions.set(guildId, {
+ owner,
+ cleanup: () => {
+ player.off("queueEnd", onEnd);
+ player.off("trackEnd", onEnd);
+ player.off("playerError", onError);
+ },
+ });
+ return { ok: true };
+ }
+
+ private async endExecution(guildId: string, silent: boolean) {
+ const e = this.executions.get(guildId);
+ if (!e) return;
+ e.cleanup();
+ this.executions.delete(guildId);
+ const player = this.manager.get(guildId);
+ if (player) {
+ // Do not leave the Discord channel: the owner is about to take the session back.
+ await player.disconnect({ silent }).catch(() => {});
+ await this.manager.destroy(guildId).catch(() => {});
+ }
+ this.hub.forget(guildId);
+ }
+}
diff --git a/net/src/crypto/handshake.ts b/net/src/crypto/handshake.ts
new file mode 100644
index 00000000..cd40da21
--- /dev/null
+++ b/net/src/crypto/handshake.ts
@@ -0,0 +1,258 @@
+import {
+ createCipheriv,
+ createDecipheriv,
+ createHash,
+ createPublicKey,
+ diffieHellman,
+ generateKeyPairSync,
+ hkdfSync,
+ randomBytes,
+ sign,
+ verify,
+ type KeyObject,
+} from "node:crypto";
+import type { NodeIdentity, TrustStore } from "./identity";
+
+/**
+ * Three-message authenticated key exchange (SIGMA-I style, built only from node:crypto):
+ *
+ * 1. hs1 A -> B ephemeral X25519 key + nonce (plaintext, reveals nothing secret)
+ * 2. hs2 B -> A B's ephemeral key + nonce + Ed25519 signature (signature encrypted under a handshake key)
+ * 3. hs3 A -> B A's Ed25519 signature over the full transcript (encrypted)
+ *
+ * Both signatures cover the whole transcript, so each side proves it owns the pinned long-term key AND
+ * took part in this exact exchange. Session keys come from HKDF over the ephemeral ECDH secret, which gives
+ * forward secrecy. Node identities are pinned in a {@link TrustStore}; unknown nodes are rejected.
+ *
+ * This is a small custom protocol on standard primitives. Get it reviewed before trusting it with anything
+ * valuable, and consider swapping in a Noise XX implementation behind the same interface.
+ */
+
+export const PROTOCOL_VERSION = 1;
+const LABEL = Buffer.from("zinet/1");
+
+export class HandshakeError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = "HandshakeError";
+ }
+}
+
+export interface Hs1 {
+ t: "hs1";
+ v: number;
+ net: string;
+ from: string;
+ to: string;
+ sid: string;
+ eA: string;
+ nA: string;
+}
+export interface Hs2 {
+ t: "hs2";
+ sid: string;
+ eB: string;
+ nB: string;
+ enc: string;
+}
+export interface Hs3 {
+ t: "hs3";
+ sid: string;
+ enc: string;
+}
+
+export interface HandshakeResult {
+ sessionId: string;
+ peerId: string;
+ /** Key for frames this node sends. */
+ sendKey: Buffer;
+ /** Key for frames this node receives. */
+ recvKey: Buffer;
+ initiator: boolean;
+}
+
+export interface HandshakeContext {
+ networkId: string;
+ selfId: string;
+ identity: NodeIdentity;
+ trust: TrustStore;
+}
+
+const SPKI_X25519_PREFIX = Buffer.from("302a300506032b656e032100", "hex");
+
+function rawPublic(key: KeyObject): Buffer {
+ return (key.export({ type: "spki", format: "der" }) as Buffer).subarray(-32);
+}
+
+function importRawPublic(raw: Buffer): KeyObject {
+ if (raw.length !== 32) throw new HandshakeError("Invalid ephemeral key length");
+ return createPublicKey({ key: Buffer.concat([SPKI_X25519_PREFIX, raw]), format: "der", type: "spki" });
+}
+
+function lp(...parts: Array): Buffer {
+ const buffers = parts.map((p) => (typeof p === "string" ? Buffer.from(p, "utf8") : p));
+ const out: Buffer[] = [];
+ for (const b of buffers) {
+ const len = Buffer.alloc(2);
+ len.writeUInt16BE(b.length);
+ out.push(len, b);
+ }
+ return Buffer.concat(out);
+}
+
+function b64(buf: Buffer): string {
+ return buf.toString("base64");
+}
+function unb64(value: unknown, label: string, length?: number): Buffer {
+ if (typeof value !== "string") throw new HandshakeError(`Missing ${label}`);
+ const buf = Buffer.from(value, "base64");
+ if (length !== undefined && buf.length !== length) throw new HandshakeError(`Invalid ${label}`);
+ return buf;
+}
+
+function transcript(hs1: Hs1, eB?: Buffer, nB?: Buffer): Buffer {
+ const base = lp(LABEL, hs1.net, hs1.from, hs1.to, hs1.sid, Buffer.from(hs1.eA, "base64"), Buffer.from(hs1.nA, "base64"));
+ return eB && nB ? Buffer.concat([base, lp(eB, nB)]) : base;
+}
+
+function deriveKeys(dh: Buffer, nA: Buffer, nB: Buffer, th: Buffer) {
+ const salt = Buffer.concat([nA, nB]);
+ const expand = (label: string) => Buffer.from(hkdfSync("sha256", dh, salt, Buffer.concat([Buffer.from(label), th]), 32));
+ return { hs: expand("zinet/hs"), a2b: expand("zinet/a2b"), b2a: expand("zinet/b2a") };
+}
+
+function hsNonce(step: 2 | 3): Buffer {
+ const n = Buffer.alloc(12);
+ n[11] = step;
+ return n;
+}
+
+function seal(key: Buffer, nonce: Buffer, aad: Buffer, plaintext: Buffer): Buffer {
+ const cipher = createCipheriv("chacha20-poly1305", key, nonce, { authTagLength: 16 });
+ cipher.setAAD(aad, { plaintextLength: plaintext.length });
+ const ct = Buffer.concat([cipher.update(plaintext), cipher.final()]);
+ return Buffer.concat([ct, cipher.getAuthTag()]);
+}
+
+function open(key: Buffer, nonce: Buffer, aad: Buffer, sealed: Buffer): Buffer {
+ if (sealed.length < 16) throw new HandshakeError("Handshake payload too short");
+ try {
+ const decipher = createDecipheriv("chacha20-poly1305", key, nonce, { authTagLength: 16 });
+ decipher.setAAD(aad, { plaintextLength: sealed.length - 16 });
+ decipher.setAuthTag(sealed.subarray(sealed.length - 16));
+ return Buffer.concat([decipher.update(sealed.subarray(0, sealed.length - 16)), decipher.final()]);
+ } catch {
+ throw new HandshakeError("Handshake authentication failed");
+ }
+}
+
+const sigDigest = (tag: string, th: Buffer, extra?: Buffer) =>
+ createHash("sha256")
+ .update(tag)
+ .update(th)
+ .update(extra ?? Buffer.alloc(0))
+ .digest();
+
+export class HandshakeInitiator {
+ private readonly ephemeral = generateKeyPairSync("x25519");
+ private readonly hs1: Hs1;
+ private done = false;
+
+ constructor(
+ private readonly ctx: HandshakeContext,
+ private readonly peerId: string,
+ ) {
+ if (!ctx.trust.has(peerId)) throw new HandshakeError(`Peer "${peerId}" is not trusted`);
+ this.hs1 = {
+ t: "hs1",
+ v: PROTOCOL_VERSION,
+ net: ctx.networkId,
+ from: ctx.selfId,
+ to: peerId,
+ sid: randomBytes(8).toString("hex"),
+ eA: b64(rawPublic(this.ephemeral.publicKey)),
+ nA: b64(randomBytes(16)),
+ };
+ }
+
+ get sessionId(): string {
+ return this.hs1.sid;
+ }
+
+ hello(): Hs1 {
+ return this.hs1;
+ }
+
+ /** Verifies B, returns hs3 plus the session keys. */
+ finish(hs2: Hs2): { hs3: Hs3; result: HandshakeResult } {
+ if (this.done) throw new HandshakeError("Handshake already completed");
+ if (hs2.t !== "hs2" || hs2.sid !== this.hs1.sid) throw new HandshakeError("Unexpected handshake reply");
+ const eB = unb64(hs2.eB, "eB", 32);
+ const nB = unb64(hs2.nB, "nB", 16);
+ const th = createHash("sha256")
+ .update(transcript(this.hs1, eB, nB))
+ .digest();
+ const dh = diffieHellman({ privateKey: this.ephemeral.privateKey, publicKey: importRawPublic(eB) });
+ const keys = deriveKeys(dh, Buffer.from(this.hs1.nA, "base64"), nB, th);
+
+ const sigB = open(keys.hs, hsNonce(2), th, unb64(hs2.enc, "enc"));
+ const peerKey = this.ctx.trust.publicKey(this.peerId);
+ if (!peerKey || !verify(null, sigDigest("resp", th), peerKey, sigB)) throw new HandshakeError("Responder signature invalid");
+
+ const sigA = sign(null, sigDigest("init", th, sigB), this.ctx.identity.privateKey);
+ const hs3: Hs3 = { t: "hs3", sid: this.hs1.sid, enc: b64(seal(keys.hs, hsNonce(3), th, sigA)) };
+ this.done = true;
+ return {
+ hs3,
+ result: { sessionId: this.hs1.sid, peerId: this.peerId, sendKey: keys.a2b, recvKey: keys.b2a, initiator: true },
+ };
+ }
+}
+
+export class HandshakeResponder {
+ private readonly th: Buffer;
+ private readonly keys: ReturnType;
+ private readonly sigB: Buffer;
+ private done = false;
+ readonly hs2: Hs2;
+
+ constructor(
+ private readonly ctx: HandshakeContext,
+ private readonly hs1: Hs1,
+ ) {
+ if (hs1.t !== "hs1" || hs1.v !== PROTOCOL_VERSION) throw new HandshakeError("Unsupported handshake version");
+ if (hs1.net !== ctx.networkId) throw new HandshakeError("Wrong network");
+ if (hs1.to !== ctx.selfId) throw new HandshakeError("Handshake not addressed to this node");
+ if (!ctx.trust.has(hs1.from)) throw new HandshakeError(`Peer "${hs1.from}" is not trusted`);
+ if (!/^[0-9a-f]{16}$/.test(hs1.sid)) throw new HandshakeError("Invalid session id");
+ const eA = unb64(hs1.eA, "eA", 32);
+ const nA = unb64(hs1.nA, "nA", 16);
+ const ephemeral = generateKeyPairSync("x25519");
+ const eB = rawPublic(ephemeral.publicKey);
+ const nB = randomBytes(16);
+ this.th = createHash("sha256")
+ .update(transcript(hs1, eB, nB))
+ .digest();
+ const dh = diffieHellman({ privateKey: ephemeral.privateKey, publicKey: importRawPublic(eA) });
+ this.keys = deriveKeys(dh, nA, nB, this.th);
+ this.sigB = sign(null, sigDigest("resp", this.th), ctx.identity.privateKey);
+ this.hs2 = { t: "hs2", sid: hs1.sid, eB: b64(eB), nB: b64(nB), enc: b64(seal(this.keys.hs, hsNonce(2), this.th, this.sigB)) };
+ }
+
+ get peerId(): string {
+ return this.hs1.from;
+ }
+
+ /** Verifies A's signature and returns the session keys. */
+ finish(hs3: Hs3): HandshakeResult {
+ if (this.done) throw new HandshakeError("Handshake already completed");
+ if (hs3.t !== "hs3" || hs3.sid !== this.hs1.sid) throw new HandshakeError("Unexpected handshake message");
+ const sigA = open(this.keys.hs, hsNonce(3), this.th, unb64(hs3.enc, "enc"));
+ const peerKey = this.ctx.trust.publicKey(this.hs1.from);
+ if (!peerKey || !verify(null, sigDigest("init", this.th, this.sigB), peerKey, sigA)) {
+ throw new HandshakeError("Initiator signature invalid");
+ }
+ this.done = true;
+ return { sessionId: this.hs1.sid, peerId: this.hs1.from, sendKey: this.keys.b2a, recvKey: this.keys.a2b, initiator: false };
+ }
+}
diff --git a/net/src/crypto/identity.ts b/net/src/crypto/identity.ts
new file mode 100644
index 00000000..5d693a7f
--- /dev/null
+++ b/net/src/crypto/identity.ts
@@ -0,0 +1,115 @@
+import { createHash, createPrivateKey, createPublicKey, generateKeyPairSync, type KeyObject } from "node:crypto";
+import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
+import { dirname } from "node:path";
+
+/** Long-term Ed25519 identity of a node. Used only to sign handshake transcripts. */
+export interface NodeIdentity {
+ privateKey: KeyObject;
+ publicKey: KeyObject;
+}
+
+export interface GeneratedIdentity {
+ identity: NodeIdentity;
+ privateKeyPem: string;
+ publicKeyPem: string;
+}
+
+export function generateIdentity(): GeneratedIdentity {
+ const { privateKey, publicKey } = generateKeyPairSync("ed25519");
+ return {
+ identity: { privateKey, publicKey },
+ privateKeyPem: privateKey.export({ type: "pkcs8", format: "pem" }).toString(),
+ publicKeyPem: publicKey.export({ type: "spki", format: "pem" }).toString(),
+ };
+}
+
+export function loadIdentity(privateKeyPem: string | KeyObject): NodeIdentity {
+ const privateKey = typeof privateKeyPem === "string" ? createPrivateKey(privateKeyPem) : privateKeyPem;
+ if (privateKey.asymmetricKeyType !== "ed25519") throw new TypeError("Node identity must be an Ed25519 key");
+ return { privateKey, publicKey: createPublicKey(privateKey) };
+}
+
+/**
+ * Loads the node identity from `keyFile`, or creates and stores a new one (mode 0600, plus `.pub`)
+ * when the file does not exist yet.
+ */
+export function loadOrCreateIdentity(keyFile: string): GeneratedIdentity & { created: boolean } {
+ if (existsSync(keyFile)) {
+ const privateKeyPem = readFileSync(keyFile, "utf8");
+ const identity = loadIdentity(privateKeyPem);
+ return {
+ identity,
+ privateKeyPem,
+ publicKeyPem: identity.publicKey.export({ type: "spki", format: "pem" }).toString(),
+ created: false,
+ };
+ }
+ const generated = generateIdentity();
+ mkdirSync(dirname(keyFile), { recursive: true });
+ writeFileSync(keyFile, generated.privateKeyPem, { mode: 0o600 });
+ try {
+ chmodSync(keyFile, 0o600);
+ } catch {}
+ writeFileSync(`${keyFile}.pub`, generated.publicKeyPem);
+ return { ...generated, created: true };
+}
+
+export function parsePublicKey(key: string | KeyObject): KeyObject {
+ const publicKey = typeof key === "string" ? createPublicKey(key) : key;
+ if (publicKey.asymmetricKeyType !== "ed25519") throw new TypeError("Trusted peer key must be an Ed25519 public key");
+ return publicKey;
+}
+
+/** Short human-comparable fingerprint of a public key (SHA-256 of its DER encoding). */
+export function fingerprint(key: KeyObject): string {
+ return createHash("sha256")
+ .update(key.export({ type: "spki", format: "der" }))
+ .digest("hex");
+}
+
+export type NetRole = "provide-stream" | "provide-search" | "accept-voice" | "delegate-voice" | "*";
+
+export interface TrustedPeer {
+ nodeId: string;
+ /** Ed25519 public key (PEM or KeyObject). Pinned: a different key for this nodeId is rejected. */
+ publicKey: string | KeyObject;
+ /**
+ * What this peer is allowed to ask of us. Defaults to `["*"]` because listing a peer here is already an
+ * explicit decision; narrow it for least privilege.
+ */
+ roles?: NetRole[];
+}
+
+export class TrustStore {
+ private readonly peers = new Map }>();
+
+ constructor(peers: TrustedPeer[] = []) {
+ for (const peer of peers) this.add(peer);
+ }
+
+ add(peer: TrustedPeer): void {
+ if (!peer.nodeId) throw new TypeError("Trusted peer needs a nodeId");
+ this.peers.set(peer.nodeId, { publicKey: parsePublicKey(peer.publicKey), roles: new Set(peer.roles ?? ["*"]) });
+ }
+
+ remove(nodeId: string): boolean {
+ return this.peers.delete(nodeId);
+ }
+
+ has(nodeId: string): boolean {
+ return this.peers.has(nodeId);
+ }
+
+ publicKey(nodeId: string): KeyObject | undefined {
+ return this.peers.get(nodeId)?.publicKey;
+ }
+
+ hasRole(nodeId: string, role: NetRole): boolean {
+ const roles = this.peers.get(nodeId)?.roles;
+ return Boolean(roles && (roles.has("*") || roles.has(role)));
+ }
+
+ ids(): string[] {
+ return [...this.peers.keys()];
+ }
+}
diff --git a/net/src/crypto/session.ts b/net/src/crypto/session.ts
new file mode 100644
index 00000000..29505f35
--- /dev/null
+++ b/net/src/crypto/session.ts
@@ -0,0 +1,144 @@
+import { createCipheriv, createDecipheriv } from "node:crypto";
+
+export class SessionError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = "SessionError";
+ }
+}
+
+/** Wire kinds (first byte of every message). */
+export const KIND = { HANDSHAKE: 1, CONTROL: 2, AUDIO: 3, AUDIO_ENCRYPTED: 4 } as const;
+
+const TAG = 16;
+const MAX_COUNTER = 2 ** 48;
+
+/** Accepts each counter at most once inside a sliding window; tolerates reordering, rejects replays. */
+export class ReplayWindow {
+ private max = -1;
+ private readonly seen = new Set();
+ constructor(private readonly size = 1024) {}
+
+ accept(counter: number): boolean {
+ if (counter <= this.max - this.size || this.seen.has(counter)) return false;
+ this.seen.add(counter);
+ if (counter > this.max) {
+ this.max = counter;
+ for (const old of this.seen) if (old <= this.max - this.size) this.seen.delete(old);
+ }
+ return true;
+ }
+}
+
+function nonce(direction: number, channel: number, counter: number): Buffer {
+ const n = Buffer.alloc(12);
+ n[0] = direction;
+ n[1] = channel;
+ n.writeBigUInt64BE(BigInt(counter), 4);
+ return n;
+}
+
+function aead(key: Buffer, n: Buffer, aad: Buffer, data: Buffer): Buffer {
+ const c = createCipheriv("chacha20-poly1305", key, n, { authTagLength: TAG });
+ c.setAAD(aad, { plaintextLength: data.length });
+ return Buffer.concat([c.update(data), c.final(), c.getAuthTag()]);
+}
+
+function unaead(key: Buffer, n: Buffer, aad: Buffer, sealed: Buffer): Buffer {
+ if (sealed.length < TAG) throw new SessionError("Message too short");
+ try {
+ const d = createDecipheriv("chacha20-poly1305", key, n, { authTagLength: TAG });
+ d.setAAD(aad, { plaintextLength: sealed.length - TAG });
+ d.setAuthTag(sealed.subarray(sealed.length - TAG));
+ return Buffer.concat([d.update(sealed.subarray(0, sealed.length - TAG)), d.final()]);
+ } catch {
+ throw new SessionError("Message authentication failed");
+ }
+}
+
+export interface SecureChannelOptions {
+ /** Session lifetime; after this the node performs a fresh handshake (new keys). Default 6 h. */
+ maxAgeMs?: number;
+}
+
+/**
+ * Directional AEAD channel (ChaCha20-Poly1305). Header bytes are authenticated as AAD, nonces are
+ * `direction | channel | 64-bit counter` and never reused, and a replay window rejects duplicates.
+ *
+ * Control frame: `[KIND.CONTROL][sid 8][counter 8][ciphertext+tag]`
+ * Audio frame: `[KIND.AUDIO_ENCRYPTED][sid 8][counter 8][streamId 4][seq 4][flags 1][ciphertext+tag]`
+ */
+export class SecureChannel {
+ private sendCounter = 0;
+ private audioSendCounter = 0;
+ private readonly controlWindow = new ReplayWindow();
+ private readonly audioWindow = new ReplayWindow(4096);
+ readonly createdAt = Date.now();
+ readonly maxAgeMs: number;
+ private readonly sid: Buffer;
+ private readonly sendDir: number;
+ private readonly recvDir: number;
+ closed = false;
+
+ constructor(
+ readonly sessionId: string,
+ readonly peerId: string,
+ initiator: boolean,
+ private readonly sendKey: Buffer,
+ private readonly recvKey: Buffer,
+ options: SecureChannelOptions = {},
+ ) {
+ this.sid = Buffer.from(sessionId, "hex");
+ this.sendDir = initiator ? 1 : 2;
+ this.recvDir = initiator ? 2 : 1;
+ this.maxAgeMs = options.maxAgeMs ?? 6 * 60 * 60 * 1000;
+ }
+
+ get expired(): boolean {
+ return this.closed || Date.now() - this.createdAt > this.maxAgeMs;
+ }
+
+ seal(plaintext: Buffer): Buffer {
+ if (this.sendCounter >= MAX_COUNTER) throw new SessionError("Session exhausted; re-handshake required");
+ const counter = this.sendCounter++;
+ const header = Buffer.alloc(17);
+ header[0] = KIND.CONTROL;
+ this.sid.copy(header, 1);
+ header.writeBigUInt64BE(BigInt(counter), 9);
+ return Buffer.concat([header, aead(this.sendKey, nonce(this.sendDir, 0, counter), header, plaintext)]);
+ }
+
+ open(frame: Buffer): Buffer {
+ if (frame.length < 17 + TAG || frame[0] !== KIND.CONTROL) throw new SessionError("Malformed control frame");
+ if (!frame.subarray(1, 9).equals(this.sid)) throw new SessionError("Session id mismatch");
+ const counter = Number(frame.readBigUInt64BE(9));
+ const header = frame.subarray(0, 17);
+ const plaintext = unaead(this.recvKey, nonce(this.recvDir, 0, counter), header, frame.subarray(17));
+ // Check the window only AFTER authentication so forged frames cannot burn counters.
+ if (!this.controlWindow.accept(counter)) throw new SessionError("Replayed control frame");
+ return plaintext;
+ }
+
+ sealAudio(streamId: number, seq: number, flags: number, payload: Buffer): Buffer {
+ if (this.audioSendCounter >= MAX_COUNTER) throw new SessionError("Session exhausted; re-handshake required");
+ const counter = this.audioSendCounter++;
+ const header = Buffer.alloc(26);
+ header[0] = KIND.AUDIO_ENCRYPTED;
+ this.sid.copy(header, 1);
+ header.writeBigUInt64BE(BigInt(counter), 9);
+ header.writeUInt32BE(streamId >>> 0, 17);
+ header.writeUInt32BE(seq >>> 0, 21);
+ header[25] = flags & 0xff;
+ return Buffer.concat([header, aead(this.sendKey, nonce(this.sendDir, 1, counter), header, payload)]);
+ }
+
+ openAudio(frame: Buffer): { streamId: number; seq: number; flags: number; payload: Buffer } {
+ if (frame.length < 26 + TAG || frame[0] !== KIND.AUDIO_ENCRYPTED) throw new SessionError("Malformed audio frame");
+ if (!frame.subarray(1, 9).equals(this.sid)) throw new SessionError("Session id mismatch");
+ const counter = Number(frame.readBigUInt64BE(9));
+ const header = frame.subarray(0, 26);
+ const payload = unaead(this.recvKey, nonce(this.recvDir, 1, counter), header, frame.subarray(26));
+ if (!this.audioWindow.accept(counter)) throw new SessionError("Replayed audio frame");
+ return { streamId: header.readUInt32BE(17), seq: header.readUInt32BE(21), flags: header[25], payload };
+ }
+}
diff --git a/net/src/debug.ts b/net/src/debug.ts
new file mode 100644
index 00000000..78f3bf33
--- /dev/null
+++ b/net/src/debug.ts
@@ -0,0 +1,109 @@
+/**
+ * Debug trace of everything a {@link NetNode} puts on (or takes from) the broker.
+ *
+ * `node.on("debug", (event) => ...)` receives {@link NetDebugEvent}s on three layers:
+ *
+ * - `wire`: the exact MQTT message the broker sees: topic, qos, retain, size and the first bytes in hex.
+ * Control frames are ciphertext here, so this is what an attacker with broker access can read.
+ * - `message`: the same traffic one level up, before it is encrypted / after it is decrypted: message type,
+ * request id, and body (sensitive keys redacted). This is "what net sends".
+ * - `info`: free-form notes from routing code (for example which node a search was sent to).
+ */
+export type NetDebugLayer = "wire" | "message" | "info";
+export type NetDebugKind = "presence" | "handshake" | "control" | "audio" | "audio-encrypted" | "unknown";
+
+export interface NetDebugEvent {
+ at: number;
+ /** Node that emitted the event. */
+ node: string;
+ layer: NetDebugLayer;
+ /** `out` = sent by this node, `in` = received, `info` = not a message. */
+ dir: "out" | "in" | "info";
+ kind?: NetDebugKind;
+ /** wire: MQTT topic. */
+ topic?: string;
+ /** The other node, when known (recipient for `out`, sender for decrypted `in` messages). */
+ peer?: string;
+ qos?: number;
+ retain?: boolean;
+ /** Size of the MQTT payload (wire) or of the frame (message). */
+ bytes?: number;
+ /** wire: first bytes of the payload in hex. */
+ hex?: string;
+ /** True when the payload on the wire is ciphertext. */
+ encrypted?: boolean;
+ sessionId?: string;
+ /** message: request/notify type (`net.search`, `voice.event`...), `reply` for replies, `hs1`/`hs2`/`hs3` for handshakes. */
+ type?: string;
+ /** message: request id. */
+ id?: number;
+ /** message: id of the request this replies to. */
+ re?: number;
+ /** message: decoded body (redacted copy). */
+ body?: unknown;
+ /** audio frames. */
+ streamId?: number;
+ seq?: number;
+ flags?: number;
+ /** info: text. */
+ note?: string;
+ /** wire: the publish failed. */
+ error?: string;
+}
+
+const SENSITIVE_KEY = /token|secret|password|passwd|private|session_?id|authorization|cookie/i;
+const MAX_DEPTH = 6;
+const MAX_STRING = 300;
+const MAX_ARRAY = 20;
+
+/** Copy of `value` that is safe to print: sensitive keys hidden, long strings and arrays shortened. */
+export function redact(value: unknown, depth = 0): unknown {
+ if (typeof value === "string")
+ return value.length > MAX_STRING ? `${value.slice(0, MAX_STRING)}…(+${value.length - MAX_STRING} chars)` : value;
+ if (value === null || typeof value !== "object") return typeof value === "bigint" ? value.toString() : value;
+ if (depth >= MAX_DEPTH) return "[…]";
+ if (Array.isArray(value)) {
+ const head = value.slice(0, MAX_ARRAY).map((v) => redact(v, depth + 1));
+ return value.length > MAX_ARRAY ? [...head, `…(+${value.length - MAX_ARRAY} items)`] : head;
+ }
+ const out: Record = {};
+ for (const [key, v] of Object.entries(value as Record)) {
+ out[key] = SENSITIVE_KEY.test(key) ? "[redacted]" : redact(v, depth + 1);
+ }
+ return out;
+}
+
+export function hexPreview(buf: Uint8Array, max = 24): string {
+ const head = Buffer.from(buf.subarray(0, max)).toString("hex");
+ return buf.length > max ? `${head}…` : head;
+}
+
+/** One-line, human readable rendering of a debug event. */
+export function formatNetDebug(e: NetDebugEvent): string {
+ const arrow =
+ e.dir === "out" ? "→"
+ : e.dir === "in" ? "←"
+ : "•";
+ if (e.layer === "info") return `[net:${e.node}] ${arrow} ${e.note ?? ""}`;
+ if (e.layer === "wire") {
+ const flags = `${e.qos !== undefined ? ` qos${e.qos}` : ""}${e.retain ? " retain" : ""}`;
+ const detail =
+ e.body !== undefined ? ` ${JSON.stringify(e.body)}`
+ : e.type ? ` ${e.type}`
+ : "";
+ return (
+ `[net:${e.node}] ${arrow} MQTT ${e.dir === "out" ? "PUBLISH" : "MESSAGE"} ${e.topic}${flags} ${e.bytes}B ` +
+ `${e.kind}${e.encrypted ? "(encrypted)" : ""}${detail}${e.hex ? ` [${e.hex}]` : ""}${e.error ? ` FAILED: ${e.error}` : ""}`
+ );
+ }
+ if (e.kind === "audio" || e.kind === "audio-encrypted") {
+ return `[net:${e.node}] ${arrow} audio ${e.dir === "out" ? "to" : "from"} ${e.peer ?? "?"} stream#${e.streamId} seq ${e.seq} ${e.bytes}B${e.flags ? ` flags ${e.flags}` : ""}`;
+ }
+ const who = e.peer ? ` ${e.dir === "out" ? "to" : "from"} ${e.peer}` : "";
+ const ref =
+ e.re !== undefined ? ` re#${e.re}`
+ : e.id !== undefined ? ` #${e.id}`
+ : "";
+ const body = e.body !== undefined ? ` ${JSON.stringify(e.body)}` : "";
+ return `[net:${e.node}] ${arrow} ${e.kind ?? "msg"}${who} ${e.type ?? ""}${ref}${e.bytes !== undefined ? ` ${e.bytes}B` : ""}${body}`;
+}
diff --git a/net/src/ext/NetExtension.ts b/net/src/ext/NetExtension.ts
new file mode 100644
index 00000000..eb4b8571
--- /dev/null
+++ b/net/src/ext/NetExtension.ts
@@ -0,0 +1,41 @@
+import { BaseExtension, type ExtensionContext, type ExtensionStreamRequest, type Player, type StreamInfo } from "ziplayer";
+import type { ZiNet } from "../ZiNet";
+
+/**
+ * Per-player extension. Supplies streams from another node (`track.metadata.net.owner`) and, when the
+ * player's voice has been delegated, a remote playback handle that drives the executor.
+ */
+export class NetExtension extends BaseExtension {
+ name = "ziplayer-net";
+ version = "0.1.0";
+ player: Player | null;
+
+ constructor(
+ private readonly net: ZiNet,
+ player: Player | null = null,
+ ) {
+ super();
+ this.player = player;
+ }
+
+ active(): boolean {
+ return true;
+ }
+
+ async provideStream(context: ExtensionContext, payload: ExtensionStreamRequest): Promise {
+ const player = (context.player ?? this.player) as Player | null;
+ const track = payload.track;
+ if (!player) return null;
+
+ if (this.net.delegationFor(player.guildId)) {
+ return this.net.buildRemoteStream(player, track) as unknown as StreamInfo | null;
+ }
+
+ const owner = (track.metadata as any)?.net?.owner as string | undefined;
+ if (owner && owner !== this.net.nodeId) {
+ const info = await this.net.openRemoteStream(owner, track, 0, context.signal);
+ return info as unknown as StreamInfo;
+ }
+ return null;
+ }
+}
diff --git a/net/src/index.ts b/net/src/index.ts
new file mode 100644
index 00000000..dd6d1e03
--- /dev/null
+++ b/net/src/index.ts
@@ -0,0 +1,28 @@
+export { NetNode, NetError } from "./NetNode";
+export type { NetNodeOptions, RequestContext, RequestHandler } from "./NetNode";
+export { ZiNet, markTrack } from "./ZiNet";
+export type { ZiNetOptions, DelegateVoiceOptions } from "./ZiNet";
+export { parseSearchQuery, DEFAULT_SEARCH_ALIASES } from "./search";
+export type { NetSearchOptions, NetSearchResult, ServeSearchOptions, WireSearchResult } from "./search";
+export { formatNetDebug, redact } from "./debug";
+export type { NetDebugEvent, NetDebugKind, NetDebugLayer } from "./debug";
+export { NetExtension } from "./ext/NetExtension";
+export { generateIdentity, loadIdentity, loadOrCreateIdentity, fingerprint, TrustStore } from "./crypto/identity";
+export type { NodeIdentity, TrustedPeer, NetRole, GeneratedIdentity } from "./crypto/identity";
+export { HandshakeError, HandshakeInitiator, HandshakeResponder, PROTOCOL_VERSION } from "./crypto/handshake";
+export { SecureChannel, SessionError, ReplayWindow } from "./crypto/session";
+export type { Transport, PublishOptions } from "./transport/Transport";
+export { topicMatches } from "./transport/Transport";
+export { MemoryBroker, MemoryTransport } from "./transport/MemoryTransport";
+export { MqttTransport } from "./transport/MqttTransport";
+export type { MqttTransportOptions } from "./transport/MqttTransport";
+export { StreamProvider, DEFAULT_ALLOWED_STREAM_TYPES } from "./stream/StreamProvider";
+export type { StreamProviderOptions, ProvidedStreamInfo } from "./stream/StreamProvider";
+export { StreamImporter } from "./stream/StreamImporter";
+export type { RemoteStream, StreamImporterOptions } from "./stream/StreamImporter";
+export { RemoteVoiceHub, serializeTrack } from "./voice/RemoteVoice";
+export type { RemoteVoiceChannel } from "./voice/RemoteVoice";
+export { discordJsGateway } from "./voice/Gateway";
+export type { GatewayLike } from "./voice/Gateway";
+export { planRoute } from "./router";
+export type { RoutePlan, RoutePeer, RouteTrack, PlanRouteInput } from "./router";
diff --git a/net/src/protocol/frames.ts b/net/src/protocol/frames.ts
new file mode 100644
index 00000000..5e8c2eff
--- /dev/null
+++ b/net/src/protocol/frames.ts
@@ -0,0 +1,48 @@
+import { KIND } from "../crypto/session";
+
+/** Plain (unencrypted) audio frame: `[KIND.AUDIO][sid 8][streamId 4][seq 4][flags 1][payload]`. */
+export const AUDIO_FLAG_EOS = 0x01;
+export const AUDIO_HEADER_BYTES = 18;
+
+export interface AudioFrame {
+ streamId: number;
+ seq: number;
+ flags: number;
+ payload: Buffer;
+}
+
+export function encodePlainAudio(sessionId: string, frame: AudioFrame): Buffer {
+ const header = Buffer.alloc(AUDIO_HEADER_BYTES);
+ header[0] = KIND.AUDIO;
+ Buffer.from(sessionId, "hex").copy(header, 1);
+ header.writeUInt32BE(frame.streamId >>> 0, 9);
+ header.writeUInt32BE(frame.seq >>> 0, 13);
+ header[17] = frame.flags & 0xff;
+ return Buffer.concat([header, frame.payload]);
+}
+
+export function decodePlainAudio(buf: Buffer): { sessionId: string; frame: AudioFrame } {
+ if (buf.length < AUDIO_HEADER_BYTES || buf[0] !== KIND.AUDIO) throw new Error("Malformed audio frame");
+ return {
+ sessionId: buf.subarray(1, 9).toString("hex"),
+ frame: {
+ streamId: buf.readUInt32BE(9),
+ seq: buf.readUInt32BE(13),
+ flags: buf[17],
+ payload: buf.subarray(AUDIO_HEADER_BYTES),
+ },
+ };
+}
+
+export function sessionIdOf(buf: Buffer): string | null {
+ if (buf.length < 9) return null;
+ return buf.subarray(1, 9).toString("hex");
+}
+
+/** Topic layout. Everything lives under `zi/v1/`. */
+export const topics = {
+ presence: (net: string, node: string) => `zi/v1/${net}/presence/${node}`,
+ presenceAll: (net: string) => `zi/v1/${net}/presence/+`,
+ inbox: (net: string, node: string) => `zi/v1/${net}/node/${node}/in`,
+ audio: (net: string, node: string) => `zi/v1/${net}/node/${node}/au`,
+};
diff --git a/net/src/router.ts b/net/src/router.ts
new file mode 100644
index 00000000..dd300ebb
--- /dev/null
+++ b/net/src/router.ts
@@ -0,0 +1,86 @@
+/**
+ * Route planning: decide, for a batch of tracks, whether to keep the voice here and pull audio from other
+ * nodes ("relay"), or move the voice to the node that can play most of them itself ("handoff").
+ *
+ * Rule of thumb from the design discussion: if most tracks can only be resolved elsewhere (e.g. this node
+ * only has SoundCloud and a 50-song YouTube playlist is added) moving the voice is cheaper than relaying
+ * every packet; if only a few tracks are foreign, relaying them keeps the voice where it is.
+ */
+export interface RoutePeer {
+ id: string;
+ /** Plugin / source names the peer can resolve streams for (e.g. "youtube"). */
+ sources: Iterable;
+ /** Optional load hint (lower is better), used to break ties. */
+ load?: number;
+}
+
+export interface RouteTrack {
+ source?: string;
+}
+
+export interface RoutePlan {
+ mode: "local" | "relay" | "handoff";
+ /** Handoff target. */
+ executor?: string;
+ /** For each track, the node that should resolve its stream. */
+ owners: string[];
+ /** Fraction of tracks this node cannot resolve itself. */
+ foreignShare: number;
+ /** Indices nobody can resolve. */
+ unresolvable: number[];
+}
+
+export interface PlanRouteInput {
+ selfId: string;
+ selfSources: Iterable;
+ peers: RoutePeer[];
+ tracks: RouteTrack[];
+ /** Foreign share at or above which the voice is handed off. Default 0.5. */
+ handoffThreshold?: number;
+}
+
+export function planRoute(input: PlanRouteInput): RoutePlan {
+ const selfSources = new Set(input.selfSources);
+ const peers = input.peers.map((p) => ({ ...p, set: new Set(p.sources) }));
+ const tracks = input.tracks;
+ const canSelf = (t: RouteTrack) => !t.source || selfSources.has(t.source);
+ const canPeer = (p: { set: Set }, t: RouteTrack) => !t.source || p.set.has(t.source);
+
+ const foreign = tracks.map((t, i) => (canSelf(t) ? -1 : i)).filter((i) => i >= 0);
+ const owners = tracks.map(() => input.selfId);
+ const unresolvable: number[] = [];
+ const share = tracks.length ? foreign.length / tracks.length : 0;
+ if (foreign.length === 0) return { mode: "local", owners, foreignShare: 0, unresolvable };
+
+ // Best single node for the foreign tracks (most coverage, then lowest load).
+ const ranked = peers
+ .map((p) => ({ p, covered: foreign.filter((i) => canPeer(p, tracks[i])).length }))
+ .filter((x) => x.covered > 0)
+ .sort((a, b) => b.covered - a.covered || (a.p.load ?? 0) - (b.p.load ?? 0));
+
+ const pickFor = (i: number, preferred?: string): string | null => {
+ const cands = peers.filter((p) => canPeer(p, tracks[i]));
+ if (!cands.length) return null;
+ return (cands.find((p) => p.id === preferred) ?? cands.sort((a, b) => (a.load ?? 0) - (b.load ?? 0))[0]).id;
+ };
+
+ const best = ranked[0];
+ const threshold = input.handoffThreshold ?? 0.5;
+ if (best && share >= threshold) {
+ const executor = best.p.id;
+ tracks.forEach((t, i) => {
+ if (canPeer(best.p, t)) return void (owners[i] = executor);
+ const other = canSelf(t) ? input.selfId : pickFor(i);
+ if (other) owners[i] = other;
+ else unresolvable.push(i);
+ });
+ return { mode: "handoff", executor, owners, foreignShare: share, unresolvable };
+ }
+
+ for (const i of foreign) {
+ const owner = pickFor(i, best?.p.id);
+ if (owner) owners[i] = owner;
+ else unresolvable.push(i);
+ }
+ return { mode: "relay", owners, foreignShare: share, unresolvable };
+}
diff --git a/net/src/search.ts b/net/src/search.ts
new file mode 100644
index 00000000..96129cb4
--- /dev/null
+++ b/net/src/search.ts
@@ -0,0 +1,136 @@
+import { serializeTrack } from "./voice/RemoteVoice";
+
+/** Wire shape of a search result. Tracks are plain JSON; `metadata.net.owner` is set by the receiver, never trusted from the wire. */
+export interface WireSearchResult {
+ tracks: any[];
+ playlist?: { name: string; url?: string; thumbnail?: string } | null;
+ query?: string;
+ source?: string;
+}
+
+export interface NetSearchOptions {
+ /** Forwarded as `requestedBy` of the returned tracks. */
+ requestedBy?: unknown;
+ /** Restrict to one source (plugin name or alias such as `yt`). A `yt:` prefix in the query does the same. */
+ source?: string;
+ /** Only ask these nodes (default: every online, trusted node that serves search). */
+ peers?: string[];
+ /**
+ * Where this node's own plugins come in. `first` (default): try them first, ask the others only when nothing is found.
+ * `last`: ask the others first. `only`: never leave this node. `never`: skip them.
+ */
+ local?: "first" | "last" | "only" | "never";
+ /** `true`: ask every candidate and merge the tracks (de-duplicated). Default `false`: the first non-empty answer wins. */
+ merge?: boolean;
+ /** Max tracks returned (default 10). */
+ limit?: number;
+ timeoutMs?: number;
+ signal?: AbortSignal;
+}
+
+export interface NetSearchResult {
+ tracks: any[];
+ playlist?: { name: string; url?: string; thumbnail?: string } | null;
+ query?: string;
+ source?: string;
+ /** Node whose plugins produced the tracks (this node for local results). With `merge`, the first contributor. */
+ node: string;
+ /** Every node that contributed tracks. */
+ nodes: string[];
+}
+
+export interface ServeSearchOptions {
+ /** Decide per query / caller. Throw or return `false` to refuse. */
+ allow?: (query: string, peerId: string) => boolean | Promise;
+ /** Max tracks sent back per request (default 25). */
+ maxResults?: number;
+ /** Soft cap for the JSON size of one answer, trailing tracks are dropped (default 200 000). */
+ maxResponseBytes?: number;
+}
+
+export const DEFAULT_SEARCH_ALIASES: Record = {
+ yt: "youtube",
+ youtube: "youtube",
+ sc: "soundcloud",
+ soundcloud: "soundcloud",
+ sp: "spotify",
+ spotify: "spotify",
+ tts: "tts",
+};
+
+export const MAX_QUERY_CHARS = 512;
+export const MAX_IMPORTED_TRACKS = 100;
+
+/**
+ * `yt:lofi` → `{ source: "youtube", query: "lofi" }`. The `tts:` prefix stays in the query because the TTS plugin needs it.
+ * Anything without a known prefix (including `https://…`) has no source.
+ */
+export function parseSearchQuery(
+ text: string,
+ aliases: Record = DEFAULT_SEARCH_ALIASES,
+ explicitSource?: string,
+): { source?: string; query: string } {
+ const resolve = (name: string) => aliases[name.toLowerCase()] ?? name.toLowerCase();
+ if (explicitSource) return { source: resolve(explicitSource), query: text.trim() };
+ const m = text.match(/^(\w+):([\s\S]*)$/);
+ const source = m ? aliases[m[1].toLowerCase()] : undefined;
+ if (!m || !source) return { query: text.trim() };
+ return { source, query: source === "tts" ? text.trim() : m[2].trim() };
+}
+
+/** Provider side: turn a plugin SearchResult into something safe and small enough for one control frame. */
+export function toWireResult(result: any, limit: number, maxBytes: number): WireSearchResult {
+ const tracks: any[] = [];
+ let bytes = 0;
+ for (const track of (result?.tracks ?? []).slice(0, limit)) {
+ const wire = serializeTrack(track);
+ if (!wire || typeof wire !== "object") continue;
+ // Whoever asked is the requester; the provider's requester (a Discord user object...) is meaningless over there.
+ delete wire.requestedBy;
+ if (wire.metadata?.net) delete wire.metadata.net;
+ const size = Buffer.byteLength(JSON.stringify(wire));
+ if (tracks.length && bytes + size > maxBytes) break;
+ tracks.push(wire);
+ bytes += size;
+ }
+ const playlist = result?.playlist ? serializeTrack(result.playlist) : null;
+ return { tracks, playlist, query: typeof result?.query === "string" ? result.query : undefined, source: result?.source };
+}
+
+/**
+ * Consumer side: validate what a peer answered and stamp the ONLY owner that matters, the node that answered.
+ * The peer cannot point playback at a different node by writing `metadata.net.owner` itself.
+ */
+export function importWireResult(raw: any, owner: string, requestedBy?: unknown, limit = 10): WireSearchResult {
+ const tracks: any[] = [];
+ if (Array.isArray(raw?.tracks)) {
+ for (const item of raw.tracks.slice(0, Math.min(limit, MAX_IMPORTED_TRACKS))) {
+ if (!item || typeof item !== "object" || Array.isArray(item)) continue;
+ if (item.id === undefined && typeof item.url !== "string") continue;
+ const metadata = item.metadata && typeof item.metadata === "object" && !Array.isArray(item.metadata) ? item.metadata : {};
+ const track = { ...item, metadata: { ...metadata, net: { owner } } };
+ if (requestedBy !== undefined) track.requestedBy = requestedBy;
+ tracks.push(track);
+ }
+ }
+ const p = raw?.playlist;
+ const playlist =
+ p && typeof p === "object" && typeof p.name === "string" ? { name: p.name, url: p.url, thumbnail: p.thumbnail } : null;
+ return {
+ tracks,
+ playlist,
+ query: typeof raw?.query === "string" ? raw.query : undefined,
+ source: typeof raw?.source === "string" ? raw.source : undefined,
+ };
+}
+
+/** Order-preserving de-duplication of tracks that came from the same node with the same id / url. */
+export function dedupeNetTracks(tracks: any[]): any[] {
+ const seen = new Set();
+ return tracks.filter((t) => {
+ const key = `${t?.metadata?.net?.owner ?? ""}|${t?.id ?? ""}|${t?.url ?? ""}`;
+ if (seen.has(key)) return false;
+ seen.add(key);
+ return true;
+ });
+}
diff --git a/net/src/stream/StreamImporter.ts b/net/src/stream/StreamImporter.ts
new file mode 100644
index 00000000..7e65ae71
--- /dev/null
+++ b/net/src/stream/StreamImporter.ts
@@ -0,0 +1,165 @@
+import { Readable } from "node:stream";
+import type { NetNode } from "../NetNode";
+import { DEFAULT_ALLOWED_STREAM_TYPES } from "./StreamProvider";
+import { AUDIO_FLAG_EOS, type AudioFrame } from "../protocol/frames";
+
+export interface RemoteStream {
+ stream: Readable;
+ streamType: string;
+ seekable: boolean;
+ /** Re-open the stream at `positionMs` from the same owner (seek / URL refresh). */
+ recreate: (positionMs: number) => Promise;
+}
+
+export interface StreamImporterOptions {
+ /** Receive buffer in bytes; also the maximum credit outstanding. Default 512 KiB. */
+ bufferBytes?: number;
+ /** Max out-of-order chunks held while waiting for a gap. Default 256. */
+ maxReorder?: number;
+ openTimeoutMs?: number;
+ /** Accepted stream types from peers. Default: compressed audio (Opus containers and `arbitrary`), never raw PCM. */
+ allowedStreamTypes?: string[];
+}
+
+class IncomingStream extends Readable {
+ expected = 0;
+ received = 0;
+ granted: number;
+ readonly pendingChunks = new Map();
+
+ constructor(
+ readonly streamId: number,
+ readonly peerId: string,
+ readonly bufferBytes: number,
+ private readonly grant: (bytes: number) => void,
+ private readonly onDestroy: () => void,
+ ) {
+ super({ highWaterMark: bufferBytes });
+ this.granted = bufferBytes;
+ }
+
+ _read(): void {
+ // Node may call _read() before the consumer has drained its read, so re-check once it has.
+ queueMicrotask(() => this.topUp());
+ }
+
+ /** Every consumption path (flowing mode, async iteration, pipe) calls read(); re-grant credit right after. */
+ read(size?: number): any {
+ const chunk = super.read(size);
+ this.topUp();
+ return chunk;
+ }
+
+ topUp(): void {
+ if (this.destroyed) return;
+ const outstanding = this.granted - this.received;
+ const want = this.bufferBytes - this.readableLength - outstanding;
+ if (want >= this.bufferBytes / 4) {
+ this.granted += want;
+ this.grant(want);
+ }
+ }
+
+ _destroy(error: Error | null, callback: (error?: Error | null) => void): void {
+ this.onDestroy();
+ callback(error);
+ }
+}
+
+/** Consumer side: asks the owner streamInfo node for audio and exposes it as a normal Readable. */
+export class StreamImporter {
+ private readonly streams = new Map();
+ private nextStreamId = 1;
+ private readonly bufferBytes: number;
+ private readonly maxReorder: number;
+
+ constructor(
+ private readonly node: NetNode,
+ private readonly options: StreamImporterOptions = {},
+ ) {
+ this.bufferBytes = options.bufferBytes ?? 512 * 1024;
+ this.maxReorder = options.maxReorder ?? 256;
+ node.on("sessionClose", (peerId: string) => {
+ for (const s of [...this.streams.values()]) if (s.peerId === peerId) s.destroy(new Error(`Session with ${peerId} closed`));
+ });
+ node.handle("stream.error", (body, ctx) => {
+ this.streams
+ .get(`${ctx.from}#${Number(body?.streamId)}`)
+ ?.destroy(new Error(String(body?.message ?? "Remote stream error")));
+ });
+ }
+
+ /** Called by the owner of the audio handler for every frame received. */
+ onFrame(peerId: string, frame: AudioFrame): void {
+ const stream = this.streams.get(`${peerId}#${frame.streamId}`);
+ if (!stream || stream.destroyed) return;
+ if (frame.seq < stream.expected) return; // duplicate
+ if (frame.seq > stream.expected) {
+ if (stream.pendingChunks.size >= this.maxReorder)
+ return void stream.destroy(new Error("Too many out-of-order audio frames"));
+ stream.pendingChunks.set(frame.seq, frame);
+ return;
+ }
+ let next: AudioFrame | undefined = frame;
+ while (next) {
+ stream.expected++;
+ stream.pendingChunks.delete(next.seq);
+ if (next.payload.length) {
+ stream.received += next.payload.length;
+ stream.push(next.payload);
+ }
+ if (next.flags & AUDIO_FLAG_EOS) {
+ stream.push(null);
+ return;
+ }
+ next = stream.pendingChunks.get(stream.expected);
+ }
+ }
+
+ async open(
+ peerId: string,
+ track: unknown,
+ options?: { position?: number; fresh?: boolean; signal?: AbortSignal },
+ ): Promise {
+ const streamId = this.nextStreamId++ >>> 0;
+ const key = `${peerId}#${streamId}`;
+ const incoming = new IncomingStream(
+ streamId,
+ peerId,
+ this.bufferBytes,
+ (bytes) => void this.node.notify(peerId, "stream.credit", { streamId, bytes }).catch(() => {}),
+ () => {
+ if (this.streams.delete(key)) void this.node.notify(peerId, "stream.close", { streamId }).catch(() => {});
+ },
+ );
+ this.streams.set(key, incoming);
+ try {
+ const reply = await this.node.request<{ streamType: string; seekable: boolean; positionApplied: boolean }>(
+ peerId,
+ "stream.open",
+ { streamId, track, position: options?.position ?? 0, fresh: options?.fresh === true, credit: this.bufferBytes },
+ { timeoutMs: this.options.openTimeoutMs ?? 20_000, signal: options?.signal },
+ );
+ const allowed = (this.options.allowedStreamTypes ?? DEFAULT_ALLOWED_STREAM_TYPES).map((t) => t.toLowerCase());
+ if (!allowed.includes(String(reply.streamType).toLowerCase())) {
+ throw new Error(`Peer offered disallowed stream type "${reply.streamType}"`);
+ }
+ if ((options?.position ?? 0) > 0 && !reply.positionApplied) {
+ throw new Error("Stream owner cannot seek this stream");
+ }
+ return {
+ stream: incoming,
+ streamType: reply.streamType,
+ seekable: reply.seekable,
+ recreate: async (positionMs) => (await this.open(peerId, track, { position: positionMs, fresh: true })).stream,
+ };
+ } catch (error) {
+ incoming.destroy();
+ throw error;
+ }
+ }
+
+ closeAll(): void {
+ for (const s of [...this.streams.values()]) s.destroy();
+ }
+}
diff --git a/net/src/stream/StreamProvider.ts b/net/src/stream/StreamProvider.ts
new file mode 100644
index 00000000..5e20db85
--- /dev/null
+++ b/net/src/stream/StreamProvider.ts
@@ -0,0 +1,177 @@
+import { Readable } from "node:stream";
+import type { NetNode } from "../NetNode";
+import { AUDIO_FLAG_EOS } from "../protocol/frames";
+
+/** The subset of ziplayer's `StreamInfo` the provider needs (keeps this module free of a runtime ziplayer dependency). */
+/**
+ * Compressed audio only. Official plugins (YouTube, SoundCloud, TTS...) return `arbitrary` (a compressed container the
+ * receiver demuxes exactly as it would locally), so it is allowed; raw PCM is not. Pass `["webm/opus", "ogg/opus", "opus"]`
+ * to accept Opus containers only.
+ */
+export const DEFAULT_ALLOWED_STREAM_TYPES = ["webm/opus", "ogg/opus", "opus", "arbitrary"];
+
+export interface ProvidedStreamInfo {
+ stream?: Readable;
+ url?: string;
+ streamType?: string;
+ type?: string;
+ recreate?: (position: number) => Promise;
+ remote?: boolean;
+}
+
+export interface StreamProviderOptions {
+ /** Resolve a stream for a track, typically `(track) => manager.resolveStream(track)`. */
+ resolveStream: (track: any, options: { fresh?: boolean }) => Promise;
+ /** Return false to refuse a track (allowlist of sources, etc.). */
+ allow?: (track: any, peerId: string) => boolean | Promise;
+ /** Stream types that may leave this node. Default: compressed audio (Opus containers and `arbitrary`), never raw PCM. */
+ allowedStreamTypes?: string[];
+ chunkBytes?: number;
+ maxStreamsPerPeer?: number;
+ debug?: (message: string, ...args: unknown[]) => void;
+}
+
+interface OpenStream {
+ peerId: string;
+ streamId: number;
+ source: Readable;
+ credit: number;
+ waiter: (() => void) | null;
+ closed: boolean;
+}
+
+/**
+ * Owner-streamInfo side. The node whose plugins resolve the stream keeps the source and pushes encoded
+ * audio (webm/ogg/opus, never PCM) to the requesting node, paced by credit the receiver grants.
+ */
+export class StreamProvider {
+ private readonly open = new Map();
+ private readonly chunkBytes: number;
+ private readonly allowedTypes: Set;
+
+ constructor(
+ private readonly node: NetNode,
+ private readonly options: StreamProviderOptions,
+ ) {
+ this.allowedTypes = new Set((options.allowedStreamTypes ?? DEFAULT_ALLOWED_STREAM_TYPES).map((t) => t.toLowerCase()));
+ this.chunkBytes = Math.max(1024, Math.min(options.chunkBytes ?? 16 * 1024, 256 * 1024));
+ node.handle("stream.open", (body, ctx) => this.onOpen(body, ctx.from), { role: "provide-stream" });
+ node.handle("stream.credit", (body, ctx) => this.onCredit(body, ctx.from), { role: "provide-stream" });
+ node.handle("stream.close", (body, ctx) => this.close(ctx.from, body?.streamId), { role: "provide-stream" });
+ node.on("sessionClose", (peerId: string) => this.closePeer(peerId));
+ }
+
+ private key(peerId: string, streamId: number) {
+ return `${peerId}#${streamId}`;
+ }
+
+ private async onOpen(body: any, from: string) {
+ const streamId = Number(body?.streamId);
+ if (!Number.isInteger(streamId) || streamId < 0 || streamId > 0xffffffff) throw new Error("Invalid streamId");
+ const track = body?.track;
+ if (!track || typeof track !== "object") throw new Error("Missing track");
+ if (this.options.allow && !(await this.options.allow(track, from))) throw new Error("Track refused by provider");
+ const perPeer = [...this.open.values()].filter((s) => s.peerId === from).length;
+ if (perPeer >= (this.options.maxStreamsPerPeer ?? 8)) throw new Error("Too many open streams");
+ if (this.open.has(this.key(from, streamId))) this.close(from, streamId);
+
+ const info = await this.options.resolveStream(track, { fresh: body?.fresh === true });
+ if (!info) throw new Error("No stream available");
+ const streamType = String(info.streamType ?? info.type ?? "arbitrary");
+ if (!this.allowedTypes.has(streamType.toLowerCase())) {
+ info.stream?.destroy();
+ throw new Error(`Stream type "${streamType}" is not transferable (allowed: ${[...this.allowedTypes].join(", ")})`);
+ }
+ const position = Number(body?.position) > 0 ? Number(body.position) : 0;
+ let source: Readable | null = null;
+ if (position > 0 && info.recreate) {
+ info.stream?.destroy();
+ source = await info.recreate(position);
+ } else if (info.stream) {
+ source = info.stream;
+ } else if (info.url) {
+ source = await fetchUrl(info.url);
+ }
+ if (!source) throw new Error("Stream has no readable source");
+
+ const state: OpenStream = {
+ peerId: from,
+ streamId,
+ source,
+ credit: Math.max(0, Number(body?.credit) || 0),
+ waiter: null,
+ closed: false,
+ };
+ this.open.set(this.key(from, streamId), state);
+ // Start pumping after the reply has been queued.
+ setImmediate(() => void this.pump(state));
+ return { streamId, streamType, seekable: Boolean(info.recreate), positionApplied: position > 0 && Boolean(info.recreate) };
+ }
+
+ private onCredit(body: any, from: string) {
+ const state = this.open.get(this.key(from, Number(body?.streamId)));
+ if (!state) return;
+ state.credit += Math.max(0, Number(body?.bytes) || 0);
+ state.waiter?.();
+ }
+
+ private async pump(state: OpenStream): Promise {
+ let seq = 0;
+ try {
+ for await (const chunk of state.source as AsyncIterable) {
+ const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
+ for (let offset = 0; offset < buf.length; offset += this.chunkBytes) {
+ const part = buf.subarray(offset, offset + this.chunkBytes);
+ while (state.credit < part.length && !state.closed) {
+ await new Promise((resolve) => (state.waiter = resolve));
+ state.waiter = null;
+ }
+ if (state.closed) return;
+ state.credit -= part.length;
+ await this.node.sendAudio(state.peerId, { streamId: state.streamId, seq: seq++, flags: 0, payload: part });
+ }
+ }
+ if (!state.closed) {
+ await this.node.sendAudio(state.peerId, {
+ streamId: state.streamId,
+ seq: seq++,
+ flags: AUDIO_FLAG_EOS,
+ payload: Buffer.alloc(0),
+ });
+ }
+ } catch (error) {
+ if (!state.closed) {
+ this.options.debug?.(`stream ${state.streamId} failed: ${(error as Error).message}`);
+ this.node
+ .notify(state.peerId, "stream.error", { streamId: state.streamId, message: (error as Error).message })
+ .catch(() => {});
+ }
+ } finally {
+ this.close(state.peerId, state.streamId);
+ }
+ }
+
+ close(peerId: string, streamId: number): void {
+ const k = this.key(peerId, Number(streamId));
+ const state = this.open.get(k);
+ if (!state) return;
+ state.closed = true;
+ this.open.delete(k);
+ state.waiter?.();
+ state.source.destroy();
+ }
+
+ closePeer(peerId: string): void {
+ for (const s of [...this.open.values()]) if (s.peerId === peerId) this.close(peerId, s.streamId);
+ }
+
+ closeAll(): void {
+ for (const s of [...this.open.values()]) this.close(s.peerId, s.streamId);
+ }
+}
+
+async function fetchUrl(url: string): Promise {
+ const res = await fetch(url);
+ if (!res.ok || !res.body) throw new Error(`Upstream returned ${res.status}`);
+ return Readable.fromWeb(res.body as any);
+}
diff --git a/net/src/transport/MemoryTransport.ts b/net/src/transport/MemoryTransport.ts
new file mode 100644
index 00000000..7ced6676
--- /dev/null
+++ b/net/src/transport/MemoryTransport.ts
@@ -0,0 +1,83 @@
+import { topicMatches, type MessageHandler, type PublishOptions, type Transport } from "./Transport";
+
+interface Subscription {
+ client: MemoryTransport;
+ filter: string;
+ handler: MessageHandler;
+}
+
+/** In-process broker for tests and single-process setups. Mimics retained messages and last-will. */
+export class MemoryBroker {
+ readonly subscriptions = new Set();
+ readonly retained = new Map();
+ /** Messages delivered, so tests can assert what an untrusted broker would see. */
+ readonly log: Array<{ topic: string; payload: Uint8Array }> = [];
+ /** Optional tamper hook: return null to drop, or a replacement payload. */
+ intercept?: (topic: string, payload: Uint8Array) => Uint8Array | null;
+
+ deliver(topic: string, payload: Uint8Array, options?: PublishOptions): void {
+ const out = this.intercept ? this.intercept(topic, payload) : payload;
+ if (!out) return;
+ this.log.push({ topic, payload: out });
+ if (options?.retain) {
+ if (out.length === 0) this.retained.delete(topic);
+ else this.retained.set(topic, out);
+ }
+ for (const sub of [...this.subscriptions]) {
+ if (topicMatches(sub.filter, topic)) queueMicrotask(() => sub.handler(topic, out));
+ }
+ }
+
+ transport(): MemoryTransport {
+ return new MemoryTransport(this);
+ }
+}
+
+export class MemoryTransport implements Transport {
+ private will?: { topic: string; payload: Uint8Array; options?: PublishOptions };
+ private connected = false;
+ private readonly owned = new Set();
+
+ constructor(private readonly broker: MemoryBroker) {}
+
+ setLastWill(topic: string, payload: Uint8Array, options?: PublishOptions): void {
+ this.will = { topic, payload, options };
+ }
+
+ async connect(): Promise {
+ this.connected = true;
+ }
+
+ /** Graceful close: the last will is NOT published. */
+ async close(): Promise {
+ this.connected = false;
+ for (const sub of this.owned) this.broker.subscriptions.delete(sub);
+ this.owned.clear();
+ }
+
+ /** Simulates a crash: drops subscriptions and publishes the last will. */
+ async kill(): Promise {
+ const will = this.will;
+ await this.close();
+ if (will) this.broker.deliver(will.topic, will.payload, will.options);
+ }
+
+ async publish(topic: string, payload: Uint8Array, options?: PublishOptions): Promise {
+ if (!this.connected) throw new Error("MemoryTransport is not connected");
+ this.broker.deliver(topic, payload, options);
+ }
+
+ async subscribe(filter: string, handler: MessageHandler): Promise<() => void> {
+ if (!this.connected) throw new Error("MemoryTransport is not connected");
+ const sub: Subscription = { client: this, filter, handler };
+ this.broker.subscriptions.add(sub);
+ this.owned.add(sub);
+ for (const [topic, payload] of this.broker.retained) {
+ if (topicMatches(filter, topic)) queueMicrotask(() => handler(topic, payload));
+ }
+ return () => {
+ this.broker.subscriptions.delete(sub);
+ this.owned.delete(sub);
+ };
+ }
+}
diff --git a/net/src/transport/MqttTransport.ts b/net/src/transport/MqttTransport.ts
new file mode 100644
index 00000000..63f2af97
--- /dev/null
+++ b/net/src/transport/MqttTransport.ts
@@ -0,0 +1,117 @@
+import { topicMatches, type MessageHandler, type PublishOptions, type Transport } from "./Transport";
+
+export interface MqttTransportOptions {
+ /** e.g. `mqtts://broker.example.com:8883`. Use TLS: node ids and message sizes are visible otherwise. */
+ url: string;
+ username?: string;
+ password?: string;
+ clientId?: string;
+ /** Extra options passed straight to `mqtt.connect` (TLS certs, keepalive...). */
+ connectOptions?: Record;
+ connectTimeoutMs?: number;
+ /** MQTT protocol level. Default 5; use 4 (3.1.1) for brokers without v5 support. Nothing here depends on v5-only features. */
+ protocolVersion?: 3 | 4 | 5;
+}
+
+/** MQTT v5 transport. Requires the optional peer dependency `mqtt`. */
+export class MqttTransport implements Transport {
+ private client: any = null;
+ private will?: { topic: string; payload: Uint8Array; options?: PublishOptions };
+ private readonly handlers = new Map>();
+
+ constructor(private readonly options: MqttTransportOptions) {}
+
+ setLastWill(topic: string, payload: Uint8Array, options?: PublishOptions): void {
+ this.will = { topic, payload, options };
+ }
+
+ async connect(): Promise {
+ let mqtt: any;
+ try {
+ mqtt = require("mqtt");
+ } catch {
+ throw new Error('MqttTransport requires the "mqtt" package: npm install mqtt');
+ }
+ const opts: Record = {
+ protocolVersion: this.options.protocolVersion ?? 5,
+ clean: true,
+ reconnectPeriod: 2000,
+ username: this.options.username,
+ password: this.options.password,
+ clientId: this.options.clientId,
+ ...this.options.connectOptions,
+ };
+ if (this.will) {
+ opts.will = {
+ topic: this.will.topic,
+ payload: Buffer.from(this.will.payload),
+ qos: this.will.options?.qos ?? 1,
+ retain: this.will.options?.retain ?? false,
+ };
+ }
+ const client = mqtt.connect(this.options.url, opts);
+ this.client = client;
+ client.on("message", (topic: string, payload: Buffer) => {
+ for (const [filter, set] of this.handlers) {
+ if (!topicMatches(filter, topic)) continue;
+ for (const handler of set) handler(topic, payload);
+ }
+ });
+ await new Promise((resolve, reject) => {
+ const timer = setTimeout(() => reject(new Error("MQTT connect timed out")), this.options.connectTimeoutMs ?? 10_000);
+ client.once("connect", () => {
+ clearTimeout(timer);
+ resolve();
+ });
+ client.once("error", (error: Error) => {
+ clearTimeout(timer);
+ reject(error);
+ });
+ });
+ // Clean sessions drop subscriptions on reconnect, so subscribe again.
+ client.on("connect", () => {
+ for (const filter of this.handlers.keys()) client.subscribe(filter, { qos: 1 });
+ });
+ }
+
+ async close(): Promise {
+ const client = this.client;
+ this.client = null;
+ this.handlers.clear();
+ if (client) await new Promise((resolve) => client.end(false, {}, () => resolve()));
+ }
+
+ publish(topic: string, payload: Uint8Array, options?: PublishOptions): Promise {
+ const client = this.client;
+ if (!client) return Promise.reject(new Error("MqttTransport is not connected"));
+ return new Promise((resolve, reject) =>
+ client.publish(
+ topic,
+ Buffer.from(payload),
+ { qos: options?.qos ?? 1, retain: options?.retain ?? false },
+ (error?: Error) => (error ? reject(error) : resolve()),
+ ),
+ );
+ }
+
+ async subscribe(filter: string, handler: MessageHandler): Promise<() => void> {
+ const client = this.client;
+ if (!client) throw new Error("MqttTransport is not connected");
+ let set = this.handlers.get(filter);
+ const first = !set;
+ if (!set) this.handlers.set(filter, (set = new Set()));
+ set.add(handler);
+ if (first) {
+ await new Promise((resolve, reject) =>
+ client.subscribe(filter, { qos: 1 }, (error?: Error) => (error ? reject(error) : resolve())),
+ );
+ }
+ return () => {
+ set!.delete(handler);
+ if (set!.size === 0) {
+ this.handlers.delete(filter);
+ this.client?.unsubscribe(filter);
+ }
+ };
+ }
+}
diff --git a/net/src/transport/Transport.ts b/net/src/transport/Transport.ts
new file mode 100644
index 00000000..1f0168f6
--- /dev/null
+++ b/net/src/transport/Transport.ts
@@ -0,0 +1,33 @@
+export interface PublishOptions {
+ qos?: 0 | 1 | 2;
+ retain?: boolean;
+}
+
+export type MessageHandler = (topic: string, payload: Uint8Array) => void;
+
+/**
+ * Minimal pub/sub transport used by {@link NetNode}. MQTT is the first implementation; any other
+ * carrier (WebSocket, TCP, NATS...) only has to implement this interface, because encryption and
+ * authentication live above it.
+ */
+export interface Transport {
+ /** Registers a last-will message, published by the broker if this client disappears. Call before `connect()`. */
+ setLastWill?(topic: string, payload: Uint8Array, options?: PublishOptions): void;
+ connect(): Promise;
+ close(): Promise;
+ publish(topic: string, payload: Uint8Array, options?: PublishOptions): Promise;
+ /** Subscribes to a topic filter (`+` and `#` wildcards allowed). Returns an unsubscribe function. */
+ subscribe(filter: string, handler: MessageHandler): Promise<() => void>;
+}
+
+/** MQTT-style topic filter matching (`+` single level, `#` multi level). */
+export function topicMatches(filter: string, topic: string): boolean {
+ const f = filter.split("/");
+ const t = topic.split("/");
+ for (let i = 0; i < f.length; i++) {
+ if (f[i] === "#") return true;
+ if (i >= t.length) return false;
+ if (f[i] !== "+" && f[i] !== t[i]) return false;
+ }
+ return f.length === t.length;
+}
diff --git a/net/src/voice/Gateway.ts b/net/src/voice/Gateway.ts
new file mode 100644
index 00000000..8526ac58
--- /dev/null
+++ b/net/src/voice/Gateway.ts
@@ -0,0 +1,52 @@
+/**
+ * What the node that owns the Discord gateway connection must provide. The owner receives the
+ * bot's VOICE_STATE_UPDATE / VOICE_SERVER_UPDATE and relays them to the node that does the audio.
+ */
+export interface GatewayLike {
+ /** The bot's user id. */
+ userId: string;
+ /** Subscribes to the bot's voice events. `data` is the inner `d` of the gateway payload. */
+ onVoiceUpdate(listener: (guildId: string, kind: "state" | "server", data: any) => void): () => void;
+ /** Sends a raw gateway payload (only op 4 is ever relayed) on the right shard. */
+ send(guildId: string, payload: unknown): void;
+ /** Optional: resolve a channel object so the owner can reconnect locally on reclaim/failure. */
+ resolveChannel?(guildId: string, channelId: string): any;
+}
+
+/** Gateway adapter for a discord.js v14 `Client`. */
+export function discordJsGateway(client: any): GatewayLike {
+ const voiceServers = new Map();
+ client.on("raw", (packet: any) => {
+ if (packet?.t === "VOICE_SERVER_UPDATE" && packet.d?.guild_id) {
+ voiceServers.set(String(packet.d.guild_id), packet.d);
+ }
+ });
+
+ return {
+ get userId() {
+ return client.user?.id as string;
+ },
+ onVoiceUpdate(listener) {
+ const handler = (packet: any) => {
+ if (!packet?.d) return;
+ if (packet.t === "VOICE_STATE_UPDATE" && packet.d.user_id === client.user?.id) {
+ listener(String(packet.d.guild_id), "state", packet.d);
+ } else if (packet.t === "VOICE_SERVER_UPDATE") {
+ listener(String(packet.d.guild_id), "server", packet.d);
+ }
+ };
+ client.on("raw", handler);
+ // A hand-off may begin after the owner's initial join already delivered this gateway event.
+ for (const [guildId, data] of voiceServers) listener(guildId, "server", data);
+ return () => client.off("raw", handler);
+ },
+ send(guildId, payload) {
+ const guild = client.guilds.cache.get(guildId);
+ if (!guild) throw new Error(`Guild ${guildId} not cached`);
+ guild.shard.send(payload);
+ },
+ resolveChannel(_guildId, channelId) {
+ return client.channels.cache.get(channelId);
+ },
+ };
+}
diff --git a/net/src/voice/RemoteVoice.ts b/net/src/voice/RemoteVoice.ts
new file mode 100644
index 00000000..0ea86015
--- /dev/null
+++ b/net/src/voice/RemoteVoice.ts
@@ -0,0 +1,106 @@
+import type { NetNode } from "../NetNode";
+
+export interface RemoteVoiceChannel {
+ id: string;
+ guildId: string;
+ type: 2;
+ guild: { id: string; voiceAdapterCreator: (methods: any) => any };
+}
+
+interface Registered {
+ methods: any;
+ owner: string;
+ hasState: boolean;
+ server?: any;
+}
+
+/**
+ * Executor side of a voice hand-off. Builds a fake guild voice channel whose gateway adapter talks to the
+ * owner over the network, so `player.connect(channel)` runs the normal @discordjs/voice machinery
+ * (UDP, encryption, DAVE) on this node while the owner keeps the real Discord gateway.
+ */
+export class RemoteVoiceHub {
+ private readonly adapters = new Map();
+ private readonly early = new Map>();
+
+ constructor(private readonly node: NetNode) {}
+
+ createChannel(guildId: string, channelId: string, ownerId: string): RemoteVoiceChannel {
+ const adapterCreator = (methods: any) => {
+ const registration: Registered = { methods, owner: ownerId, hasState: false };
+ this.adapters.set(guildId, registration);
+ const early = this.early.get(guildId) ?? [];
+ this.early.delete(guildId);
+ queueMicrotask(() => {
+ if (this.adapters.get(guildId) !== registration) return;
+ for (const e of early) {
+ if (e.from === ownerId) this.deliverEvent(registration, e.kind, e.data);
+ }
+ });
+ return {
+ sendPayload: (payload: unknown) => {
+ this.node.notify(ownerId, "voice.payload", { guildId, payload }).catch(() => {});
+ return true;
+ },
+ destroy: () => {
+ if (this.adapters.get(guildId)?.methods === methods) this.adapters.delete(guildId);
+ },
+ };
+ };
+ return { id: channelId, guildId, type: 2, guild: { id: guildId, voiceAdapterCreator: adapterCreator } };
+ }
+
+ /** Feed a voice event relayed from the owner. Events arriving before the adapter exists are queued. */
+ feed(guildId: string, from: string, kind: "state" | "server", data: any): void {
+ const reg = this.adapters.get(guildId);
+ if (reg) {
+ if (reg.owner !== from) return;
+ return this.deliverEvent(reg, kind, data);
+ }
+ const q = this.early.get(guildId) ?? [];
+ if (q.length < 8) q.push({ from, kind, data });
+ this.early.set(guildId, q);
+ }
+
+ owns(guildId: string): boolean {
+ return this.adapters.has(guildId);
+ }
+
+ forget(guildId: string): void {
+ this.adapters.delete(guildId);
+ this.early.delete(guildId);
+ }
+
+ private deliver(methods: any, kind: "state" | "server", data: any) {
+ if (kind === "state") methods.onVoiceStateUpdate(data);
+ else methods.onVoiceServerUpdate(data);
+ }
+
+ private deliverEvent(reg: Registered, kind: "state" | "server", data: any) {
+ if (kind === "server") {
+ reg.server = data;
+ if (reg.hasState) this.deliver(reg.methods, kind, data);
+ return;
+ }
+
+ this.deliver(reg.methods, kind, data);
+ if (!reg.hasState && reg.server) this.deliver(reg.methods, "server", reg.server);
+ reg.hasState = true;
+ }
+}
+
+/** JSON-safe copy of a track (drops streams, functions and circular references such as Discord user objects). */
+export function serializeTrack(track: any): any {
+ const seen = new WeakSet();
+ return JSON.parse(
+ JSON.stringify(track, (_key, value) => {
+ if (typeof value === "function") return undefined;
+ if (value && typeof value === "object") {
+ if (seen.has(value)) return undefined;
+ seen.add(value);
+ if (typeof (value as any).pipe === "function") return undefined;
+ }
+ return typeof value === "bigint" ? value.toString() : value;
+ }),
+ );
+}
diff --git a/net/tsconfig.json b/net/tsconfig.json
new file mode 100644
index 00000000..3c008e98
--- /dev/null
+++ b/net/tsconfig.json
@@ -0,0 +1,17 @@
+{
+ "compilerOptions": {
+ "target": "ES2022",
+ "module": "commonjs",
+ "lib": ["ES2022"],
+ "outDir": "./dist",
+ "rootDir": "./src",
+ "strict": true,
+ "esModuleInterop": true,
+ "skipLibCheck": true,
+ "forceConsistentCasingInFileNames": true,
+ "declaration": true,
+ "sourceMap": true
+ },
+ "include": ["src/**/*"],
+ "exclude": ["node_modules", "dist"]
+}
diff --git a/package.json b/package.json
index c4cb6b64..49b89ac9 100644
--- a/package.json
+++ b/package.json
@@ -2,8 +2,12 @@
"name": "ziplayer-dev-root",
"private": true,
"scripts": {
- "build:core": "npm run build --prefix core",
+ "build:core": "npm install --prefix core && npm run build --prefix core",
"build:core:fast": "npm run build:fast --prefix core",
+ "build:plugins": "npm install --prefix plugins && npm run build --prefix plugins",
+ "build:extensions": "npm install --prefix extensions && npm run build --prefix extensions",
+ "build:net": "npm install --prefix net && npm run build --prefix net",
+ "setup": "npm run build:core && npm run build:plugins && npm run build:extensions && npm run build:net",
"pretest": "node scripts/ensure-core-build.js",
"test": "node --test --test-concurrency=4 tests/*.test.js",
"test:integration": "node --test tests/plugins/*.test.js tests/extensions/*.test.js",
diff --git a/page/pages/docs/player.tsx b/page/pages/docs/player.tsx
index 9a87d6f4..0b7193b9 100644
--- a/page/pages/docs/player.tsx
+++ b/page/pages/docs/player.tsx
@@ -15,11 +15,11 @@ const manager = new PlayerManager({
new YouTubePlugin(),
new SpotifyPlugin()
],
- // Cấu hình tùy chọn
- defaultVolume: 50,
- maxQueueSize: 100,
- leaveOnEmpty: true,
- leaveOnEmptyCooldown: 30000,
+ // Cấu hình manager
+ extractorTimeout: 50000,
+ autoCleanup: true,
+ cleanupInterval: 60000,
+ enableSearchCache: true,
});`;
const createPlayerCode = `const player = await manager.create(guildId, {
@@ -31,12 +31,9 @@ const createPlayerCode = `const player = await manager.create(guildId, {
guild: guild
},
extensions: ["voiceExt"],
- // Cấu hình queue
- queue: {
- autoPlay: false,
- shuffle: false,
- repeat: "off"
- }
+ volume: 80,
+ leaveOnEmpty: true,
+ leaveTimeout: 100000
});`;
const playerMethodsCode = `// Kết nối voice channel
@@ -78,19 +75,19 @@ player.destroy();
// Cần tạo player mới nếu muốn phát nhạc lại`;
const eventsCode = `// Lắng nghe events
-player.on("trackStart", (player, track) => {
+player.on("trackStart", (track) => {
console.log("Bắt đầu phát:", track.title);
});
-player.on("trackEnd", (player, track) => {
+player.on("trackEnd", (track) => {
console.log("Kết thúc:", track.title);
});
-player.on("queueEnd", (player) => {
+player.on("queueEnd", () => {
console.log("Hết queue, tự động thoát...");
});
-player.on("error", (player, error) => {
+player.on("playerError", (error, track) => {
console.error("Lỗi player:", error);
});
diff --git a/page/scripts/generateApiContent.js b/page/scripts/generateApiContent.js
index 8ed20842..27744cd9 100644
--- a/page/scripts/generateApiContent.js
+++ b/page/scripts/generateApiContent.js
@@ -13,7 +13,7 @@ const { ReflectionKind } = require("typedoc");
const EXPORT_ROOTS = [
{ name: "core", entry: path.join(repoDir, "core", "src", "index.ts") },
{ name: "plugins", entry: path.join(repoDir, "plugins", "src", "index.ts") },
- { name: "extensions", entry: path.join(repoDir, "extension", "src", "index.ts") },
+ { name: "extensions", entry: path.join(repoDir, "extensions", "src", "index.ts") },
];
const KIND_NAME_BY_VALUE = {
@@ -185,7 +185,7 @@ function sourceFilesOfSymbol(symbol, checker) {
function createExportProgram() {
const sourceFiles = [];
- for (const directory of ["core/src", "plugins/src", "extension/src"]) {
+ for (const directory of ["core/src", "plugins/src", "extensions/src"]) {
const absoluteDirectory = path.join(repoDir, directory);
if (fs.existsSync(absoluteDirectory)) {
sourceFiles.push(...ts.sys.readDirectory(absoluteDirectory, [".ts", ".tsx"], undefined, undefined, undefined));
diff --git a/plugins/package.json b/plugins/package.json
index 26d78b77..516749e9 100644
--- a/plugins/package.json
+++ b/plugins/package.json
@@ -1,6 +1,6 @@
{
"name": "@ziplayer/plugin",
- "version": "1.0.2-dev.4",
+ "version": "1.0.3",
"description": "A modular Discord voice player with plugin system",
"keywords": [
"ZiPlayer",
@@ -38,19 +38,19 @@
"axios": "^1.19.0",
"bgutils-js": "^4.0.3",
"file-type": "^22.0.1",
- "googlevideo": "^4.1.1",
+ "googlevideo": "^5.0.1",
"jsdom": "^28.1.0",
"mime-types": "^3.0.2",
"music-metadata": "^11.12.3",
"spotify-url-info": "^3.3.0",
- "youtubei.js": "^18.0.0",
- "ziplayer": "^1.0.5-dev.5"
+ "youtubei.js": "^18.3.0",
+ "ziplayer": "^1.0.5"
},
"devDependencies": {
"@types/jsdom": "^27.0.0",
"@types/mime-types": "^3.0.1",
"@types/node": "^20.19.43",
- "typescript": "^5.0.0"
+ "typescript": "^5.9.3"
},
"allowScripts": {
"ffmpeg-static": true
diff --git a/plugins/src/BilibiliPlugin.ts b/plugins/src/BilibiliPlugin.ts
new file mode 100644
index 00000000..3d2834c2
--- /dev/null
+++ b/plugins/src/BilibiliPlugin.ts
@@ -0,0 +1,1015 @@
+/**
+ * @file BilibiliPlugin.ts
+ * @source https://github.com/ScottSloan/Bili23-Downloader
+ * @description Bilibili source plugin for ZiPlayer.
+ * @note Browser emulation and ExClimbWuzhi/WBI logic are adapted from Bili23-Downloader and ported to the ZiPlayer plugin architecture.
+ */
+import { createHash, createHmac } from "node:crypto";
+import type { Readable } from "node:stream";
+import axios, { AxiosRequestConfig } from "axios";
+import { BasePlugin } from "ziplayer";
+import type { Track, SearchResult, StreamInfo, RelatedTracksOptions } from "ziplayer";
+
+type Requester = Track["requestedBy"]; // string | object
+
+/* -------------------------------------------------------------------------- */
+/* Options */
+/* -------------------------------------------------------------------------- */
+
+export interface BilibiliPluginOptions {
+ /** Optional Bilibili account SESSDATA cookie. Required for restricted videos / higher quality. */
+ sessdata?: string;
+ /** Preferred audio quality. Defaults to `super` (highest available). */
+ quality?: "low" | "standard" | "high" | "super";
+ /** Allows fetching Hi-Res audio (FLAC / Dolby) when available (usually requires VIP SESSDATA). Defaults to false. */
+ preferHiRes?: boolean;
+ /** Multi-part videos (P1, P2, ...) are returned as a playlist. Defaults to true. */
+ multiPartAsPlaylist?: boolean;
+ /** Maximum track count for extractPlaylist (favorites / UP channel). Defaults to 100. */
+ maxPlaylistItems?: number;
+ /** Request timeout (ms). Defaults to 15000. */
+ timeout?: number;
+}
+
+/* -------------------------------------------------------------------------- */
+/* Constants & helpers */
+/* -------------------------------------------------------------------------- */
+
+const UA =
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/147.0.0.0 Safari/537.36 Edg/147.0.0.0";
+
+const SEARCH_PAGE_SIZE = 20;
+const BVID_RE = /BV[0-9A-Za-z]{10}/;
+const AID_RE = /(?:^|[^a-z])av(\d+)/i;
+
+/** Only allow media downloads from Bilibili CDNs (mitigates SSRF because the plugin uses URLs returned by the API). */
+const MEDIA_HOST_RE = /(^|\.)(bilivideo\.(com|cn)|hdslb\.com|akamaized\.net)$/i;
+
+const MIXIN_KEY_TAB = [
+ 46, 47, 18, 2, 53, 8, 23, 32, 15, 50, 10, 31, 58, 3, 45, 35, 27, 43, 5, 49, 33, 9, 42, 19, 29, 28, 14, 39, 12, 38, 41, 13, 37,
+ 48, 7, 16, 24, 55, 40, 61, 26, 17, 0, 1, 60, 51, 30, 4, 22, 25, 54, 21, 56, 59, 6, 63, 57, 62, 11, 36, 20, 34, 44, 52,
+];
+
+/**
+ * Payload template for "ExClimbWuzhi" used to activate buvid3 (adapted from Bili23-Downloader).
+ * Without this activation step, several APIs (playurl, view...) return 412 / -352.
+ */
+const EXCLIMBWUZHI_TEMPLATE: Record = {
+ "3064": 1,
+ "5062": "1",
+ "03bf": "https%3A%2F%2Fwww.bilibili.com%2F",
+ "39c8": "333.1007.fp.risk",
+ "34f1": "",
+ d402: "",
+ "654a": "",
+ "6e7c": "1699x794",
+ "3c43": {
+ "2673": 0,
+ "5766": 32,
+ "6527": 0,
+ "7003": 1,
+ "807e": 1,
+ b8ce: "__UA__",
+ "641c": 0,
+ "07a4": "zh-CN",
+ "1c57": 32,
+ "0bd0": 20,
+ "748e": [960, 1707],
+ d61f: [912, 1707],
+ fc9d: -480,
+ "6aa9": "Asia/Shanghai",
+ "75b8": 1,
+ "3b21": 1,
+ "8a1c": 0,
+ d52f: "not available",
+ adca: "Win32",
+ "80c9": [
+ [
+ "PDF Viewer",
+ "Portable Document Format",
+ [
+ ["application/pdf", "pdf"],
+ ["text/pdf", "pdf"],
+ ],
+ ],
+ [
+ "Chrome PDF Viewer",
+ "Portable Document Format",
+ [
+ ["application/pdf", "pdf"],
+ ["text/pdf", "pdf"],
+ ],
+ ],
+ [
+ "Chromium PDF Viewer",
+ "Portable Document Format",
+ [
+ ["application/pdf", "pdf"],
+ ["text/pdf", "pdf"],
+ ],
+ ],
+ [
+ "Microsoft Edge PDF Viewer",
+ "Portable Document Format",
+ [
+ ["application/pdf", "pdf"],
+ ["text/pdf", "pdf"],
+ ],
+ ],
+ [
+ "WebKit built-in PDF",
+ "Portable Document Format",
+ [
+ ["application/pdf", "pdf"],
+ ["text/pdf", "pdf"],
+ ],
+ ],
+ ],
+ "13ab": "EPQAAAAASUVORK5CYII=",
+ bfe9: "//TgNIfAAAAAZJREFUAwBde+3wgcxEHQAAAABJRU5ErkJggg==",
+ a3c1: [
+ "extensions:ANGLE_instanced_arrays;EXT_blend_minmax;EXT_clip_control;EXT_color_buffer_half_float;EXT_depth_clamp;EXT_disjoint_timer_query;EXT_float_blend;EXT_frag_depth;EXT_polygon_offset_clamp;EXT_shader_texture_lod;EXT_texture_compression_bptc;EXT_texture_compression_rgtc;EXT_texture_filter_anisotropic;EXT_texture_mirror_clamp_to_edge;EXT_sRGB;KHR_parallel_shader_compile;OES_element_index_uint;OES_fbo_render_mipmap;OES_standard_derivatives;OES_texture_float;OES_texture_float_linear;OES_texture_half_float;OES_texture_half_float_linear;OES_vertex_array_object;WEBGL_blend_func_extended;WEBGL_color_buffer_float;WEBGL_compressed_texture_s3tc;WEBGL_compressed_texture_s3tc_srgb;WEBGL_debug_renderer_info;WEBGL_debug_shaders;WEBGL_depth_texture;WEBGL_draw_buffers;WEBGL_lose_context;WEBGL_multi_draw;WEBGL_polygon_mode",
+ "webgl aliased line width range:[1, 1]",
+ "webgl aliased point size range:[1, 1024]",
+ "webgl alpha bits:8",
+ "webgl antialiasing:yes",
+ "webgl blue bits:8",
+ "webgl depth bits:24",
+ "webgl green bits:8",
+ "webgl max anisotropy:16",
+ "webgl max combined texture image units:32",
+ "webgl max cube map texture size:16384",
+ "webgl max fragment uniform vectors:1024",
+ "webgl max render buffer size:16384",
+ "webgl max texture image units:16",
+ "webgl max texture size:16384",
+ "webgl max varying vectors:30",
+ "webgl max vertex attribs:16",
+ "webgl max vertex texture image units:16",
+ "webgl max vertex uniform vectors:4095",
+ "webgl max viewport dims:[32767, 32767]",
+ "webgl red bits:8",
+ "webgl renderer:WebKit WebGL",
+ "webgl shading language version:WebGL GLSL ES 1.0 (OpenGL ES GLSL ES 1.0 Chromium)",
+ "webgl stencil bits:0",
+ "webgl vendor:WebKit",
+ "webgl version:WebGL 1.0 (OpenGL ES 2.0 Chromium)",
+ "webgl unmasked vendor:Google Inc. (NVIDIA)",
+ "webgl unmasked renderer:ANGLE (NVIDIA, NVIDIA GeForce RTX 4060 Laptop GPU (0x000028E0) Direct3D11 vs_5_0 ps_5_0, D3D11)",
+ "webgl vertex shader high float precision:23",
+ "webgl vertex shader high float precision rangeMin:127",
+ "webgl vertex shader high float precision rangeMax:127",
+ "webgl vertex shader medium float precision:23",
+ "webgl vertex shader medium float precision rangeMin:127",
+ "webgl vertex shader medium float precision rangeMax:127",
+ "webgl vertex shader low float precision:23",
+ "webgl vertex shader low float precision rangeMin:127",
+ "webgl vertex shader low float precision rangeMax:127",
+ "webgl fragment shader high float precision:23",
+ "webgl fragment shader high float precision rangeMin:127",
+ "webgl fragment shader high float precision rangeMax:127",
+ "webgl fragment shader medium float precision:23",
+ "webgl fragment shader medium float precision rangeMin:127",
+ "webgl fragment shader medium float precision rangeMax:127",
+ "webgl fragment shader low float precision:23",
+ "webgl fragment shader low float precision rangeMin:127",
+ "webgl fragment shader low float precision rangeMax:127",
+ "webgl vertex shader high int precision:0",
+ "webgl vertex shader high int precision rangeMin:31",
+ "webgl vertex shader high int precision rangeMax:30",
+ "webgl vertex shader medium int precision:0",
+ "webgl vertex shader medium int precision rangeMin:31",
+ "webgl vertex shader medium int precision rangeMax:30",
+ "webgl vertex shader low int precision:0",
+ "webgl vertex shader low int precision rangeMin:31",
+ "webgl vertex shader low int precision rangeMax:30",
+ "webgl fragment shader high int precision:0",
+ "webgl fragment shader high int precision rangeMin:31",
+ "webgl fragment shader high int precision rangeMax:30",
+ "webgl fragment shader medium int precision:0",
+ "webgl fragment shader medium int precision rangeMin:31",
+ "webgl fragment shader medium int precision rangeMax:30",
+ "webgl fragment shader low int precision:0",
+ "webgl fragment shader low int precision rangeMin:31",
+ "webgl fragment shader low int precision rangeMax:30",
+ ],
+ "6bc5":
+ "Google Inc. (NVIDIA)~ANGLE (NVIDIA, NVIDIA GeForce RTX 4060 Laptop GPU (0x000028E0) Direct3D11 vs_5_0 ps_5_0, D3D11)",
+ ed31: 0,
+ "72bd": 0,
+ "097b": 0,
+ "52cd": [0, 0, 0],
+ a658: [
+ "Arial",
+ "Arial Black",
+ "Arial Narrow",
+ "Book Antiqua",
+ "Bookman Old Style",
+ "Calibri",
+ "Cambria",
+ "Cambria Math",
+ "Century",
+ "Century Gothic",
+ "Century Schoolbook",
+ "Comic Sans MS",
+ "Consolas",
+ "Courier",
+ "Courier New",
+ "Georgia",
+ "Helvetica",
+ "Impact",
+ "Lucida Bright",
+ "Lucida Calligraphy",
+ "Lucida Console",
+ "Lucida Fax",
+ "Lucida Handwriting",
+ "Lucida Sans",
+ "Lucida Sans Typewriter",
+ "Lucida Sans Unicode",
+ "Microsoft Sans Serif",
+ "Monotype Corsiva",
+ "MS Gothic",
+ "MS PGothic",
+ "MS Reference Sans Serif",
+ "MS Sans Serif",
+ "MS Serif",
+ "Palatino Linotype",
+ "Segoe Print",
+ "Segoe Script",
+ "Segoe UI",
+ "Segoe UI Light",
+ "Segoe UI Semibold",
+ "Segoe UI Symbol",
+ "Tahoma",
+ "Times",
+ "Times New Roman",
+ "Trebuchet MS",
+ "Verdana",
+ "Wingdings",
+ "Wingdings 2",
+ "Wingdings 3",
+ ],
+ d02f: "124.04347527516074",
+ },
+ "54ef":
+ '{"b_ut":"","home_version":"V8","in_new_ab":true,"ab_version":{"for_ai_home_version":"V8","in_theme_version":"OPEN","enable_web_push":"DISABLE","enable_ai_floor_api":"ENABLE","enable_shortcut_key":"DISABLE","rcmd_timeout_config":"550","home_performance_opt":"ssr_fetch_opt","infra_projection":"OFF"},"ab_split_num":{"for_ai_home_version":54,"in_theme_version":30,"enable_web_push":10,"enable_ai_floor_api":137,"enable_shortcut_key":54,"rcmd_timeout_config":49,"home_performance_opt":49,"infra_projection":49},"uniq_page_id":"1671272756362","is_modern":true}',
+ "8b94": "",
+ df35: "__UUID__",
+ "07a4": "zh-CN",
+ "5f45": null,
+ db46: 0,
+};
+
+const MASK64 = (1n << 64n) - 1n;
+const rotl64 = (x: bigint, k: bigint) => ((x << k) | (x >> (64n - k))) & MASK64;
+function fmix64(k: bigint): bigint {
+ let t = k;
+ t ^= t >> 33n;
+ t = (t * 0xff51afd7ed558ccdn) & MASK64;
+ t ^= t >> 33n;
+ t = (t * 0xc4ceb9fe1a85ec53n) & MASK64;
+ t ^= t >> 33n;
+ return t;
+}
+
+/** murmur3 x64 128 (seed 31) over ASCII string → buvid_fp. */
+function buvidFp(key: string, seed = 31n): string {
+ const data = Buffer.from(key, "ascii");
+ const C1 = 0x87c37b91114253d5n;
+ const C2 = 0x4cf5ad432745937fn;
+ let h1 = seed;
+ let h2 = seed;
+ const len = data.length;
+ const blocks = Math.floor(len / 16);
+
+ for (let i = 0; i < blocks; i++) {
+ const k1 = data.readBigUInt64LE(i * 16);
+ const k2 = data.readBigUInt64LE(i * 16 + 8);
+ h1 ^= (rotl64((k1 * C1) & MASK64, 31n) * C2) & MASK64;
+ h1 = ((rotl64(h1, 27n) + h2) * 5n + 0x52dce729n) & MASK64;
+ h2 ^= (rotl64((k2 * C2) & MASK64, 33n) * C1) & MASK64;
+ h2 = ((rotl64(h2, 31n) + h1) * 5n + 0x38495ab5n) & MASK64;
+ }
+
+ const tail = data.subarray(blocks * 16);
+ if (tail.length) {
+ let k1 = 0n;
+ let k2 = 0n;
+ for (let i = tail.length - 1; i >= 8; i--) k2 ^= BigInt(tail[i]) << BigInt((i - 8) * 8);
+ if (tail.length > 8) h2 ^= (rotl64((k2 * C2) & MASK64, 33n) * C1) & MASK64;
+ for (let i = Math.min(tail.length, 8) - 1; i >= 0; i--) k1 ^= BigInt(tail[i]) << BigInt(i * 8);
+ h1 ^= (rotl64((k1 * C1) & MASK64, 31n) * C2) & MASK64;
+ }
+
+ const n = BigInt(len);
+ h1 ^= n;
+ h2 ^= n;
+ h1 = (h1 + h2) & MASK64;
+ h2 = (h2 + h1) & MASK64;
+ h1 = fmix64(h1);
+ h2 = fmix64(h2);
+ h1 = (h1 + h2) & MASK64;
+ h2 = (h2 + h1) & MASK64;
+ return h1.toString(16) + h2.toString(16);
+}
+
+function randomUuid(): string {
+ const mp = "123456789ABCDEF".split("").concat(["10"]);
+ const part = (n: number) => Array.from({ length: n }, () => mp[Math.floor(Math.random() * mp.length)]).join("");
+ const t = String(Date.now() % 100000).padEnd(5, "0");
+ return [8, 4, 4, 4, 12].map(part).join("-") + t + "infoc";
+}
+
+function randomLsid(): string {
+ const a = Array.from({ length: 8 }, () =>
+ Math.floor(Math.random() * 16)
+ .toString(16)
+ .toUpperCase(),
+ ).join("");
+ return `${a}_${Math.floor(Date.now() / 1000)
+ .toString(16)
+ .toUpperCase()}`;
+}
+
+const md5 = (s: string) => createHash("md5").update(s).digest("hex");
+
+function durationToMS(duration: string | number | undefined | null): number {
+ if (typeof duration === "number") return duration * 1000;
+ if (typeof duration === "string") return duration.split(":").reduce((p, c) => 60 * p + +c, 0) * 1000 || 0;
+ return 0;
+}
+
+const ENTITIES: Record = { "&": "&", "<": "<", ">": ">", """: '"', "'": "'", "'": "'" };
+function cleanTitle(raw: unknown): string {
+ return String(raw ?? "")
+ .replace(/<\/?em[^>]*>/g, "")
+ .replace(/&(amp|lt|gt|quot|apos|#39);/g, (m) => ENTITIES[m] ?? m)
+ .replace(/(\d+);/g, (_, n) => String.fromCodePoint(Number(n)));
+}
+
+function fixUrl(u?: string): string | undefined {
+ if (!u) return undefined;
+ if (u.startsWith("//")) return `https:${u}`;
+ return u.replace(/^http:\/\//, "https://");
+}
+
+function isAllowedMediaUrl(u: string): boolean {
+ try {
+ const url = new URL(u);
+ return url.protocol === "https:" && MEDIA_HOST_RE.test(url.hostname);
+ } catch {
+ return false;
+ }
+}
+
+/* -------------------------------------------------------------------------- */
+/* Plugin */
+/* -------------------------------------------------------------------------- */
+
+export class BilibiliPlugin extends BasePlugin {
+ name = "bilibili";
+ version = "1.0.0";
+
+ private readonly opts: Required> & { sessdata?: string };
+
+ // Browser emulation session: buvid3/4 + _uuid + b_lsid + b_nut + buvid_fp + bili_ticket (already activated via ExClimbWuzhi)
+ private session?: { jar: Record; at: number };
+ private sessionPromise?: Promise<{ jar: Record; at: number }>;
+ // WBI keys
+ private wbi?: { img: string; sub: string; at: number };
+
+ constructor(options: BilibiliPluginOptions = {}) {
+ super();
+ this.opts = {
+ sessdata: options.sessdata,
+ quality: options.quality ?? "super",
+ preferHiRes: options.preferHiRes ?? false,
+ multiPartAsPlaylist: options.multiPartAsPlaylist ?? true,
+ maxPlaylistItems: options.maxPlaylistItems ?? 100,
+ timeout: options.timeout ?? 15_000,
+ };
+ }
+
+ /* ------------------------------ SourcePlugin ----------------------------- */
+
+ canHandle(query: string): boolean {
+ if (!query || typeof query !== "string") return false;
+ const q = query.trim();
+ return (
+ /(?:^|\.)bilibili\.com\//i.test(q.replace(/^https?:\/\//i, "")) ||
+ /(?:^|\/\/)b23\.tv\//i.test(q) ||
+ /^BV[0-9A-Za-z]{10}$/.test(q) ||
+ /^av\d+$/i.test(q) ||
+ /^(?:bilibili|bili|b站)\s*[::]/i.test(q)
+ );
+ }
+
+ validate(url: string): boolean {
+ return this.canHandle(url);
+ }
+
+ async search(query: string, requestedBy: Requester, signal?: AbortSignal): Promise {
+ let q = query.trim().replace(/^(?:bilibili|bili|b站)\s*[::]?\s*/i, "") || query.trim();
+
+ if (/b23\.tv\//i.test(q)) q = await this.resolveShortUrl(q, signal);
+
+ // 1) Link / BV / av → fetch video info directly
+ const ref = this.parseVideoRef(q);
+ if (ref) {
+ const view = await this.getView(ref, signal);
+ const tracks = this.tracksFromView(view, requestedBy, ref.page);
+ const playlist =
+ this.opts.multiPartAsPlaylist && !ref.page && tracks.length > 1 ?
+ { name: cleanTitle(view.title), url: `https://www.bilibili.com/video/${view.bvid}`, thumbnail: fixUrl(view.pic) }
+ : null;
+ return { tracks: playlist ? tracks : tracks.slice(0, 1), playlist, query, source: this.name };
+ }
+
+ // 2) Keyword → search for videos
+ const data = await this.searchVideos(q, 1, signal);
+ const tracks = (data?.result ?? []).map((r: any) => this.trackFromSearch(r, requestedBy));
+ return { tracks, playlist: null, query, source: this.name };
+ }
+
+ async getStream(track: Track, signal?: AbortSignal): Promise {
+ const meta = await this.resolveMeta(track, signal);
+ const candidates = await this.getAudioCandidates(meta, signal);
+ if (!candidates.length) throw new Error("Bilibili: no valid audio stream found for this video");
+
+ let lastError: unknown;
+ for (const url of candidates) {
+ try {
+ const stream = await this.openMedia(url, meta.bvid ?? String(meta.aid), signal);
+ return { stream, type: "arbitrary", track, metadata: { ...track.metadata, ...meta, source: this.name } };
+ } catch (err) {
+ lastError = err;
+ if (signal?.aborted) throw err;
+ }
+ }
+ throw new Error(`Bilibili: unable to open stream (${(lastError as Error)?.message ?? "unknown"})`);
+ }
+
+ /**
+ * Video (already combined picture + audio). Bilibili's DASH separates video/audio, so this uses the `durl` stream
+ * (full MP4, up to ~720p, 1080p if SESSDATA is available).
+ */
+ async getVideo(track: Track, signal?: AbortSignal): Promise {
+ const meta = await this.resolveMeta(track, signal);
+ const data = await this.fetchPlayUrl(
+ meta,
+ { fnver: 0, fnval: 0, qn: this.opts.sessdata ? 80 : 64, platform: "html5", high_quality: 1 },
+ signal,
+ );
+
+ const durl: any[] = data?.durl ?? [];
+ const urls = [
+ ...new Set(
+ durl
+ .flatMap((d) => [d.url, ...(d.backup_url ?? [])])
+ .filter(Boolean)
+ .map((u: string) => fixUrl(u)!),
+ ),
+ ].filter(isAllowedMediaUrl);
+ if (!urls.length) throw new Error("Bilibili: no valid video stream found");
+
+ let lastError: unknown;
+ for (const url of urls) {
+ try {
+ const stream = await this.openMedia(url, meta.bvid ?? String(meta.aid), signal);
+ return { stream, type: "arbitrary", track, metadata: { ...track.metadata, ...meta, source: this.name, video: true } };
+ } catch (err) {
+ lastError = err;
+ if (signal?.aborted) throw err;
+ }
+ }
+ throw new Error(`Bilibili: unable to open video (${(lastError as Error)?.message ?? "unknown"})`);
+ }
+
+ async getFallback(track: Track, signal?: AbortSignal): Promise {
+ // Retry from the start at the lowest quality (different CDN/bitrate).
+ const prev = this.opts.quality;
+ this.opts.quality = "low";
+ try {
+ return await this.getStream(track, signal);
+ } finally {
+ this.opts.quality = prev;
+ }
+ }
+
+ async getRelatedTracks(track: Track, opts: RelatedTracksOptions = {}): Promise {
+ const meta = track.metadata ?? {};
+ const bvid = meta.bvid ?? track.id.match(BVID_RE)?.[0];
+ const aid = meta.aid;
+ if (!bvid && !aid) return [];
+
+ const res = await this.http({
+ url: "https://api.bilibili.com/x/web-interface/archive/related",
+ params: bvid ? { bvid } : { aid },
+ });
+ const list: any[] = res?.data?.data ?? [];
+ const seen = new Set((opts.history ?? []).map((t) => t.metadata?.bvid ?? t.id));
+ seen.add(bvid);
+
+ const offset = opts.offset ?? 0;
+ const limit = opts.limit ?? 10;
+ return list
+ .filter((v) => v.bvid && !seen.has(v.bvid))
+ .slice(offset, offset + limit)
+ .map((v) => this.trackFromView(v, track.requestedBy));
+ }
+
+ async extractPlaylist(url: string, requestedBy: Requester): Promise {
+ if (/b23\.tv\//i.test(url)) url = await this.resolveShortUrl(url);
+
+ // Multi-part videos
+ const ref = this.parseVideoRef(url);
+ if (ref && !/fid=|\/list\/ml|\/playlist\/pl|favlist/i.test(url)) {
+ return this.tracksFromView(await this.getView(ref), requestedBy, ref.page);
+ }
+
+ // Favorites
+ const fid =
+ url.match(/^\s*(\d+)\s*$/)?.[1] ??
+ url.match(/[?&]fid=(\d+)/)?.[1] ??
+ url.match(/\/list\/ml(\d+)/i)?.[1] ??
+ url.match(/\/playlist\/pl(\d+)/i)?.[1];
+ if (fid) return this.getFavoriteTracks(fid, requestedBy);
+
+ // UP channel
+ const mid = url.match(/space\.bilibili\.com\/(\d+)/i)?.[1];
+ if (mid) return this.getUploaderTracks(mid, requestedBy);
+
+ return [];
+ }
+
+ /* --------------------------------- HTTP ---------------------------------- */
+
+ private async http(config: AxiosRequestConfig & { signal?: AbortSignal }, retried = false): Promise {
+ const extra = (config.headers ?? {}) as Record;
+ const cookies: string[] = [extra.cookie ?? (await this.buvidCookie())];
+ if (this.opts.sessdata) cookies.push(`SESSDATA=${this.opts.sessdata}`);
+
+ const headers: Record = {
+ "user-agent": UA,
+ accept: "application/json, text/plain, */*",
+ "accept-language": "zh-CN,zh;q=0.9,en;q=0.8",
+ referer: "https://www.bilibili.com/",
+ origin: "https://www.bilibili.com",
+ ...extra,
+ cookie: cookies.join("; "),
+ };
+
+ try {
+ const res = await axios.request({ timeout: this.opts.timeout, ...config, headers });
+ const code = res?.data?.code;
+ if (!retried && (code === -412 || code === -352)) throw Object.assign(new Error("risk-control"), { __risk: true });
+ return res;
+ } catch (err: any) {
+ const status = err?.response?.status;
+ const code = err?.response?.data?.code;
+ const risk = err?.__risk || status === 412 || status === 403 || code === -412 || code === -352;
+ if (!retried && risk && !config.signal?.aborted) {
+ // Refresh buvid and retry once.
+ this.session = undefined;
+ this.wbi = undefined;
+ await new Promise((r) => setTimeout(r, 400));
+ return this.http({ ...config, headers: { ...extra, cookie: undefined as any } }, true);
+ }
+ throw err;
+ }
+ }
+
+ private async ensureSession() {
+ if (this.session && Date.now() - this.session.at < 6 * 3600_000) return this.session;
+ if (!this.sessionPromise) {
+ this.sessionPromise = this.createSession()
+ .then((s) => (this.session = s))
+ .finally(() => (this.sessionPromise = undefined));
+ }
+ return this.sessionPromise;
+ }
+
+ private async createSession() {
+ const base = { "user-agent": UA, referer: "https://www.bilibili.com/", origin: "https://www.bilibili.com" };
+ const timeout = this.opts.timeout;
+
+ // 1) buvid3 / buvid4
+ const spi = await axios.get("https://api.bilibili.com/x/frontend/finger/spi", { headers: base, timeout });
+ const ids = spi.data?.data;
+ if (!ids?.b_3) throw new Error(`Bilibili: failed to obtain buvid (code ${spi.data?.code})`);
+
+ const uuid = randomUuid();
+ const nowSec = Math.floor(Date.now() / 1000);
+ const jar: Record = {
+ _uuid: uuid,
+ b_lsid: randomLsid(),
+ b_nut: String(nowSec),
+ buvid_fp: buvidFp(UA),
+ buvid3: ids.b_3,
+ buvid4: ids.b_4,
+ CURRENT_FNVAL: "4048",
+ CURRENT_QUALITY: "0",
+ };
+ const cookie = () =>
+ Object.entries(jar)
+ .map(([k, v]) => `${k}=${v}`)
+ .join("; ");
+
+ // 2) bili_ticket (with WBI key in nav)
+ try {
+ const hexsign = createHmac("sha256", "XgwSnGZ1p").update(`ts${nowSec}`).digest("hex");
+ const res = await axios.post("https://api.bilibili.com/bapis/bilibili.api.ticket.v1.Ticket/GenWebTicket", null, {
+ params: { key_id: "ec02", hexsign, "context[ts]": nowSec, csrf: "" },
+ headers: { ...base, cookie: cookie() },
+ timeout,
+ });
+ const d = res.data?.data;
+ if (d?.ticket) {
+ jar.bili_ticket = d.ticket;
+ jar.bili_ticket_expires = String(nowSec + 3 * 24 * 3600);
+ }
+ if (d?.nav?.img && d?.nav?.sub) {
+ const strip = (u: string) => u.slice(u.lastIndexOf("/") + 1, u.lastIndexOf("."));
+ this.wbi = { img: strip(d.nav.img), sub: strip(d.nav.sub), at: Date.now() };
+ }
+ } catch {
+ /* optional */
+ }
+
+ // 3) Activate buvid3 (ExClimbWuzhi)
+ try {
+ const payload = JSON.parse(JSON.stringify(EXCLIMBWUZHI_TEMPLATE));
+ payload["5062"] = String(Date.now());
+ payload["3c43"]["b8ce"] = UA;
+ payload["df35"] = uuid;
+ await axios.post(
+ "https://api.bilibili.com/x/internal/gaia-gateway/ExClimbWuzhi",
+ JSON.stringify({ payload: JSON.stringify(payload) }),
+ {
+ headers: { ...base, "content-type": "application/json", cookie: cookie() },
+ timeout,
+ },
+ );
+ } catch {
+ /* optional, but if it fails the API may still return 412 */
+ }
+
+ return { jar, at: Date.now() };
+ }
+
+ /** Full session cookie string (without SESSDATA). */
+ private async buvidCookie() {
+ const { jar } = await this.ensureSession();
+ return Object.entries(jar)
+ .map(([k, v]) => `${k}=${v}`)
+ .join("; ");
+ }
+
+ private async resolveShortUrl(url: string, signal?: AbortSignal): Promise {
+ try {
+ const res = await axios.get(url, {
+ maxRedirects: 0,
+ validateStatus: (s: number) => s >= 200 && s < 400,
+ headers: { "user-agent": UA },
+ timeout: this.opts.timeout,
+ signal,
+ });
+ return (res.headers.location as string) ?? url;
+ } catch {
+ return url;
+ }
+ }
+
+ /* ---------------------------------- WBI ---------------------------------- */
+
+ private async getWbiKeys(): Promise<{ img: string; sub: string }> {
+ if (this.wbi && Date.now() - this.wbi.at < 6 * 3600_000) return this.wbi;
+
+ await this.ensureSession(); // createSession fills this.wbi if it gets a ticket
+ if (this.wbi) return this.wbi;
+
+ // Fallback: x/web-interface/nav (even without login it still returns wbi_img even with code = -101)
+ const res = await this.http({ url: "https://api.bilibili.com/x/web-interface/nav" }).catch((e: any) => e?.response);
+ const img = res?.data?.data?.wbi_img;
+ if (!img?.img_url || !img?.sub_url) throw new Error("Bilibili: failed to obtain WBI key");
+ const strip = (u: string) => u.slice(u.lastIndexOf("/") + 1, u.lastIndexOf("."));
+ this.wbi = { img: strip(img.img_url), sub: strip(img.sub_url), at: Date.now() };
+ return this.wbi;
+ }
+
+ /** Sign parameters with WBI → return params including `wts` + `w_rid`. */
+ private async signWbi(params: Record): Promise> {
+ const { img, sub } = await this.getWbiKeys();
+ const raw = img + sub;
+ const mixin = MIXIN_KEY_TAB.map((i) => raw.charAt(i))
+ .join("")
+ .slice(0, 32);
+
+ const withTs: Record = { ...params, wts: Math.round(Date.now() / 1000) };
+ const query = Object.keys(withTs)
+ .sort()
+ .map((k) => {
+ const v = typeof withTs[k] === "string" ? withTs[k].replace(/[!'()*]/g, "") : withTs[k];
+ return `${encodeURIComponent(k)}=${encodeURIComponent(v)}`;
+ })
+ .join("&");
+ return { ...withTs, w_rid: md5(query + mixin) };
+ }
+
+ /* ------------------------------- Video info ------------------------------ */
+
+ private parseVideoRef(input: string): { bvid?: string; aid?: number; page?: number } | null {
+ const bvid = input.match(BVID_RE)?.[0];
+ const aidStr = !bvid ? input.match(AID_RE)?.[1] : undefined;
+ if (!bvid && !aidStr) return null;
+ const p = input.match(/[?&]p=(\d+)/)?.[1];
+ return { bvid, aid: aidStr ? Number(aidStr) : undefined, page: p ? Number(p) : undefined };
+ }
+
+ private async getView(ref: { bvid?: string; aid?: number }, signal?: AbortSignal) {
+ const base = ref.bvid ? { bvid: ref.bvid } : { aid: ref.aid };
+ let res: any;
+ try {
+ res = await this.http({ url: "https://api.bilibili.com/x/web-interface/view", params: base, signal });
+ } catch (err) {
+ if (signal?.aborted) throw err;
+ // Fallback: WBI-signed endpoint
+ res = await this.http({
+ url: "https://api.bilibili.com/x/web-interface/wbi/view",
+ params: await this.signWbi(base),
+ signal,
+ });
+ }
+ if (res.data.code !== 0) throw new Error(`Bilibili: ${res.data.message ?? "failed to fetch video info"} (${res.data.code})`);
+ return res.data.data;
+ }
+
+ private tracksFromView(view: any, requestedBy: Requester, onlyPage?: number): Track[] {
+ const pages: any[] =
+ view.pages?.length ? view.pages : [{ cid: view.cid, page: 1, part: view.title, duration: view.duration }];
+ const selected = onlyPage ? pages.filter((p) => p.page === onlyPage) : pages;
+ const list = selected.length ? selected : pages.slice(0, 1);
+ const multi = pages.length > 1;
+
+ return list.map((p) => {
+ const base = this.trackFromView(view, requestedBy);
+ return {
+ ...base,
+ id: multi ? `${view.bvid}_p${p.page}` : view.bvid,
+ title: multi ? `${cleanTitle(view.title)} - P${p.page} ${cleanTitle(p.part)}` : cleanTitle(view.title),
+ url: multi ? `https://www.bilibili.com/video/${view.bvid}?p=${p.page}` : base.url,
+ duration: durationToMS(p.duration ?? view.duration),
+ metadata: { ...base.metadata, cid: p.cid, page: p.page },
+ } as Track;
+ });
+ }
+
+ private trackFromView(v: any, requestedBy: Requester): Track {
+ return {
+ id: v.bvid ?? String(v.aid),
+ title: cleanTitle(v.title),
+ url: `https://www.bilibili.com/video/${v.bvid ?? "av" + v.aid}`,
+ duration: durationToMS(v.duration),
+ thumbnail: fixUrl(v.pic),
+ author: v.owner?.name ?? v.author,
+ requestedBy,
+ source: this.name,
+ isLive: false,
+ metadata: { bvid: v.bvid, aid: v.aid, cid: v.cid, mid: v.owner?.mid ?? v.mid },
+ };
+ }
+
+ private trackFromSearch(r: any, requestedBy: Requester): Track {
+ return {
+ id: r.bvid ?? String(r.aid),
+ title: cleanTitle(r.title),
+ url: `https://www.bilibili.com/video/${r.bvid}`,
+ duration: durationToMS(r.duration),
+ thumbnail: fixUrl(r.pic),
+ author: r.author,
+ requestedBy,
+ source: this.name,
+ isLive: false,
+ metadata: { bvid: r.bvid, aid: r.aid, mid: r.mid, tags: r.tag?.split?.(","), play: r.play },
+ };
+ }
+
+ /* --------------------------------- Search -------------------------------- */
+
+ private async searchVideos(keyword: string, page: number, signal?: AbortSignal) {
+ const res = await this.http({
+ url: "https://api.bilibili.com/x/web-interface/search/type",
+ params: {
+ page,
+ page_size: SEARCH_PAGE_SIZE,
+ keyword,
+ search_type: "video",
+ order: "",
+ highlight: 1,
+ platform: "pc",
+ __refresh__: true,
+ dynamic_offset: 0,
+ },
+ headers: {
+ origin: "https://search.bilibili.com",
+ referer: "https://search.bilibili.com/",
+ cookie: await this.buvidCookie(),
+ },
+ signal,
+ });
+ if (res.data.code !== 0) throw new Error(`Bilibili search: ${res.data.message} (${res.data.code})`);
+ return res.data.data;
+ }
+
+ /* ------------------------------ Playlist helpers ------------------------- */
+
+ private async getFavoriteTracks(fid: string, requestedBy: Requester): Promise {
+ const out: Track[] = [];
+ for (let pn = 1; out.length < this.opts.maxPlaylistItems; pn++) {
+ const res = await this.http({
+ url: "https://api.bilibili.com/x/v3/fav/resource/list",
+ params: { media_id: fid, platform: "web", ps: 20, pn },
+ });
+ const data = res.data?.data;
+ if (res.data.code !== 0 || !data?.medias) break;
+ for (const m of data.medias) {
+ if (!m.bvid || m.attr > 0) continue; // attr > 0: video deleted / hidden
+ out.push({
+ id: m.bvid,
+ title: cleanTitle(m.title),
+ url: `https://www.bilibili.com/video/${m.bvid}`,
+ duration: durationToMS(m.duration),
+ thumbnail: fixUrl(m.cover),
+ author: m.upper?.name,
+ requestedBy,
+ source: this.name,
+ isLive: false,
+ metadata: { bvid: m.bvid, aid: m.id ?? m.aid, mid: m.upper?.mid },
+ });
+ }
+ if (!data.has_more) break;
+ }
+ return out.slice(0, this.opts.maxPlaylistItems);
+ }
+
+ private async getUploaderTracks(mid: string, requestedBy: Requester): Promise {
+ const out: Track[] = [];
+ const cookie = await this.buvidCookie();
+ for (let pn = 1; out.length < this.opts.maxPlaylistItems; pn++) {
+ const params = await this.signWbi({
+ mid,
+ ps: 30,
+ tid: 0,
+ pn,
+ web_location: 1550101,
+ order_avoided: true,
+ order: "pubdate",
+ keyword: "",
+ platform: "web",
+ dm_img_list: "[]",
+ dm_img_str: "V2ViR0wgMS4wIChPcGVuR0wgRVMgMi4wIENocm9taXVtKQ",
+ dm_cover_img_str:
+ "QU5HTEUgKE5WSURJQSwgTlZJRElBIEdlRm9yY2UgR1RYIDE2NTAgKDB4MDAwMDFGOTEpIERpcmVjdDNEMTEgdnNfNV8wIHBzXzVfMCwgRDNEMTEpR29vZ2xlIEluYy4gKE5WSURJQS",
+ dm_img_inter: '{"ds":[],"wh":[0,0,0],"of":[0,0,0]}',
+ });
+ const res = await this.http({
+ url: "https://api.bilibili.com/x/space/wbi/arc/search",
+ params,
+ headers: { origin: "https://space.bilibili.com", referer: `https://space.bilibili.com/${mid}/video`, cookie },
+ });
+ if (res.data.code !== 0) throw new Error(`Bilibili space: ${res.data.message} (${res.data.code})`);
+ const list: any[] = res.data.data?.list?.vlist ?? [];
+ for (const v of list) out.push(this.trackFromView({ ...v, owner: { name: v.author, mid } }, requestedBy));
+ const page = res.data.data?.page;
+ if (!list.length || !page || page.pn * page.ps >= page.count) break;
+ }
+ return out.slice(0, this.opts.maxPlaylistItems);
+ }
+
+ /* ------------------------------- Stream helpers -------------------------- */
+
+ private async resolveMeta(track: Track, signal?: AbortSignal): Promise<{ bvid?: string; aid?: number; cid: number }> {
+ const m = track.metadata ?? {};
+ let bvid: string | undefined = m.bvid ?? track.id?.match(BVID_RE)?.[0] ?? track.url?.match(BVID_RE)?.[0];
+ let aid: number | undefined = m.aid;
+ let cid: number | undefined = m.cid;
+
+ if (!cid) {
+ const page = m.page ?? Number(track.url?.match(/[?&]p=(\d+)/)?.[1] ?? 1);
+ const view = await this.getView({ bvid, aid }, signal);
+ bvid = view.bvid;
+ aid = view.aid;
+ cid = (view.pages?.find((p: any) => p.page === page) ?? view.pages?.[0])?.cid ?? view.cid;
+ }
+ if (!cid) throw new Error("Bilibili: failed to determine cid");
+ return { bvid, aid, cid };
+ }
+
+ private describeError(label: string, err: any): Error {
+ const status = err?.response?.status;
+ const code = err?.response?.data?.code;
+ const msg = err?.response?.data?.message ?? err?.message ?? "unknown";
+ return new Error(`Bilibili ${label}: HTTP ${status ?? "?"} code ${code ?? "?"} - ${msg}`);
+ }
+
+ /** Fetch playurl: prefer the WBI-signed endpoint, and fall back to the legacy endpoint on failure. */
+ private async fetchPlayUrl(
+ meta: { bvid?: string; aid?: number; cid: number },
+ extra: Record,
+ signal?: AbortSignal,
+ ): Promise {
+ const base = { ...(meta.bvid ? { bvid: meta.bvid } : { avid: meta.aid }), cid: meta.cid, ...extra };
+ const errors: Error[] = [];
+
+ try {
+ const res = await this.http({
+ url: "https://api.bilibili.com/x/player/wbi/playurl",
+ params: await this.signWbi(base),
+ signal,
+ });
+ if (res.data.code === 0) return res.data.data;
+ errors.push(new Error(`wbi/playurl code ${res.data.code} - ${res.data.message}`));
+ } catch (err) {
+ if (signal?.aborted) throw err;
+ errors.push(this.describeError("wbi/playurl", err));
+ }
+
+ try {
+ const legacy: Record = { ...base };
+ if (legacy.avid) {
+ legacy.aid = legacy.avid;
+ delete legacy.avid;
+ }
+ const res = await this.http({ url: "https://api.bilibili.com/x/player/playurl", params: legacy, signal });
+ if (res.data.code === 0) return res.data.data;
+ errors.push(new Error(`playurl code ${res.data.code} - ${res.data.message}`));
+ } catch (err) {
+ if (signal?.aborted) throw err;
+ errors.push(this.describeError("playurl", err));
+ }
+
+ throw new Error(`Bilibili: failed to fetch playurl (${errors.map((e) => e.message).join(" | ")})`);
+ }
+
+ /** Return the list of audio URLs in priority order (baseUrl first, backup later). */
+ private async getAudioCandidates(meta: { bvid?: string; aid?: number; cid: number }, signal?: AbortSignal): Promise {
+ const data = await this.fetchPlayUrl(meta, { qn: 64, fnver: 0, fnval: 4048, fourk: 1 }, signal);
+
+ let urls: string[] = [];
+ if (data.dash) {
+ const pool: any[] = [...(data.dash.audio ?? [])];
+ if (this.opts.preferHiRes) {
+ if (data.dash.flac?.audio) pool.push(data.dash.flac.audio);
+ if (data.dash.dolby?.audio?.length) pool.push(...data.dash.dolby.audio);
+ }
+ pool.sort((a, b) => a.bandwidth - b.bandwidth);
+ if (pool.length) {
+ const idx = { low: 0, standard: 1, high: 2, super: pool.length - 1 }[this.opts.quality];
+ const chosen = pool[Math.min(idx, pool.length - 1)];
+ // Add the closest alternatives as backups (high → low).
+ const ordered = [chosen, ...pool.filter((a) => a !== chosen).reverse()];
+ urls = ordered.flatMap((a) => [a.baseUrl ?? a.base_url, ...(a.backupUrl ?? a.backup_url ?? [])]);
+ }
+ } else if (data.durl?.length) {
+ urls = data.durl.flatMap((d: any) => [d.url, ...(d.backup_url ?? [])]);
+ }
+
+ return [...new Set(urls.filter(Boolean).map((u) => fixUrl(u)!))].filter(isAllowedMediaUrl);
+ }
+
+ /** Bilibili CDNs require Referer + UA, so the stream must be opened locally instead of returning `url`. */
+ private async openMedia(url: string, videoId: string, signal?: AbortSignal): Promise {
+ const res = await axios
+ .get(url, {
+ responseType: "stream",
+ timeout: this.opts.timeout,
+ signal,
+ maxRedirects: 3,
+ headers: {
+ "user-agent": UA,
+ accept: "*/*",
+ "accept-encoding": "identity",
+ range: "bytes=0-",
+ origin: "https://www.bilibili.com",
+ referer: `https://www.bilibili.com/video/${videoId}`,
+ },
+ validateStatus: (s: number) => s === 200 || s === 206,
+ beforeRedirect: (opts: any) => {
+ if (!isAllowedMediaUrl(`${opts.protocol}//${opts.hostname}${opts.path}`)) {
+ throw new Error("Bilibili: redirect to a disallowed host");
+ }
+ },
+ })
+ .catch((err) => {
+ if (signal?.aborted) throw err;
+ let host = "?";
+ try {
+ host = new URL(url).hostname;
+ } catch {}
+ throw this.describeError(`media(${host})`, err);
+ });
+ return res.data as Readable;
+ }
+}
+
+export default BilibiliPlugin;
diff --git a/plugins/src/YouTubePlugin.ts b/plugins/src/YouTubePlugin.ts
index 94a2c9c8..f0f0200b 100644
--- a/plugins/src/YouTubePlugin.ts
+++ b/plugins/src/YouTubePlugin.ts
@@ -1,9 +1,10 @@
import { BasePlugin, Track, SearchResult, StreamInfo, Player } from "ziplayer";
import { EnabledTrackTypes } from "googlevideo/utils";
+import type { VideoFormatPreferences, AudioFormatPreferences } from "googlevideo/sabr-stream";
import { Innertube, Log, UniversalCache, Platform, type Types } from "youtubei.js";
import { createSabrStream, createSabrVideoStream } from "./utils/sabr-stream-factory.js";
-import { webStreamToNodeStream } from "./utils/stream-converter.js";
+import { webStreamToNodeStream, calculateSeekBytes } from "./utils/stream-converter.js";
import { mintYouTubePoToken } from "./utils/youtube-botguard.js";
import { Readable } from "stream";
import { createPluginDebugLogger } from "./utils/debugLog.js";
@@ -22,6 +23,8 @@ export interface PluginOptions {
clientType?: Types.InnerTubeClient;
searchClientType?: Types.InnerTubeClient;
preferYoutubei?: boolean;
+ videoPreferences?: Partial;
+ audioPreferences?: Partial;
fallbackStream?: (track: Track) => Promise;
fistStream?: (track: Track) => Promise;
}
@@ -237,6 +240,8 @@ export class YouTubePlugin extends BasePlugin {
// metadata: raw.metadata,
// });
+ const isLive = Boolean(raw?.is_live ?? raw?.basic_info?.is_live ?? duration === 0);
+
return {
id: String(id),
title: String(title),
@@ -245,9 +250,11 @@ export class YouTubePlugin extends BasePlugin {
thumbnail: thumb,
requestedBy,
source: this.name,
+ isLive,
metadata: {
author,
views,
+ isLive,
...(extra?.playlist ? { playlist: extra.playlist } : {}),
},
} as Track;
@@ -528,15 +535,22 @@ export class YouTubePlugin extends BasePlugin {
const id = track.id || this.extractVideoId(track.url);
if (!id) throw new Error("Invalid track id");
+ const isLive = Boolean(track.isLive || track.duration === 0 || (track.metadata as any)?.isLive);
const downloads =
- this.options?.preferYoutubei ?
+ this.options?.preferYoutubei && !isLive ?
[
- { name: "youtubei.js download with BotGuard", run: () => this.downloadWithYoutubei(track, id, signal) },
+ {
+ name: "Direct format URL download with BotGuard",
+ run: () => (this as any).downloadWithYoutubei?.(track, id, signal) ?? this.downloadWithDirectUrl(track, id, signal),
+ },
{ name: "SABR download", run: () => this.downloadWithSabr(track, id, signal) },
]
: [
{ name: "SABR download", run: () => this.downloadWithSabr(track, id, signal) },
- { name: "youtubei.js download with BotGuard", run: () => this.downloadWithYoutubei(track, id, signal) },
+ {
+ name: "Direct format URL download with BotGuard",
+ run: () => (this as any).downloadWithYoutubei?.(track, id, signal) ?? this.downloadWithDirectUrl(track, id, signal),
+ },
];
let lastError: unknown;
for (let index = 0; index < downloads.length; index++) {
@@ -571,105 +585,149 @@ export class YouTubePlugin extends BasePlugin {
throw lastError;
}
- private async downloadWithYoutubei(track: Track, id: string, signal?: AbortSignal): Promise {
- this.debug("🚀 Attempting youtubei.js download with BotGuard WebPO token");
- this.throwIfAborted(signal);
-
- const poToken = await mintYouTubePoToken(id, signal);
- this.throwIfAborted(signal);
-
- const videoInfo = await this.client.getBasicInfo(id, {
- client: "YTMUSIC",
- });
-
- this.throwIfAborted(signal);
-
- const format = videoInfo.chooseFormat({
- quality: "best",
- type: "audio",
- });
-
- if (!format) {
- throw new Error("youtubei.js could not choose an audio format");
- }
-
- this.debug("🎵 Selected youtubei.js audio format:", {
- itag: format.itag,
- mimeType: format.mime_type,
- bitrate: format.bitrate,
- contentLength: format.content_length,
- });
-
- const decipheredUrl = await format.decipher(this.client.session.player);
-
+ private async downloadWithDirectUrl(track: Track, id: string, signal?: AbortSignal): Promise {
+ this.debug("🚀 Attempting direct format URL download with BotGuard WebPO token");
this.throwIfAborted(signal);
- if (!decipheredUrl) {
- throw new Error("youtubei.js returned an empty deciphered URL");
+ if (track.isLive || track.duration === 0 || (track.metadata as any)?.isLive) {
+ throw new Error("Direct format download is not supported for live streams (requires SABR)");
}
- const separator = decipheredUrl.includes("&") ? "&" : "?";
- const audioStreamingURL = `${decipheredUrl}${separator}pot=${encodeURIComponent(poToken)}`;
-
- this.debug("✅ youtubei.js format deciphered successfully");
-
- const response = await fetch(audioStreamingURL, {
- signal,
- headers: {
- "User-Agent": "Mozilla/5.0",
- Accept: "*/*",
- },
- });
-
+ const poToken = await mintYouTubePoToken(id, signal);
this.throwIfAborted(signal);
- if (!response.ok) {
- throw new Error(`youtubei.js audio request failed: HTTP ${response.status} ${response.statusText}`);
- }
-
- if (!response.body) {
- throw new Error("youtubei.js audio request returned no response body");
- }
-
- this.debug("🔄 Converting youtubei.js audio Web Stream to Node.js stream");
-
- const nodeStream = await webStreamToNodeStream(response.body, 32 * 1024, 0, signal);
+ const clientsToTry = ["YTMUSIC", "IOS", "ANDROID"] as const;
+ for (const clientType of clientsToTry) {
+ try {
+ this.throwIfAborted(signal);
+ const videoInfo = await this.client.getBasicInfo(id, { client: clientType as any });
+ if (videoInfo.basic_info?.is_live) {
+ throw new Error("Direct format download is not supported for live streams (requires SABR)");
+ }
+ const format = videoInfo.chooseFormat({ quality: "best", type: "audio" });
+ if (!format) continue;
- nodeStream.on("error", (error: Error) => {
- const errorMsg = error.message || String(error);
+ let directUrl: string | undefined = format.url;
+ if (!directUrl && typeof format.decipher === "function") {
+ try {
+ directUrl = await format.decipher(this.client.session.player);
+ } catch {}
+ }
- if (!errorMsg.includes("Controller is already closed")) {
- this.debug("⚠️ youtubei.js stream error:", errorMsg);
+ if (!directUrl) continue;
+
+ const separator = directUrl.includes("?") ? "&" : "?";
+ const audioStreamingURL = `${directUrl}${separator}pot=${encodeURIComponent(poToken)}`;
+
+ const response = await fetch(audioStreamingURL, {
+ signal,
+ headers: {
+ "User-Agent": "Mozilla/5.0",
+ Accept: "*/*",
+ },
+ });
+
+ if (!response.ok || !response.body) continue;
+
+ const nodeStream = await webStreamToNodeStream(response.body, 64 * 1024, 0, signal);
+ if (!Readable.isReadable(nodeStream)) continue;
+
+ this.debug(`✅ Direct format audio download successful with client ${clientType}`);
+ return {
+ stream: nodeStream,
+ type: "arbitrary",
+ position: 0,
+ metadata: {
+ ...track.metadata,
+ itag: format.itag,
+ mime: (format as any).mime_type ?? (format as any).mimeType,
+ contentLength: (format as any).content_length ?? (format as any).contentLength,
+ },
+ recreate: async (position: number, recreateSignal?: AbortSignal) => {
+ const startTimeMs =
+ typeof position === "number" && Number.isFinite(position) && position > 0 ? Math.floor(position) : undefined;
+ try {
+ const recreateResult = await createSabrStream(
+ id,
+ this.client,
+ {
+ audioPreferences: {
+ preferredAudioCodec: "opus" as const,
+ ...this.options?.audioPreferences,
+ },
+ enabledTrackTypes: EnabledTrackTypes.AUDIO_ONLY,
+ startTimeMs,
+ },
+ recreateSignal,
+ );
+ return recreateResult.stream;
+ } catch {
+ const seekBytes = calculateSeekBytes(startTimeMs ?? 0, ((format as any).bitrate ?? 128000) / 1000);
+ const poToken = await mintYouTubePoToken(id, recreateSignal);
+ const separator = directUrl.includes("?") ? "&" : "?";
+ const audioStreamingURL = `${directUrl}${separator}pot=${encodeURIComponent(poToken)}`;
+ const response = await fetch(audioStreamingURL, {
+ signal: recreateSignal,
+ headers: {
+ "User-Agent": "Mozilla/5.0",
+ Accept: "*/*",
+ ...(seekBytes > 0 ? { Range: `bytes=${seekBytes}-` } : {}),
+ },
+ });
+ if (!response.ok || !response.body) throw new Error("Failed to recreate direct audio stream");
+ const bytesToSkip = response.status === 206 ? 0 : seekBytes;
+ return await webStreamToNodeStream(response.body, 64 * 1024, bytesToSkip, recreateSignal);
+ }
+ },
+ };
+ } catch (err) {
+ this.debug(`Direct format download failed with client ${clientType}:`, err);
}
- });
-
- if (!Readable.isReadable(nodeStream)) {
- throw new Error("youtubei.js audio stream is not readable");
}
- this.debug("✅ youtubei.js audio stream ready");
+ throw new Error("Direct format URL download failed for all clients");
+ }
- return {
- stream: nodeStream,
- type: "arbitrary",
- metadata: {
- ...track.metadata,
- itag: format.itag,
- mime: (format as any).mime_type ?? (format as any).mimeType,
- },
- };
+ protected async downloadWithYoutubei(track: Track, id: string, signal?: AbortSignal): Promise {
+ return this.downloadWithDirectUrl(track, id, signal);
}
+
private async downloadWithSabr(track: Track, id: string, signal?: AbortSignal): Promise {
- const { stream, format } = await this.getSabrDL(track, id, signal);
- const expectedId = track.id || this.extractVideoId(track.url);
+ const { stream, format, title, author, duration } = await this.getSabrDL(track, id, signal);
+ const isLive = Boolean(track.isLive || duration === 0 || track.duration === 0);
return {
stream,
type: "arbitrary",
+ position: 0,
metadata: {
...track.metadata,
+ title,
+ author,
+ duration,
itag: format.itag,
mime: format.mimeType,
+ contentLength: format.contentLength,
+ isLive,
+ },
+ recreate: async (position: number, recreateSignal?: AbortSignal) => {
+ const startTimeMs =
+ typeof position === "number" && Number.isFinite(position) && position > 0 ? Math.floor(position) : undefined;
+ const recreateResult = await createSabrStream(
+ id,
+ this.client,
+ {
+ audioPreferences: {
+ container: isLive ? ("mp4" as const) : undefined,
+ preferredAudioCodec: isLive ? ("aac" as const) : ("opus" as const),
+ ...this.options?.audioPreferences,
+ },
+ enabledTrackTypes: EnabledTrackTypes.AUDIO_ONLY,
+ startTimeMs,
+ },
+ recreateSignal,
+ );
+ return recreateResult.stream;
},
};
}
@@ -686,40 +744,27 @@ export class YouTubePlugin extends BasePlugin {
this.debug("🚀 Attempting sabr download for video ID:", id);
+ const isLive = Boolean(track.isLive || track.duration === 0 || (track.metadata as any)?.isLive);
const sabrOptions = {
- preferWebM: true,
- preferOpus: true,
- audioQuality: "medium",
+ audioPreferences: {
+ container: isLive ? ("mp4" as const) : undefined,
+ preferredAudioCodec: isLive ? ("aac" as const) : ("opus" as const),
+ ...this.options?.audioPreferences,
+ },
enabledTrackTypes: EnabledTrackTypes.AUDIO_ONLY,
};
- const { stream, title, format } = await createSabrStream(id, this.client, sabrOptions, signal);
+ const result = await createSabrStream(id, this.client, sabrOptions, signal);
- if (title && expectedTitle) {
- const actualTitle = title.toLowerCase().trim();
+ if (result.title && expectedTitle) {
+ const actualTitle = result.title.toLowerCase().trim();
const similarity = this.calculateTitleSimilarity(expectedTitle, actualTitle);
- this.debug(`Title similarity: ${similarity}% (Expected: "${expectedTitle}", Actual: "${title}")`);
+ this.debug(`Title similarity: ${similarity}% (Expected: "${expectedTitle}", Actual: "${result.title}")`);
}
this.debug("✅ Sabr download successful, stream ready");
- if (!stream) {
- throw new Error("Sabr download did not return a stream");
- }
-
- // Add error handler to prevent unhandled rejections from SABR
- stream.on("error", (error: Error) => {
- const errorMsg = error.message || String(error);
- // Log but suppress "Controller is already closed" errors as they're expected during cleanup
- if (!errorMsg.includes("Controller is already closed")) {
- this.debug("⚠️ SABR stream error:", errorMsg);
- }
- });
-
- return {
- stream,
- format,
- };
+ return result;
}
/**
* Gets related tracks for a given YouTube video.
@@ -810,41 +855,229 @@ export class YouTubePlugin extends BasePlugin {
async getVideo(track: Track, signal?: AbortSignal): Promise {
if (!track?.url && !track?.id && !track?.title) throw new Error("Track must have a URL, ID, or title");
- const plugin = this as any;
- plugin.throwIfAborted?.(signal);
- await plugin.ready;
- plugin.throwIfAborted?.(signal);
- let id = track.id || plugin.extractVideoId(track.url);
+ this.throwIfAborted(signal);
+ await this.ready;
+ this.throwIfAborted(signal);
+
+ let id = track.id || this.extractVideoId(track.url);
if (!id && track.title) {
const query = `${track.title} ${track.author || track.metadata?.author || ""}`.trim();
- plugin.debug("🎬 No direct YouTube ID for track, searching video:", query);
+ this.debug("🎬 No direct YouTube ID for track, searching video:", query);
try {
- const searchRes = await plugin.search(query, "youtube-video");
+ const searchRes = await this.search(query, "youtube-video");
const first = searchRes.tracks?.[0];
if (first) {
- id = first.id || plugin.extractVideoId(first.url);
+ id = first.id || this.extractVideoId(first.url);
}
} catch (err) {
- plugin.debug("⚠️ Video fallback search failed:", err);
+ this.debug("⚠️ Video fallback search failed:", err);
}
}
if (!id) throw new Error("Invalid YouTube video id");
- plugin.debug("🎬 Resolving YouTube video through SABR:", id);
- const result = await createSabrVideoStream(id, plugin.client, undefined, signal);
- plugin.throwIfAborted?.(signal);
- plugin.debug("✅ YouTube SABR video stream ready:", result.format);
- return {
- stream: result.stream,
- type: "arbitrary",
- metadata: {
- ...track.metadata,
- title: result.title,
- itag: result.format.itag,
- mime: result.format.mimeType,
- contentLength: result.format.contentLength,
- mediaType: "video",
+
+ const isLive = Boolean(track.isLive || track.duration === 0 || (track.metadata as any)?.isLive);
+ const downloads = [
+ {
+ name: "SABR video download",
+ run: async () => {
+ this.debug("🎬 Resolving YouTube video through SABR:", id);
+ const videoOptions = {
+ videoPreferences: {
+ quality: isLive ? "720p" : "1080p",
+ preferredVideoCodec: (isLive ? "vp9" : "h264") as any,
+ ...this.options?.videoPreferences,
+ },
+ audioPreferences: {
+ container: isLive ? ("mp4" as const) : undefined,
+ preferredAudioCodec: isLive ? ("aac" as const) : ("opus" as const),
+ ...this.options?.audioPreferences,
+ },
+ };
+
+ const result = await createSabrVideoStream(id, this.client, videoOptions as any, signal);
+ this.throwIfAborted(signal);
+ this.debug("✅ YouTube SABR video stream ready:", result.format);
+
+ return {
+ stream: result.stream,
+ type: "arbitrary",
+ position: 0,
+ metadata: {
+ ...track.metadata,
+ title: result.title,
+ author: result.author,
+ duration: result.duration,
+ itag: result.format.itag,
+ mime: result.format.mimeType,
+ contentLength: result.format.contentLength,
+ mediaType: "video",
+ isLive,
+ },
+ destroy: (result as any).destroy,
+ recreate: async (position: number, recreateSignal?: AbortSignal) => {
+ const startTimeMs =
+ typeof position === "number" && Number.isFinite(position) && position > 0 ? Math.floor(position) : undefined;
+ const res = await createSabrVideoStream(
+ id,
+ this.client,
+ {
+ videoPreferences: {
+ quality: isLive ? "720p" : "1080p",
+ preferredVideoCodec: (isLive ? "vp9" : "h264") as any,
+ ...this.options?.videoPreferences,
+ },
+ audioPreferences: {
+ container: isLive ? ("mp4" as const) : undefined,
+ preferredAudioCodec: isLive ? ("aac" as const) : ("opus" as const),
+ ...this.options?.audioPreferences,
+ },
+ startTimeMs,
+ } as any,
+ recreateSignal,
+ );
+ return res.stream;
+ },
+ } as StreamInfo;
+ },
},
- };
+ {
+ name: "Direct video URL download with BotGuard",
+ run: () => this.downloadVideoWithDirectUrl(track, id, signal),
+ },
+ ];
+
+ let lastError: unknown;
+ for (let i = 0; i < downloads.length; i++) {
+ const dl = downloads[i];
+ try {
+ this.debug(`🎬 Attempting ${dl.name}`);
+ return await dl.run();
+ } catch (err) {
+ if (signal?.aborted) throw signal.reason ?? new DOMException("The operation was aborted", "AbortError");
+ lastError = err;
+ this.debug(`⚠️ ${dl.name} failed:`, err);
+ }
+ }
+
+ throw lastError;
+ }
+
+ private async downloadVideoWithDirectUrl(track: Track, id: string, signal?: AbortSignal): Promise {
+ this.debug("🎬 Attempting direct video format URL download with BotGuard WebPO token");
+ this.throwIfAborted(signal);
+
+ if (track.isLive || track.duration === 0 || (track.metadata as any)?.isLive) {
+ throw new Error("Direct video format download is not supported for live streams (requires SABR)");
+ }
+
+ const poToken = await mintYouTubePoToken(id, signal);
+ this.throwIfAborted(signal);
+
+ const clientsToTry = ["IOS", "WEB", "TVHTML5"] as const;
+ for (const clientType of clientsToTry) {
+ try {
+ this.throwIfAborted(signal);
+ const videoInfo = await this.client.getBasicInfo(id, { client: clientType as any });
+ if (videoInfo.basic_info?.is_live) {
+ throw new Error("Direct video format download is not supported for live streams (requires SABR)");
+ }
+ const format = videoInfo.chooseFormat({
+ quality: "best",
+ type: "video",
+ format: "mp4",
+ });
+ if (!format) continue;
+
+ let directUrl: string | undefined = format.url;
+ if (!directUrl && typeof format.decipher === "function") {
+ try {
+ directUrl = await format.decipher(this.client.session.player);
+ } catch {}
+ }
+
+ if (!directUrl) continue;
+
+ const separator = directUrl.includes("?") ? "&" : "?";
+ const videoUrl = `${directUrl}${separator}pot=${encodeURIComponent(poToken)}`;
+
+ const response = await fetch(videoUrl, {
+ signal,
+ headers: {
+ "User-Agent": "Mozilla/5.0",
+ Accept: "*/*",
+ },
+ });
+
+ if (!response.ok || !response.body) continue;
+
+ const nodeStream = await webStreamToNodeStream(response.body, 256 * 1024, 0, signal);
+ if (!Readable.isReadable(nodeStream)) continue;
+
+ return {
+ stream: nodeStream,
+ type: "arbitrary",
+ position: 0,
+ metadata: {
+ ...track.metadata,
+ itag: format.itag,
+ mime: (format as any).mime_type ?? (format as any).mimeType,
+ contentLength: (format as any).content_length ?? (format as any).contentLength,
+ mediaType: "video",
+ },
+ destroy: () => {
+ if (!nodeStream.destroyed && typeof nodeStream.destroy === "function") {
+ try {
+ nodeStream.destroy();
+ } catch {}
+ }
+ },
+ recreate: async (position: number, recreateSignal?: AbortSignal) => {
+ const startTimeMs =
+ typeof position === "number" && Number.isFinite(position) && position > 0 ? Math.floor(position) : undefined;
+ try {
+ const res = await createSabrVideoStream(
+ id,
+ this.client,
+ {
+ videoPreferences: {
+ quality: "1080p",
+ preferredVideoCodec: "h264" as const,
+ ...this.options?.videoPreferences,
+ },
+ audioPreferences: {
+ preferredAudioCodec: "opus" as const,
+ ...this.options?.audioPreferences,
+ },
+ startTimeMs,
+ } as any,
+ recreateSignal,
+ );
+ return res.stream;
+ } catch {
+ const seekBytes = calculateSeekBytes(startTimeMs ?? 0, ((format as any).bitrate ?? 2500000) / 1000);
+ const poToken = await mintYouTubePoToken(id, recreateSignal);
+ const separator = directUrl.includes("?") ? "&" : "?";
+ const videoUrl = `${directUrl}${separator}pot=${encodeURIComponent(poToken)}`;
+ const response = await fetch(videoUrl, {
+ signal: recreateSignal,
+ headers: {
+ "User-Agent": "Mozilla/5.0",
+ Accept: "*/*",
+ ...(seekBytes > 0 ? { Range: `bytes=${seekBytes}-` } : {}),
+ },
+ });
+ if (!response.ok || !response.body) throw new Error("Failed to recreate direct video stream");
+ const bytesToSkip = response.status === 206 ? 0 : seekBytes;
+ return await webStreamToNodeStream(response.body, 256 * 1024, bytesToSkip, recreateSignal);
+ }
+ },
+ };
+ } catch (err) {
+ this.debug(`Direct video download with client ${clientType} failed:`, err);
+ }
+ }
+
+ throw new Error("Direct video format URL download failed for all available clients");
}
private normalizeYouTubeMixUrl(input: string): string {
diff --git a/plugins/src/index.ts b/plugins/src/index.ts
index 32300e1d..a85ad7cd 100644
--- a/plugins/src/index.ts
+++ b/plugins/src/index.ts
@@ -107,3 +107,25 @@ export * from "./TTSPlugin.js";
* );
*/
export * from "./AttachmentsPlugin.js";
+
+/**
+ * Bilibili plugin for handling Bilibili videos, playlists, and search.
+ *
+ * Provides comprehensive support for Bilibili content including:
+ * - Video URLs (bilibili.com, b23.tv)
+ * - Playlist URLs and user favorites
+ * - Search functionality
+ * - Audio stream extraction
+ * - Related track recommendations
+ *
+ * @example
+ * const bilibiliPlugin = new BilibiliPlugin({
+ * quality: "super",
+ * preferHiRes: false,
+ * multiPartAsPlaylist: true,
+ * maxPlaylistItems: 100
+ * });
+ * const result = await bilibiliPlugin.search("周杰伦 青花瓷", "user123");
+ */
+
+export * from "./BilibiliPlugin.js";
diff --git a/plugins/src/utils/sabr-stream-factory.ts b/plugins/src/utils/sabr-stream-factory.ts
index 5f2b949a..0b4f152b 100644
--- a/plugins/src/utils/sabr-stream-factory.ts
+++ b/plugins/src/utils/sabr-stream-factory.ts
@@ -1,21 +1,37 @@
-import { createWriteStream } from "node:fs";
+import { createWriteStream, type WriteStream } from "node:fs";
import { join } from "node:path";
import { tmpdir } from "node:os";
import { Readable } from "node:stream";
+import crypto from "node:crypto";
+import zlib from "node:zlib";
-import { BotGuardClient, getChallenge } from "bgutils-js/botguard";
-import type { WebPoSignalOutput } from "bgutils-js/shared-types";
-import { buildURL, getHeaders, USER_AGENT } from "bgutils-js/utils";
-import { WebPoMinter } from "bgutils-js/webpo";
-import { JSDOM } from "jsdom";
-import { Constants, Innertube, Platform, UniversalCache, type Types } from "youtubei.js";
-import { SabrStream, type SabrPlaybackOptions } from "googlevideo/sabr-stream";
-import { buildSabrFormat, EnabledTrackTypes } from "googlevideo/utils";
+import { Constants, type IPlayerResponse, Platform, YTNodes, type Types, type Context } from "youtubei.js";
+import { SabrStream, type SabrPlaybackOptions, type PlayabilityStatus } from "googlevideo/sabr-stream";
+import { buildSabrFormat, EnabledTrackTypes, base64ToU8, concatenateChunks } from "googlevideo/utils";
+import { UmpReader } from "googlevideo/ump";
+import {
+ UMPPartId,
+ OnesieInnertubeRequest,
+ OnesieHeader,
+ OnesieProxyStatus,
+ OnesieInnertubeResponse,
+ OnesieRequest,
+ CompressionType,
+ OnesieHeaderType,
+ type ReloadPlaybackContext,
+} from "googlevideo/protos";
import type { SabrFormat } from "googlevideo/shared-types";
-import type { ReloadPlaybackContext } from "googlevideo/protos";
+
+import type { Innertube } from "youtubei.js";
+import { mintYouTubePoToken, mintYouTubePoTokenBytes } from "./youtube-botguard.js";
+import { webStreamToNodeStream } from "./stream-converter.js";
+
+Platform.shim.eval = async (data: Types.BuildScriptResult) => {
+ return new Function(data.output)();
+};
export interface OutputStream {
- stream: NodeJS.WritableStream;
+ stream: WriteStream;
filePath: string;
}
@@ -27,6 +43,9 @@ export interface SabrAudioResult {
itag: number;
contentLength: number;
};
+ author?: string;
+ duration?: number;
+ destroy?: () => void | Promise;
}
export interface SabrVideoResult {
@@ -37,88 +56,271 @@ export interface SabrVideoResult {
itag: number;
contentLength: number;
};
+ author?: string;
+ duration?: number;
+ destroy?: () => void | Promise;
}
-Platform.shim.eval = async (data: Types.BuildScriptResult) => new Function(data.output)();
+/**
+ * Standard YouTube player request with signature timestamp and web client context.
+ */
+export async function makePlayerRequest(
+ innertube: Innertube,
+ input: string | YTNodes.NavigationEndpoint,
+ reloadPlaybackContext?: ReloadPlaybackContext,
+ client: string = "WEB",
+): Promise {
+ const watchEndpoint = typeof input === "string" ? new YTNodes.NavigationEndpoint({ watchEndpoint: { videoId: input } }) : input;
-async function generatePoToken(contentBinding: string, signal?: AbortSignal): Promise {
- const requestKey = "O43z0dpjhgX20SCx4KAo";
- const dom = new JSDOM(' ', {
- url: "https://www.youtube.com/",
- referrer: "https://www.youtube.com/",
- userAgent: USER_AGENT,
- });
- Object.assign(globalThis, {
- window: dom.window,
- document: dom.window.document,
- location: dom.window.location,
- origin: dom.window.origin,
- });
- if (!Reflect.has(globalThis, "navigator")) Object.defineProperty(globalThis, "navigator", { value: dom.window.navigator });
- const challenge = await getChallenge({ fetchFunction: fetch, requestKey });
- const interpreterJavascript = challenge.interpreterJavascript?.privateDoNotAccessOrElseSafeScriptWrappedValue;
- if (!interpreterJavascript) throw new Error("BotGuard interpreter javascript is not available");
- new Function(interpreterJavascript)();
- const botGuardClient = await BotGuardClient.create({
- program: challenge.program,
- globalName: challenge.globalName,
- globalObject: globalThis,
- });
- const webPoSignalOutput: WebPoSignalOutput = [];
- const botguardResponse = await botGuardClient.snapshot({ webPoSignalOutput });
- const response = await fetch(buildURL("GenerateIT", true), {
- method: "POST",
- headers: getHeaders(),
- body: JSON.stringify([requestKey, botguardResponse]),
+ const extraArgs: Record = {
+ playbackContext: {
+ contentPlaybackContext: {
+ vis: 0,
+ splay: false,
+ signatureTimestamp: innertube.session.player?.signature_timestamp,
+ },
+ },
+ contentCheckOk: true,
+ racyCheckOk: true,
+ client,
+ };
+
+ if (reloadPlaybackContext) {
+ extraArgs.playbackContext.reloadPlaybackContext = reloadPlaybackContext;
+ }
+
+ return await watchEndpoint.call(innertube.actions, { ...extraArgs, parse: true });
+}
+
+type TVClientConfig = {
+ clientKeyData: Uint8Array;
+ encryptedClientKey: Uint8Array;
+ onesieUstreamerConfig: Uint8Array;
+ baseUrl: string;
+};
+
+async function getYouTubeTVClientConfig(signal?: AbortSignal): Promise {
+ const tvConfigResponse = await fetch("https://www.youtube.com/tv_config?action_get_config=true&client=lb4&theme=cl", {
+ method: "GET",
signal,
+ headers: {
+ "User-Agent": "Mozilla/5.0 (ChromiumStylePlatform) Cobalt/Version",
+ },
});
- if (!response.ok) throw new Error(`GenerateIT failed: HTTP ${response.status}`);
- const [integrityToken, estimatedTtlSecs, mintRefreshThreshold, websafeFallbackToken] = (await response.json()) as [
- string,
- number,
- number,
- string,
- ];
- if (!integrityToken) throw new Error("GenerateIT returned an empty integrity token");
- const webPoMinter = await WebPoMinter.create(
- { integrityToken, estimatedTtlSecs, mintRefreshThreshold, websafeFallbackToken },
- webPoSignalOutput,
- );
- return webPoMinter.mintAsWebsafeString(contentBinding);
-}
-export async function createSabrInnertube(): Promise {
- return Innertube.create({ cache: new UniversalCache(true) });
+ const tvConfig = await tvConfigResponse.text();
+ if (!tvConfig.startsWith(")]}'")) {
+ throw new Error("Invalid response from YouTube TV config endpoint");
+ }
+
+ const tvConfigJson = JSON.parse(tvConfig.slice(4));
+ const webPlayerContextConfig = tvConfigJson.webPlayerContextConfig.WEB_PLAYER_CONTEXT_CONFIG_ID_LIVING_ROOM_WATCH;
+ const onesieHotConfig = webPlayerContextConfig.onesieHotConfig;
+
+ return {
+ clientKeyData: base64ToU8(onesieHotConfig.clientKey),
+ encryptedClientKey: base64ToU8(onesieHotConfig.encryptedClientKey),
+ onesieUstreamerConfig: base64ToU8(onesieHotConfig.onesieUstreamerConfig),
+ baseUrl: onesieHotConfig.baseUrl,
+ };
}
-async function makePlayerRequest(
- innertube: Innertube,
- videoId: string,
- _reloadPlaybackContext?: ReloadPlaybackContext,
-): Promise {
- return innertube.getBasicInfo(videoId, { client: "YTMUSIC" });
+async function encryptRequest(clientKey: Uint8Array, data: Uint8Array) {
+ const aesKeyData = clientKey.slice(0, 16);
+ const hmacKeyData = clientKey.slice(16, 32);
+ const iv = crypto.getRandomValues(new Uint8Array(16));
+
+ const aesKey = await crypto.subtle.importKey("raw", aesKeyData, { name: "AES-CTR", length: 128 }, false, ["encrypt"]);
+
+ const encrypted = new Uint8Array(
+ await crypto.subtle.encrypt({ name: "AES-CTR", counter: iv, length: 128 }, aesKey, data as any),
+ );
+
+ const hmacKey = await crypto.subtle.importKey("raw", hmacKeyData, { name: "HMAC", hash: { name: "SHA-256" } }, false, ["sign"]);
+
+ const hmac = new Uint8Array(await crypto.subtle.sign("HMAC", hmacKey, new Uint8Array([...encrypted, ...iv])));
+
+ return { encrypted, hmac, iv };
}
-function getClientInfo(innertube: Innertube) {
- const clientName =
- Constants.CLIENT_NAME_IDS[innertube.session.context.client.clientName as keyof typeof Constants.CLIENT_NAME_IDS];
- if (clientName === undefined) throw new Error(`Unknown InnerTube client: ${innertube.session.context.client.clientName}`);
- return { clientName: parseInt(String(clientName), 10), clientVersion: innertube.session.context.client.clientVersion };
+/**
+ * Fallback: Fetches player response using UMP Onesie request (/initplayback)
+ * when normal player endpoints fail or are blocked.
+ */
+export async function getOnesiePlayerResponse(innertube: Innertube, videoId: string, signal?: AbortSignal): Promise