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
38 changes: 29 additions & 9 deletions src/audio/MediaService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import {
distanceBetween,
distanceCompensatedSend,
profileDistanceGain,
reverbOnsetSendFactor,
type SpatialProfile,
} from './distanceModel';
import {
Expand Down Expand Up @@ -473,12 +474,27 @@ export class MediaService {
* ratio is how a listener hears distance: so the distance gain is divided
* back out of the send ({@link distanceCompensatedSend}) and the chain gets
* volume × send wherever the source is. Band gains sit before the tap and
* still dims direct and reverb alike.
* still dims direct and reverb alike. For an HRTF point source the send then
* falls with distance as the room's decay starts later
* ({@link reverbOnsetSendFactor}, from `chain`'s 1 kHz reverberation time);
* a chain with no reverb decay time, or a sound that is not a point source,
* is unchanged.
*/
private sendGain(sound: ExtendedSound, send: number | undefined): number | undefined {
return send === undefined
? undefined
: distanceCompensatedSend(send, this.levelDistanceGain(sound));
private sendGain(
sound: ExtendedSound,
chain: string | undefined,
send: number | undefined,
): number | undefined {
if (send === undefined) {
return undefined;
}
const compensated = distanceCompensatedSend(send, this.levelDistanceGain(sound));
if (!sound.pointSource || sound.upmix === 'ambisonic' || !chain) {
return compensated;
}
const reverbTime = this.effects.getChain(chain)?.reverbTimeAt1k;
const distance = distanceBetween(this.cacophony.listenerPosition, sound.mediaPosition);
return compensated * reverbOnsetSendFactor(distance, reverbTime);
}

/**
Expand All @@ -491,7 +507,11 @@ export class MediaService {
return;
}
if (sound.effectChain) {
this.pointInlineChain(sound.effectChain, sound.namedChain, this.sendGain(sound, sound.namedSend));
this.pointInlineChain(
sound.effectChain,
sound.namedChain,
this.sendGain(sound, sound.namedChain, sound.namedSend),
);
} else if (sound.chainRouted) {
this.routeNamedChain(sound, sound.namedChain, sound.namedSend);
}
Expand Down Expand Up @@ -1480,7 +1500,7 @@ export class MediaService {
chain,
send,
this.cacophony.getBus('master'),
this.sendGain(sound, send),
this.sendGain(sound, chain, send),
);
if (error) {
console.warn(`Client.Media: chain '${chain}' unavailable; playing dry`, error);
Expand Down Expand Up @@ -1546,7 +1566,7 @@ export class MediaService {
// Update without effects: keep the inline chain, re-point what it feeds.
sound.namedChain = chain;
sound.namedSend = send;
this.pointInlineChain(sound.effectChain, chain, this.sendGain(sound, send));
this.pointInlineChain(sound.effectChain, chain, this.sendGain(sound, chain, send));
return;
}
this.routeNamedChain(sound, chain, send);
Expand Down Expand Up @@ -1611,7 +1631,7 @@ export class MediaService {
if (!inline) {
return;
}
this.pointInlineChain(inline, data.chain, this.sendGain(sound, data.send));
this.pointInlineChain(inline, data.chain, this.sendGain(sound, data.chain, data.send));
try {
sound.routeTo(inline.bus);
} catch (error) {
Expand Down
22 changes: 22 additions & 0 deletions src/audio/distanceModel.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
DEFAULT_SPATIAL_PROFILE,
distanceBetween,
distanceCompensatedSend,
reverbOnsetSendFactor,
inverseDistanceGain,
MAX_SEND_DISTANCE_BOOST,
profileDistanceGain,
Expand Down Expand Up @@ -155,3 +156,24 @@ describe('distanceCompensatedSend', () => {
expect(distanceCompensatedSend(0.3, Number.NaN)).toBeCloseTo(0.3 * MAX_SEND_DISTANCE_BOOST, 12);
});
});

describe('reverbOnsetSendFactor', () => {
const db = (amplitude: number) => 20 * Math.log10(amplitude);

it('lowers the Living Room send 0.5, 1.0 and 1.5 dB at 1, 2 and 3 m (Barron & Lee 1988 Eq. 6)', () => {
expect(db(reverbOnsetSendFactor(1, 0.345))).toBeCloseTo(-0.5, 2);
expect(db(reverbOnsetSendFactor(2, 0.345))).toBeCloseTo(-1.01, 2);
expect(db(reverbOnsetSendFactor(3, 0.345))).toBeCloseTo(-1.51, 2);
});

it('is the square root of the energy factor exp(-0.04 r / T)', () => {
expect(reverbOnsetSendFactor(5, 1.2) ** 2).toBeCloseTo(Math.exp((-0.04 * 5) / 1.2), 12);
});

it('leaves the send alone without a reverberation time or a distance', () => {
expect(reverbOnsetSendFactor(2, undefined)).toBe(1);
expect(reverbOnsetSendFactor(2, 0)).toBe(1);
expect(reverbOnsetSendFactor(0, 0.345)).toBe(1);
expect(reverbOnsetSendFactor(Number.NaN, 0.345)).toBe(1);
});
});
20 changes: 20 additions & 0 deletions src/audio/distanceModel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,26 @@ export function distanceCompensatedSend(send: number, distanceGain: number): num
return send * boost;
}

/**
* Amplitude factor for a source's reverb send at `distance` metres in a room
* whose 1 kHz reverberation time is `reverbTime` seconds: exp(-0.02 r / T).
* Barron & Lee 1988 (JASA 84(2), 618-628) Eq. (6), p.624: the reflected
* energy at distance r is the classical diffuse-field value times
* exp(-0.04 r / T), because a source's reverberant decay cannot start before
* its direct sound arrives (r / c), and energy falls 60 dB in T (0.04 is
* 13.82 / c); the amplitude factor is its square root. The fit was made in
* halls of 2,900 to 86,650 m3 and is applied here on its physical argument,
* not on a fit to rooms this small. In a room with T = 0.345 s the send falls
* 0.5, 1.0 and 1.5 dB at 1, 2 and 3 m. A non-positive or non-finite distance
* or time gives 1.
*/
export function reverbOnsetSendFactor(distance: number, reverbTime: number | undefined): number {
if (reverbTime === undefined || !(reverbTime > 0) || !Number.isFinite(distance) || distance <= 0) {
return 1;
}
return Math.exp((-0.02 * distance) / reverbTime);
}

/** Euclidean distance between two 3D positions; missing/short vectors → 0 (co-located). */
export function distanceBetween(
a?: readonly number[] | null,
Expand Down
14 changes: 13 additions & 1 deletion src/audio/effects/EffectChain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
import type { Bus, Cacophony, FadeType } from 'cacophony';

import { buildEffect } from './buildEffect';
import { resolveEffect } from './resolveEffect';
import { resolveEffect, reverbTimeAt1k } from './resolveEffect';
import type { EffectParams, EffectSpec } from './types';

/** The live node type `Bus.addFilter` returns / the bus methods accept. */
Expand Down Expand Up @@ -62,6 +62,8 @@ export class EffectChain {
private sendTarget: Bus | null = null;
/** The gain of the feed into {@link sendTarget}. */
private sendGain = 1;
/** 1 kHz reverberation time (s) of the chain's first reverb that has one. */
private reverbTime: number | undefined;

private constructor(cacophony: Cacophony, id: string | null, bus: Bus, mode: ChainMode) {
this.cacophony = cacophony;
Expand Down Expand Up @@ -144,6 +146,14 @@ export class EffectChain {
}
}

/**
* The 1 kHz reverberation time (s) of the first built reverb in this chain
* that carries a decay time, or `undefined` when it has none.
*/
get reverbTimeAt1k(): number | undefined {
return this.reverbTime;
}

/** Replace the effect graph in place (re-`Chain`), gain-dipped to mask the click. */
async replace(effects: EffectSpec[], options: ChainOptions = {}): Promise<void> {
await this.maskedRebuild(async () => {
Expand Down Expand Up @@ -232,6 +242,7 @@ export class EffectChain {
try {
const built = buildEffect(this.cacophony, resolved);
const node = await this.bus.addFilter(built);
this.reverbTime ??= reverbTimeAt1k(spec);
this.entries.push({
id: spec.id,
type: spec.type === 'echo' ? 'delay' : spec.type,
Expand Down Expand Up @@ -266,6 +277,7 @@ export class EffectChain {
}
}
this.entries = [];
this.reverbTime = undefined;
}

private setGain(gain: number | undefined, fadein?: number): void {
Expand Down
23 changes: 22 additions & 1 deletion src/audio/effects/resolveEffect.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest';

import { resolveEffect } from './resolveEffect';
import { resolveEffect, reverbTimeAt1k } from './resolveEffect';
import type { ResolvedEffect } from './types';

/** Narrow a result to a worklet plan (throws in-test if it isn't). */
Expand Down Expand Up @@ -314,3 +314,24 @@ describe('resolveEffect — presets', () => {
expect(r.options.drive).toBe(4);
});
});

describe('reverbTimeAt1k', () => {
const living = [0.155, 0.268, 0.318, 0.345, 0.306, 0.261, 0.223, 0.189];

it('takes the 1 kHz band of decayTimes, else decayTime', () => {
expect(reverbTimeAt1k({ type: 'reverb', algorithm: 'diffuse', params: { decayTimes: living } })).toBe(0.345);
expect(reverbTimeAt1k({ type: 'reverb', algorithm: 'plate', params: { decayTime: 1.2 } })).toBe(1.2);
expect(reverbTimeAt1k({ type: 'reverb', params: { decayTimes: living, decayTime: 2 } })).toBe(0.345);
});

it('reads a preset and clamps like the FDN bands', () => {
expect(reverbTimeAt1k({ type: 'reverb', preset: 'hall' })).toBe(1.77);
expect(reverbTimeAt1k({ type: 'reverb', params: { decayTime: 60 } })).toBe(20);
});

it('has none for other effects or a reverb without a decay time', () => {
expect(reverbTimeAt1k({ type: 'lowpass', params: { frequency: 400 } })).toBeUndefined();
expect(reverbTimeAt1k({ type: 'reverb', params: { mix: 0.3 } })).toBeUndefined();
expect(reverbTimeAt1k({ type: 'reverb', params: { decayTimes: [1, 2] } })).toBeUndefined();
});
});
19 changes: 19 additions & 0 deletions src/audio/effects/resolveEffect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -261,6 +261,25 @@ const SIMPLE_FACTORY: Partial<Record<string, WorkletFactory>> = {
doubling: 'createDoubling',
};

/**
* The 1 kHz reverberation time (s) of a reverb effect: the fourth of its
* `decayTimes` (125 Hz to 16 kHz), or its `decayTime` when it has only that,
* after its preset; clamped like the FDN's bands. `undefined` for an effect
* that is not a reverb or has neither.
*/
export function reverbTimeAt1k(spec: EffectSpec): number | undefined {
if (spec.type !== 'reverb') {
return undefined;
}
const p = mergedParams(spec);
const decayTimes = p.decayTimes;
const t =
Array.isArray(decayTimes) && decayTimes.length === FDN_DECAY_BANDS && Number.isFinite(decayTimes[3])
? (decayTimes[3] as number)
: num(p, 'decayTime');
return t === undefined ? undefined : clamp(t, 0.001, 20);
}

/**
* Translate one wire {@link EffectSpec} into a cacophony build plan, or `null`
* if the `type` is unknown (the caller skips it and the sound still plays dry).
Expand Down