Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions .github/workflows/node.js.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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 }}-

Expand All @@ -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
Expand Down
10 changes: 8 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)`.
Expand Down
75 changes: 0 additions & 75 deletions AUDIO_ENGINE_REVIEW.md

This file was deleted.

4 changes: 1 addition & 3 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -201,9 +201,7 @@ export class MyPlugin extends BasePlugin {
async search(query: string, requestedBy: string): Promise<SearchResult> {
// Implement search logic
return {
tracks: [
/* ... */
],
tracks: [/* ... */],
};
}

Expand Down
4 changes: 1 addition & 3 deletions adapters/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
10 changes: 10 additions & 0 deletions client/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`:
Expand Down
13 changes: 12 additions & 1 deletion client/browser/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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();
Expand Down
2 changes: 1 addition & 1 deletion client/package.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down
72 changes: 72 additions & 0 deletions client/test/protocol.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
});
Loading
Loading