195 lines
7.4 KiB
JavaScript
195 lines
7.4 KiB
JavaScript
// Notification sound output (official TS6 Notifications › Sound: "Output Device" + "Volume").
|
||
// Separate from voice playback: its own AudioContext on its own sink, so a notification device or level
|
||
// never changes how voices sound. Device choice (official audioSettings[Out].notificationsDevice):
|
||
// 'voice' — follow the voice playback device (default), '' — system default device,
|
||
// 'none' — never play, any other value — that output device id.
|
||
// Level is a dB modifier on the official fader (default -23 dB). The context is created on the first
|
||
// sound and closed again after IDLE_MS without sounds, so no output stream stays open while idle.
|
||
//
|
||
// Sounds are files of the renderer's own assets/sounds folder (official native playWaveFile(name) → sound pack
|
||
// "default"), fetched from the app's read-only scheme only, never remote. The bytes are untrusted input: capped at
|
||
// MAX_FILE_BYTES while reading, decoded by Chromium's own decoder in an OfflineAudioContext (no output device),
|
||
// and the result checked (1–2 channels, at most MAX_SECONDS). Decoded buffers live in a least-recently-used
|
||
// cache bounded to CACHE_BYTES; failures are not cached.
|
||
import { dbToGain } from './fader.js';
|
||
|
||
const IDLE_MS = 15000;
|
||
const MAX_SECONDS = 10;
|
||
const MAX_ACTIVE = 4;
|
||
const SAMPLE_RATE = 48000;
|
||
const SOUND_DIR = new URL('../../assets/sounds/', import.meta.url);
|
||
const SOUND_NAME = /^[a-z][a-z_]{0,63}$/;
|
||
const MAX_FILE_BYTES = 1024 * 1024;
|
||
const MAX_CHANNELS = 2;
|
||
const CACHE_BYTES = 8 * 1024 * 1024;
|
||
|
||
const config = { deviceId: 'voice', levelDb: -23, voiceDeviceId: '' };
|
||
let ctx = null;
|
||
let gain = null;
|
||
let sinkId = null;
|
||
let active = 0;
|
||
let idleTimer = null;
|
||
let log = () => {};
|
||
let revision = 0;
|
||
let preparing = Promise.resolve();
|
||
const sources = new Set();
|
||
|
||
/** name → {buffer, size}; Map order is the LRU order (oldest first). */
|
||
const cache = new Map();
|
||
let cachedBytes = 0;
|
||
/** name → in-flight load, so concurrent requests decode a file once. */
|
||
const loading = new Map();
|
||
let decoder = null;
|
||
|
||
/** Effective sink for the current config, or null for 'none'. */
|
||
export function notificationSink(c = config) {
|
||
if (c.deviceId === 'none') return null;
|
||
if (c.deviceId === 'voice') return c.voiceDeviceId || '';
|
||
return c.deviceId;
|
||
}
|
||
|
||
/** Updates device/level/voice device; applies to the next sound (and the level at once). */
|
||
export function configureNotifications({ deviceId, levelDb, voiceDeviceId, logger } = {}) {
|
||
const before = notificationSink();
|
||
if (typeof deviceId === 'string') config.deviceId = deviceId;
|
||
if (typeof levelDb === 'number') config.levelDb = levelDb;
|
||
if (typeof voiceDeviceId === 'string') config.voiceDeviceId = voiceDeviceId;
|
||
if (typeof logger === 'function') log = logger;
|
||
if (gain) gain.gain.value = dbToGain(config.levelDb);
|
||
if (before !== notificationSink() || config.levelDb <= -200) {
|
||
revision += 1;
|
||
for (const source of sources) { try { source.stop(); } catch { /* already ended */ } }
|
||
}
|
||
}
|
||
|
||
async function ensureContext(sink) {
|
||
if (!ctx || ctx.state === 'closed') {
|
||
ctx = new AudioContext({ sampleRate: 48000, latencyHint: 'interactive' });
|
||
gain = ctx.createGain();
|
||
gain.connect(ctx.destination);
|
||
sinkId = '';
|
||
}
|
||
gain.gain.value = dbToGain(config.levelDb);
|
||
if (sink !== sinkId) {
|
||
if (typeof ctx.setSinkId !== 'function') throw new Error('Output device selection is not supported');
|
||
await ctx.setSinkId(sink);
|
||
sinkId = sink;
|
||
}
|
||
if (ctx.state !== 'running') await ctx.resume();
|
||
}
|
||
|
||
function scheduleIdleClose() {
|
||
clearTimeout(idleTimer);
|
||
idleTimer = setTimeout(() => {
|
||
if (active > 0 || !ctx) return;
|
||
const closing = ctx;
|
||
ctx = null;
|
||
gain = null;
|
||
sinkId = null;
|
||
closing.close().catch(() => {});
|
||
}, IDLE_MS);
|
||
}
|
||
|
||
async function readCapped(name) {
|
||
const response = await fetch(new URL(`${name}.wav`, SOUND_DIR));
|
||
if (!response.ok) throw new Error(`sound ${name}: HTTP ${response.status}`);
|
||
if (Number(response.headers.get('content-length')) > MAX_FILE_BYTES) throw new Error(`sound ${name}: file too large`);
|
||
const reader = response.body.getReader();
|
||
const chunks = [];
|
||
let total = 0;
|
||
for (;;) {
|
||
const { done, value } = await reader.read();
|
||
if (done) break;
|
||
total += value.byteLength;
|
||
if (total > MAX_FILE_BYTES) {
|
||
reader.cancel().catch(() => {});
|
||
throw new Error(`sound ${name}: file too large`);
|
||
}
|
||
chunks.push(value);
|
||
}
|
||
if (total === 0) throw new Error(`sound ${name}: empty file`);
|
||
const bytes = new Uint8Array(total);
|
||
let at = 0;
|
||
for (const chunk of chunks) { bytes.set(chunk, at); at += chunk.byteLength; }
|
||
return bytes.buffer;
|
||
}
|
||
|
||
async function decodeSound(name) {
|
||
const bytes = await readCapped(name);
|
||
decoder ??= new OfflineAudioContext(1, 1, SAMPLE_RATE);
|
||
const buffer = await decoder.decodeAudioData(bytes);
|
||
if (buffer.numberOfChannels < 1 || buffer.numberOfChannels > MAX_CHANNELS || buffer.length === 0 || buffer.duration > MAX_SECONDS) {
|
||
throw new Error(`sound ${name}: ${buffer.numberOfChannels} channels, ${buffer.duration} s`);
|
||
}
|
||
return buffer;
|
||
}
|
||
|
||
function remember(name, buffer) {
|
||
const size = buffer.length * buffer.numberOfChannels * 4;
|
||
cache.set(name, { buffer, size });
|
||
cachedBytes += size;
|
||
for (const [key, entry] of cache) {
|
||
if (cachedBytes <= CACHE_BYTES || key === name) break;
|
||
cache.delete(key);
|
||
cachedBytes -= entry.size;
|
||
}
|
||
}
|
||
|
||
/** Decoded sound `name`, from the cache or loaded once (concurrent callers share the load). */
|
||
function soundBuffer(name) {
|
||
const hit = cache.get(name);
|
||
if (hit) {
|
||
cache.delete(name);
|
||
cache.set(name, hit);
|
||
return Promise.resolve(hit.buffer);
|
||
}
|
||
let job = loading.get(name);
|
||
if (!job) {
|
||
job = decodeSound(name).then((buffer) => { remember(name, buffer); return buffer; }).finally(() => loading.delete(name));
|
||
loading.set(name, job);
|
||
}
|
||
return job;
|
||
}
|
||
|
||
/**
|
||
* Plays notification sound file `name` (assets/sounds/<name>.wav). Resolves true once it started, false when not
|
||
* played: device 'none', level at silence, too many sounds at once, or the file/decoder/device failed (logged).
|
||
*/
|
||
export async function playNotificationSound(name) {
|
||
const sink = notificationSink();
|
||
if (sink === null || config.levelDb <= -200) return false;
|
||
if (typeof name !== 'string' || !SOUND_NAME.test(name) || active >= MAX_ACTIVE) return false;
|
||
clearTimeout(idleTimer);
|
||
active += 1;
|
||
const expected = revision;
|
||
try {
|
||
const buffer = await soundBuffer(name);
|
||
// Serialize sink changes; two concurrent sounds must not race one another onto another device.
|
||
preparing = preparing.catch(() => {}).then(() => ensureContext(sink));
|
||
await preparing;
|
||
if (expected !== revision || sink !== notificationSink()) { active -= 1; if (active === 0) scheduleIdleClose(); return false; }
|
||
const source = ctx.createBufferSource();
|
||
source.buffer = buffer;
|
||
source.connect(gain);
|
||
sources.add(source);
|
||
source.onended = () => {
|
||
source.disconnect();
|
||
sources.delete(source);
|
||
active -= 1;
|
||
if (active === 0) scheduleIdleClose();
|
||
};
|
||
source.start();
|
||
return true;
|
||
} catch (err) {
|
||
active -= 1;
|
||
log('warn', `notifications: sound not played: ${err?.name ?? ''} ${err?.message ?? err}`);
|
||
if (active === 0) scheduleIdleClose();
|
||
return false;
|
||
}
|
||
}
|
||
|
||
/** Diagnostics: whether a notification context is open, its sink and the decoded-sound cache. */
|
||
export function notificationOutputState() {
|
||
return { open: Boolean(ctx && ctx.state !== 'closed'), sinkId, active, cachedSounds: cache.size, cachedBytes, ...config };
|
||
}
|