-
Notifications
You must be signed in to change notification settings - Fork 1.9k
feat(plugin): audio stream #4396
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
ArjixWasTaken
wants to merge
50
commits into
master
Choose a base branch
from
plugin/audio-stream
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
50 commits
Select commit
Hold shift + click to select a range
f8e6045
new plugin: audio-stream
dnecra f44a1f0
fix audio-stream
dnecra bb38318
Merge branch 'pear-devs:master' into master
dnecra 1e8b093
fix audio-stream
dnecra 70673db
fix audio-stream
dnecra f27372a
Update src/plugins/audio-stream/backend.ts
dnecra fab4b6b
Update src/plugins/audio-stream/backend.ts
dnecra 8b36e8b
Update src/plugins/audio-stream/backend.ts
dnecra d19c899
Update src/plugins/audio-stream/backend.ts
dnecra ec30930
Update src/plugins/audio-stream/backend.ts
dnecra e679311
Update src/plugins/audio-stream/backend.ts
dnecra 16da921
Update src/plugins/audio-stream/backend.ts
dnecra 8b4448a
Update src/plugins/audio-stream/backend.ts
dnecra 87146da
Update src/plugins/audio-stream/backend.ts
dnecra bc9d099
Update src/plugins/audio-stream/backend.ts
dnecra e4c748e
Update src/plugins/audio-stream/backend.ts
dnecra 792b440
Update src/plugins/audio-stream/backend.ts
dnecra d1d891b
Update src/plugins/audio-stream/backend.ts
dnecra 7a1fbea
Update src/plugins/audio-stream/backend.ts
dnecra 024508b
Update src/plugins/audio-stream/backend.ts
dnecra 0af3e8e
Update src/plugins/audio-stream/backend.ts
dnecra 6c112be
Update src/plugins/audio-stream/backend.ts
dnecra 5ca2a7f
Update src/plugins/audio-stream/backend.ts
dnecra 738872d
Update src/plugins/audio-stream/backend.ts
dnecra 13f818a
Update src/plugins/audio-stream/backend.ts
dnecra d995d9f
Update src/plugins/audio-stream/backend.ts
dnecra 8fa70f8
Update src/plugins/audio-stream/backend.ts
dnecra 59490ed
Update src/plugins/audio-stream/backend.ts
dnecra d87c843
Update src/plugins/audio-stream/backend.ts
dnecra 668ac39
Update src/plugins/audio-stream/backend.ts
dnecra 80e17d9
Update src/plugins/audio-stream/backend.ts
dnecra a2fea13
Merge branch 'pear-devs:master' into master
dnecra d443777
Migrate audio processing to AudioWorkletNode
dnecra 01842c8
Implement binary PCM data handling in audio stream
dnecra 02a74de
Update src/plugins/audio-stream/backend.ts
dnecra 5e85f8b
Update src/plugins/audio-stream/backend.ts
dnecra d6aa17d
Update src/plugins/audio-stream/backend.ts
dnecra ddefbb6
Update src/plugins/audio-stream/backend.ts
dnecra 278bcaf
Update src/plugins/audio-stream/backend.ts
dnecra b562ea1
Merge branch 'master' into master
ArjixWasTaken 9078890
init rewrite of plugin
ArjixWasTaken 39275d6
Merge branch 'master' into master
ArjixWasTaken 966142d
Merge branch 'master' into master
ArjixWasTaken 88bb2a0
bla
ArjixWasTaken 85e3144
Merge branch 'master' into plugin/audio-stream
ArjixWasTaken ad31a28
feat(audio-stream): Switch to Opus/Ogg streaming
ArjixWasTaken ef89712
Merge branch 'master' into plugin/audio-stream
ArjixWasTaken 1132ba7
apply suggestions from CodeRabbit
ArjixWasTaken 32d9fc5
Merge remote-tracking branch 'upstream/master' into plugin/audio-stream
ArjixWasTaken f2f79dd
fix oxlint rants
ArjixWasTaken File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,48 @@ | ||
| export class BroadcastStream { | ||
| private subscribers: Set<ReadableStreamDefaultController<Uint8Array>> = | ||
| new Set(); | ||
|
|
||
| // Get a new stream. Any priming pages (e.g. cached Ogg header pages) are | ||
| // enqueued first so the subscriber can initialise its decoder before the | ||
| // live audio pages arrive. | ||
| subscribe(primingPages: Uint8Array[] = []) { | ||
| let controller!: ReadableStreamDefaultController<Uint8Array>; | ||
| const subscribers = this.subscribers; | ||
| const stream = new ReadableStream<Uint8Array>({ | ||
| start(c) { | ||
| controller = c; | ||
| for (const page of primingPages) c.enqueue(page); | ||
| subscribers.add(c); | ||
| }, | ||
| cancel() { | ||
| subscribers.delete(controller); | ||
| }, | ||
| }); | ||
|
|
||
| return stream; | ||
| } | ||
|
|
||
| // Write data to all readers. | ||
| write(chunk: Uint8Array) { | ||
| for (const controller of this.subscribers) { | ||
| // Drop slow clients whose queue has backed up rather than buffering | ||
| // chunks for them unboundedly. | ||
| if ((controller.desiredSize ?? 0) <= 0) { | ||
| this.subscribers.delete(controller); | ||
| continue; | ||
| } | ||
| try { | ||
| controller.enqueue(chunk); | ||
| } catch { | ||
| this.subscribers.delete(controller); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| close() { | ||
| for (const controller of this.subscribers) { | ||
| controller.close(); | ||
| } | ||
| this.subscribers.clear(); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,36 @@ | ||
| /* eslint-disable no-undef, typescript/no-unsafe-assignment, typescript/no-unsafe-member-access, typescript/no-unsafe-call */ | ||
| class RecorderProcessor extends AudioWorkletProcessor { | ||
| constructor(options) { | ||
| super(); | ||
| const bufferSize = options?.processorOptions?.bufferSize || 4096; | ||
| // Prepare an interleaved stereo buffer [L,R,L,R,...] | ||
| this.buffer = new Float32Array(bufferSize * 2); | ||
| this.bufferIndex = 0; | ||
| } | ||
|
|
||
| process(inputs, outputs) { | ||
| const input = inputs[0]; | ||
| if (input && input[0]) { | ||
| const left = input[0]; | ||
| const right = input[1] || left; // if mono input, duplicate for right | ||
| for (let i = 0; i < left.length; i++) { | ||
| this.buffer[this.bufferIndex++] = left[i]; | ||
| this.buffer[this.bufferIndex++] = right[i]; | ||
| if (this.bufferIndex >= this.buffer.length) { | ||
| // Buffer full: send a copy to the main thread | ||
| this.port.postMessage(new Float32Array(this.buffer)); | ||
| this.bufferIndex = 0; | ||
| } | ||
| } | ||
| } | ||
| // Optionally pass the audio through unchanged. outputs[0] can be an empty | ||
| // array (no channels connected), so guard each channel before .set(). | ||
| if (outputs[0] && inputs[0]) { | ||
| if (outputs[0][0] && inputs[0][0]) outputs[0][0].set(inputs[0][0]); | ||
| if (outputs[0][1] && inputs[0][1]) outputs[0][1].set(inputs[0][1]); | ||
| } | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
| return true; | ||
| } | ||
| } | ||
|
|
||
| registerProcessor('recorder-processor', RecorderProcessor); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,135 @@ | ||
| import { serve, type ServerType } from '@hono/node-server'; | ||
| import { Hono } from 'hono'; | ||
| import { stream } from 'hono/streaming'; | ||
|
|
||
| import { registerCallback, type SongInfo } from '@/providers/song-info'; | ||
| import { createBackend } from '@/utils'; | ||
|
|
||
| import { BroadcastStream } from './BroadcastStream'; | ||
| import { type AudioStreamConfig } from './config'; | ||
| import { OggOpusMuxer, OggDechainer } from './ogg-opus'; | ||
|
|
||
| const VENDOR = 'Pear Desktop'; | ||
|
|
||
| let config: AudioStreamConfig; | ||
| const broadcast = new BroadcastStream(); | ||
|
|
||
| // Current track metadata (no ffprobe - comes straight from the player). | ||
| let currentSong: SongInfo | null = null; | ||
|
|
||
| // Chained Ogg/Opus stream: one logical stream per song. Pages go straight to | ||
| // every subscriber; the muxer caches the current stream's header pages for late | ||
| // joiners. | ||
| const muxer = new OggOpusMuxer((page) => broadcast.write(page)); | ||
|
|
||
| // OpusTags comments for the current track (text only). | ||
| function currentComments(): string[] { | ||
| const comments: string[] = []; | ||
| if (currentSong?.title) comments.push(`TITLE=${currentSong.title}`); | ||
| if (currentSong?.artist) comments.push(`ARTIST=${currentSong.artist}`); | ||
| if (currentSong?.album) comments.push(`ALBUM=${currentSong.album}`); | ||
| return comments.length ? comments : ['TITLE=Pear Desktop']; | ||
| } | ||
|
|
||
| export const backend = createBackend< | ||
| { | ||
| app: Hono; | ||
| server?: ServerType; | ||
| }, | ||
| AudioStreamConfig | ||
| >({ | ||
| app: new Hono().get('/stream', (ctx) => { | ||
| // Per-song TEXT metadata is carried in-band via chained Ogg logical streams | ||
| // (OpusTags per track). Some clients can't follow chains - browsers | ||
| // (<audio>/MSE) reload on a new BOS, and VLC's clock chokes on it - so they | ||
| // get a de-chained single logical stream instead. | ||
| const ua = ctx.req.header('User-Agent') ?? ''; | ||
| const needsDechain = /Mozilla|VLC/i.test(ua); | ||
|
|
||
| ctx.header('Content-Type', 'audio/ogg'); | ||
| ctx.header('Transfer-Encoding', 'chunked'); | ||
| ctx.header('Access-Control-Allow-Origin', '*'); | ||
|
|
||
| if (!needsDechain) { | ||
| ctx.header('icy-name', 'Pear Desktop'); | ||
| ctx.header('icy-url', 'https://github.com/pear-devs/pear-desktop'); | ||
| ctx.header( | ||
| 'icy-audio-info', | ||
| `ice-channels=${config.channels};ice-samplerate=48000;ice-bitrate=${Math.round( | ||
| config.bitrate / 1000, | ||
| )}`, | ||
| ); | ||
| ctx.header('icy-pub', '1'); | ||
| } | ||
|
|
||
| ctx.header('Server', 'Pear Desktop'); | ||
|
|
||
| return stream(ctx, async (stream) => { | ||
| // New subscriber gets the cached OpusHead + OpusTags pages first, so the | ||
| // decoder can initialise before any audio page arrives. | ||
| let readable = broadcast.subscribe(muxer.headerPages); | ||
|
|
||
| if (needsDechain) { | ||
| const dechainer = new OggDechainer(); | ||
| readable = readable.pipeThrough( | ||
| new TransformStream<Uint8Array, Uint8Array>({ | ||
| transform(page, controller) { | ||
| for (const out of dechainer.push(page)) controller.enqueue(out); | ||
| }, | ||
| }), | ||
| ); | ||
| } | ||
|
|
||
| return await stream.pipe(readable); | ||
| }); | ||
| }), | ||
|
|
||
| async start({ getConfig, ipc }) { | ||
| config = await getConfig(); | ||
|
|
||
| this.server = serve( | ||
| { | ||
| fetch: this.app.fetch.bind(this.app), | ||
| hostname: config.hostname, | ||
| port: config.port, | ||
| }, | ||
| ({ address, port }) => console.log('Listening on', { address, port }), | ||
| ); | ||
|
|
||
| // Track metadata (no ffprobe needed). On an actual song change, start a new | ||
| // logical stream so the new title/artist/album are embedded in-band. | ||
| // SongInfo also fires for play/pause and time updates, so gate on videoId. | ||
| let lastVideoId = ''; | ||
| registerCallback((songInfo: SongInfo) => { | ||
| currentSong = songInfo; | ||
| if (songInfo.videoId && songInfo.videoId !== lastVideoId) { | ||
| lastVideoId = songInfo.videoId; | ||
| if (muxer.ready) muxer.chain(VENDOR, currentComments()); | ||
| } | ||
| }); | ||
|
|
||
| // OpusHead (from WebCodecs decoderConfig.description) opens the first stream. | ||
| ipc.on('audio-stream:opus-head', (head: Uint8Array) => { | ||
| muxer.setHead(head); | ||
| muxer.start(VENDOR, currentComments()); | ||
| }); | ||
|
|
||
| // Each Opus packet → one Ogg audio page. durationUs is the packet length; | ||
| // Opus granule positions are counted in 48 kHz samples. | ||
| ipc.on( | ||
| 'audio-stream:opus', | ||
| (packet: { bytes: Uint8Array; durationUs: number }) => { | ||
| const samples = (packet.durationUs * 48000) / 1_000_000; | ||
| muxer.writePacket(packet.bytes, samples); | ||
| }, | ||
| ); | ||
| }, | ||
| async stop() { | ||
| if (!this.server) return; | ||
|
|
||
| await new Promise<void>((resolve) => this.server!.close(() => resolve())); | ||
| }, | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
| onConfigChange(newConfig) { | ||
| config = newConfig; | ||
| }, | ||
| }); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,20 @@ | ||
| export interface AudioStreamConfig { | ||
| enabled: boolean; | ||
| port: number; | ||
| hostname: string; | ||
| // Audio settings for the Opus/Ogg stream. | ||
| sampleRate: number; // Capture sample rate hint (Opus always encodes at 48 kHz) | ||
| bitrate: number; // Opus target bitrate in bits/sec (e.g. 128000) | ||
| channels: number; // Number of channels (2 = stereo) | ||
| bufferSize: number; // AudioWorklet batch size in frames - affects latency | ||
| } | ||
|
|
||
| export const defaultAudioStreamConfig: AudioStreamConfig = { | ||
| enabled: false, | ||
| port: 8765, | ||
| hostname: '0.0.0.0', | ||
| sampleRate: 48000, // 48kHz - Opus native rate | ||
| bitrate: 128000, // 128 kbps Opus | ||
| channels: 2, // Stereo | ||
| bufferSize: 4096, // AudioWorklet batch (frames) | ||
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,17 @@ | ||
| import { t } from '@/i18n'; | ||
| import { createPlugin } from '@/utils'; | ||
|
|
||
| import { backend } from './backend'; | ||
| import { defaultAudioStreamConfig } from './config'; | ||
| import { onMenu } from './menu'; | ||
| import { renderer } from './renderer'; | ||
|
|
||
| export default createPlugin({ | ||
| name: () => t('plugins.audio-stream.name'), | ||
| description: () => t('plugins.audio-stream.description'), | ||
| restartNeeded: false, | ||
| config: defaultAudioStreamConfig, | ||
| backend, | ||
| renderer, | ||
| menu: onMenu, | ||
| }); |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.