Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 | 10x 10x 10x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 8x 8x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 1x 1x 1x 1x 1x 1x | import { isAbortError, throwIfAborted } from '@be-music/shared-utils/core';
import { loadOptionalNodeModule } from '@be-music/shared-utils/optional-node-module';
// Cooperative wait used for output backpressure and graceful draining.
const delay = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));
export type AudioRuntime = 'node' | 'browser';
export type AudioEngine = 'webaudio';
export interface AudioSink {
runtime: AudioRuntime;
engine: AudioEngine;
label: string;
write: (chunk: Uint8Array) => boolean;
waitWritable: (shouldStop: () => boolean) => Promise<void>;
end: () => Promise<void>;
destroy: () => void;
onError: (listener: () => void) => void;
getClockState: () => AudioSinkClockState;
suspend: () => Promise<void>;
resume: () => Promise<void>;
}
export interface AudioSinkCreateOptions {
sampleRate: number;
channels: number;
samplesPerFrame: number;
mode: 'auto' | 'manual';
signal?: AbortSignal;
}
export interface WebAudioBufferLike {
getChannelData: (channel: number) => Float32Array;
}
export interface WebAudioBufferSourceLike {
buffer: WebAudioBufferLike | null;
connect: (destination: unknown) => unknown;
/**
* Optional in the structural type because not every test fake bothers to model it, but every real Web Audio
* implementation (browser + `node-web-audio-api`) provides it. Used by the sink to detach the source from the
* destination once playback ends so the node becomes GC-eligible — without it, idle source nodes accumulate per
* chunk written.
*/
disconnect?: () => void;
start: (when?: number) => void;
/**
* Spec-defined `ended` callback. Same optionality reasoning as {@link disconnect}.
*/
onended?: (() => void) | null;
}
export interface WebAudioContextLike {
readonly currentTime: number;
readonly destination: unknown;
createBuffer: (numberOfChannels: number, length: number, sampleRate: number) => WebAudioBufferLike;
createBufferSource: () => WebAudioBufferSourceLike;
close?: () => Promise<void>;
suspend?: () => Promise<void>;
resume?: () => Promise<void>;
}
export type { AudioSinkClockState } from '@be-music/player-engine';
import type { AudioSinkClockState } from '@be-music/player-engine';
interface NodeWebAudioModule {
AudioContext?: unknown;
default?: {
AudioContext?: unknown;
};
}
interface NodeWebAudioContextConstructor {
new (options?: { sampleRate?: number }): WebAudioContextLike;
}
const WEBAUDIO_HIGH_WATER_MS = 64;
const WEBAUDIO_LOW_WATER_MS = 32;
export function createBrowserAudioSink(context: WebAudioContextLike, options: AudioSinkCreateOptions): AudioSink {
return createWebAudioSink('browser', context, options);
}
export async function createNodeAudioSink(options: AudioSinkCreateOptions): Promise<AudioSink | undefined> {
throwIfAborted(options.signal);
const AudioContext = await loadNodeWebAudioContextConstructor(options.signal);
throwIfAborted(options.signal);
if (!AudioContext) {
return undefined;
}
let context: WebAudioContextLike;
try {
context = new AudioContext({
sampleRate: options.sampleRate,
});
} catch {
try {
context = new AudioContext();
} catch {
return undefined;
}
}
if (options.signal?.aborted) {
await closeContextSafely(context);
throwIfAborted(options.signal);
}
return createWebAudioSink('node', context, options);
}
function createWebAudioSink(
runtime: AudioRuntime,
context: WebAudioContextLike,
options: AudioSinkCreateOptions,
): AudioSink {
const errorListeners = new Set<() => void>();
const highWaterFrames = Math.max(256, Math.ceil((options.sampleRate * WEBAUDIO_HIGH_WATER_MS) / 1000));
const lowWaterFrames = Math.max(
128,
Math.min(highWaterFrames - 1, Math.ceil((options.sampleRate * WEBAUDIO_LOW_WATER_MS) / 1000)),
);
let closed = false;
let scheduledUntilSeconds = Math.max(0, context.currentTime);
const emitError = (): void => {
for (const listener of errorListeners) {
listener();
}
};
const queuedFrames = (): number => {
Iif (closed) {
return 0;
}
const now = Math.max(0, context.currentTime);
return Math.max(0, Math.ceil((scheduledUntilSeconds - now) * options.sampleRate));
};
const closeContext = async (): Promise<void> => {
if (closed) {
return;
}
closed = true;
// Drop the error-listener registry first so anything still holding the
// sink alive (e.g. an upstream player loop) can't accidentally call into
// a torn-down context. Listeners that already fired stay invoked; the
// clear only affects re-entrant emits after the sink is closed.
errorListeners.clear();
try {
await context.close?.();
} catch {
// noop
}
};
return {
runtime,
engine: 'webaudio',
label: runtime === 'node' ? 'node-webaudio' : 'browser-webaudio',
write: (chunk: Uint8Array) => {
Iif (closed || chunk.byteLength <= 0) {
return true;
}
const channels = Math.max(1, options.channels);
const bytesPerFrame = channels * 2;
Iif (chunk.byteLength < bytesPerFrame) {
return true;
}
const frameCount = Math.floor(chunk.byteLength / bytesPerFrame);
Iif (frameCount <= 0) {
return true;
}
try {
const pcm = new Int16Array(chunk.buffer, chunk.byteOffset, frameCount * channels);
const buffer = context.createBuffer(channels, frameCount, options.sampleRate);
for (let channel = 0; channel < channels; channel += 1) {
const channelData = buffer.getChannelData(channel);
let pcmIndex = channel;
for (let frame = 0; frame < frameCount; frame += 1) {
channelData[frame] = pcm[pcmIndex]! / 32768;
pcmIndex += channels;
}
}
const source = context.createBufferSource();
source.buffer = buffer;
source.connect(context.destination);
// Per Web Audio spec, an `AudioBufferSourceNode` keeps its outgoing edge to `destination` alive after playback
// ends until either explicit `disconnect()` or GC. The Node `node-web-audio-api` shim doesn't reliably collect
// those edges between `write` calls — at 100+ chunks per second the renderer accumulates idle source nodes
// backing every chunk we ever scheduled. Wiring `onended` to `disconnect()` lets each chunk's node detach the
// moment its frames finish and then become eligible for GC.
source.onended = () => {
try {
source.disconnect?.();
} catch {
// Already disconnected or context closed — both terminal states for this node.
}
};
const now = Math.max(0, context.currentTime);
const startAt = Math.max(now, scheduledUntilSeconds);
source.start(startAt);
scheduledUntilSeconds = startAt + frameCount / options.sampleRate;
} catch {
emitError();
return false;
}
return queuedFrames() <= highWaterFrames;
},
waitWritable: async (shouldStop: () => boolean) => {
while (!shouldStop() && !closed && queuedFrames() > lowWaterFrames) {
await delay(1);
}
},
end: async () => {
if (closed) {
return;
}
while (!closed && queuedFrames() > 0) {
await delay(1);
}
await closeContext();
},
destroy: () => {
void closeContext();
},
onError: (listener: () => void) => {
errorListeners.add(listener);
},
getClockState: () => {
const outputSeconds = Math.max(0, context.currentTime);
return {
outputSeconds,
scheduledSeconds: Math.max(outputSeconds, scheduledUntilSeconds),
};
},
suspend: async () => {
Iif (closed) {
return;
}
try {
await context.suspend?.();
} catch {
emitError();
}
},
resume: async () => {
Iif (closed) {
return;
}
try {
await context.resume?.();
} catch {
emitError();
}
},
};
}
async function loadNodeWebAudioContextConstructor(
signal?: AbortSignal,
): Promise<NodeWebAudioContextConstructor | undefined> {
try {
throwIfAborted(signal);
// In a SEA binary the bare-specifier import always fails; the helper retries from a `node_modules`
// directory next to the executable (or the working directory) before giving up.
const imported = await loadOptionalNodeModule<NodeWebAudioModule>(
'node-web-audio-api',
() => import('node-web-audio-api') as Promise<NodeWebAudioModule>,
);
throwIfAborted(signal);
if (!imported) {
return undefined;
}
const candidate = imported.AudioContext ?? imported.default?.AudioContext ?? imported.default;
if (typeof candidate !== 'function') {
return undefined;
}
return candidate as NodeWebAudioContextConstructor;
} catch (error) {
if (isAbortError(error)) {
throw error;
}
return undefined;
}
}
async function closeContextSafely(context: WebAudioContextLike): Promise<void> {
try {
await context.close?.();
} catch {
// noop
}
}
|