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
55 changes: 26 additions & 29 deletions packages/audio-context/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -153,35 +153,32 @@ and each input mixes up or down by its `channelCount`, `channelCountMode` and
`channelInterpretation` (the speaker rules for mono, stereo, quad and 5.1). A cycle plays only
through a `DelayNode`, whose delay is then at least one quantum, as in the spec; a cycle without
one is silent. An `OfflineAudioContext` renders on its own engine with nothing reaching the
device, and a source connected to it reads an `AudioBuffer` in place. A `ConvolverNode` passes its
input through.

On iOS a `GainNode` and a `DelayNode` evaluate `gain` and `delayTime` every frame, so automation
lands on its frame, in an `OfflineAudioContext` and a realtime one, and `gain` can go above 1 or
below 0. A `DelayNode`'s `maxDelayTime` defaults to 1 s and can be up to 180 s; a `delayTime`
between two frames interpolates linearly.

On iOS `disconnect(destination)`, `disconnect(output)`, `disconnect(destination, output, input)`
and `disconnect(param)` remove only the matching connections. Each connection into a
`ChannelMergerNode`, `ChannelSplitterNode` or `AudioWorkletNode` input gets its own bus, mixed by
the speaker rules for mono, stereo, quad and 5.1 (other counts mix discretely); each splitter
output plays its own channel, and the merger puts each input on its channel. Each output of a
multi-output `AudioWorkletNode` plays from its own node, so any number of them can be connected.
`GainNode`, `DelayNode` and `BiquadFilterNode` mix their inputs to `channelCount` when
`channelCountMode` is `'clamped-max'` or `'explicit'` (up to 8 channels); other nodes keep the
`channelCount`, `channelCountMode` and `channelInterpretation` you set without applying them. A
`PannerNode` mixes its inputs to at most two channels and pans with the spec's equal-power law; a
`'HRTF'` panner pans the same way. A cycle plays only through a `DelayNode`, whose delay is then
at least one render call (one quantum offline, the device's buffer in a realtime context); a
connection that would close a cycle without one is not made. An `AudioBuffer` with more channels
than the context plays all of them.

On iOS `node.connect(param)` adds the node's output, mixed down to mono, to the param every frame
for `GainNode.gain`, `DelayNode.delayTime`, the `BiquadFilterNode` params, oscillator `frequency`
and `detune`, `ConstantSourceNode.offset`, `AudioBufferSourceNode.playbackRate` and `detune`, and
the params of an `AudioWorkletNode` with inputs. Other params, such as `StereoPannerNode.pan`,
the `PannerNode` position and orientation and a worklet's params when it has no inputs, follow
the connected audio once per quantum, a quantum late.
device, and a source connected to it reads an `AudioBuffer` in place.

On iOS the engine renders 128-frame quanta in a realtime context too: an `AudioContext` runs from
construction at the requested `sampleRate` (else the device's), `currentTime` counts its own frames
from 0, and the device plays the quanta through one more buffer (`baseLatency`). Params are read
every frame (`exponentialRampToValueAtTime`, `setTargetAtTime`, `setValueCurveAtTime` and
`cancelAndHoldAtTime` included), and `AudioParam.value` reads the automated value.

On iOS every node mixes its inputs per its `channelCount`, `channelCountMode` and
`channelInterpretation` (the speaker rules for mono, stereo, quad and 5.1, other counts
discretely, up to 8 channels), with the spec's limits (`PannerNode`, `StereoPannerNode`,
`ConvolverNode` and `DynamicsCompressorNode` at most two channels and never `'max'`; splitter and
merger fixed). Each node's output keeps its own channel count through the graph, so a mono
source stays mono into a panner. `disconnect(...)` forms remove only the matching connections.
A `PannerNode` pans with the equal-power law or, for `'HRTF'`, convolves each ear with the MIT
KEMAR head-related impulse responses (Gardner and Martin, MIT Media Lab, 1994; free to use with
citation). `ConvolverNode` convolves with its buffer (partitioned FFT, no latency),
`WaveShaperNode` applies its curve with 2x and 4x oversampling, `IIRFilterNode` filters,
`AnalyserNode` analyses its input on the render thread (Blackman window, as specified), and
oscillators play band-limited waves and `PeriodicWave`s. A cycle plays only through a
`DelayNode`, whose delay is then at least one quantum; it reads its input directly again once
the cycle is broken. A connection that would close a cycle without one is not made.
`node.connect(param)` adds the node's output, mixed down to mono, to the param every frame, for
every param including the `PannerNode` and `AudioListener` ones. `DynamicsCompressorNode` runs
Chromium's compressor kernel (6 ms look-ahead, knee curve, makeup gain), and MediaStream nodes throw `NotSupportedError` (NativeScript
has no `MediaStream`).

On Android `node.connect(param)` adds the node's output, mixed down to mono, to the param every
frame for `GainNode.gain`, `DelayNode.delayTime`, `ConstantSourceNode.offset`,
Expand Down
70 changes: 68 additions & 2 deletions packages/audio-context/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -244,8 +244,56 @@ export interface IIRFilterOptions {
feedback: number[];
}
export interface ConvolverOptions {
buffer?: any;
disableNormalization?: boolean;
}

/** ConvolverOptions per the spec: normalize is set before the buffer, which it scales. */
export function applyConvolverOptions(node: { normalize: boolean; buffer: any }, options: ConvolverOptions = {}) {
node.normalize = !options.disableNormalization;
if (options.buffer != null) node.buffer = options.buffer;
}

export interface AudioNodeChannelOptions {
channelCount?: number;
channelCountMode?: 'max' | 'clamped-max' | 'explicit';
channelInterpretation?: 'speakers' | 'discrete';
}

/** A node kind's limits on channelCount, channelCountMode and channelInterpretation. */
export interface ChannelRule {
maxCount?: number;
fixedCount?: number;
noMax?: boolean;
fixedMode?: string;
fixedInterpretation?: string;
/** The error a disallowed value raises. */
error?: 'NotSupportedError' | 'InvalidStateError' | 'IndexSizeError';
}

export const CHANNEL_RULES: Record<string, ChannelRule> = {
PannerNode: { maxCount: 2, noMax: true },
StereoPannerNode: { maxCount: 2, noMax: true },
ConvolverNode: { maxCount: 2, noMax: true },
DynamicsCompressorNode: { maxCount: 2, noMax: true },
ChannelSplitterNode: { fixedMode: 'explicit', fixedInterpretation: 'discrete', error: 'InvalidStateError' },
ChannelMergerNode: { fixedCount: 1, fixedMode: 'explicit', error: 'InvalidStateError' },
};

/** Throws the spec's error for a channel setting `rule` disallows; `name` is the DOMException name helper. */
export function checkChannelSetting(rule: ChannelRule | undefined, prop: 'channelCount' | 'channelCountMode' | 'channelInterpretation', value: any, current: number, makeError: (name: string, message: string) => Error) {
if (prop === 'channelCount') {
if (!(value >= 1 && value <= 32)) throw makeError('NotSupportedError', `channelCount ${value} is out of range`);
if (rule?.fixedCount != null && value !== rule.fixedCount) throw makeError(rule.error ?? 'InvalidStateError', `channelCount must be ${rule.fixedCount}`);
if (rule?.fixedMode && rule.fixedInterpretation && value !== current) throw makeError(rule.error ?? 'InvalidStateError', 'channelCount cannot change');
if (rule?.maxCount != null && value > rule.maxCount) throw makeError('NotSupportedError', `channelCount ${value} is above ${rule.maxCount}`);
} else if (prop === 'channelCountMode') {
if (rule?.fixedMode && value !== rule.fixedMode) throw makeError(rule.error ?? 'InvalidStateError', `channelCountMode must be '${rule.fixedMode}'`);
if (rule?.noMax && value === 'max') throw makeError('NotSupportedError', "channelCountMode cannot be 'max'");
} else if (rule?.fixedInterpretation && value !== rule.fixedInterpretation) {
throw makeError(rule.error ?? 'InvalidStateError', `channelInterpretation must be '${rule.fixedInterpretation}'`);
}
}
export interface DynamicsCompressorOptions {
threshold?: number;
knee?: number;
Expand Down Expand Up @@ -274,6 +322,8 @@ export interface AudioParamHooks {
nativeScheduleTarget?(value: number, startTime: number, timeConstant: number): void;
nativeScheduleCurve?(values: Float32Array, startTime: number, duration: number): void;
nativeGetValue?(): number;
/** The value automation and connected audio give at the current time. */
nativeComputedValue?(): number;
nativeSetAutomationRate?(rate: string): void;
nativeCancelAndHold(heldValue: number, time: number): void;
}
Expand Down Expand Up @@ -301,6 +351,10 @@ export function makeStubParamHooks(): AudioParamHooks {
};
}

function checkTime(method: string, time: number) {
if (typeof time === 'number' && time < 0) throw new RangeError(`AudioParam.${method}: time must be >= 0`);
}

export class AudioParamBase {
private readonly hooks: AudioParamHooks;
private _cachedValue: number;
Expand All @@ -312,12 +366,16 @@ export class AudioParamBase {
}

get value(): number {
if (this.hooks.nativeComputedValue) {
const v = this.hooks.nativeComputedValue();
if (Number.isFinite(v)) return v;
}
return this._cachedValue;
}

set value(v: number) {
const nv = +v;
if (nv === this._cachedValue) return;
if (nv === this._cachedValue && !this.hooks.nativeComputedValue) return;
this._cachedValue = nv;
this.hooks.nativeSet(nv);
}
Expand All @@ -339,22 +397,25 @@ export class AudioParamBase {
}

setValueAtTime(value: number, time: number = 0): AudioParamBase {
checkTime('setValueAtTime', time);
const nv = +value;
this._cachedValue = nv;
this.hooks.nativeScheduleSet(nv, time || 0);
return this;
}

linearRampToValueAtTime(value: number, time: number): AudioParamBase {
checkTime('linearRampToValueAtTime', time);
const nv = +value;
this._cachedValue = nv;
this.hooks.nativeScheduleLinearRamp(nv, time);
return this;
}

exponentialRampToValueAtTime(value: number, time: number): AudioParamBase {
checkTime('exponentialRampToValueAtTime', time);
const nv = +value;
if (nv <= 0) throw new RangeError('exponentialRampToValueAtTime: value must be > 0');
if (nv === 0) throw new RangeError('exponentialRampToValueAtTime: value must not be 0');
this._cachedValue = nv;
if (this.hooks.nativeScheduleExpRamp) {
this.hooks.nativeScheduleExpRamp(nv, time);
Expand All @@ -365,6 +426,7 @@ export class AudioParamBase {
}

setTargetAtTime(target: number, startTime: number, timeConstant: number): AudioParamBase {
checkTime('setTargetAtTime', startTime);
const nv = +target;
if (timeConstant < 0) throw new RangeError('setTargetAtTime: timeConstant must be >= 0');
this._cachedValue = nv;
Expand All @@ -381,6 +443,8 @@ export class AudioParamBase {
if (!values || (values as { length: number }).length < 2) {
throw new RangeError('setValueCurveAtTime: values must have length >= 2');
}
checkTime('setValueCurveAtTime', startTime);
if (!(duration > 0)) throw new RangeError('setValueCurveAtTime: duration must be > 0');
const f32 = values instanceof Float32Array ? values : Float32Array.from(values);
this._cachedValue = f32[f32.length - 1];
if (this.hooks.nativeScheduleCurve) {
Expand All @@ -398,11 +462,13 @@ export class AudioParamBase {
}

cancelScheduledValues(time: number): AudioParamBase {
checkTime('cancelScheduledValues', time);
this.hooks.nativeCancel(time || 0);
return this;
}

cancelAndHoldAtTime(time: number): AudioParamBase {
checkTime('cancelAndHoldAtTime', time);
const t = time || 0;
const held = this._cachedValue;
this.hooks.nativeCancelAndHold(held, t);
Expand Down
39 changes: 29 additions & 10 deletions packages/audio-context/index.android.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,9 @@ function makeAndroidHooks(native: org.nativescript.audiocontext.AudioParam): Aud
nativeGetValue() {
return native.getValue();
},
nativeComputedValue() {
return native.getComputedValue();
},
nativeSetAutomationRate(rate) {
native.setAutomationRate(rate);
},
Expand Down Expand Up @@ -1080,11 +1083,11 @@ export class OfflineAudioContext extends BaseAudioContext {
createDynamicsCompressor(options?: DynamicsCompressorOptions) {
return new DynamicsCompressorNode(this as never, options ?? {});
}
createChannelSplitter(options?: ChannelSplitterOptions) {
return new ChannelSplitterNode(this as never, options ?? {});
createChannelSplitter(numberOfOutputs?: number | ChannelSplitterOptions) {
return new ChannelSplitterNode(this as never, typeof numberOfOutputs === 'number' ? { numberOfOutputs } : (numberOfOutputs ?? {}));
}
createChannelMerger(options?: ChannelMergerOptions) {
return new ChannelMergerNode(this as never, options ?? {});
createChannelMerger(numberOfInputs?: number | ChannelMergerOptions) {
return new ChannelMergerNode(this as never, typeof numberOfInputs === 'number' ? { numberOfInputs } : (numberOfInputs ?? {}));
}
createPeriodicWave(real: Float32Array | number[], imag: Float32Array | number[], options?: { disableNormalization?: boolean }) {
return new PeriodicWave(this as never, { real, imag, disableNormalization: options?.disableNormalization });
Expand Down Expand Up @@ -1220,6 +1223,10 @@ export class AudioWorkletNode extends AudioNode {
throw domError('NotSupportedError', 'AudioWorkletNode: this runtime copies SharedArrayBuffers passed to native code');
}
this[native_] = native;
const config = options as any;
if (config.channelCount !== undefined) this.channelCount = config.channelCount;
if (config.channelCountMode !== undefined) this.channelCountMode = config.channelCountMode;
if (config.channelInterpretation !== undefined) this.channelInterpretation = config.channelInterpretation;
this._ring = ring;
this._numberOfInputs = numberOfInputs;
this._numberOfOutputs = numberOfOutputs;
Expand Down Expand Up @@ -1336,6 +1343,18 @@ export class AudioContext extends BaseAudioContext {
return new MediaElementAudioSourceNode(this, mediaElement);
}

createMediaStreamSource(_stream: any): never {
throw domError('NotSupportedError', 'AudioContext.createMediaStreamSource: NativeScript has no MediaStream');
}

createMediaStreamTrackSource(_track: any): never {
throw domError('NotSupportedError', 'AudioContext.createMediaStreamTrackSource: NativeScript has no MediaStream');
}

createMediaStreamDestination(_options?: any): never {
throw domError('NotSupportedError', 'AudioContext.createMediaStreamDestination: NativeScript has no MediaStream');
}

createSourceNodeFromPlayer(playerNative: any): MediaElementAudioSourceNode | null {
try {
const native: any = this.native;
Expand Down Expand Up @@ -1405,11 +1424,11 @@ export class AudioContext extends BaseAudioContext {
createDynamicsCompressor(options?: DynamicsCompressorOptions) {
return new DynamicsCompressorNode(this as never, options ?? {});
}
createChannelSplitter(options?: ChannelSplitterOptions) {
return new ChannelSplitterNode(this as never, options ?? {});
createChannelSplitter(numberOfOutputs?: number | ChannelSplitterOptions) {
return new ChannelSplitterNode(this as never, typeof numberOfOutputs === 'number' ? { numberOfOutputs } : (numberOfOutputs ?? {}));
}
createChannelMerger(options?: ChannelMergerOptions) {
return new ChannelMergerNode(this as never, options ?? {});
createChannelMerger(numberOfInputs?: number | ChannelMergerOptions) {
return new ChannelMergerNode(this as never, typeof numberOfInputs === 'number' ? { numberOfInputs } : (numberOfInputs ?? {}));
}
createPeriodicWave(real: Float32Array | number[], imag: Float32Array | number[], options?: { disableNormalization?: boolean }) {
return new PeriodicWave(this as never, { real, imag, disableNormalization: options?.disableNormalization });
Expand All @@ -1429,7 +1448,7 @@ export class AudioContext extends BaseAudioContext {
if (this._state === 'closed' || this._closing) return Promise.reject(domError('InvalidStateError', 'AudioContext.resume: the context is closed'));
return new Promise((resolve, reject) => {
const ref = new WeakRef(this);
AudioContext.getInstance().resumeAsync(
this.native.resumeAsync(
new org.nativescript.audiocontext.AudioContext.AsyncCallback({
onComplete(ok) {
if (ok) {
Expand All @@ -1451,7 +1470,7 @@ export class AudioContext extends BaseAudioContext {
if (this._state === 'closed' || this._closing) return Promise.reject(domError('InvalidStateError', 'AudioContext.suspend: the context is closed'));
return new Promise((resolve, reject) => {
const ref = new WeakRef(this);
AudioContext.getInstance().suspendAsync(
this.native.suspendAsync(
new org.nativescript.audiocontext.AudioContext.AsyncCallback({
onComplete(ok) {
if (ok) {
Expand Down
Loading
Loading