Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
55 commits
Select commit Hold shift + click to select a range
e81c641
Audio processing engine is in place and verified
zijipia Oct 9, 2026
b51e957
Raw PCM contract fix is validated
zijipia Oct 9, 2026
7085783
Harden stream error handling trong resource creation
zijipia Oct 9, 2026
1931755
Implemented and verified the first output-backend boundary while reta…
zijipia Oct 9, 2026
4859693
refactor: update playback control methods to support async/await
zijipia Oct 10, 2026
ac2dabc
Enhance error handling in playback controllers and backend interactions
zijipia Oct 10, 2026
51bc189
fix: harden playback lifecycle error handling
zijipia Oct 10, 2026
e85765e
fix: isolate cancellation for coalesced remote stops
zijipia Oct 10, 2026
dbda1db
fix: reconcile remote stop after session replacement
zijipia Oct 10, 2026
f6e8168
feat: implement WebSocket audio output backend with encoding and deco…
zijipia Oct 10, 2026
03b12bc
feat: enhance WebSocket audio output backend with improved session ma…
zijipia Oct 10, 2026
26b3638
feat: add Web Audio client and backend example for ZiPlayer
zijipia Oct 10, 2026
2411c36
feat: update README and example configurations for improved local set…
zijipia Oct 10, 2026
ae86dc9
feat: update README and example configurations for improved setup and…
zijipia Oct 10, 2026
9ab9840
Support tokenless gateway and player controls
zijipia Oct 10, 2026
429e6c7
Fix preload and listener cleanup
zijipia Oct 10, 2026
37d35aa
format
zijipia Oct 10, 2026
ec41354
Use first search match unless playlist
zijipia Oct 10, 2026
7e49fdb
Fix stale pause/resume and stream player state
zijipia Oct 10, 2026
7c1c324
Harden PCM pipeline and docs
zijipia Oct 10, 2026
a5a9cbb
Cancellation and cleanup
zijipia Oct 10, 2026
d5e45da
Replace legacy audio DSP with FFmpeg engine
zijipia Oct 11, 2026
520de62
Add FFmpeg DSP safety and output negotiation
zijipia Oct 11, 2026
a5d8151
Fix FFmpeg path and playback refresh lifecycle
zijipia Oct 11, 2026
291c642
Delete AGENTS.md
zijipia Oct 11, 2026
277e16d
Update package.json
zijipia Oct 11, 2026
ffb924f
Update PlaybackController.ts
zijipia Oct 12, 2026
85a51b5
Add multi-output fanout with safer FFmpeg
zijipia Oct 12, 2026
6104b77
Support concurrent multi-output audio sinks
zijipia Oct 12, 2026
71cc1be
Add native Opus passthrough and browser Opus support
zijipia Oct 12, 2026
ce89a49
Add Wire Format v1 audio framing
zijipia Oct 12, 2026
63c8471
Unify native Opus passthrough across outputs
zijipia Oct 12, 2026
7cc2f75
Validate audio framing/flags; add resource-play RPC
zijipia Oct 13, 2026
2f64a61
Fix WebAudio lifecycle and Opus validation
zijipia Oct 13, 2026
6663cd4
Fix Opus lifecycle and metadata regressions
zijipia Oct 13, 2026
a41c3e2
Fix Opus source lifecycle and validation
zijipia Oct 13, 2026
a15ac81
Update Player.ts
zijipia Oct 13, 2026
7b183a3
Switch browser output to Opus-only pipeline
zijipia Oct 14, 2026
53d278d
Simplify audio outputs to shared AudioPlayer
zijipia Oct 14, 2026
9f62b28
Move WebAudio outputs into ConnectionController
zijipia Oct 14, 2026
a5897d8
Expose all player connections
zijipia Oct 14, 2026
2bc8bc1
Share plugin manager with isolated runtimes
zijipia Oct 16, 2026
a22a902
Support requester objects and scoped extensions
zijipia Oct 17, 2026
0958c13
Add player data maps and runtime ID changes
zijipia Oct 18, 2026
26180e1
Improve hot player ID changes
zijipia Oct 18, 2026
bd035dc
Update core.ts
zijipia Oct 18, 2026
0f1de64
Improve playback fallbacks and test reliability
zijipia Oct 18, 2026
ec577c0
Align plugins with the latest core API
zijipia Oct 18, 2026
81bf957
Fix TTS search and playback routing
zijipia Oct 24, 2026
74f9444
Add browser audio visualizer helpers
zijipia Oct 24, 2026
1174ab0
Queue TTS playback and support desktop clients
zijipia Oct 28, 2026
7d35019
Fix concurrent TTS and WebAudio reconnects
zijipia Oct 28, 2026
ee7f91e
format
zijipia Oct 28, 2026
fc55251
Remove redundant audio processing engine
zijipia Oct 29, 2026
a9f48b9
Seeking on a stream providing `streamInfo.recreate(position)
zijipia Oct 29, 2026
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
70 changes: 26 additions & 44 deletions .github/workflows/node.js.yml
Original file line number Diff line number Diff line change
@@ -1,48 +1,16 @@
name: Node.js CI

permissions:
contents: write
contents: read
issues: write
pull-requests: write

on:
push:
branches: ["main"]
branches: ["main", "AudioEngine"]
pull_request:
branches: ["main"]

jobs:
format-fix-on-push:
if: github.event_name == 'push'
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
with:
token: ${{ secrets.ACTIONS_TOKEN }}
fetch-depth: 0

- name: Use Node.js
uses: actions/setup-node@v4
with:
node-version: "20.x"

- name: Run Prettier (write)
run: npx prettier --ignore-path .gitignore --write .

- name: Commit changes
run: |
git config --local user.email "41898282+github-actions[bot]@users.noreply.github.com"
git config --local user.name "github-actions[bot]"
git add .
git diff --cached --exit-code || git commit -m "chore: format with prettier"

- name: Push changes
uses: ad-m/github-push-action@master
with:
github_token: ${{ secrets.ACTIONS_TOKEN }}
branch: ${{ github.head_ref || github.ref_name }}

format-check-on-pr:
if: github.event_name == 'pull_request'
runs-on: ubuntu-latest
Expand All @@ -62,7 +30,7 @@ jobs:
shell: bash
run: |
set -e
OUTPUT="$(npx prettier --ignore-path .gitignore -l . || true)"
OUTPUT="$(npx prettier --ignore-path .gitignore -l .)"
echo "files<<EOF" >> "$GITHUB_OUTPUT"
echo "$OUTPUT" >> "$GITHUB_OUTPUT"
echo "EOF" >> "$GITHUB_OUTPUT"
Expand Down Expand Up @@ -119,22 +87,36 @@ jobs:
- name: Use Node.js
uses: actions/setup-node@v4
with:
node-version: "20.x"
node-version: "22.x"

- name: Cache npm
uses: actions/cache@v4
with:
path: ~/.npm
key:
npm-${{ runner.os }}-${{ hashFiles('core/package.json', 'plugins/package.json', 'extension/package.json',
'package.json') }}
restore-keys: npm-${{ runner.os }}-

- name: Bootstrap core package
run: |
npm -C core ci || npm -C core i --force
npm -C core run build || true
# package-lock.json is ignored and no lockfiles are committed for these packages.
# core/package.json overrides prism-media's opusscript peer so install has no ERESOLVE.
npm -C core install --package-lock=false --no-audit --no-fund
npm -C core run build

- name: Bootstrap plugins package
run: |
npm -C plugins ci || npm -C plugins i --force
npm -C plugins run build || true
npm -C plugins install --package-lock=false --no-audit --no-fund
npm -C plugins run build

- name: Bootstrap extension package
run: |
npm -C extension ci || npm -C extension i --force
npm -C extension run build || true
npm -C extension install --package-lock=false --no-audit --no-fund
npm -C extension run build

- name: Bootstrap root package
run: npm install --no-save --package-lock=false --no-audit --no-fund ./core

- name: Run tests
id: tests
Expand All @@ -158,7 +140,7 @@ jobs:
if: github.event_name == 'pull_request'
uses: actions/github-script@v7
with:
github-token: ${{ secrets.ACTIONS_TOKEN }}
github-token: ${{ secrets.GITHUB_TOKEN }}
script: |
const marker = '<!-- test-report -->';
const status = `${{ steps.tests.outputs.status }}` || 'unknown';
Expand All @@ -173,7 +155,7 @@ jobs:
summary || 'No summary captured',
'```',
'',
'_Node.js 20.x_'
'_Node.js 22.x_'
].join('\n');
const { owner, repo } = context.repo;
const issue_number = context.issue.number;
Expand Down
41 changes: 41 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# ZiPlayer repository guide for coding agents

Read the root [`README.md`](README.md) for public setup and player workflows. For core API use and internal architecture, read
[`core/AGENTS.md`](core/AGENTS.md). The core package's agent guide is included in the published `ziplayer` package.

## Repository structure

- `core/src/` contains the player facade, manager, controllers, stream handling, audio subscribers, and public exports. Edit
source here; `core/dist/` is generated.
- `plugins/`, `extension/`, `infinity/`, and `adapters/` 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.
- `tests/` contains core regression tests; each package can also provide focused tests.

## User-facing behavior

- Normal applications should use `PlayerManager`, `Player`, plugins, and documented player options, not private Bus/controller
internals.
- Discord Voice 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.
- 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)`.
- The current player stack supports queue orchestration, smart preloading, crossfade/transition flow, loudness normalization,
anti-stuck recovery, filter chains, and browser/WebSocket publishing in addition to standard voice playback.
- Normal playback feeds the source stream directly to `createAudioResource` (with inline volume enabled) without running FFmpeg.
When filters are active or seeking on a non-seekable stream is performed, `FilterController` runs FFmpeg as a single-pass filter
child process emitting Ogg Opus, which is consumed directly by the resource pipeline. PCM remains internal to codec/DSP
processing and browser decoding, not an intermediate pipeline or WebSocket transport format.
- Keep public documentation and the package `AGENTS.md` guides aligned with changes to exported APIs and expected workflows.

## Validation

- `npm test` builds core and runs the root unit/regression tests.
- `npm test --prefix examples/backend` checks gateway handoff behavior.
- `npm test --prefix client` checks browser protocol validation and frame decoding.
- `npm run test:integration` runs plugin/extension integration tests when relevant.
- Use `npx prettier --check <changed paths>` and `git diff --check` for changed source and documentation.
- Do not edit generated `core/dist/` files directly.
75 changes: 75 additions & 0 deletions AUDIO_ENGINE_REVIEW.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
# 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.
4 changes: 3 additions & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,9 @@ export class MyPlugin extends BasePlugin {
async search(query: string, requestedBy: string): Promise<SearchResult> {
// Implement search logic
return {
tracks: [/* ... */],
tracks: [
/* ... */
],
};
}

Expand Down
29 changes: 29 additions & 0 deletions IMPLEMENTATION_STATUS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# Audio playback architecture

## Current design

- Each managed player owns one `@discordjs/voice` `AudioPlayer`.
- Playback wraps a source `Readable` in an inline-volume `AudioResource` and starts it with `AudioPlayer.play(resource)`.
- Discord Voice and `WebAudioConnection` subscribe directly to the same player and receive the same Opus packets. WebAudio wraps
those packets in ZI v1 frames for the application gateway.
- Player controls, volume, resource replacement, and lifecycle are handled directly by the shared `AudioPlayer` and
`AudioResource`.
- There is no server-side PCM output path, `AudioOutputBackend`, `DiscordVoiceOutputBackend`, `MultiAudioOutputBackend`, or
output-backend factory. Generic stream-output backends are not accepted by `Player.connect()`.
- PCM remains an internal DSP/codec representation and is produced locally by browser Opus decoding for AudioWorklet playback; PCM
is not sent over the WebSocket protocol.
- FFmpeg protections remain in place, including executable selection, concurrency limits, redirect-by-redirect URL validation with
DNS address pinning, and rejection of unsafe direct FFmpeg URL input.

## Validation

Core build and regression tests are run from the repository root:

```sh
npm run build:core
npm test
npm test --prefix examples/backend
npm test --prefix client
```

Real Discord Voice/UDP readiness and end-to-end gateway delivery still require a live deployment environment.
Loading
Loading