diff --git a/packages/audio-context/README.md b/packages/audio-context/README.md index b733ca12..46fe36c5 100644 --- a/packages/audio-context/README.md +++ b/packages/audio-context/README.md @@ -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`, diff --git a/packages/audio-context/common.ts b/packages/audio-context/common.ts index 995617c7..6a155b11 100644 --- a/packages/audio-context/common.ts +++ b/packages/audio-context/common.ts @@ -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 = { + 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; @@ -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; } @@ -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; @@ -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); } @@ -339,6 +397,7 @@ 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); @@ -346,6 +405,7 @@ export class AudioParamBase { } linearRampToValueAtTime(value: number, time: number): AudioParamBase { + checkTime('linearRampToValueAtTime', time); const nv = +value; this._cachedValue = nv; this.hooks.nativeScheduleLinearRamp(nv, time); @@ -353,8 +413,9 @@ export class AudioParamBase { } 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); @@ -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; @@ -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) { @@ -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); diff --git a/packages/audio-context/index.android.ts b/packages/audio-context/index.android.ts index 28ac8fbf..5106b1c2 100644 --- a/packages/audio-context/index.android.ts +++ b/packages/audio-context/index.android.ts @@ -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); }, @@ -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 }); @@ -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; @@ -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; @@ -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 }); @@ -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) { @@ -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) { diff --git a/packages/audio-context/index.d.ts b/packages/audio-context/index.d.ts index 11196581..4eebc4da 100644 --- a/packages/audio-context/index.d.ts +++ b/packages/audio-context/index.d.ts @@ -26,6 +26,11 @@ export declare class AudioNode { constructor(context: BaseAudioContext); readonly context: BaseAudioContext; + readonly numberOfInputs: number; + readonly numberOfOutputs: number; + channelCount: number; + channelCountMode: 'max' | 'clamped-max' | 'explicit'; + channelInterpretation: 'speakers' | 'discrete'; connect(): void; @@ -108,7 +113,9 @@ export declare class PannerNode extends AudioNode { setOrientation(x: number, y: number, z: number); } -export declare class AudioDestinationNode extends GainNode {} +export declare class AudioDestinationNode extends AudioNode { + readonly maxChannelCount: number; +} export class AudioScheduledSourceNode extends AudioNode { start(when?: number, offset?: number, duration?: number); @@ -125,11 +132,12 @@ export declare class MediaElementAudioSourceNode extends AudioNode { } export declare class OscillatorNode extends AudioScheduledSourceNode { - constructor(context: BaseAudioContext, options?: { type?: string; frequency?: number }); + constructor(context: BaseAudioContext, options?: { type?: string; frequency?: number; detune?: number; periodicWave?: PeriodicWave }); type: string; readonly frequency: AudioParam; + readonly detune: AudioParam; setPeriodicWave(wave: PeriodicWave): void; } @@ -205,10 +213,13 @@ export declare class PeriodicWave { } export declare class AudioBufferSourceNode extends AudioScheduledSourceNode { - constructor(context: BaseAudioContext, options: { buffer?: AudioBuffer }); + constructor(context: BaseAudioContext, options?: { buffer?: AudioBuffer; loop?: boolean; loopStart?: number; loopEnd?: number; playbackRate?: number; detune?: number }); loop: boolean; + loopStart: number; + loopEnd: number; buffer: AudioBuffer | null; readonly playbackRate: AudioParam; + readonly detune: AudioParam; } export interface AudioWorkletNodeOptions { @@ -247,6 +258,7 @@ export declare class AudioContext extends BaseAudioContext { createPanner(options?: PannerOptions): PannerNode; createOscillator(options?: { type?: string; frequency?: number }): OscillatorNode; createBuffer(options: { length: number; numberOfChannels: number; sampleRate: number }): AudioBuffer; + createBuffer(numberOfChannels: number, length: number, sampleRate: number): AudioBuffer; createBufferSource(): AudioBufferSourceNode; createStereoPanner(options?: StereoPannerOptions): StereoPannerNode; createDelay(options?: DelayOptions): DelayNode; @@ -256,8 +268,8 @@ export declare class AudioContext extends BaseAudioContext { createIIRFilter(feedforward: number[], feedback: number[]): IIRFilterNode; createConvolver(options?: ConvolverOptions): ConvolverNode; createDynamicsCompressor(options?: DynamicsCompressorOptions): DynamicsCompressorNode; - createChannelSplitter(options?: ChannelSplitterOptions): ChannelSplitterNode; - createChannelMerger(options?: ChannelMergerOptions): ChannelMergerNode; + createChannelSplitter(numberOfOutputs?: number | ChannelSplitterOptions): ChannelSplitterNode; + createChannelMerger(numberOfInputs?: number | ChannelMergerOptions): ChannelMergerNode; createPeriodicWave(real: Float32Array | number[], imag: Float32Array | number[], options?: { disableNormalization?: boolean }): PeriodicWave; createMediaElementSource(mediaElement: MediaElementLike): MediaElementAudioSourceNode; @@ -270,6 +282,14 @@ export declare class AudioContext extends BaseAudioContext { readonly sampleRate: number; readonly currentTime: number; + readonly baseLatency: number; + readonly outputLatency: number; + readonly listener: AudioListener; + getOutputTimestamp(): { contextTime: number; performanceTime: number }; + /** Throws NotSupportedError: NativeScript has no MediaStream. */ + createMediaStreamSource(stream: any): never; + createMediaStreamTrackSource(track: any): never; + createMediaStreamDestination(options?: any): never; resume(): Promise; suspend(): Promise; @@ -285,6 +305,13 @@ export declare class OfflineAudioContext extends BaseAudioContext { readonly audioWorklet: AudioWorklet | undefined; constructor(numberOfChannels: number, lengthInFrames: number, sampleRate: number); + constructor(options: { numberOfChannels?: number; length: number; sampleRate: number }); + + readonly sampleRate: number; + readonly currentTime: number; + readonly listener: AudioListener; + createBuffer(options: { length: number; numberOfChannels: number; sampleRate: number }): AudioBuffer; + createBuffer(numberOfChannels: number, length: number, sampleRate: number): AudioBuffer; createGain(options?: { gain?: number }): GainNode; createBiquadFilter(options?: { type?: string; frequency?: number; Q?: number; gain?: number }): BiquadFilterNode; @@ -299,8 +326,8 @@ export declare class OfflineAudioContext extends BaseAudioContext { createIIRFilter(feedforward: number[], feedback: number[]): IIRFilterNode; createConvolver(options?: ConvolverOptions): ConvolverNode; createDynamicsCompressor(options?: DynamicsCompressorOptions): DynamicsCompressorNode; - createChannelSplitter(options?: ChannelSplitterOptions): ChannelSplitterNode; - createChannelMerger(options?: ChannelMergerOptions): ChannelMergerNode; + createChannelSplitter(numberOfOutputs?: number | ChannelSplitterOptions): ChannelSplitterNode; + createChannelMerger(numberOfInputs?: number | ChannelMergerOptions): ChannelMergerNode; createPeriodicWave(real: Float32Array | number[], imag: Float32Array | number[], options?: { disableNormalization?: boolean }): PeriodicWave; decodeAudioData(source: string | ArrayBuffer | ArrayBufferView, successCallback?: (buffer: AudioBuffer) => void, errorCallback?: (error: Error) => void): Promise; diff --git a/packages/audio-context/index.ios.ts b/packages/audio-context/index.ios.ts index 77a11206..e1dd5583 100644 --- a/packages/audio-context/index.ios.ts +++ b/packages/audio-context/index.ios.ts @@ -38,6 +38,10 @@ import { unmarkMediaElementUsed, resolveNativePlayer, throwInvalidMediaElement, + applyConvolverOptions, + AudioNodeChannelOptions, + CHANNEL_RULES, + checkChannelSetting, } from './common'; import { File, knownFolders } from '@nativescript/core'; import { AUDIO_WORKLET_SCOPE } from './audio-worklet-scope'; @@ -89,9 +93,22 @@ function makeIOSHooks(native: NSCAudioParam): AudioParamHooks { nativeCancelAndHold(v, t) { native.cancelAndHoldAtTime(v, t); }, + nativeScheduleExpRamp(v, t) { + native.exponentialRampToValueAtTime(v, t); + }, + nativeScheduleTarget(v, t, c) { + native.setTargetAtTime(v, t, c); + }, + nativeScheduleCurve(values, t, d) { + const copy = values.slice(); + native.setValueCurveAtTime(copy.buffer as never, t, d); + }, nativeGetValue() { return native.value; }, + nativeComputedValue() { + return native.computedValue(); + }, nativeSetAutomationRate(rate) { native.automationRate = rate; }, @@ -100,17 +117,52 @@ function makeIOSHooks(native: NSCAudioParam): AudioParamHooks { export class AudioParam extends AudioParamBase { private [native_]: NSCAudioParam; - constructor(a?: any, b?: any) { + private _range: ParamRange; + + constructor(a?: any, b?: any, range?: ParamRange) { if (a !== nativeCtor_ || !(b instanceof NSCAudioParam)) { throw new TypeError('Illegal constructor.'); } super(makeIOSHooks(b), b.value); this[native_] = b; + this._range = range ?? {}; + if (this._range.fixedRate) super.automationRate = this._range.fixedRate; } get native() { return this[native_]; } + + get defaultValue(): number { + return this._range.defaultValue ?? this[native_].value; + } + + get minValue(): number { + return this._range.min ?? -FLT_MAX; + } + + get maxValue(): number { + return this._range.max ?? FLT_MAX; + } + + get automationRate(): string { + return super.automationRate; + } + + set automationRate(v: string) { + if (v !== 'a-rate' && v !== 'k-rate') return; + if (this._range.fixedRate && v !== this._range.fixedRate) throw domError('InvalidStateError', `this AudioParam is always ${this._range.fixedRate}`); + super.automationRate = v; + } +} + +const FLT_MAX = 3.4028234663852886e38; + +interface ParamRange { + defaultValue?: number; + min?: number; + max?: number; + fixedRate?: 'a-rate' | 'k-rate'; } const COUNT_MODES = ['max', 'clamped-max', 'explicit']; @@ -125,6 +177,40 @@ export class AudioNode extends AudioNodeBase { super(context); } + get numberOfInputs(): number { + return this instanceof AudioScheduledSourceNode || this instanceof MediaElementAudioSourceNode ? 0 : 1; + } + + get numberOfOutputs(): number { + return this instanceof AudioDestinationNode ? 0 : 1; + } + + /** AudioNodeOptions, applied once the native node exists. */ + protected _applyNodeOptions(options?: AudioNodeChannelOptions) { + if (!options) return; + if (options.channelCount !== undefined) this.channelCount = options.channelCount; + if (options.channelCountMode !== undefined) this.channelCountMode = options.channelCountMode; + if (options.channelInterpretation !== undefined) this.channelInterpretation = options.channelInterpretation; + } + + private _checkChannel(prop: 'channelCount' | 'channelCountMode' | 'channelInterpretation', value: any) { + if (this instanceof AudioDestinationNode) { + if (prop === 'channelCount' && this.context instanceof OfflineAudioContext && value !== this.channelCount) throw domError('InvalidStateError', 'OfflineAudioContext destination channelCount cannot change'); + if (prop === 'channelCount' && value > this.maxChannelCount) throw domError('IndexSizeError', `channelCount ${value} is above maxChannelCount`); + } + checkChannelSetting(this._channelRule(), prop, value, this.channelCount, domError); + } + + private _channelRule() { + if (this instanceof PannerNode) return CHANNEL_RULES.PannerNode; + if (this instanceof StereoPannerNode) return CHANNEL_RULES.StereoPannerNode; + if (this instanceof ConvolverNode) return CHANNEL_RULES.ConvolverNode; + if (this instanceof DynamicsCompressorNode) return CHANNEL_RULES.DynamicsCompressorNode; + if (this instanceof ChannelSplitterNode) return CHANNEL_RULES.ChannelSplitterNode; + if (this instanceof ChannelMergerNode) return CHANNEL_RULES.ChannelMergerNode; + return undefined; + } + // The Web Audio defaults for this node's kind. private _channelDefaults(): [number, string, string] { if (this instanceof ChannelSplitterNode) return [this.numberOfOutputs, 'explicit', 'discrete']; @@ -145,8 +231,8 @@ export class AudioNode extends AudioNodeBase { } set channelCount(value: number) { - const count = Math.floor(Number(value)); - if (!(count >= 1 && count <= 32)) throw domError('NotSupportedError', `AudioNode.channelCount: ${value} is out of range`); + const count = Math.floor(value); + this._checkChannel('channelCount', count); this._channelCount = count; this._applyChannelConfig(count, -1, -1); } @@ -158,6 +244,7 @@ export class AudioNode extends AudioNodeBase { set channelCountMode(value: string) { const mode = COUNT_MODES.indexOf(value); if (mode < 0) return; + this._checkChannel('channelCountMode', value); this._channelCountMode = value; this._applyChannelConfig(-1, mode, -1); } @@ -169,6 +256,7 @@ export class AudioNode extends AudioNodeBase { set channelInterpretation(value: string) { const interpretation = INTERPRETATIONS.indexOf(value); if (interpretation < 0) return; + this._checkChannel('channelInterpretation', value); this._channelInterpretation = value; this._applyChannelConfig(-1, -1, interpretation); } @@ -227,9 +315,12 @@ export class AudioBuffer { this[native_] = buffer; } else { const opts = options as { length: number; numberOfChannels?: number; sampleRate?: number }; - const length = Math.max(0, opts.length | 0); - const ch = opts.numberOfChannels != null ? Math.max(1, opts.numberOfChannels | 0) : 1; - const sr = opts.sampleRate != null ? opts.sampleRate : 48000; + const length = opts.length | 0; + const ch = opts.numberOfChannels ?? 1; + const sr = opts.sampleRate ?? 48000; + if (!(ch >= 1 && ch <= 32)) throw domError('NotSupportedError', `AudioBuffer: numberOfChannels ${ch} is outside 1 to 32`); + if (!(length >= 1)) throw domError('NotSupportedError', `AudioBuffer: length ${opts.length} must be at least 1`); + if (!(sr >= 3000 && sr <= 768000)) throw domError('NotSupportedError', `AudioBuffer: sampleRate ${sr} is outside 3000 to 768000`); this[native_] = NSCAudioBuffer.alloc().initWithLengthNumberOfChannelsSampleRate(length, ch, sr); } @@ -253,7 +344,7 @@ export class AudioBuffer { } getChannelData(channel: number): Float32Array | null { - if (channel < 0 || channel >= this.numberOfChannels) return null; + if (!(channel >= 0 && channel < this.numberOfChannels)) throw domError('IndexSizeError', `getChannelData: channel ${channel} is out of range`); const native = this.native as any; const audioModule = (globalThis as any)?.AudioModule; @@ -276,6 +367,7 @@ export class AudioBuffer { copyFromChannel(dest: Float32Array, channel: number, startInChannel: number | AudioBufferCopyOptions = 0) { if (!dest) return; + if (!(channel >= 0 && channel < this.numberOfChannels)) throw domError('IndexSizeError', `copyFromChannel: channel ${channel} is out of range`); const native = this.native; const options = resolveAudioBufferCopyOptions(dest, startInChannel); native.copyFromChannelWithByteOffsetByteLength(dest.buffer as any, channel, options.startInChannel, options.byteOffset, dest.byteLength); @@ -283,6 +375,7 @@ export class AudioBuffer { copyToChannel(source: Float32Array, channel: number, startInChannel: number | AudioBufferCopyOptions = 0) { if (!source) return; + if (!(channel >= 0 && channel < this.numberOfChannels)) throw domError('IndexSizeError', `copyToChannel: channel ${channel} is out of range`); const native = this.native; const options = resolveAudioBufferCopyOptions(source, startInChannel); native.copyToChannelWithByteOffsetByteLength(source.buffer as any, channel, options.startInChannel, options.byteOffset, source.byteLength); @@ -300,6 +393,7 @@ export class GainNode extends AudioNode { if (typeof options?.gain === 'number') { this._native.gain = options.gain; } + this._applyNodeOptions(options); } get native() { return this._native; @@ -308,7 +402,7 @@ export class GainNode extends AudioNode { if (!this._gainParam) { const gain = this._native.gainParam; if (this._initialGain !== 1) gain.setValue(this._initialGain); - this._gainParam = new AudioParam(nativeCtor_, gain); + this._gainParam = new AudioParam(nativeCtor_, gain, { defaultValue: 1 }); } return this._gainParam; } @@ -322,28 +416,30 @@ export class BiquadFilterNode extends AudioNode { private _detuneParam!: AudioParam; constructor(context: NativeBaseAudioContext, options: { type?: string; frequency?: number; Q?: number; gain?: number } = {}) { super(context); - const initialFreq = typeof options?.frequency === 'number' ? options!.frequency! : 440; + const initialFreq = typeof options?.frequency === 'number' ? options!.frequency! : 350; const initialQ = typeof options?.Q === 'number' ? options!.Q! : 1.0; const initialGain = typeof options?.gain === 'number' ? options!.gain! : 0.0; this[native_] = context.native.createBiquadNodeFrequencyQGain(options.type ?? 'lowpass', initialFreq, initialQ, initialGain); + if (typeof (options as any).detune === 'number') this.detune.value = (options as any).detune; + this._applyNodeOptions(options); } get native() { return this[native_]; } get frequency(): AudioParam { - if (!this._frequencyParam) this._frequencyParam = new AudioParam(nativeCtor_, this.native.frequencyParam); + if (!this._frequencyParam) this._frequencyParam = new AudioParam(nativeCtor_, this.native.frequencyParam, { defaultValue: 350, min: 0, max: this.context.sampleRate / 2 }); return this._frequencyParam; } get Q(): AudioParam { - if (!this._qParam) this._qParam = new AudioParam(nativeCtor_, this.native.qParam); + if (!this._qParam) this._qParam = new AudioParam(nativeCtor_, this.native.qParam, { defaultValue: 1 }); return this._qParam; } get gain(): AudioParam { - if (!this._gainParam) this._gainParam = new AudioParam(nativeCtor_, this.native.gainParam); + if (!this._gainParam) this._gainParam = new AudioParam(nativeCtor_, this.native.gainParam, { defaultValue: 0 }); return this._gainParam; } get detune(): AudioParam { - if (!this._detuneParam) this._detuneParam = new AudioParam(nativeCtor_, this.native.detuneParam); + if (!this._detuneParam) this._detuneParam = new AudioParam(nativeCtor_, this.native.detuneParam, { defaultValue: 0 }); return this._detuneParam; } set type(v: string) { @@ -352,6 +448,84 @@ export class BiquadFilterNode extends AudioNode { get type(): string { return this.native.getType(); } + + /** The filter's response at the params' current values, as the render computes it. */ + getFrequencyResponse(frequencyHz: Float32Array, magResponse: Float32Array, phaseResponse: Float32Array) { + if (magResponse.length !== frequencyHz.length || phaseResponse.length !== frequencyHz.length) throw domError('InvalidAccessError', 'getFrequencyResponse: the arrays differ in length'); + const rate = this.context.sampleRate; + const [b0, b1, b2, a1, a2] = biquadCoefficients(this.type, this.frequency.value, this.Q.value, this.gain.value, this.detune.value, rate); + for (let i = 0; i < frequencyHz.length; i++) { + const f = frequencyHz[i]; + if (!(f >= 0 && f <= rate / 2)) { + magResponse[i] = NaN; + phaseResponse[i] = NaN; + continue; + } + const w = (2 * Math.PI * f) / rate; + const c1 = Math.cos(w), s1 = Math.sin(w), c2 = Math.cos(2 * w), s2 = Math.sin(2 * w); + const nr = b0 + b1 * c1 + b2 * c2, ni = -(b1 * s1 + b2 * s2); + const dr = 1 + a1 * c1 + a2 * c2, di = -(a1 * s1 + a2 * s2); + magResponse[i] = Math.hypot(nr, ni) / Math.hypot(dr, di); + phaseResponse[i] = Math.atan2(ni, nr) - Math.atan2(di, dr); + } + } +} + +// Chromium's biquad coefficients (the Audio EQ Cookbook with its limits), normalized: b0, b1, b2, a1, a2. +function biquadCoefficients(type: string, frequency: number, Q: number, gain: number, detune: number, rate: number): number[] { + const n = (b0: number, b1: number, b2: number, a0: number, a1: number, a2: number) => [b0 / a0, b1 / a0, b2 / a0, a1 / a0, a2 / a0]; + let f = (frequency * Math.pow(2, detune / 1200)) / (rate / 2); + f = Number.isFinite(f) ? Math.max(0, Math.min(f, 1)) : 0; + const A = Math.pow(10, gain / 40); + const w0 = Math.PI * f, cw = Math.cos(w0), sw = Math.sin(w0); + const inside = f > 0 && f < 1; + const q = Math.max(0, Q); + switch (type) { + case 'lowpass': { + if (f === 1) return n(1, 0, 0, 1, 0, 0); + if (f === 0) return n(0, 0, 0, 1, 0, 0); + const alpha = 0.5 * sw * Math.pow(10, -0.05 * Q); + return n(0.5 * (1 - cw), 1 - cw, 0.5 * (1 - cw), 1 + alpha, -2 * cw, 1 - alpha); + } + case 'highpass': { + if (f === 1) return n(0, 0, 0, 1, 0, 0); + if (f === 0) return n(1, 0, 0, 1, 0, 0); + const alpha = 0.5 * sw * Math.pow(10, -0.05 * Q); + return n(0.5 * (1 + cw), -(1 + cw), 0.5 * (1 + cw), 1 + alpha, -2 * cw, 1 - alpha); + } + case 'bandpass': { + if (!inside || q <= 0) return n(inside ? 1 : 0, 0, 0, 1, 0, 0); + const alpha = sw / (2 * q); + return n(alpha, 0, -alpha, 1 + alpha, -2 * cw, 1 - alpha); + } + case 'lowshelf': { + if (f === 1) return n(A * A, 0, 0, 1, 0, 0); + if (f === 0) return n(1, 0, 0, 1, 0, 0); + const s = 2 * Math.sqrt(A) * 0.5 * sw * Math.SQRT2; + return n(A * (A + 1 - (A - 1) * cw + s), 2 * A * (A - 1 - (A + 1) * cw), A * (A + 1 - (A - 1) * cw - s), A + 1 + (A - 1) * cw + s, -2 * (A - 1 + (A + 1) * cw), A + 1 + (A - 1) * cw - s); + } + case 'highshelf': { + if (f === 1) return n(1, 0, 0, 1, 0, 0); + if (f === 0) return n(A * A, 0, 0, 1, 0, 0); + const s = 2 * Math.sqrt(A) * 0.5 * sw * Math.SQRT2; + return n(A * (A + 1 + (A - 1) * cw + s), -2 * A * (A - 1 + (A + 1) * cw), A * (A + 1 + (A - 1) * cw - s), A + 1 - (A - 1) * cw + s, 2 * (A - 1 - (A + 1) * cw), A + 1 - (A - 1) * cw - s); + } + case 'peaking': { + if (!inside || q <= 0) return n(inside ? A * A : 1, 0, 0, 1, 0, 0); + const alpha = sw / (2 * q); + return n(1 + alpha * A, -2 * cw, 1 - alpha * A, 1 + alpha / A, -2 * cw, 1 - alpha / A); + } + case 'notch': { + if (!inside || q <= 0) return n(inside ? 0 : 1, 0, 0, 1, 0, 0); + const alpha = sw / (2 * q); + return n(1, -2 * cw, 1, 1 + alpha, -2 * cw, 1 - alpha); + } + default: { + if (!inside || q <= 0) return n(inside ? -1 : 1, 0, 0, 1, 0, 0); + const alpha = sw / (2 * q); + return n(1 - alpha, -2 * cw, 1 + alpha, 1 + alpha, -2 * cw, 1 - alpha); + } + } } export class PannerNode extends AudioNode { @@ -359,8 +533,11 @@ export class PannerNode extends AudioNode { constructor(context: NativeBaseAudioContext, options: PannerOptions = {}) { super(context); + if ((options.refDistance ?? 1) < 0 || (options.maxDistance ?? 1) <= 0 || (options.rolloffFactor ?? 1) < 0) throw new RangeError('PannerNode: refDistance, maxDistance or rolloffFactor out of range'); + if (!((options.coneOuterGain ?? 0) >= 0 && (options.coneOuterGain ?? 0) <= 1)) throw domError('InvalidStateError', 'PannerNode: coneOuterGain is outside 0 to 1'); const p = resolvePannerOptions(options); this[native_] = NSCAudioPannerNode.alloc().initWithContextAndParams(context.native, p.positionX, p.positionY, p.positionZ, p.orientationX, p.orientationY, p.orientationZ, p.pan, p.distanceModel, p.panningModel, p.refDistance, p.maxDistance, p.rolloffFactor, p.coneInnerAngle, p.coneOuterAngle, p.coneOuterGain); + this._applyNodeOptions(options); } get native() { @@ -375,22 +552,22 @@ export class PannerNode extends AudioNode { private _orientationZ!: AudioParam; get positionX() { - return this._positionX || (this._positionX = new AudioParam(nativeCtor_, this.native.positionXParam)); + return this._positionX || (this._positionX = new AudioParam(nativeCtor_, this.native.positionXParam, { defaultValue: 0 })); } get positionY() { - return this._positionY || (this._positionY = new AudioParam(nativeCtor_, this.native.positionYParam)); + return this._positionY || (this._positionY = new AudioParam(nativeCtor_, this.native.positionYParam, { defaultValue: 0 })); } get positionZ() { - return this._positionZ || (this._positionZ = new AudioParam(nativeCtor_, this.native.positionZParam)); + return this._positionZ || (this._positionZ = new AudioParam(nativeCtor_, this.native.positionZParam, { defaultValue: 0 })); } get orientationX() { - return this._orientationX || (this._orientationX = new AudioParam(nativeCtor_, this.native.orientationXParam)); + return this._orientationX || (this._orientationX = new AudioParam(nativeCtor_, this.native.orientationXParam, { defaultValue: 1 })); } get orientationY() { - return this._orientationY || (this._orientationY = new AudioParam(nativeCtor_, this.native.orientationYParam)); + return this._orientationY || (this._orientationY = new AudioParam(nativeCtor_, this.native.orientationYParam, { defaultValue: 0 })); } get orientationZ() { - return this._orientationZ || (this._orientationZ = new AudioParam(nativeCtor_, this.native.orientationZParam)); + return this._orientationZ || (this._orientationZ = new AudioParam(nativeCtor_, this.native.orientationZParam, { defaultValue: 0 })); } get distanceModel(): DistanceModelType { @@ -409,18 +586,21 @@ export class PannerNode extends AudioNode { return this.native.getRefDistance(); } set refDistance(v: number) { + if (v < 0) throw new RangeError(`PannerNode.refDistance: ${v} is out of range`); this.native.setRefDistance(v); } get maxDistance() { return this.native.getMaxDistance(); } set maxDistance(v: number) { + if (v <= 0) throw new RangeError(`PannerNode.maxDistance: ${v} is out of range`); this.native.setMaxDistance(v); } get rolloffFactor() { return this.native.getRolloffFactor(); } set rolloffFactor(v: number) { + if (v < 0) throw new RangeError(`PannerNode.rolloffFactor: ${v} is out of range`); this.native.setRolloffFactor(v); } get coneInnerAngle() { @@ -439,6 +619,7 @@ export class PannerNode extends AudioNode { return this.native.getConeOuterGain(); } set coneOuterGain(v: number) { + if (!(v >= 0 && v <= 1)) throw domError('InvalidStateError', `PannerNode.coneOuterGain: ${v} is outside 0 to 1`); this.native.setConeOuterGain(v); } @@ -452,6 +633,14 @@ export class PannerNode extends AudioNode { export class AudioDestinationNode extends AudioNode { [native_]: NSCAudioNode; + get maxChannelCount(): number { + if (this.context instanceof OfflineAudioContext) return this.channelCount; + try { + return Math.max(2, AVAudioSession.sharedInstance().maximumOutputNumberOfChannels); + } catch (e) { + return 2; + } + } constructor(context: NativeBaseAudioContext, node: NSCAudioNode) { super(context); if (!(node instanceof NSCAudioNode)) throw new TypeError('Illegal constructor.'); @@ -467,6 +656,7 @@ export class AudioScheduledSourceNode extends AudioNode { private _onended: ((ev: { type: 'ended' }) => void) | null = null; private _nativeEndedWired = false; private _endedFired = false; + private _started = false; constructor(context: NativeBaseAudioContext, node: NSCAudioScheduledSourceNode) { super(context); @@ -507,6 +697,10 @@ export class AudioScheduledSourceNode extends AudioNode { } start(when?: number, offset?: number, duration?: number) { + if (this._started) throw domError('InvalidStateError', `${this.constructor.name}.start: already started`); + if ([when, offset, duration].some((v) => typeof v === 'number' && !Number.isFinite(v))) throw new TypeError(`${this.constructor.name}.start: arguments must be finite`); + if ((typeof when === 'number' && when < 0) || (typeof offset === 'number' && offset < 0) || (typeof duration === 'number' && duration < 0)) throw new RangeError(`${this.constructor.name}.start: arguments must be >= 0`); + this._started = true; this._endedFired = false; const at = typeof when === 'number' && Number.isFinite(when) && when > 0 ? when : 0; if (at > 0) this._ensureNativeEndedWired(); @@ -527,6 +721,8 @@ export class AudioScheduledSourceNode extends AudioNode { } stop(when?: number) { + if (!this._started) throw domError('InvalidStateError', `${this.constructor.name}.stop: not started`); + if (typeof when === 'number' && when < 0) throw new RangeError(`${this.constructor.name}.stop: when must be >= 0`); const now = (this.context as any)?.currentTime ?? 0; if (typeof when === 'number' && Number.isFinite(when) && when > now) { this._ensureNativeEndedWired(); @@ -539,10 +735,14 @@ export class AudioScheduledSourceNode extends AudioNode { } export class OscillatorNode extends AudioScheduledSourceNode { - constructor(context: NativeBaseAudioContext, options: { type?: string; frequency?: number } = {}) { + constructor(context: NativeBaseAudioContext, options: { type?: string; frequency?: number; detune?: number; periodicWave?: PeriodicWave } & AudioNodeChannelOptions = {}) { const type = options?.type || 'sine'; + if (type === 'custom' && !options.periodicWave) throw domError('InvalidStateError', "OscillatorNode: type 'custom' needs a periodicWave"); const freq = typeof options?.frequency === 'number' ? options.frequency : 440; - super(context, context.native.createOscillatorNodeFrequency(type, freq)); + super(context, context.native.createOscillatorNodeFrequency(type === 'custom' ? 'sine' : type, freq)); + if (typeof options.detune === 'number') this.detune.value = options.detune; + if (options.periodicWave) this.setPeriodicWave(options.periodicWave); + this._applyNodeOptions(options); } get native() { @@ -554,18 +754,20 @@ export class OscillatorNode extends AudioScheduledSourceNode { } set type(v: string) { + if (v === 'custom') throw domError('InvalidStateError', "OscillatorNode.type: use setPeriodicWave for 'custom'"); + if (!['sine', 'square', 'sawtooth', 'triangle'].includes(v)) return; this.native.type = v; } private _frequencyParam!: AudioParam; get frequency(): AudioParam { - if (!this._frequencyParam) this._frequencyParam = new AudioParam(nativeCtor_, this.native.frequencyParam); + if (!this._frequencyParam) this._frequencyParam = new AudioParam(nativeCtor_, this.native.frequencyParam, { defaultValue: 440, min: -this.context.sampleRate / 2, max: this.context.sampleRate / 2 }); return this._frequencyParam; } private _detuneParam!: AudioParam; get detune(): AudioParam { - if (!this._detuneParam) this._detuneParam = new AudioParam(nativeCtor_, this.native.detuneParam); + if (!this._detuneParam) this._detuneParam = new AudioParam(nativeCtor_, this.native.detuneParam, { defaultValue: 0 }); return this._detuneParam; } @@ -582,12 +784,13 @@ export class StereoPannerNode extends AudioNode { super(context); const pan = typeof options.pan === 'number' ? options.pan : 0; this[native_] = context.native.createStereoPannerNode(pan); + this._applyNodeOptions(options); } get native() { return this[native_]; } get pan(): AudioParam { - if (!this._panParam) this._panParam = new AudioParam(nativeCtor_, this.native.panParam); + if (!this._panParam) this._panParam = new AudioParam(nativeCtor_, this.native.panParam, { defaultValue: 0, min: -1, max: 1 }); return this._panParam; } } @@ -599,7 +802,9 @@ export class DelayNode extends AudioNode { super(context); const delay = typeof options.delayTime === 'number' ? options.delayTime : 0; const max = typeof options.maxDelayTime === 'number' ? options.maxDelayTime : 1.0; + if (!(max > 0 && max < 180)) throw domError('NotSupportedError', `DelayNode: maxDelayTime ${max} must be above 0 and below 180`); this[native_] = context.native.createDelayNodeMaxDelayTime(delay, max); + this._applyNodeOptions(options); } get native() { return this[native_]; @@ -607,7 +812,7 @@ export class DelayNode extends AudioNode { get delayTime(): AudioParamBase { if (!this._delayTimeParam) { const n = this.native; - this._delayTimeParam = new AudioParam(nativeCtor_, n.delayTimeParam); + this._delayTimeParam = new AudioParam(nativeCtor_, n.delayTimeParam, { defaultValue: 0, min: 0, max: n.maxDelayTime }); } return this._delayTimeParam; } @@ -621,6 +826,7 @@ export class ConstantSourceNode extends AudioScheduledSourceNode { constructor(context: NativeBaseAudioContext, options: ConstantSourceOptions = {}) { const offset = typeof options.offset === 'number' ? options.offset : 1.0; super(context, context.native.createConstantSourceNode(offset) as NSCAudioScheduledSourceNode); + this._applyNodeOptions(options as any); } get native() { return this[native_] as NSCConstantSourceNode; @@ -628,7 +834,7 @@ export class ConstantSourceNode extends AudioScheduledSourceNode { get offset(): AudioParamBase { if (!this._offsetParam) { const n = this.native; - this._offsetParam = new AudioParam(nativeCtor_, n.offsetParam); + this._offsetParam = new AudioParam(nativeCtor_, n.offsetParam, { defaultValue: 1 }); } return this._offsetParam; } @@ -639,10 +845,14 @@ export class AnalyserNode extends AudioNode { constructor(context: NativeBaseAudioContext, options: AnalyserOptions = {}) { super(context); this[native_] = context.native.createAnalyserNode(); - if (typeof options.fftSize === 'number') this.native.fftSize = options.fftSize; - if (typeof options.smoothingTimeConstant === 'number') this.native.smoothingTimeConstant = options.smoothingTimeConstant; - if (typeof options.minDecibels === 'number') this.native.minDecibels = options.minDecibels; - if (typeof options.maxDecibels === 'number') this.native.maxDecibels = options.maxDecibels; + if (typeof options.fftSize === 'number') this.fftSize = options.fftSize; + if (typeof options.smoothingTimeConstant === 'number') this.smoothingTimeConstant = options.smoothingTimeConstant; + const min = options.minDecibels ?? this.minDecibels; + const max = options.maxDecibels ?? this.maxDecibels; + if (min >= max) throw domError('IndexSizeError', 'AnalyserNode: minDecibels must be below maxDecibels'); + this.native.minDecibels = min; + this.native.maxDecibels = max; + this._applyNodeOptions(options); } get native() { return this[native_]; @@ -651,6 +861,7 @@ export class AnalyserNode extends AudioNode { return this.native.fftSize; } set fftSize(v: number) { + if (!(v >= 32 && v <= 32768 && (v & (v - 1)) === 0)) throw domError('IndexSizeError', `AnalyserNode.fftSize: ${v} must be a power of two from 32 to 32768`); this.native.fftSize = v; } get frequencyBinCount() { @@ -660,18 +871,21 @@ export class AnalyserNode extends AudioNode { return this.native.smoothingTimeConstant; } set smoothingTimeConstant(v: number) { + if (!(v >= 0 && v <= 1)) throw domError('IndexSizeError', `AnalyserNode.smoothingTimeConstant: ${v} is outside 0 to 1`); this.native.smoothingTimeConstant = v; } get minDecibels() { return this.native.minDecibels; } set minDecibels(v: number) { + if (v >= this.maxDecibels) throw domError('IndexSizeError', 'AnalyserNode.minDecibels must be below maxDecibels'); this.native.minDecibels = v; } get maxDecibels() { return this.native.maxDecibels; } set maxDecibels(v: number) { + if (v <= this.minDecibels) throw domError('IndexSizeError', 'AnalyserNode.maxDecibels must be above minDecibels'); this.native.maxDecibels = v; } getFloatTimeDomainData(dest: Float32Array) { @@ -686,8 +900,9 @@ export class AnalyserNode extends AudioNode { } getByteTimeDomainData(dest: Uint8Array) { if (!dest || dest.length === 0) return; - const native = this.native; - native.getByteTimeDomainData(dest as never); + const data = new Float32Array(Math.min(dest.length, this.fftSize)); + this.getFloatTimeDomainData(data); + for (let i = 0; i < data.length; i++) dest[i] = Math.max(0, Math.min(255, Math.floor(128 * (1 + data[i])))); } getFloatFrequencyData(dest: Float32Array) { if (!dest || dest.length === 0) return; @@ -701,8 +916,10 @@ export class AnalyserNode extends AudioNode { } getByteFrequencyData(dest: Uint8Array) { if (!dest || dest.length === 0) return; - const native = this.native; - native.getByteFrequencyData(dest as never); + const data = new Float32Array(Math.min(dest.length, this.frequencyBinCount)); + this.getFloatFrequencyData(data); + const min = this.minDecibels, scale = 255 / (this.maxDecibels - min); + for (let i = 0; i < data.length; i++) dest[i] = Math.max(0, Math.min(255, Math.floor(scale * (data[i] - min)))); } } @@ -714,14 +931,17 @@ export class WaveShaperNode extends AudioNode { this[native_] = context.native.createWaveShaperNode(); if (options.curve) this.curve = options.curve instanceof Float32Array ? options.curve : Float32Array.from(options.curve); if (options.oversample) this.oversample = options.oversample; + this._applyNodeOptions(options); } get native() { return this[native_]; } get curve(): Float32Array | null { - return this._curve; + return this._curve ? this._curve.slice() : null; } - set curve(v: Float32Array | null) { + set curve(input: Float32Array | null) { + if (input && input.length < 2) throw domError('InvalidStateError', 'WaveShaperNode.curve needs at least 2 values'); + const v = input ? Float32Array.from(input) : null; this._curve = v; if (!v) { this.native.setCurveFromData(null as never); @@ -752,14 +972,18 @@ export class IIRFilterNode extends AudioNode { super(context); const ff = options?.feedforward ?? []; const fb = options?.feedback ?? []; - if (!ff.length || !fb.length) throw new TypeError('IIRFilterNode: feedforward and feedback are required'); + if (!ff.length || !fb.length || ff.length > 20 || fb.length > 20) throw domError('NotSupportedError', 'IIRFilterNode: feedforward and feedback need 1 to 20 coefficients'); + if (ff.every((v) => v === 0)) throw domError('InvalidStateError', 'IIRFilterNode: feedforward is all zero'); + if (fb[0] === 0) throw domError('InvalidStateError', 'IIRFilterNode: feedback[0] is zero'); this[native_] = context.native.createIIRFilterNodeFeedback(ff as never, fb as never); + this._applyNodeOptions(options as any); } get native() { return this[native_]; } getFrequencyResponse(frequencyHz: Float32Array, magResponse: Float32Array, phaseResponse: Float32Array) { if (!frequencyHz || !magResponse || !phaseResponse) return; + if (magResponse.length !== frequencyHz.length || phaseResponse.length !== frequencyHz.length) throw domError('InvalidAccessError', 'getFrequencyResponse: the arrays differ in length'); const native: any = this.native; const frequencyHzByteOffset = normalizeCopyByteOffset(frequencyHz); const magResponseByteOffset = normalizeCopyByteOffset(magResponse); @@ -777,18 +1001,27 @@ export class ConvolverNode extends AudioNode { constructor(context: NativeBaseAudioContext, options: ConvolverOptions = {}) { super(context); this[native_] = context.native.createConvolverNode(); - this.native.normalize = !options.disableNormalization; + applyConvolverOptions(this, options); + this._applyNodeOptions(options as any); } get native() { return this[native_]; } + private _buffer: AudioBuffer | null = null; get buffer(): AudioBuffer | null { - const b = this.native.buffer; - return b ? new AudioBuffer(nativeCtor_, b) : null; + return this._buffer; } set buffer(v: AudioBuffer | null) { + this._checkBuffer(v); + this._buffer = v; this.native.buffer = v?.native ?? (null as never); } + private _checkBuffer(v: AudioBuffer | null) { + if (v) { + if (![1, 2, 4].includes(v.numberOfChannels)) throw domError('NotSupportedError', `ConvolverNode.buffer: ${v.numberOfChannels} channels; it takes 1, 2 or 4`); + if (v.sampleRate !== (this.context as any).sampleRate) throw domError('NotSupportedError', "ConvolverNode.buffer: the buffer's sampleRate differs from the context's"); + } + } get normalize() { return this.native.normalize; @@ -805,7 +1038,6 @@ export class DynamicsCompressorNode extends AudioNode { private _ratio: AudioParam | null = null; private _attack: AudioParam | null = null; private _release: AudioParam | null = null; - private _reduction: AudioParam | null = null; constructor(context: NativeBaseAudioContext, options: DynamicsCompressorOptions = {}) { super(context); @@ -816,6 +1048,7 @@ export class DynamicsCompressorNode extends AudioNode { if (typeof options.ratio === 'number') this.ratio.value = options.ratio; if (typeof options.attack === 'number') this.attack.value = options.attack; if (typeof options.release === 'number') this.release.value = options.release; + this._applyNodeOptions(options as any); } get native() { @@ -823,27 +1056,28 @@ export class DynamicsCompressorNode extends AudioNode { } get threshold() { - return this._threshold || (this._threshold = new AudioParam(nativeCtor_, this.native.thresholdParam)); + return this._threshold || (this._threshold = new AudioParam(nativeCtor_, this.native.thresholdParam, { defaultValue: -24, min: -100, max: 0, fixedRate: 'k-rate' })); } get knee() { - return this._knee || (this._knee = new AudioParam(nativeCtor_, this.native.kneeParam)); + return this._knee || (this._knee = new AudioParam(nativeCtor_, this.native.kneeParam, { defaultValue: 30, min: 0, max: 40, fixedRate: 'k-rate' })); } get ratio() { - return this._ratio || (this._ratio = new AudioParam(nativeCtor_, this.native.ratioParam)); + return this._ratio || (this._ratio = new AudioParam(nativeCtor_, this.native.ratioParam, { defaultValue: 12, min: 1, max: 20, fixedRate: 'k-rate' })); } get attack() { - return this._attack || (this._attack = new AudioParam(nativeCtor_, this.native.attackParam)); + return this._attack || (this._attack = new AudioParam(nativeCtor_, this.native.attackParam, { defaultValue: 0.003, min: 0, max: 1, fixedRate: 'k-rate' })); } get release() { - return this._release || (this._release = new AudioParam(nativeCtor_, this.native.releaseParam)); + return this._release || (this._release = new AudioParam(nativeCtor_, this.native.releaseParam, { defaultValue: 0.25, min: 0, max: 1, fixedRate: 'k-rate' })); } - get reduction() { - return this._reduction || (this._reduction = new AudioParam(nativeCtor_, this.native.reductionParam)); + /** The gain reduction in dB the compressor last applied. */ + get reduction(): number { + return this.native.reduction; } } @@ -853,8 +1087,11 @@ export class ChannelSplitterNode extends AudioNode { constructor(context: NativeBaseAudioContext, options: ChannelSplitterOptions = {}) { super(context); - this._numberOfOutputs = Math.max(1, options.numberOfOutputs ?? 6); + const outputs = options.numberOfOutputs ?? 6; + if (!(outputs >= 1 && outputs <= 32)) throw domError('IndexSizeError', `ChannelSplitterNode: numberOfOutputs ${outputs} is outside 1 to 32`); + this._numberOfOutputs = outputs; this[native_] = context.native.createChannelSplitterNode(this._numberOfOutputs); + this._applyNodeOptions(options as any); } get native() { @@ -874,8 +1111,11 @@ export class ChannelMergerNode extends AudioNode { constructor(context: NativeBaseAudioContext, options: ChannelMergerOptions = {}) { super(context); - this._numberOfInputs = Math.max(1, options.numberOfInputs ?? 6); + const inputs = options.numberOfInputs ?? 6; + if (!(inputs >= 1 && inputs <= 32)) throw domError('IndexSizeError', `ChannelMergerNode: numberOfInputs ${inputs} is outside 1 to 32`); + this._numberOfInputs = inputs; this[native_] = context.native.createChannelMergerNode(this._numberOfInputs); + this._applyNodeOptions(options as any); } get native() { @@ -894,6 +1134,7 @@ export class PeriodicWave { constructor(_context: NativeBaseAudioContext, options: PeriodicWaveOptions = {}) { const real = options.real ? (options.real instanceof Float32Array ? options.real : Float32Array.from(options.real)) : new Float32Array(2); const imag = options.imag ? (options.imag instanceof Float32Array ? options.imag : Float32Array.from(options.imag)) : new Float32Array(real.length); + if (real.length !== imag.length || real.length < 2) throw domError('IndexSizeError', 'PeriodicWave: real and imag need the same length, at least 2'); const realByteOffset = normalizeCopyByteOffset(real); const imagByteOffset = normalizeCopyByteOffset(imag); @@ -915,9 +1156,32 @@ export class PeriodicWave { export class AudioBufferSourceNode extends AudioScheduledSourceNode { private _playbackRateParam: AudioParam | null = null; - constructor(context: NativeBaseAudioContext, options: { buffer?: AudioBuffer } = {}) { + constructor(context: NativeBaseAudioContext, options: { buffer?: AudioBuffer; loop?: boolean; loopStart?: number; loopEnd?: number; playbackRate?: number; detune?: number } & AudioNodeChannelOptions = {}) { const param: NSCAudioBuffer | null = options?.buffer != null ? options.buffer.native : null; super(context, context.native.createBufferSourceNode(param as never)); + if (options.buffer) { + this._bufferSet = true; + this._buffer = options.buffer; + } + if (options.loop) this.loop = true; + if (typeof options.loopStart === 'number') this.loopStart = options.loopStart; + if (typeof options.loopEnd === 'number') this.loopEnd = options.loopEnd; + if (typeof options.playbackRate === 'number') this.playbackRate.value = options.playbackRate; + if (typeof options.detune === 'number') this.detune.value = options.detune; + this._applyNodeOptions(options); + } + + get loopStart(): number { + return this.native.loopStart; + } + set loopStart(v: number) { + this.native.loopStart = v; + } + get loopEnd(): number { + return this.native.loopEnd; + } + set loopEnd(v: number) { + this.native.loopEnd = v; } get native() { @@ -935,23 +1199,27 @@ export class AudioBufferSourceNode extends AudioScheduledSourceNode { return this.native.loop; } + private _buffer: AudioBuffer | null = null; get buffer(): AudioBuffer | null { - const b = this.native.buffer; - return b ? new AudioBuffer(nativeCtor_, b) : null; + return this._buffer; } set buffer(v: AudioBuffer | null) { + if (v && this._bufferSet) throw domError('InvalidStateError', 'AudioBufferSourceNode.buffer can only be set once'); + if (v) this._bufferSet = true; + this._buffer = v; this.native.buffer = v?.native ?? (null as never); } + private _bufferSet = false; get playbackRate(): AudioParam | null { if (this._playbackRateParam) return this._playbackRateParam; - this._playbackRateParam = new AudioParam(nativeCtor_, this.native.getPlaybackRateParam()); + this._playbackRateParam = new AudioParam(nativeCtor_, this.native.getPlaybackRateParam(), { defaultValue: 1, fixedRate: 'k-rate' }); return this._playbackRateParam; } private _detuneParam: AudioParam | null = null; get detune(): AudioParam { - if (!this._detuneParam) this._detuneParam = new AudioParam(nativeCtor_, this.native.detuneParam); + if (!this._detuneParam) this._detuneParam = new AudioParam(nativeCtor_, this.native.detuneParam, { defaultValue: 0, fixedRate: 'k-rate' }); return this._detuneParam; } } @@ -1141,6 +1409,7 @@ export class AudioWorkletNode extends AudioNode { defaults, ); if (!this._native) throw domError('NotSupportedError', 'AudioWorkletNode: the audio unit could not be created'); + this._applyNodeOptions(options as any); const params = this._native.params; this.parameters = new AudioParamMap(new Map(descriptors.map((d, i) => [d.name, new AudioParam(nativeCtor_, params.objectAtIndex(i))]))); const id = nextWorkletNode++; @@ -1205,9 +1474,13 @@ export class AudioContext extends BaseAudioContext { constructor(options?: AudioContextOptions) { super(); - const sampleRate = options?.sampleRate ?? 48000; - const latencyHint = resolveLatencyHint(options?.latencyHint); + const sampleRate = options?.sampleRate ?? 0; + if (options?.sampleRate !== undefined && !(sampleRate >= 3000 && sampleRate <= 768000)) throw domError('NotSupportedError', `AudioContext: sampleRate ${sampleRate} is out of range`); + const hint = options?.latencyHint; + if (typeof hint === 'string' && !['interactive', 'balanced', 'playback'].includes(hint)) throw new TypeError(`AudioContext: latencyHint '${hint}' is not a valid AudioContextLatencyCategory`); + const latencyHint = resolveLatencyHint(hint); this[native_] = NSCAudioContext.alloc().initWithSampleRateLatencyHint(sampleRate, latencyHint); + this._sampleRate = this[native_].sampleRate; try { const nd = this[native_].destination; this._destination = nd ? new AudioDestinationNode(this, nd) : null; @@ -1255,8 +1528,8 @@ export class AudioContext extends BaseAudioContext { createOscillator(options?: { type?: string; frequency?: number }) { return new OscillatorNode(this, options ?? {}); } - createBuffer(options: { length: number; numberOfChannels: number; sampleRate: number }) { - return new AudioBuffer(options); + createBuffer(options: { length: number; numberOfChannels: number; sampleRate: number } | number, length?: number, sampleRate?: number) { + return new AudioBuffer(typeof options === 'number' ? { numberOfChannels: options, length, sampleRate } : options); } createBufferSource(options?: { buffer?: AudioBuffer }) { return new AudioBufferSourceNode(this, options ?? {}); @@ -1264,8 +1537,8 @@ export class AudioContext extends BaseAudioContext { createStereoPanner(options?: StereoPannerOptions) { return new StereoPannerNode(this, options ?? {}); } - createDelay(options?: DelayOptions) { - return new DelayNode(this, options ?? {}); + createDelay(options?: DelayOptions | number) { + return new DelayNode(this, typeof options === 'number' ? { maxDelayTime: options } : (options ?? {})); } createConstantSource(options?: ConstantSourceOptions) { return new ConstantSourceNode(this, options ?? {}); @@ -1285,11 +1558,11 @@ export class AudioContext extends BaseAudioContext { createDynamicsCompressor(options?: DynamicsCompressorOptions) { return new DynamicsCompressorNode(this, options ?? {}); } - createChannelSplitter(options?: ChannelSplitterOptions) { - return new ChannelSplitterNode(this, options ?? {}); + createChannelSplitter(numberOfOutputs?: number | ChannelSplitterOptions) { + return new ChannelSplitterNode(this, typeof numberOfOutputs === 'number' ? { numberOfOutputs } : (numberOfOutputs ?? {})); } - createChannelMerger(options?: ChannelMergerOptions) { - return new ChannelMergerNode(this, options ?? {}); + createChannelMerger(numberOfInputs?: number | ChannelMergerOptions) { + return new ChannelMergerNode(this, typeof numberOfInputs === 'number' ? { numberOfInputs } : (numberOfInputs ?? {})); } createPeriodicWave(real: Float32Array | number[], imag: Float32Array | number[], options?: { disableNormalization?: boolean }) { return new PeriodicWave(this, { real, imag, disableNormalization: options?.disableNormalization }); @@ -1298,8 +1571,10 @@ export class AudioContext extends BaseAudioContext { get native() { return this[native_]; } + private _sampleRate = 0; + private _closedTime = 0; get sampleRate(): number { - return this.native.sampleRate; + return this._sampleRate; } get baseLatency(): number { if (typeof this.native.baseLatency === 'number') return this.native.baseLatency; @@ -1320,11 +1595,30 @@ export class AudioContext extends BaseAudioContext { } } get currentTime(): number { - return this.native.currentTime; + return this.native ? this.native.currentTime : this._closedTime; + } + + /** The context time last sent to the output, and when (performance.now()). */ + getOutputTimestamp(): { contextTime: number; performanceTime: number } { + if (!this.native || this._state !== 'running') return { contextTime: this.currentTime, performanceTime: 0 }; + const contextTime = Math.max(0, this.currentTime - this.outputLatency); + return { contextTime, performanceTime: performance.now() - (this.currentTime - contextTime) * 1000 }; + } + + 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'); } resume(): Promise { - if (this._state === 'closed') return Promise.reject(new Error('AudioContext is closed')); + if (this._state === 'closed') return Promise.reject(domError('InvalidStateError', 'AudioContext is closed')); const native = this.native; if (!native) return Promise.reject(new Error('AudioContext: native engine unavailable')); return new Promise((resolve, reject) => { @@ -1340,7 +1634,7 @@ export class AudioContext extends BaseAudioContext { } suspend(): Promise { - if (this._state === 'closed') return Promise.reject(new Error('AudioContext is closed')); + if (this._state === 'closed') return Promise.reject(domError('InvalidStateError', 'AudioContext is closed')); const native = this.native; if (!native) return Promise.reject(new Error('AudioContext: native engine unavailable')); return new Promise((resolve, reject) => { @@ -1356,7 +1650,7 @@ export class AudioContext extends BaseAudioContext { } close(): Promise { - if (this._state === 'closed') return Promise.resolve(); + if (this._state === 'closed') return Promise.reject(domError('InvalidStateError', 'AudioContext is already closed')); this._audioWorklet?._scope(false)?.close(); connectedWorkletNodes.forEach((node) => { if (node.context === this) connectedWorkletNodes.delete(node); @@ -1364,6 +1658,7 @@ export class AudioContext extends BaseAudioContext { const native = this.native; return new Promise((resolve) => { const finish = () => { + this._closedTime = native?.currentTime ?? 0; this[native_] = null as any; this._destination = null; this._listener = null; @@ -1402,20 +1697,20 @@ export class AudioContext extends BaseAudioContext { if (!isBase64Source(source)) { const filePath = normalizeSourcePath(source); this.native.decodeAudioDataFromFileAsync(filePath, (wrapper) => { - if (!wrapper) return reject(new Error('decodeAudioData failed')); + if (!wrapper) return reject(domError('EncodingError', 'decodeAudioData: the data could not be decoded')); resolve(new AudioBuffer(nativeCtor_, wrapper)); }); return; } this.native.decodeAudioDataAsync(source, (wrapper) => { - if (!wrapper) return reject(new Error('decodeAudioData failed')); + if (!wrapper) return reject(domError('EncodingError', 'decodeAudioData: the data could not be decoded')); resolve(new AudioBuffer(nativeCtor_, wrapper)); }); return; } this.native.decodeAudioDataFromDataAsync(source as never, (wrapper) => { - if (!wrapper) return reject(new Error('decodeAudioData failed')); + if (!wrapper) return reject(domError('EncodingError', 'decodeAudioData: the data could not be decoded')); resolve(new AudioBuffer(nativeCtor_, wrapper)); }); } catch (e) { @@ -1449,8 +1744,12 @@ export class OfflineAudioContext extends BaseAudioContext { constructor(numberOfChannels: number | { numberOfChannels?: number; length: number; sampleRate: number }, lengthInFrames?: number, sampleRate?: number) { super(); const options = typeof numberOfChannels === 'object' ? numberOfChannels : { numberOfChannels, length: lengthInFrames, sampleRate }; + const channels = options.numberOfChannels ?? 1; + if (!(channels >= 1 && channels <= 32)) throw domError('NotSupportedError', `OfflineAudioContext: numberOfChannels ${channels} is outside 1 to 32`); + if (!(options.length >= 1)) throw domError('NotSupportedError', `OfflineAudioContext: length ${options.length} must be at least 1`); + if (!(options.sampleRate >= 3000 && options.sampleRate <= 768000)) throw domError('NotSupportedError', `OfflineAudioContext: sampleRate ${options.sampleRate} is outside 3000 to 768000`); this[native_] = NSCOfflineAudioContext.new(); - this[native_].configure(Math.max(1, (options.numberOfChannels ?? 1) | 0), Math.max(0, options.length | 0), options.sampleRate && Number.isFinite(options.sampleRate) ? options.sampleRate : 48000); + this[native_].configure(channels | 0, options.length | 0, options.sampleRate); try { const nd = this[native_].destination; this.destination = nd ? new AudioDestinationNode(this, nd) : null; @@ -1509,8 +1808,8 @@ export class OfflineAudioContext extends BaseAudioContext { return this._audioWorklet ?? undefined; } - createBuffer(options: { length: number; numberOfChannels: number; sampleRate: number }) { - return new AudioBuffer(options); + createBuffer(options: { length: number; numberOfChannels: number; sampleRate: number } | number, length?: number, sampleRate?: number) { + return new AudioBuffer(typeof options === 'number' ? { numberOfChannels: options, length, sampleRate } : options); } createGain(options?: { gain?: number }) { @@ -1531,8 +1830,8 @@ export class OfflineAudioContext extends BaseAudioContext { createStereoPanner(options?: StereoPannerOptions) { return new StereoPannerNode(this, options ?? {}); } - createDelay(options?: DelayOptions) { - return new DelayNode(this, options ?? {}); + createDelay(options?: DelayOptions | number) { + return new DelayNode(this, typeof options === 'number' ? { maxDelayTime: options } : (options ?? {})); } createConstantSource(options?: ConstantSourceOptions) { return new ConstantSourceNode(this, options ?? {}); @@ -1552,11 +1851,11 @@ export class OfflineAudioContext extends BaseAudioContext { createDynamicsCompressor(options?: DynamicsCompressorOptions) { return new DynamicsCompressorNode(this, options ?? {}); } - createChannelSplitter(options?: ChannelSplitterOptions) { - return new ChannelSplitterNode(this, options ?? {}); + createChannelSplitter(numberOfOutputs?: number | ChannelSplitterOptions) { + return new ChannelSplitterNode(this, typeof numberOfOutputs === 'number' ? { numberOfOutputs } : (numberOfOutputs ?? {})); } - createChannelMerger(options?: ChannelMergerOptions) { - return new ChannelMergerNode(this, options ?? {}); + createChannelMerger(numberOfInputs?: number | ChannelMergerOptions) { + return new ChannelMergerNode(this, typeof numberOfInputs === 'number' ? { numberOfInputs } : (numberOfInputs ?? {})); } createPeriodicWave(real: Float32Array | number[], imag: Float32Array | number[], options?: { disableNormalization?: boolean }) { return new PeriodicWave(this, { real, imag, disableNormalization: options?.disableNormalization }); @@ -1569,20 +1868,20 @@ export class OfflineAudioContext extends BaseAudioContext { if (!isBase64Source(source)) { const filePath = normalizeSourcePath(source); this.native.decodeAudioDataFromFileAsyncOffline(filePath, (wrapper) => { - if (!wrapper) return reject(new Error('decodeAudioData failed')); + if (!wrapper) return reject(domError('EncodingError', 'decodeAudioData: the data could not be decoded')); resolve(new AudioBuffer(nativeCtor_, wrapper)); }); return; } this.native.decodeAudioDataAsync(source, (wrapper) => { - if (!wrapper) return reject(new Error('decodeAudioData failed')); + if (!wrapper) return reject(domError('EncodingError', 'decodeAudioData: the data could not be decoded')); resolve(new AudioBuffer(nativeCtor_, wrapper)); }); return; } this.native.decodeAudioDataFromDataAsync(source as never, (wrapper) => { - if (!wrapper) return reject(new Error('decodeAudioData failed')); + if (!wrapper) return reject(domError('EncodingError', 'decodeAudioData: the data could not be decoded')); resolve(new AudioBuffer(nativeCtor_, wrapper)); }); } catch (e) { @@ -1596,6 +1895,16 @@ export class OfflineAudioContext extends BaseAudioContext { return ret; } + private _oncomplete: ((ev: any) => void) | null = null; + get oncomplete() { + return this._oncomplete; + } + set oncomplete(cb: ((ev: any) => void) | null) { + if (this._oncomplete) this.removeEventListener('complete', this._oncomplete); + this._oncomplete = typeof cb === 'function' ? cb : null; + if (this._oncomplete) this.addEventListener('complete', this._oncomplete); + } + startRendering(): Promise { if (this._rendering) return Promise.reject(domError('InvalidStateError', 'OfflineAudioContext: rendering has already started')); this._setState('running'); @@ -1608,7 +1917,9 @@ export class OfflineAudioContext extends BaseAudioContext { this._setState('closed'); this._suspends.rejectAll(() => domError('InvalidStateError', 'OfflineAudioContext: rendering finished before the suspend')); if (!wrapper) return reject(new Error('startRendering failed')); - resolve(new AudioBuffer(nativeCtor_, wrapper)); + const rendered = new AudioBuffer(nativeCtor_, wrapper); + resolve(rendered); + setTimeout(() => this.dispatchEvent({ type: 'complete', renderedBuffer: rendered, target: this })); }); }); return this._rendering; diff --git a/packages/audio-context/platforms/android/audiocontext-release.aar b/packages/audio-context/platforms/android/audiocontext-release.aar index d08ca583..5fce9d35 100644 Binary files a/packages/audio-context/platforms/android/audiocontext-release.aar and b/packages/audio-context/platforms/android/audiocontext-release.aar differ diff --git a/packages/audio-context/platforms/ios/build.xcconfig b/packages/audio-context/platforms/ios/build.xcconfig index a9cb162e..f20eaf75 100644 --- a/packages/audio-context/platforms/ios/build.xcconfig +++ b/packages/audio-context/platforms/ios/build.xcconfig @@ -13,5 +13,7 @@ CLANG_CXX_LANGUAGE_STANDARD = c++20 AUDIO_CONTEXT_V8_HEADERS_NPM = $(SRCROOT)/../../node_modules/@nativescript/audio-context/platforms/ios/NativeScriptV8/Headers/include AUDIO_CONTEXT_V8_HEADERS_MONOREPO = $(SRCROOT)/../../../../nativescript-v8/Headers/include AUDIO_CONTEXT_V8_HEADER_FLAGS = -I"$(AUDIO_CONTEXT_V8_HEADERS_NPM)" -I"$(AUDIO_CONTEXT_V8_HEADERS_MONOREPO)" -OTHER_CFLAGS = $(inherited) $(AUDIO_CONTEXT_V8_HEADER_FLAGS) -OTHER_CPLUSPLUSFLAGS = $(inherited) $(AUDIO_CONTEXT_V8_HEADER_FLAGS) +// The HRTF set in src-native/common, shared with the Android build. +AUDIO_CONTEXT_COMMON_HEADER_FLAGS = -I"$(SRCROOT)/../../node_modules/@nativescript/audio-context/src-native/common" +OTHER_CFLAGS = $(inherited) $(AUDIO_CONTEXT_V8_HEADER_FLAGS) $(AUDIO_CONTEXT_COMMON_HEADER_FLAGS) +OTHER_CPLUSPLUSFLAGS = $(inherited) $(AUDIO_CONTEXT_V8_HEADER_FLAGS) $(AUDIO_CONTEXT_COMMON_HEADER_FLAGS) diff --git a/packages/audio-context/platforms/ios/src/NSCAnalyserNode.h b/packages/audio-context/platforms/ios/src/NSCAnalyserNode.h index 585b6208..51443d3a 100644 --- a/packages/audio-context/platforms/ios/src/NSCAnalyserNode.h +++ b/packages/audio-context/platforms/ios/src/NSCAnalyserNode.h @@ -1,12 +1,12 @@ #import #import -#import "NSCAudioNode.h" +#import "NSCProcessorNode.h" NS_ASSUME_NONNULL_BEGIN @class NSCAudioContext; -@interface NSCAnalyserNode : NSCAudioNode +@interface NSCAnalyserNode : NSCProcessorNode @property (nonatomic) NSInteger fftSize; @property (nonatomic, readonly) NSInteger frequencyBinCount; @@ -14,8 +14,7 @@ NS_ASSUME_NONNULL_BEGIN @property (nonatomic) double minDecibels; @property (nonatomic) double maxDecibels; -- (instancetype)initWithContext:(NSCAudioContext *)context NS_DESIGNATED_INITIALIZER; -- (instancetype)initWithContext:(NSCAudioContext *)context node:(nullable AVAudioNode *)node NS_UNAVAILABLE; +- (instancetype)initWithContext:(NSCAudioContext *)context; - (void)getFloatTimeDomainData:(NSMutableData *)data; - (void)getFloatTimeDomainDataWithByteOffset:(NSMutableData *)data :(NSInteger)byteOffset; @@ -25,9 +24,6 @@ NS_ASSUME_NONNULL_BEGIN - (void)getByteFrequencyData:(NSMutableData *)data; - (void)appendBufferToRing:(AVAudioPCMBuffer *)buffer; -- (void)setAcceptingFrames:(BOOL)accept; - -- (AVAudioNode *)mixerNode; @end diff --git a/packages/audio-context/platforms/ios/src/NSCAnalyserNode.m b/packages/audio-context/platforms/ios/src/NSCAnalyserNode.m index dfdb61cc..69d007a0 100644 --- a/packages/audio-context/platforms/ios/src/NSCAnalyserNode.m +++ b/packages/audio-context/platforms/ios/src/NSCAnalyserNode.m @@ -58,13 +58,24 @@ static inline NSUInteger NSCAnalyserNormalizeFloatByteOffset(NSInteger byteOffse return offset; } -@implementation NSCAnalyserNode { - AVAudioMixerNode *_mixer; +#define ANALYSER_RING 32768 + +// The last 32768 frames, down-mixed to mono; written on the render thread. +@interface NSCAnalyserRing : NSObject { +@public + float ring[ANALYSER_RING]; + atomic_int_least64_t writeIndex; + atomic_uint_least64_t framesWritten; +} +@end +@implementation NSCAnalyserRing +@end + +@implementation NSCAnalyserNode { + NSCAnalyserRing *_ring; float *_timeRing; NSInteger _timeRingCapacity; - atomic_int_least64_t _timeRingWriteIdx; - atomic_uint_least64_t _framesWritten; float *_smoothedMag; float *_dbCache; @@ -83,46 +94,38 @@ @implementation NSCAnalyserNode { int64_t _spectrumFrameStamp; int64_t _dbCacheFrameStamp; - - BOOL _tapInstalled; - AVAudioFormat *_tapFormat; - _Atomic(bool) _acceptingFrames; - - int _quantumFrames; } #pragma mark - Setup / teardown - (instancetype)initWithContext:(NSCAudioContext *)context { - AVAudioMixerNode *mixer = [[AVAudioMixerNode alloc] init]; - [context.engine attachNode:mixer]; - if (self = [super initWithContext:context node:mixer]) { - _mixer = mixer; - _fftSize = 2048; - _smoothingTimeConstant = 0.8; - _minDecibels = -100.0; - _maxDecibels = -30.0; - _quantumFrames = 1024; - _timeRingCapacity = _fftSize; - _timeRing = (float *)calloc((size_t)_timeRingCapacity, sizeof(float)); - _smoothedMagCount = _fftSize / 2; - _smoothedMag = (float *)calloc((size_t)_smoothedMagCount, sizeof(float)); - _dbCache = (float *)calloc((size_t)_smoothedMagCount, sizeof(float)); - _magLock = [NSLock new]; - atomic_init(&_timeRingWriteIdx, 0); - atomic_init(&_framesWritten, 0); - atomic_store(&_acceptingFrames, false); - _spectrumFrameStamp = -1; - _dbCacheFrameStamp = -1; - [self rebuildFftCachesForSize:_fftSize]; - } + if (!(self = [super initWithContext:context outputChannels:2])) return nil; + _fftSize = 2048; + _smoothingTimeConstant = 0.8; + _minDecibels = -100.0; + _maxDecibels = -30.0; + _ring = [NSCAnalyserRing new]; + _timeRing = _ring->ring; + _timeRingCapacity = ANALYSER_RING; + _smoothedMagCount = _fftSize / 2; + _smoothedMag = (float *)calloc((size_t)_smoothedMagCount, sizeof(float)); + _dbCache = (float *)calloc((size_t)_smoothedMagCount, sizeof(float)); + _magLock = [NSLock new]; + _spectrumFrameStamp = -1; + _dbCacheFrameStamp = -1; + [self rebuildFftCachesForSize:_fftSize]; + NSCAnalyserRing *ring = _ring; + [self setProcess:^UInt32(int64_t frame, UInt32 frames, float *const *in, UInt32 inChannels, float *const *out, UInt32 outChannels) { + NSCAnalyser_appendToRing(ring->ring, ANALYSER_RING, &ring->writeIndex, &ring->framesWritten, in, inChannels, frames); + UInt32 channels = MIN(inChannels, outChannels); + for (UInt32 c = 0; c < channels; c++) memcpy(out[c], in[c], frames * sizeof(float)); + return channels; + }]; + [self keepPulled]; return self; } - (void)dealloc { - atomic_store_explicit(&_acceptingFrames, false, memory_order_relaxed); - [self removeTapIfInstalled]; - if (_timeRing) { free(_timeRing); _timeRing = NULL; } if (_smoothedMag) { free(_smoothedMag); _smoothedMag = NULL; } if (_dbCache) { free(_dbCache); _dbCache = NULL; } [self freeFftCaches]; @@ -152,127 +155,11 @@ - (void)rebuildFftCachesForSize:(NSInteger)n { _realOut = (float *)malloc((size_t)half * sizeof(float)); _imagOut = (float *)malloc((size_t)half * sizeof(float)); _magScratch = (float *)malloc((size_t)half * sizeof(float)); - if (_window) vDSP_hann_window(_window, (vDSP_Length)n, vDSP_HANN_NORM); + if (_window) vDSP_blkman_window(_window, (vDSP_Length)n, 0); _spectrumFrameStamp = -1; _dbCacheFrameStamp = -1; } -- (AVAudioNode *)mixerNode { return _mixer; } - -- (void)setAcceptingFrames:(BOOL)accept { - atomic_store_explicit(&_acceptingFrames, accept, memory_order_relaxed); -} - -#pragma mark - Tap lifecycle - -- (BOOL)hasAnyInputConnection { - if (!_mixer) return NO; - AVAudioEngine *engine = self.context.engine; - if (!engine) return NO; - if (![engine respondsToSelector:@selector(inputConnectionPointForNode:inputBus:)]) return YES; - for (AVAudioNodeBus bus = 0; bus < (AVAudioNodeBus)_mixer.numberOfInputs; ++bus) { - AVAudioConnectionPoint *p = nil; - @try { p = [engine inputConnectionPointForNode:_mixer inputBus:bus]; } - @catch (NSException *e) { p = nil; } - if (p && p.node) return YES; - } - return NO; -} - -- (AVAudioFormat *)resolveTapFormat { - if (!_mixer) return nil; - AVAudioFormat *fmt = nil; - @try { fmt = [_mixer outputFormatForBus:0]; } - @catch (NSException *e) { fmt = nil; } - if (!fmt || fmt.sampleRate <= 0 || fmt.channelCount == 0) { - AVAudioEngine *engine = self.context.engine; - @try { fmt = engine ? [engine.mainMixerNode outputFormatForBus:0] : nil; } - @catch (NSException *e) { fmt = nil; } - } - if (!fmt || fmt.sampleRate <= 0 || fmt.channelCount == 0) return nil; - return fmt; -} - -- (void)installTapIfNeeded { - if (!_mixer || _tapInstalled) return; - AVAudioFormat *fmt = [self resolveTapFormat]; - if (!fmt) return; - - __weak typeof(self) weakSelf = self; - AVAudioMixerNode *mixer = _mixer; - AVAudioNodeTapBlock tapBlock = ^(AVAudioPCMBuffer *buf, AVAudioTime *when) { - __strong typeof(weakSelf) s = weakSelf; - if (!s) return; - if (!atomic_load_explicit(&s->_acceptingFrames, memory_order_relaxed)) return; - float * const *cd = buf.floatChannelData; - if (!cd) return; - AVAudioFrameCount frames = buf.frameLength; - if (frames == 0) return; - AVAudioChannelCount channels = buf.format.channelCount; - NSCAnalyser_appendToRing(s->_timeRing, s->_timeRingCapacity, - &s->_timeRingWriteIdx, &s->_framesWritten, - cd, channels, frames); - }; - - @try { - [_mixer installTapOnBus:0 - bufferSize:(AVAudioFrameCount)_quantumFrames - format:fmt - block:tapBlock]; - _tapInstalled = YES; - _tapFormat = fmt; - atomic_store_explicit(&_acceptingFrames, true, memory_order_release); - } @catch (NSException *e) { - NSCLogDebug(@"NSCAnalyserNode: installTapOnBus failed: %@ (mixer=%p sr=%.0f ch=%u)", - e, mixer, fmt.sampleRate, (unsigned)fmt.channelCount); - } -} - -- (void)removeTapIfInstalled { - atomic_store_explicit(&_acceptingFrames, false, memory_order_relaxed); - if (!_tapInstalled || !_mixer) return; - @try { [_mixer removeTapOnBus:0]; } @catch (NSException *e) {} - _tapInstalled = NO; - _tapFormat = nil; -} - -#pragma mark - Connection hooks - -- (void)handleConnectFrom:(NSCAudioNode *)source output:(NSNumber *)output input:(NSNumber *)input { - [super handleConnectFrom:source output:output input:input]; - [self installTapIfNeeded]; -} - -- (void)handleConnectedTo:(NSCAudioNode *)destination output:(NSNumber *)output input:(NSNumber *)input { - [super handleConnectedTo:destination output:output input:input]; - [self installTapIfNeeded]; -} - -- (void)handleDisconnectFrom:(NSCAudioNode *)source output:(NSNumber *)output input:(NSNumber *)input { - [super handleDisconnectFrom:source output:output input:input]; - if (![self hasAnyInputConnection]) { - [self resetAfterDisconnect]; - } -} - -- (void)disconnect { - [super disconnect]; - if (![self hasAnyInputConnection]) { - [self resetAfterDisconnect]; - } -} - -- (void)resetAfterDisconnect { - [self removeTapIfInstalled]; - atomic_store_explicit(&_timeRingWriteIdx, 0, memory_order_relaxed); - atomic_store_explicit(&_framesWritten, 0, memory_order_relaxed); - _spectrumFrameStamp = -1; - _dbCacheFrameStamp = -1; - if (_smoothedMag) memset(_smoothedMag, 0, (size_t)_smoothedMagCount * sizeof(float)); - if (_dbCache) memset(_dbCache, 0, (size_t)_smoothedMagCount * sizeof(float)); - if (_timeRing) memset(_timeRing, 0, (size_t)_timeRingCapacity * sizeof(float)); -} - #pragma mark - Properties - (NSInteger)frequencyBinCount { return _fftSize / 2; } @@ -282,17 +169,8 @@ - (void)setFftSize:(NSInteger)fftSize { if (fftSize > 32768) fftSize = 32768; NSInteger p = 1; while (p < fftSize) p <<= 1; if (p == _fftSize && _dftSetupSize == p) return; - - BOOL hadTap = _tapInstalled; - if (hadTap) [self removeTapIfInstalled]; - [_magLock lock]; _fftSize = p; - _timeRingCapacity = p; - if (_timeRing) free(_timeRing); - _timeRing = (float *)calloc((size_t)_timeRingCapacity, sizeof(float)); - atomic_store_explicit(&_timeRingWriteIdx, 0, memory_order_relaxed); - atomic_store_explicit(&_framesWritten, 0, memory_order_relaxed); if (_smoothedMag) free(_smoothedMag); if (_dbCache) free(_dbCache); _smoothedMagCount = p / 2; @@ -302,8 +180,6 @@ - (void)setFftSize:(NSInteger)fftSize { _dbCacheFrameStamp = -1; [self rebuildFftCachesForSize:p]; [_magLock unlock]; - - if (hadTap) [self installTapIfNeeded]; } - (void)setSmoothingTimeConstant:(double)smoothingTimeConstant { @@ -319,7 +195,7 @@ - (void)setSmoothingTimeConstant:(double)smoothingTimeConstant { - (void)copyLatestTimeSamplesInto:(float *)dst count:(NSInteger)n { NSInteger cap = _timeRingCapacity; if (cap <= 0 || n <= 0) return; - int64_t widx = atomic_load_explicit(&_timeRingWriteIdx, memory_order_acquire); + int64_t widx = atomic_load_explicit(&_ring->writeIndex, memory_order_acquire); int64_t start = widx - n; NSInteger leadZeros = (start < 0) ? (NSInteger)MIN((int64_t)n, -start) : 0; if (leadZeros > 0) memset(dst, 0, (size_t)leadZeros * sizeof(float)); @@ -381,7 +257,7 @@ - (void)computeMagnitudeSpectrumSmoothed { [self rebuildFftCachesForSize:n]; if (!_dftSetup) return; } - int64_t widx = atomic_load_explicit(&_timeRingWriteIdx, memory_order_acquire); + int64_t widx = atomic_load_explicit(&_ring->writeIndex, memory_order_acquire); [_magLock lock]; if (_spectrumFrameStamp == widx) { [_magLock unlock]; return; } @@ -394,8 +270,12 @@ - (void)computeMagnitudeSpectrumSmoothed { vDSP_DFT_Execute(_dftSetup, _realIn, _imagIn, _realOut, _imagOut); DSPSplitComplex c = { _realOut, _imagOut }; vDSP_zvmags(&c, 1, _magScratch, 1, (vDSP_Length)half); - - float scale = 1.0f / (float)(n * n); + // Bin 0's imaginary slot holds the Nyquist bin. + _magScratch[0] = _realOut[0] * _realOut[0]; + int count = (int)half; + vvsqrtf(_magScratch, _magScratch, &count); + // |X[k]| / N; vDSP's real DFT is twice the DFT. + float scale = 0.5f / (float)n; vDSP_vsmul(_magScratch, 1, &scale, _magScratch, 1, (vDSP_Length)half); float tau = (float)MAX(0.0, MIN(1.0, _smoothingTimeConstant)); @@ -418,7 +298,7 @@ - (void)ensureDbCacheLocked { float floor_ = 1e-20f; vDSP_vthr(_smoothedMag, 1, &floor_, _dbCache, 1, (vDSP_Length)lim); float ref = 1.0f; - vDSP_vdbcon(_dbCache, 1, &ref, _dbCache, 1, (vDSP_Length)lim, 0); + vDSP_vdbcon(_dbCache, 1, &ref, _dbCache, 1, (vDSP_Length)lim, 1); _dbCacheFrameStamp = _spectrumFrameStamp; } @@ -467,15 +347,9 @@ - (void)getByteFrequencyData:(NSMutableData *)data { } - (void)appendBufferToRing:(AVAudioPCMBuffer *)buffer { - if (!buffer) return; - if (!atomic_load_explicit(&_acceptingFrames, memory_order_relaxed)) return; - float * const *cd = buffer.floatChannelData; - if (!cd) return; - AVAudioFrameCount frames = buffer.frameLength; - if (frames == 0) return; - NSCAnalyser_appendToRing(_timeRing, _timeRingCapacity, - &_timeRingWriteIdx, &_framesWritten, - cd, buffer.format.channelCount, frames); + if (!buffer.floatChannelData || buffer.frameLength == 0) return; + NSCAnalyser_appendToRing(_ring->ring, ANALYSER_RING, &_ring->writeIndex, &_ring->framesWritten, + buffer.floatChannelData, buffer.format.channelCount, buffer.frameLength); } @end diff --git a/packages/audio-context/platforms/ios/src/NSCAudioBufferSourceNode.h b/packages/audio-context/platforms/ios/src/NSCAudioBufferSourceNode.h index 8c175965..0d66710f 100644 --- a/packages/audio-context/platforms/ios/src/NSCAudioBufferSourceNode.h +++ b/packages/audio-context/platforms/ios/src/NSCAudioBufferSourceNode.h @@ -23,6 +23,9 @@ NS_ASSUME_NONNULL_BEGIN buffer:(nullable NSCAudioBuffer *)buffer NS_DESIGNATED_INITIALIZER; - (instancetype)initWithContext:(NSCAudioContext *)context node:(nullable AVAudioNode *)node NS_UNAVAILABLE; +@property (nonatomic) double loopStart; +@property (nonatomic) double loopEnd; + @end NS_ASSUME_NONNULL_END diff --git a/packages/audio-context/platforms/ios/src/NSCAudioBufferSourceNode.m b/packages/audio-context/platforms/ios/src/NSCAudioBufferSourceNode.m index 8875c2e7..84a11344 100644 --- a/packages/audio-context/platforms/ios/src/NSCAudioBufferSourceNode.m +++ b/packages/audio-context/platforms/ios/src/NSCAudioBufferSourceNode.m @@ -15,6 +15,9 @@ double pendingOffsetFrames; double position; _Atomic(void *) pcm; + // Seconds; the whole buffer loops unless 0 <= loopStart < loopEnd. + _Atomic double loopStart; + _Atomic double loopEnd; } NSCBufferSourceState; @implementation NSCAudioBufferSourceNode { @@ -105,18 +108,27 @@ static void NSCBufferSourceSilence(AudioBufferList *abl) { for (AVAudioFrameCount k = 0; k < frameCount; ++k) rates[k] *= exp2(detunes[0] / 1200.0); } double pos = st->position; + double regionStart = 0.0, regionEnd = (double)frames; + double ls = atomic_load_explicit(&st->loopStart, memory_order_relaxed), le = atomic_load_explicit(&st->loopEnd, memory_order_relaxed); + if (loop && ls >= 0.0 && le > 0.0 && ls < le) { + double bufferRate = pcm.format.sampleRate; + regionStart = MIN(ls * bufferRate, (double)frames); + regionEnd = MIN(le * bufferRate, (double)frames); + if (regionEnd <= regionStart) { regionStart = 0.0; regionEnd = (double)frames; } + } AVAudioFrameCount f = first; for (; f < end; ++f) { - if (pos >= (double)frames) { + if (pos >= (loop ? regionEnd : (double)frames)) { if (loop) { - pos = fmod(pos, (double)frames); + pos = regionStart + fmod(pos - regionStart, regionEnd - regionStart); } else { finished = YES; break; } } AVAudioFrameCount i0 = (AVAudioFrameCount)pos; - AVAudioFrameCount i1 = i0 + 1 < frames ? i0 + 1 : (loop ? 0 : i0); + AVAudioFrameCount wrapEnd = loop ? (AVAudioFrameCount)ceil(regionEnd) : frames; + AVAudioFrameCount i1 = i0 + 1 < wrapEnd ? i0 + 1 : (loop ? (AVAudioFrameCount)regionStart : i0); float frac = (float)(pos - (double)i0); for (UInt32 b = 0; b < abl->mNumberBuffers; ++b) { float *dst = (float *)abl->mBuffers[b].mData; @@ -254,8 +266,14 @@ - (void)setBuffer:(NSCAudioBuffer *)newBuffer { if (pcm && pcm.floatChannelData == NULL) pcm = nil; if (pcm) [_keepAlive addObject:pcm]; if (_state) atomic_store_explicit(&_state->pcm, (__bridge void *)pcm, memory_order_release); + [self setLogicalChannels:newBuffer ? MAX(1, [newBuffer getBuffer].format.channelCount) : 1]; } +- (double)loopStart { return _state ? atomic_load(&_state->loopStart) : 0.0; } +- (void)setLoopStart:(double)v { if (_state) atomic_store(&_state->loopStart, v); } +- (double)loopEnd { return _state ? atomic_load(&_state->loopEnd) : 0.0; } +- (void)setLoopEnd:(double)v { if (_state) atomic_store(&_state->loopEnd, v); } + - (BOOL)loop { return _state ? atomic_load_explicit(&_state->loop, memory_order_acquire) == 1 : NO; } diff --git a/packages/audio-context/platforms/ios/src/NSCAudioContext.h b/packages/audio-context/platforms/ios/src/NSCAudioContext.h index 63953dc6..19d0b64e 100644 --- a/packages/audio-context/platforms/ios/src/NSCAudioContext.h +++ b/packages/audio-context/platforms/ios/src/NSCAudioContext.h @@ -43,6 +43,7 @@ static inline double NSCContextFrame(double sampleTime, const double *timeline) @property (nonatomic, strong, readonly) NSCAudioNode *destination; @property (nonatomic, readonly) double sampleRate; @property (nonatomic, readonly) double currentTime; +@property (nonatomic, readonly) BOOL isOffline; @property (nonatomic, readonly) double baseLatency; @property (nonatomic, readonly) double outputLatency; @property (nonatomic, readonly) AVAudioFormat *format; @@ -79,6 +80,8 @@ static inline double NSCContextFrame(double sampleTime, const double *timeline) - (void)unregisterPendingNode:(NSCAudioBufferSourceNode *)node; - (void)resumeAllPendingNodes; - (void)ensureMainMixerConnectedToOutput; +/// Runs `block` with the engine stopped, holding the realtime output for that long. +- (void)whileStopped:(void (NS_NOESCAPE ^)(void))block; - (void)detachNode:(AVAudioNode *)node fromEngine:(AVAudioEngine *)engine; - (BOOL)isNode:(AVAudioNode *)node attachedToEngine:(AVAudioEngine *)engine; diff --git a/packages/audio-context/platforms/ios/src/NSCAudioContext.m b/packages/audio-context/platforms/ios/src/NSCAudioContext.m index 36892802..19896149 100644 --- a/packages/audio-context/platforms/ios/src/NSCAudioContext.m +++ b/packages/audio-context/platforms/ios/src/NSCAudioContext.m @@ -3,6 +3,7 @@ #import #import #import +#import #import #import @@ -26,8 +27,25 @@ #import "NSCChannelMergerNode.h" #import "AudioModule.h" #import "NSCAudioWorkletNode.h" +#import "NSCChannelMixerNode.h" static void *bufferKey = &bufferKey; + +// Web Audio's render quantum. +static const AVAudioFrameCount NSCQuantum = 128; +#define NSC_DRIVER_CHANNELS 2 + +// Shared with the pump's render block: one rendered quantum and how much of it is left. +typedef struct { + _Atomic int64_t frames; + // Set while the engine is reconfigured; the pump plays silence and time holds. + _Atomic int hold; + _Atomic int rendering; + UInt32 left; + float quantum[NSC_DRIVER_CHANNELS][128]; + AudioBufferList list; + AudioBuffer second; +} NSCDriver; void *NSCProducerTokenKey = &NSCProducerTokenKey; @interface NSCAudioContext () @@ -46,7 +64,7 @@ - (void)adoptFormat:(AVAudioFormat *)format; static void NSCAudioContext_registerEngine(AVAudioEngine *engine, NSCAudioContext *ctx) { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ - gEngineContextMap = [NSMapTable strongToWeakObjectsMapTable]; + gEngineContextMap = [NSMapTable weakToWeakObjectsMapTable]; }); if (!engine) return; @synchronized (gEngineContextMap) { [gEngineContextMap setObject:ctx forKey:engine]; } @@ -109,7 +127,7 @@ void NSCAudioContext_scheduleResumeOnEngineStart(AVAudioEngine *engine, double d if (!engine) return; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ - if (!gEngineContextMap) gEngineContextMap = [NSMapTable strongToWeakObjectsMapTable]; + if (!gEngineContextMap) gEngineContextMap = [NSMapTable weakToWeakObjectsMapTable]; if (!gScheduledResumeMap) gScheduledResumeMap = [NSMapTable strongToStrongObjectsMapTable]; }); @@ -157,8 +175,15 @@ @implementation NSCAudioContext { NSCAudioParam *_listenerUpZParam; dispatch_source_t _listenerAutomationTimer; NSMutableData *_timelineCell; - AVAudioSourceNode *_clock; id _configurationObserver; + NSCAudioNode *_listenerOwner; + // Realtime: the engine renders manually, a quantum at a time, pulled by _output's pump. + AVAudioEngine *_output; + AVAudioSourceNode *_pump; + NSMutableData *_driverCell; + id _outputObserver; + BOOL _userSuspended; + BOOL _closed; } - (instancetype)initWithSampleRate:(double)sampleRate { @@ -180,32 +205,20 @@ - (instancetype)initWithSampleRate:(double)sampleRate latencyHint:(double)latenc _nodeWrappers = [NSMapTable strongToWeakObjectsMapTable]; - _format = [_engine.mainMixerNode outputFormatForBus:0]; - - if (!_format || _format.sampleRate <= 0 || _format.channelCount == 0) { - _format = [[AVAudioFormat alloc] initWithCommonFormat:AVAudioPCMFormatFloat32 sampleRate:(sampleRate > 0.0 ? sampleRate : 44100.0) channels:2 interleaved:NO]; - } else { - const AudioStreamBasicDescription *asd = _format.streamDescription; - if (!asd || asd->mFormatID != kAudioFormatLinearPCM) { - _format = [[AVAudioFormat alloc] initWithCommonFormat:AVAudioPCMFormatFloat32 sampleRate:(_format.sampleRate > 0.0 ? _format.sampleRate : (sampleRate > 0.0 ? sampleRate : 44100.0)) channels:_format.channelCount interleaved:NO]; - } - } + BOOL offline = [self isKindOfClass:[NSCOfflineAudioContext class]]; + double hardwareRate = 0.0; + @try { hardwareRate = [_engine.outputNode outputFormatForBus:0].sampleRate; } @catch (NSException *e) {} + double rate = sampleRate >= 3000.0 && sampleRate <= 768000.0 ? sampleRate : (hardwareRate > 0.0 ? hardwareRate : 48000.0); + _format = [[AVAudioFormat alloc] initStandardFormatWithSampleRate:rate channels:2]; + if (!offline) [self attachDriver]; NSCAudioContext_registerEngine(_engine, self); _timelineCell = [NSMutableData dataWithLength:NSCTimelineSlots * sizeof(double)]; [self refreshTimelineRate]; - if (![self isKindOfClass:[NSCOfflineAudioContext class]]) [self attachClock]; __weak NSCAudioContext *weakSelf = self; _configurationObserver = [[NSNotificationCenter defaultCenter] addObserverForName:AVAudioEngineConfigurationChangeNotification object:_engine queue:nil usingBlock:^(NSNotification *note) { [weakSelf refreshTimelineRate]; }]; - @try { - if (_engine.mainMixerNode) { - _destination = [[NSCAudioNode alloc] initWithContext:self node:_engine.mainMixerNode]; - } - } @catch (NSException *e) { - _destination = nil; - } if (![self isKindOfClass:[NSCOfflineAudioContext class]]) { @try { [[NSCAudioSessionManager sharedManager] registerContext:self sampleRate:_format.sampleRate latencyHint:latencyHint]; @@ -216,20 +229,34 @@ - (instancetype)initWithSampleRate:(double)sampleRate latencyHint:(double)latenc return self; } +// Connections to the destination mix with Web Audio's rules before the engine's mixer. +- (void)makeDestination { + AVAudioMixerNode *main = _engine.mainMixerNode; + if (!main) return; + NSInteger channels = _format.channelCount; + if (channels <= 8) { + NSCChannelMixerNode *port = [[NSCChannelMixerNode alloc] initWithContext:self mode:NSCMixModeSum channels:channels discrete:NO]; + if (port && NSCConnectAdding(self, port.avNode, 0, main, main.nextAvailableInputBus, _format)) { + _destination = port; + return; + } + } + _destination = [[NSCAudioNode alloc] initWithContext:self node:main]; +} + - (AVAudioEngine *)engine { return _engine; } - (AVAudioEnvironmentNode *)environmentNode { return _environmentNode; } - (NSCAudioNode *)destination { return _destination; } - (double)sampleRate { return _format ? _format.sampleRate : 44100.0; } +- (BOOL)isOffline { return NO; } - (double)currentTime { - if (!_engine) return 0.0; - AVAudioTime *now = _engine.outputNode.lastRenderTime; - if (!now) return 0.0; - return (double)now.sampleTime / now.sampleRate; + if (!_driverCell) return 0.0; + NSCDriver *d = (NSCDriver *)_driverCell.mutableBytes; + return (double)atomic_load_explicit(&d->frames, memory_order_acquire) / self.sampleRate; } +// One quantum buffered between the engine and the device, plus the device buffer. - (double)baseLatency { - // IOBufferDuration is the actual applied render buffer duration, matching - // the Web Audio API definition: frames in the ring buffer / sample rate. - return [AVAudioSession sharedInstance].IOBufferDuration; + return NSCQuantum / self.sampleRate + [AVAudioSession sharedInstance].IOBufferDuration; } - (double)outputLatency { // Hardware output latency reported by the OS. @@ -293,6 +320,8 @@ - (NSCAudioNode *)nodeWrapperForAVNode:(AVAudioNode *)avNode { } } +- (NSArray *)allNodeWrappersForHealing { return [self allNodeWrappers]; } + - (NSArray *)allNodeWrappers { @synchronized(_nodeWrappers) { return _nodeWrappers ? [[_nodeWrappers objectEnumerator] allObjects] : @[]; @@ -314,14 +343,106 @@ - (NSCAudioNode *)nodeWrapperForAVNode:(AVAudioNode *)avNode { return out; } +#pragma mark - Realtime driver + +// The device pulls the pump, which renders the engine a quantum at a time, so every node +// sees 128-frame render calls and context frames count from 0, as in Web Audio. +- (void)attachDriver { + NSError *err = nil; + if (![_engine enableManualRenderingMode:AVAudioEngineManualRenderingModeRealtime format:_format maximumFrameCount:NSCQuantum error:&err]) { + NSCLogError(@"NSCAudioContext: realtime manual rendering failed: %@", err); + return; + } + @try { [_engine connect:_engine.mainMixerNode to:_engine.outputNode format:_format]; } @catch (NSException *e) {} + _driverCell = [NSMutableData dataWithLength:sizeof(NSCDriver)]; + NSMutableData *cell = _driverCell; + AVAudioEngineManualRenderingBlock render = _engine.manualRenderingBlock; + _pump = [[AVAudioSourceNode alloc] initWithFormat:_format renderBlock:^OSStatus(BOOL *isSilence, const AudioTimeStamp *ts, AVAudioFrameCount frames, AudioBufferList *out) { + NSCDriver *d = (NSCDriver *)cell.mutableBytes; + UInt32 channels = MIN(out->mNumberBuffers, (UInt32)NSC_DRIVER_CHANNELS); + AVAudioFrameCount done = 0; + atomic_store_explicit(&d->rendering, 1, memory_order_seq_cst); + while (done < frames && !atomic_load_explicit(&d->hold, memory_order_seq_cst)) { + if (d->left == 0) { + d->list.mNumberBuffers = NSC_DRIVER_CHANNELS; + for (UInt32 c = 0; c < NSC_DRIVER_CHANNELS; c++) { + d->list.mBuffers[c].mNumberChannels = 1; + d->list.mBuffers[c].mData = d->quantum[c]; + d->list.mBuffers[c].mDataByteSize = NSCQuantum * sizeof(float); + } + OSStatus status = noErr; + if (render(NSCQuantum, &d->list, &status) != AVAudioEngineManualRenderingStatusSuccess) break; + for (UInt32 c = 0; c < NSC_DRIVER_CHANNELS; c++) { + if (d->list.mBuffers[c].mData != d->quantum[c]) memcpy(d->quantum[c], d->list.mBuffers[c].mData, NSCQuantum * sizeof(float)); + } + d->left = NSCQuantum; + atomic_fetch_add_explicit(&d->frames, NSCQuantum, memory_order_release); + } + AVAudioFrameCount n = MIN(frames - done, d->left); + for (UInt32 c = 0; c < channels; c++) { + memcpy((float *)out->mBuffers[c].mData + done, d->quantum[c] + (NSCQuantum - d->left), n * sizeof(float)); + } + d->left -= n; + done += n; + } + atomic_store_explicit(&d->rendering, 0, memory_order_release); + for (UInt32 c = 0; c < out->mNumberBuffers; c++) { + if (done < frames) memset((float *)out->mBuffers[c].mData + done, 0, (frames - done) * sizeof(float)); + if (c >= channels) memcpy(out->mBuffers[c].mData, out->mBuffers[0].mData, frames * sizeof(float)); + } + return noErr; + }]; + _output = [[AVAudioEngine alloc] init]; + [_output attachNode:_pump]; + [_output connect:_pump to:_output.mainMixerNode format:_format]; + [self makeDestination]; + __weak NSCAudioContext *weakSelf = self; + _outputObserver = [[NSNotificationCenter defaultCenter] addObserverForName:AVAudioEngineConfigurationChangeNotification object:_output queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) { + [weakSelf startDriver]; + }]; + [self startDriver]; +} + +- (void)whileStopped:(void (NS_NOESCAPE ^)(void))block { + NSCDriver *d = _driverCell ? (NSCDriver *)_driverCell.mutableBytes : NULL; + if (d) { + atomic_store(&d->hold, 1); + while (atomic_load(&d->rendering)) sched_yield(); + } + BOOL wasRunning = _engine.isRunning; + @try { [_engine stop]; } @catch (NSException *e) {} + block(); + NSError *err = nil; + if (wasRunning && ![_engine startAndReturnError:&err]) NSCLogError(@"NSCAudioContext: the engine did not restart: %@", err); + if (d) atomic_store(&d->hold, 0); +} + +- (BOOL)startDriver { + if (!_output || _closed) return NO; + NSError *err = nil; + if (!_engine.isRunning && ![_engine startAndReturnError:&err]) { + NSCLogError(@"NSCAudioContext: the engine did not start: %@", err); + return NO; + } + if (_userSuspended || _output.isRunning) return YES; + NSCAudioContext_prepareAudioSessionForPlayback(); + if (![_output startAndReturnError:&err]) { + NSCLogError(@"NSCAudioContext: the output did not start: %@", err); + return NO; + } + return YES; +} + - (void)resume { if (!_engine) return; + _userSuspended = NO; [NSCAudioContext startEngineWithRetry:_engine attempts:3 label:@"context" asyncCompletion:nil]; } - (void)suspend { if (!_engine) return; - @try { [_engine pause]; } @catch (NSException *e) {} + _userSuspended = YES; + @try { [_output pause]; } @catch (NSException *e) {} } - (void)resumeAsync:(void (^)(BOOL))completion { @@ -330,6 +451,7 @@ - (void)resumeAsync:(void (^)(BOOL))completion { return; } + _userSuspended = NO; CFRunLoopRef rl = completion ? CFRunLoopGetCurrent() : NULL; if (rl) CFRetain(rl); @@ -356,7 +478,8 @@ - (void)suspendAsync:(void (^)(BOOL))completion { } CFRunLoopRef rl = completion ? CFRunLoopGetCurrent() : NULL; if (rl) CFRetain(rl); - AVAudioEngine *engine = _engine; + _userSuspended = YES; + AVAudioEngine *engine = _output ?: _engine; dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{ BOOL ok = YES; @try { [engine pause]; } @@ -380,9 +503,13 @@ - (void)closeAsync:(void (^)(void))completion { } CFRunLoopRef rl = completion ? CFRunLoopGetCurrent() : NULL; if (rl) CFRetain(rl); + _closed = YES; AVAudioEngine *engine = _engine; + AVAudioEngine *output = _output; + if (_outputObserver) [[NSNotificationCenter defaultCenter] removeObserver:_outputObserver]; + _outputObserver = nil; dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{ - @try { [engine pause]; } @catch (NSException *e) {} + @try { [output stop]; } @catch (NSException *e) {} @try { [engine stop]; } @catch (NSException *e) {} if (completion) { CFRunLoopPerformBlock(rl, kCFRunLoopCommonModes, ^{ @@ -758,9 +885,15 @@ - (void)setListenerOrientation:(double)forwardX :(double)forwardY :(double)forwa #pragma mark - Listener automation params +- (NSCAudioNode *)listenerOwner { + if (!_listenerOwner) _listenerOwner = NSCMakeListenerOwner(self); + return _listenerOwner; +} + - (NSCAudioParam *)getListenerPositionXParam { if (!_listenerPositionXParam) { _listenerPositionXParam = [[NSCAudioParam alloc] initWithContext:self defaultValue:0.0]; + _listenerPositionXParam.owner = [self listenerOwner]; __weak typeof(self) weakSelf = self; _listenerPositionXParam.onScheduleChanged = ^(NSCAudioParam *p) { __strong typeof(weakSelf) s = weakSelf; @@ -774,6 +907,7 @@ - (NSCAudioParam *)getListenerPositionXParam { - (NSCAudioParam *)getListenerPositionYParam { if (!_listenerPositionYParam) { _listenerPositionYParam = [[NSCAudioParam alloc] initWithContext:self defaultValue:0.0]; + _listenerPositionYParam.owner = [self listenerOwner]; __weak typeof(self) weakSelf = self; _listenerPositionYParam.onScheduleChanged = ^(NSCAudioParam *p) { __strong typeof(weakSelf) s = weakSelf; @@ -787,6 +921,7 @@ - (NSCAudioParam *)getListenerPositionYParam { - (NSCAudioParam *)getListenerPositionZParam { if (!_listenerPositionZParam) { _listenerPositionZParam = [[NSCAudioParam alloc] initWithContext:self defaultValue:0.0]; + _listenerPositionZParam.owner = [self listenerOwner]; __weak typeof(self) weakSelf = self; _listenerPositionZParam.onScheduleChanged = ^(NSCAudioParam *p) { __strong typeof(weakSelf) s = weakSelf; @@ -800,6 +935,7 @@ - (NSCAudioParam *)getListenerPositionZParam { - (NSCAudioParam *)getListenerForwardXParam { if (!_listenerForwardXParam) { _listenerForwardXParam = [[NSCAudioParam alloc] initWithContext:self defaultValue:0.0]; + _listenerForwardXParam.owner = [self listenerOwner]; __weak typeof(self) weakSelf = self; _listenerForwardXParam.onScheduleChanged = ^(NSCAudioParam *p) { __strong typeof(weakSelf) s = weakSelf; @@ -813,6 +949,7 @@ - (NSCAudioParam *)getListenerForwardXParam { - (NSCAudioParam *)getListenerForwardYParam { if (!_listenerForwardYParam) { _listenerForwardYParam = [[NSCAudioParam alloc] initWithContext:self defaultValue:0.0]; + _listenerForwardYParam.owner = [self listenerOwner]; __weak typeof(self) weakSelf = self; _listenerForwardYParam.onScheduleChanged = ^(NSCAudioParam *p) { __strong typeof(weakSelf) s = weakSelf; @@ -826,6 +963,7 @@ - (NSCAudioParam *)getListenerForwardYParam { - (NSCAudioParam *)getListenerForwardZParam { if (!_listenerForwardZParam) { _listenerForwardZParam = [[NSCAudioParam alloc] initWithContext:self defaultValue:-1.0]; + _listenerForwardZParam.owner = [self listenerOwner]; __weak typeof(self) weakSelf = self; _listenerForwardZParam.onScheduleChanged = ^(NSCAudioParam *p) { __strong typeof(weakSelf) s = weakSelf; @@ -839,6 +977,7 @@ - (NSCAudioParam *)getListenerForwardZParam { - (NSCAudioParam *)getListenerUpXParam { if (!_listenerUpXParam) { _listenerUpXParam = [[NSCAudioParam alloc] initWithContext:self defaultValue:0.0]; + _listenerUpXParam.owner = [self listenerOwner]; __weak typeof(self) weakSelf = self; _listenerUpXParam.onScheduleChanged = ^(NSCAudioParam *p) { __strong typeof(weakSelf) s = weakSelf; @@ -852,6 +991,7 @@ - (NSCAudioParam *)getListenerUpXParam { - (NSCAudioParam *)getListenerUpYParam { if (!_listenerUpYParam) { _listenerUpYParam = [[NSCAudioParam alloc] initWithContext:self defaultValue:1.0]; + _listenerUpYParam.owner = [self listenerOwner]; __weak typeof(self) weakSelf = self; _listenerUpYParam.onScheduleChanged = ^(NSCAudioParam *p) { __strong typeof(weakSelf) s = weakSelf; @@ -865,6 +1005,7 @@ - (NSCAudioParam *)getListenerUpYParam { - (NSCAudioParam *)getListenerUpZParam { if (!_listenerUpZParam) { _listenerUpZParam = [[NSCAudioParam alloc] initWithContext:self defaultValue:0.0]; + _listenerUpZParam.owner = [self listenerOwner]; __weak typeof(self) weakSelf = self; _listenerUpZParam.onScheduleChanged = ^(NSCAudioParam *p) { __strong typeof(weakSelf) s = weakSelf; @@ -949,6 +1090,15 @@ + (BOOL)startEngineWithRetry:(AVAudioEngine *)engine if (completion) completion(NO); return NO; } + if (engine.isInManualRenderingMode && engine.manualRenderingMode == AVAudioEngineManualRenderingModeRealtime) { + __block NSCAudioContext *ctx = nil; + @synchronized (gEngineContextMap) { ctx = [gEngineContextMap objectForKey:engine]; } + __block BOOL ok = NO; + void (^start)(void) = ^{ ok = [ctx startDriver]; }; + if ([NSThread isMainThread]) start(); else dispatch_sync(dispatch_get_main_queue(), start); + if (completion) dispatch_async(dispatch_get_main_queue(), ^{ completion(ok); }); + return ok; + } // An offline engine runs only while it renders. if (engine.isInManualRenderingMode) { BOOL running = engine.isRunning; @@ -1042,6 +1192,9 @@ + (NSMutableData *)marshalMutableData:(NSMutableData *)data { return data; } - (void)dealloc { if (_configurationObserver) [[NSNotificationCenter defaultCenter] removeObserver:_configurationObserver]; + if (_outputObserver) [[NSNotificationCenter defaultCenter] removeObserver:_outputObserver]; + @try { [_output stop]; } @catch (NSException *e) {} + @try { [_engine stop]; } @catch (NSException *e) {} @try { [[NSCAudioSessionManager sharedManager] unregisterContext:self]; } @catch (NSException *e) {} } @@ -1062,33 +1215,6 @@ - (void)refreshTimelineRate { UpdateTimelineOffset(timeline, self.sampleRate); } -// currentTime counts device samples, but render timestamps start at the device sample the engine -// started on and then count context frames; this silent input tracks that start. -- (void)attachClock { - NSMutableData *cell = _timelineCell; - double contextRate = self.sampleRate; - __block double expected = -1.0; - _clock = [[AVAudioSourceNode alloc] initWithFormat:_format renderBlock:^OSStatus(BOOL *isSilence, const AudioTimeStamp *ts, AVAudioFrameCount frames, AudioBufferList *abl) { - for (UInt32 b = 0; b < abl->mNumberBuffers; b++) if (abl->mBuffers[b].mData) memset(abl->mBuffers[b].mData, 0, abl->mBuffers[b].mDataByteSize); - if (isSilence) *isSilence = YES; - if (ts && (ts->mFlags & kAudioTimeStampSampleTimeValid)) { - double *timeline = (double *)cell.mutableBytes; - if (fabs(ts->mSampleTime - expected) > 0.5) { - timeline[NSCTimelineStart] = ts->mSampleTime; - UpdateTimelineOffset(timeline, contextRate); - } - expected = ts->mSampleTime + frames; - } - return noErr; - }]; - @try { - [_engine attachNode:_clock]; - [_engine connect:_clock to:_engine.mainMixerNode format:_format]; - } @catch (NSException *e) { - NSCLogDebug(@"NSCAudioContext: the clock input did not connect: %@", e); - } -} - - (int64_t)frameForTime:(double)when { double rate = self.sampleRate; double now = self.currentTime; @@ -1186,10 +1312,12 @@ - (void)configure:(NSNumber *)channels :(NSNumber *)lengthInFrames :(NSNumber *) // The mixer keeps the hardware format it was created with otherwise. [engine connect:engine.mainMixerNode to:engine.outputNode format:format]; [self adoptFormat:format]; + [self makeDestination]; [self refreshTimelineRate]; } - (NSInteger)length { return _length; } +- (BOOL)isOffline { return YES; } - (NSInteger)scheduleSuspend:(double)time { double rate = self.sampleRate; @@ -1209,6 +1337,11 @@ - (NSInteger)scheduleSuspend:(double)time { // An initialized mixer keeps a new input at its default format (44.1 kHz stereo: resampled, // +3 dB), so a render stops the engine before a connect and restarts it for the next quantum. // Stopping keeps the sample time but clears effect state (delay lines, filters, reverb tails). +- (void)whileStopped:(void (NS_NOESCAPE ^)(void))block { + [self willConnect]; + block(); +} + - (void)willConnect { // A paused engine is still initialized. if (_started && !_finished) { diff --git a/packages/audio-context/platforms/ios/src/NSCAudioNode.h b/packages/audio-context/platforms/ios/src/NSCAudioNode.h index 81d6910c..f6a2752d 100644 --- a/packages/audio-context/platforms/ios/src/NSCAudioNode.h +++ b/packages/audio-context/platforms/ios/src/NSCAudioNode.h @@ -1,10 +1,12 @@ #import #import +#import NS_ASSUME_NONNULL_BEGIN @class NSCAudioContext; @class NSCAudioParam; +@class NSCChannelMixerNode; @interface NSCAudioNode : NSObject @@ -48,8 +50,17 @@ NS_ASSUME_NONNULL_BEGIN @property (nonatomic, readonly) NSInteger channelCount; @property (nonatomic, readonly) NSInteger channelCountMode; @property (nonatomic, readonly) NSInteger channelInterpretation; -/// Called after the channel config changes; nodes that mix their inputs apply it. +/// Called after the channel config changes; applies it to `channelPort`. - (void)channelConfigChanged; +/// Where this node's inputs mix, if it has one mixer for them. +- (nullable NSCChannelMixerNode *)channelPort; + +/// The channel count `output` plays at, read on the render thread; NULL when it is its bus's. +- (nullable const _Atomic UInt32 *)logicalChannelCellForOutput:(NSInteger)output; +/// Sets this node's own output channel count (sources). +- (void)setLogicalChannels:(NSInteger)channels; +/// Removes nodes this one added to the engine for itself; called when the context closes or it is collected. +- (void)detachHelpers; /// Applies param automation at the context's current time. Offline rendering calls it per quantum. - (void)applyAutomation; @@ -77,6 +88,10 @@ NS_ASSUME_NONNULL_BEGIN @end +/// Allocates a unit's render resources if the engine has not. +void NSCEnsureAllocated(AVAudioNode *node); +/// Whether audio flows from `from` to `to` in the engine graph. +BOOL NSCHasPath(AVAudioEngine *engine, AVAudioNode *from, AVAudioNode *to); /// Adds a connection from `src`'s bus to `dst`'s bus, keeping `src`'s other connections. BOOL NSCConnectAdding(NSCAudioContext *_Nullable context, AVAudioNode *src, AVAudioNodeBus fromBus, AVAudioNode *dst, AVAudioNodeBus toBus, AVAudioFormat *_Nullable format); /// Removes `src`'s connections from `fromBus` (nil: every bus) to `dst` (nil: any) on `toBus` (nil: any). diff --git a/packages/audio-context/platforms/ios/src/NSCAudioNode.m b/packages/audio-context/platforms/ios/src/NSCAudioNode.m index fc86e85a..e9b7e700 100644 --- a/packages/audio-context/platforms/ios/src/NSCAudioNode.m +++ b/packages/audio-context/platforms/ios/src/NSCAudioNode.m @@ -8,6 +8,10 @@ @interface NSCAudioNode () @property (nonatomic, readwrite) AVAudioNode *avNode; @end +@interface NSCAudioContext (NSCHealing) +- (NSArray *)allNodeWrappersForHealing; +@end + static void OnMain(void (^block)(void)) { if ([NSThread isMainThread]) block(); else dispatch_sync(dispatch_get_main_queue(), block); @@ -17,6 +21,15 @@ static void WillConnect(NSCAudioContext *context) { if ([context isKindOfClass:[NSCOfflineAudioContext class]]) [(NSCOfflineAudioContext *)context willConnect]; } +// A running engine does not always allocate a unit connected upstream of a new connection. +void NSCEnsureAllocated(AVAudioNode *node) { + if (![node isKindOfClass:[AVAudioUnit class]]) return; + AUAudioUnit *au = ((AVAudioUnit *)node).AUAudioUnit; + if (au.renderResourcesAllocated) return; + NSError *err = nil; + if (![au allocateRenderResourcesAndReturnError:&err]) NSCLogError(@"NSCAudioNode: could not allocate %@: %@", NSStringFromClass([au class]), err); +} + BOOL NSCConnectAdding(NSCAudioContext *context, AVAudioNode *src, AVAudioNodeBus fromBus, AVAudioNode *dst, AVAudioNodeBus toBus, AVAudioFormat *format) { AVAudioEngine *engine = context.engine; if (!engine || !src || !dst) return NO; @@ -30,11 +43,25 @@ BOOL NSCConnectAdding(NSCAudioContext *context, AVAudioNode *src, AVAudioNodeBus } } @catch (NSException *e) {} [points addObject:[[AVAudioConnectionPoint alloc] initWithNode:dst bus:toBus]]; + if (engine.isRunning) { + NSCEnsureAllocated(src); + NSCEnsureAllocated(dst); + } @try { [engine connect:src toConnectionPoints:points fromBus:fromBus format:format]; ok = YES; } @catch (NSException *e) { - NSCLogError(@"NSCAudioNode: connect %@ -> %@ threw: %@", NSStringFromClass([src class]), NSStringFromClass([dst class]), e); + // A running engine only fans out to mixer nodes, and an allocated unit keeps its + // bus formats; a stopped engine takes either. + if (engine.isRunning) { + [context whileStopped:^{ + @try { + [engine connect:src toConnectionPoints:points fromBus:fromBus format:format]; + ok = YES; + } @catch (NSException *e2) {} + }]; + } + if (!ok) NSCLogError(@"NSCAudioNode: connect %@ -> %@ (%@ -> %@, %u ch to bus %u) threw: %@", NSStringFromClass([src class]), NSStringFromClass([dst class]), [src isKindOfClass:[AVAudioUnit class]] ? NSStringFromClass([((AVAudioUnit *)src).AUAudioUnit class]) : @"-", [dst isKindOfClass:[AVAudioUnit class]] ? NSStringFromClass([((AVAudioUnit *)dst).AUAudioUnit class]) : @"-", format.channelCount, toBus, e); } }); return ok; @@ -99,14 +126,44 @@ void NSCDisconnectRemoving(NSCAudioContext *context, AVAudioNode *src, NSNumber return nil; } +BOOL NSCHasPath(AVAudioEngine *engine, AVAudioNode *from, AVAudioNode *to) { + NSHashTable *targets = [NSHashTable hashTableWithOptions:NSPointerFunctionsObjectPointerPersonality]; + [targets addObject:to]; + return DownstreamPath(engine, @[ from ], targets) != nil; +} + +static void HealCycles(NSCAudioContext *context) { + for (NSCAudioNode *node in [context allNodeWrappersForHealing]) { + if ([node isKindOfClass:[NSCParamEffectNode class]] && [(NSCParamEffectNode *)node isSplit]) [(NSCParamEffectNode *)node healCycle]; + } +} + static BOOL BreakAt(NSCAudioNode *node) { return [node isKindOfClass:[NSCDelayNode class]] && [(NSCDelayNode *)node breakCycle]; } @implementation NSCAudioNode { NSCChannelMixerNode *_stage; + NSMutableData *_logical; +} + +- (const _Atomic UInt32 *)logicalChannelCellForOutput:(NSInteger)output { + if (_stage) return [_stage mixedChannels]; + return _logical ? (const _Atomic UInt32 *)_logical.bytes : NULL; +} + +- (void)setLogicalChannels:(NSInteger)channels { + if (!_logical) { + _logical = [NSMutableData dataWithLength:sizeof(_Atomic UInt32)]; + atomic_init((_Atomic UInt32 *)_logical.mutableBytes, 0); + } + atomic_store((_Atomic UInt32 *)_logical.mutableBytes, (UInt32)MAX(0, channels)); } +- (NSCChannelMixerNode *)channelPort { return nil; } + +- (void)detachHelpers {} + - (AVAudioNode *)outputAVNode { return _stage ? _stage.avNode : self.avNode; } @@ -141,7 +198,7 @@ - (AVAudioFormat *)formatForOutput:(AVAudioNodeBus)bus { - (void)replaceAVNode:(AVAudioNode *)node { self.avNode = node; if (self.context) [self.context registerNodeWrapper:self]; - if (_stage) [_stage connectMain:node bus:0 format:self.nativeFormat ?: self.context.format]; + if (_stage) [_stage connectMain:node bus:0 format:self.nativeFormat ?: self.context.format logical:_logical ? (const _Atomic UInt32 *)_logical.bytes : NULL]; } - (BOOL)usesOutputStage { return NO; } @@ -159,7 +216,7 @@ - (void)ensureOutputStageWithChannels:(NSInteger)channels { @try { points = [engine outputConnectionPointsForNode:node outputBus:0]; } @catch (NSException *e) {} AVAudioFormat *format = [self formatForOutput:0]; if (points.count > 0) NSCDisconnectRemoving(ctx, node, @0, nil, nil); - [stage connectMain:node bus:0 format:self.nativeFormat ?: ctx.format]; + [stage connectMain:node bus:0 format:self.nativeFormat ?: ctx.format logical:_logical ? (const _Atomic UInt32 *)_logical.bytes : NULL]; _stage = stage; if (points.count > 0) { OnMain(^{ @@ -561,6 +618,7 @@ - (void)disconnect { [self eachOutputNode:nil block:^(AVAudioNode *node, NSNumber *bus) { NSCDisconnectRemoving(self.context, node, bus, nil, nil); }]; + HealCycles(self.context); } - (void)disconnectOutput:(NSNumber *)output { @@ -568,21 +626,21 @@ - (void)disconnectOutput:(NSNumber *)output { [self eachOutputNode:output block:^(AVAudioNode *node, NSNumber *bus) { NSCDisconnectRemoving(self.context, node, bus, nil, nil); }]; + HealCycles(self.context); } - (void)disconnectTo:(NSCAudioNode *)destination { - if (!destination) return; - [destination handleDisconnectFrom:self output:nil input:nil]; + [self disconnectTo:destination output:nil input:nil]; } - (void)disconnectTo:(NSCAudioNode *)destination output:(NSNumber *)output { - if (!destination) return; - [destination handleDisconnectFrom:self output:output input:nil]; + [self disconnectTo:destination output:output input:nil]; } - (void)disconnectTo:(NSCAudioNode *)destination output:(NSNumber *)output input:(NSNumber *)input { if (!destination) return; [destination handleDisconnectFrom:self output:output input:input]; + HealCycles(self.context); } - (void)setChannelConfig:(NSInteger)count mode:(NSInteger)mode interpretation:(NSInteger)interpretation { @@ -592,7 +650,9 @@ - (void)setChannelConfig:(NSInteger)count mode:(NSInteger)mode interpretation:(N [self channelConfigChanged]; } -- (void)channelConfigChanged {} +- (void)channelConfigChanged { + [[self channelPort] configureCount:self.channelCount mode:self.channelCountMode discrete:self.channelInterpretation == 1]; +} - (void)applyAutomation {} diff --git a/packages/audio-context/platforms/ios/src/NSCAudioOscillatorNode.m b/packages/audio-context/platforms/ios/src/NSCAudioOscillatorNode.m index 12af0a6f..f48c55fa 100644 --- a/packages/audio-context/platforms/ios/src/NSCAudioOscillatorNode.m +++ b/packages/audio-context/platforms/ios/src/NSCAudioOscillatorNode.m @@ -8,12 +8,14 @@ typedef NS_ENUM(uint8_t, NSCOscWaveform) { NSCOscWaveformSquare = 1, NSCOscWaveformSawtooth = 2, NSCOscWaveformTriangle = 3, + NSCOscWaveformCustom = 4, }; static inline NSCOscWaveform NSCOscWaveformFromString(NSString * _Nullable type) { if ([type isEqualToString:@"square"]) return NSCOscWaveformSquare; if ([type isEqualToString:@"sawtooth"]) return NSCOscWaveformSawtooth; if ([type isEqualToString:@"triangle"]) return NSCOscWaveformTriangle; + if ([type isEqualToString:@"custom"]) return NSCOscWaveformCustom; return NSCOscWaveformSine; } @@ -28,6 +30,16 @@ @implementation NSCAudioOscillatorNode { atomic_int_least64_t *_stopSamplePtr; atomic_uint_least8_t *_waveTypePtr; double _phase; + // The tables the render reads, and every wave it may still be reading. + NSMutableData *_tablesData; + NSMutableArray *_waves; +} + +- (void)useWave:(NSCPeriodicWave *)wave { + if (!wave || !_tablesData) return; + const float *const *tables = [wave tables]; + [_waves addObject:wave]; + atomic_store_explicit((_Atomic(void *) *)_tablesData.mutableBytes, (void *)tables, memory_order_release); } - (void)dealloc { @@ -75,6 +87,8 @@ - (instancetype)initWithContext:(NSCAudioContext *)context type:(NSString *)type NSMutableData *capturedStartSampleData = startSampleData; NSMutableData *capturedStopSampleData = stopSampleData; NSMutableData *capturedWaveTypeData = waveTypeData; + NSMutableData *tablesData = [NSMutableData dataWithLength:sizeof(_Atomic(void *))]; + NSMutableData *capturedTablesData = tablesData; NSMutableData *timelineCell = context.timelineCell ?: [NSMutableData dataWithLength:NSCTimelineSlots * sizeof(double)]; __weak NSCAudioOscillatorNode *weakSelf = self; @@ -168,44 +182,17 @@ - (instancetype)initWithContext:(NSCAudioContext *)context type:(NSString *)type } const double TWO_PI = 2.0 * M_PI; - const double invTwoPi = 1.0 / TWO_PI; double phase = localPhase; const double phaseIncConst = hasAutomation ? 0.0 : (TWO_PI * freqValues[0] / sampleRate); const double invSampleRate = 1.0 / sampleRate; - - switch (waveEnum) { - case NSCOscWaveformSine: { - for (AVAudioFrameCount f = firstRenderIndex; f < endRenderIndex; ++f) { - out0[f] = (float)sin(phase); - phase += hasAutomation ? (TWO_PI * freqValues[f] * invSampleRate) : phaseIncConst; - if (phase >= TWO_PI) phase = fmod(phase, TWO_PI); - } - break; - } - case NSCOscWaveformSquare: { - for (AVAudioFrameCount f = firstRenderIndex; f < endRenderIndex; ++f) { - out0[f] = (phase < M_PI) ? 1.0f : -1.0f; - phase += hasAutomation ? (TWO_PI * freqValues[f] * invSampleRate) : phaseIncConst; - if (phase >= TWO_PI) phase = fmod(phase, TWO_PI); - } - break; - } - case NSCOscWaveformSawtooth: { - for (AVAudioFrameCount f = firstRenderIndex; f < endRenderIndex; ++f) { - out0[f] = (float)((2.0 * phase * invTwoPi) - 1.0); - phase += hasAutomation ? (TWO_PI * freqValues[f] * invSampleRate) : phaseIncConst; - if (phase >= TWO_PI) phase = fmod(phase, TWO_PI); - } - break; - } - case NSCOscWaveformTriangle: { - for (AVAudioFrameCount f = firstRenderIndex; f < endRenderIndex; ++f) { - out0[f] = (float)(1.0 - 4.0 * fabs((phase * invTwoPi) - 0.5)); - phase += hasAutomation ? (TWO_PI * freqValues[f] * invSampleRate) : phaseIncConst; - if (phase >= TWO_PI) phase = fmod(phase, TWO_PI); - } - break; - } + const double nyquist = sampleRate * 0.5; + // Square, sawtooth, triangle and custom read band-limited tables, as Chrome's do. + const float *const *tables = waveEnum == NSCOscWaveformSine ? NULL : (const float *const *)atomic_load_explicit((_Atomic(void *) *)capturedTablesData.mutableBytes, memory_order_acquire); + for (AVAudioFrameCount f = firstRenderIndex; f < endRenderIndex; ++f) { + double freq = hasAutomation ? freqValues[f] : freqValues[0]; + out0[f] = tables ? NSCWaveSample(tables, phase, freq, nyquist) : (float)sin(phase); + phase += hasAutomation ? (TWO_PI * freq * invSampleRate) : phaseIncConst; + if (phase >= TWO_PI || phase < 0.0) phase -= TWO_PI * floor(phase / TWO_PI); } for (AVAudioFrameCount f = endRenderIndex; f < frameCount; ++f) { out0[f] = 0.0f; @@ -246,6 +233,10 @@ - (instancetype)initWithContext:(NSCAudioContext *)context type:(NSString *)type _startSamplePtr = startSampleCell; _stopSamplePtr = stopSampleCell; _waveTypePtr = waveTypeCell; + _tablesData = tablesData; + _waves = [NSMutableArray array]; + [self setType:_type]; + [self setLogicalChannels:1]; [context.engine attachNode:source]; } return self; @@ -258,6 +249,8 @@ - (instancetype)initWithContext:(NSCAudioContext *)context node:(AVAudioNode *)n - (void)setType:(NSString *)type { NSString *resolved = (type.length > 0) ? [type copy] : @"sine"; _type = resolved; + NSCPeriodicWave *builtin = [NSCPeriodicWave waveForType:resolved]; + if (builtin) [self useWave:builtin]; if (_waveTypePtr) { atomic_store_explicit(_waveTypePtr, (uint_least8_t)NSCOscWaveformFromString(resolved), memory_order_release); } @@ -282,7 +275,7 @@ - (void)beginAtFrame:(int64_t)frame { if (_startSamplePtr) atomic_store_explicit(_startSamplePtr, frame, memory_order_release); [self setPlaying:YES]; [ctx incrementActiveCount]; - if (!ctx.engine.isRunning && !ctx.engine.isInManualRenderingMode) { + if (!ctx.engine.isRunning && !ctx.isOffline) { [NSCAudioContext startEngineWithRetry:ctx.engine attempts:3 label:@"oscillator" asyncCompletion:nil]; } } @@ -327,8 +320,10 @@ - (void)setFrequency:(double)frequency { - (BOOL)usesOutputStage { return YES; } - (void)setPeriodicWave:(NSCPeriodicWave *)wave { - if (wave) _type = @"custom"; - objc_setAssociatedObject(self, (__bridge const void *)@"periodicWave", wave, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + if (!wave) return; + [self useWave:wave]; + _type = @"custom"; + if (_waveTypePtr) atomic_store_explicit(_waveTypePtr, (uint_least8_t)NSCOscWaveformCustom, memory_order_release); } @end diff --git a/packages/audio-context/platforms/ios/src/NSCAudioPannerNode.h b/packages/audio-context/platforms/ios/src/NSCAudioPannerNode.h index 6dce55da..fe66c350 100644 --- a/packages/audio-context/platforms/ios/src/NSCAudioPannerNode.h +++ b/packages/audio-context/platforms/ios/src/NSCAudioPannerNode.h @@ -1,12 +1,12 @@ #import -#import "NSCAudioNode.h" +#import "NSCProcessorNode.h" #import "NSCAudioParam.h" NS_ASSUME_NONNULL_BEGIN @class NSCAudioContext; -@interface NSCAudioPannerNode : NSCAudioNode +@interface NSCAudioPannerNode : NSCProcessorNode @property (nonatomic, strong) NSCAudioParam *positionXParam; @property (nonatomic, strong) NSCAudioParam *positionYParam; @@ -59,4 +59,7 @@ NS_ASSUME_NONNULL_BEGIN @end +/// Owns the AudioListener params, so audio connected to them renders before every panner. +NSCAudioNode *NSCMakeListenerOwner(NSCAudioContext *context); + NS_ASSUME_NONNULL_END diff --git a/packages/audio-context/platforms/ios/src/NSCAudioPannerNode.m b/packages/audio-context/platforms/ios/src/NSCAudioPannerNode.m index 0dfed0bc..3366e8a1 100644 --- a/packages/audio-context/platforms/ios/src/NSCAudioPannerNode.m +++ b/packages/audio-context/platforms/ios/src/NSCAudioPannerNode.m @@ -1,692 +1,428 @@ -#import -#import +#import +#import #import "NSCAudioLog.h" #import "NSCAudioContext.h" #import "NSCChannelMixerNode.h" -#import - -//#ifdef NSCLogDebug -//#undef NSCLogDebug -//#endif -//#define NSCLogDebug(...) - -static inline double NSCClampDouble(double value, double minValue, double maxValue) { - if (value < minValue) return minValue; - if (value > maxValue) return maxValue; - return value; -} - -static inline void NSCNormalizeVector3(double *x, double *y, double *z, - double fallbackX, double fallbackY, double fallbackZ) { - double len = sqrt((*x) * (*x) + (*y) * (*y) + (*z) * (*z)); - if (len <= 1e-12) { - *x = fallbackX; - *y = fallbackY; - *z = fallbackZ; - return; - } - *x /= len; - *y /= len; - *z /= len; -} - -static inline double NSCWrapPannerAzimuthDegrees(double azimuth) { - azimuth = NSCClampDouble(azimuth, -180.0, 180.0); - if (azimuth < -90.0) azimuth = -180.0 - azimuth; - else if (azimuth > 90.0) azimuth = 180.0 - azimuth; - return azimuth; -} +#import "NSCHRTFKemar.h" -#pragma mark - The pan unit - -typedef struct { - _Atomic float gain; - // Azimuth in degrees, -90 to 90. - _Atomic float azimuth; - const UInt32 *inputChannels; - float *pulled; - // A mono output's right channel before the down-mix. - float *right; - UInt32 maxFrames; - AudioBufferList *pullList; -} PanRender; - -static AVAudioFormat *pendingPanFormat; - -// Web Audio's equal-power panning of a mono or stereo input, times the distance and cone gain. -@interface NSCPanUnit : AUAudioUnit -@property (nonatomic, readonly) PanRender *render; +@interface NSCAudioContext (NSCPannerNodes) +- (NSArray *)allNodeWrappers; @end -@implementation NSCPanUnit { - AUAudioUnitBusArray *_inputBusses; - AUAudioUnitBusArray *_outputBusses; - PanRender *_render; -} - -- (instancetype)initWithComponentDescription:(AudioComponentDescription)description options:(AudioComponentInstantiationOptions)options error:(NSError **)outError { - if (!(self = [super initWithComponentDescription:description options:options error:outError])) return nil; - AUAudioUnitBus *input = [[AUAudioUnitBus alloc] initWithFormat:pendingPanFormat error:outError]; - AUAudioUnitBus *output = [[AUAudioUnitBus alloc] initWithFormat:pendingPanFormat error:outError]; - if (!input || !output) return nil; - _inputBusses = [[AUAudioUnitBusArray alloc] initWithAudioUnit:self busType:AUAudioUnitBusTypeInput busses:@[ input ]]; - _outputBusses = [[AUAudioUnitBusArray alloc] initWithAudioUnit:self busType:AUAudioUnitBusTypeOutput busses:@[ output ]]; - _render = calloc(1, sizeof(PanRender)); - _render->pullList = calloc(1, sizeof(AudioBufferList) + sizeof(AudioBuffer)); - atomic_init(&_render->gain, 1.0f); - self.maximumFramesToRender = 4096; - return self; -} - -- (AUAudioUnitBusArray *)inputBusses { return _inputBusses; } -- (AUAudioUnitBusArray *)outputBusses { return _outputBusses; } -- (BOOL)canProcessInPlace { return NO; } +typedef struct { double x, y, z; } V3; -// Two channels in; one or two out, a mono output taking the down-mix. -- (BOOL)shouldChangeToFormat:(AVAudioFormat *)format forBus:(AUAudioUnitBus *)bus { - if (bus.busType == AUAudioUnitBusTypeInput) return format.channelCount == 2; - return format.channelCount == 1 || format.channelCount == 2; +static inline V3 Sub(V3 a, V3 b) { return (V3){ a.x - b.x, a.y - b.y, a.z - b.z }; } +static inline double Dot(V3 a, V3 b) { return a.x * b.x + a.y * b.y + a.z * b.z; } +static inline V3 Cross(V3 a, V3 b) { return (V3){ a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x }; } +static inline double Len(V3 a) { return sqrt(Dot(a, a)); } +static inline V3 Norm(V3 a) { + double l = Len(a); + return l > 0.0 ? (V3){ a.x / l, a.y / l, a.z / l } : a; } -- (BOOL)allocateRenderResourcesAndReturnError:(NSError **)outError { - if (![super allocateRenderResourcesAndReturnError:outError]) return NO; - PanRender *r = _render; - UInt32 frames = MAX((UInt32)self.maximumFramesToRender, 128u); - if (frames > r->maxFrames) { - free(r->pulled); - free(r->right); - r->pulled = calloc((size_t)2 * frames, sizeof(float)); - r->right = calloc(frames, sizeof(float)); - r->maxFrames = frames; - } - return r->pulled && r->right; -} +#pragma mark - HRTF database -- (AUInternalRenderBlock)internalRenderBlock { - PanRender *r = _render; - return ^AUAudioUnitStatus(AudioUnitRenderActionFlags *flags, const AudioTimeStamp *ts, AUAudioFrameCount frames, NSInteger bus, AudioBufferList *out, const AURenderEvent *events, AURenderPullInputBlock pull) { - if (!r->pulled || frames > r->maxFrames || out->mNumberBuffers < 1) return kAudioUnitErr_TooManyFramesToProcess; - AudioBufferList *abl = r->pullList; - abl->mNumberBuffers = 2; - for (UInt32 c = 0; c < 2; c++) { - abl->mBuffers[c].mNumberChannels = 1; - abl->mBuffers[c].mData = r->pulled + c * r->maxFrames; - abl->mBuffers[c].mDataByteSize = frames * sizeof(float); - } - AudioUnitRenderActionFlags pullFlags = 0; - OSStatus status = pull ? pull(&pullFlags, ts, frames, 0, abl) : kAudioUnitErr_NoConnection; - BOOL monoOut = out->mNumberBuffers == 1; - float *outL = (float *)out->mBuffers[0].mData, *outR = monoOut ? r->right : (float *)out->mBuffers[1].mData; - if (!outL) outL = out->mBuffers[0].mData = r->pulled; - if (!outR) outR = out->mBuffers[1].mData = r->pulled + r->maxFrames; - for (UInt32 c = 0; c < out->mNumberBuffers; c++) out->mBuffers[c].mDataByteSize = frames * sizeof(float); - if (status != noErr || (pullFlags & kAudioUnitRenderAction_OutputIsSilence)) { - memset(outL, 0, frames * sizeof(float)); - memset(outR, 0, frames * sizeof(float)); - *flags |= kAudioUnitRenderAction_OutputIsSilence; - return noErr; - } - const float *inL = abl->mBuffers[0].mData ?: r->pulled, *inR = abl->mBuffers[1].mData ?: r->pulled + r->maxFrames; - float g = atomic_load_explicit(&r->gain, memory_order_relaxed); - double az = atomic_load_explicit(&r->azimuth, memory_order_relaxed); - // Sources here play at the context's channel count, so identical channels are taken as mono. - BOOL mono = r->inputChannels && *r->inputChannels == 1; - if (!mono) { - mono = YES; - for (AUAudioFrameCount k = 0; k < frames && mono; k++) mono = inL[k] == inR[k]; +// The KEMAR set resampled to the context rate, scaled so an ear averages half the input's power. +typedef struct { + double rate; + int taps; + int positions; + float *data; + int offsets[NSC_HRIR_ELEVATIONS]; +} HRTFDatabase; + +static HRTFDatabase *HRTFDatabaseForRate(double rate) { + static NSMutableDictionary *cache; + static dispatch_once_t once; + dispatch_once(&once, ^{ cache = [NSMutableDictionary dictionary]; }); + @synchronized (cache) { + NSValue *found = cache[@(rate)]; + if (found) return (HRTFDatabase *)found.pointerValue; + HRTFDatabase *db = calloc(1, sizeof(HRTFDatabase)); + db->rate = rate; + double ratio = rate / NSCHRIRRate; + db->taps = (int)ceil(NSCHRIRTaps * ratio); + int positions = 0; + for (int e = 0; e < NSC_HRIR_ELEVATIONS; e++) { + db->offsets[e] = positions; + positions += NSCHRIRAzimuthCount[e]; } - if (mono) { - double x = (az + 90.0) / 180.0; - float gl = (float)cos(x * M_PI_2) * g, gr = (float)sin(x * M_PI_2) * g; - for (AUAudioFrameCount k = 0; k < frames; k++) { - float m = inL[k]; - outL[k] = m * gl; - outR[k] = m * gr; - } - } else if (az <= 0.0) { - double x = (az + 90.0) / 90.0; - float gl = (float)cos(x * M_PI_2), gr = (float)sin(x * M_PI_2); - for (AUAudioFrameCount k = 0; k < frames; k++) { - float l = inL[k], rr = inR[k]; - outL[k] = (l + rr * gl) * g; - outR[k] = rr * gr * g; - } - } else { - double x = az / 90.0; - float gl = (float)cos(x * M_PI_2), gr = (float)sin(x * M_PI_2); - for (AUAudioFrameCount k = 0; k < frames; k++) { - float l = inL[k], rr = inR[k]; - outL[k] = l * gl * g; - outR[k] = (rr + l * gr) * g; + db->positions = positions; + db->data = calloc((size_t)positions * 2 * db->taps, sizeof(float)); + double energy = 0.0; + for (int p = 0; p < positions; p++) { + for (int ear = 0; ear < 2; ear++) { + const int16_t *src = NSCHRIRData + ((size_t)p * 2 + ear) * NSCHRIRTaps; + float *dst = db->data + ((size_t)p * 2 + ear) * db->taps; + for (int k = 0; k < db->taps; k++) { + double at = k / ratio; + int i = (int)at; + double f = at - i; + double a = i < NSCHRIRTaps ? src[i] : 0.0, b = i + 1 < NSCHRIRTaps ? src[i + 1] : 0.0; + // Resampling up keeps the response's gain; down needs the rate ratio. + dst[k] = (float)(((1.0 - f) * a + f * b) / 32768.0 * MIN(1.0, 1.0 / ratio)); + energy += (double)dst[k] * dst[k]; + } } } - if (monoOut) for (AUAudioFrameCount k = 0; k < frames; k++) outL[k] = 0.5f * (outL[k] + outR[k]); - return noErr; - }; -} - -- (void)dealloc { - free(_render->pulled); - free(_render->right); - free(_render->pullList); - free(_render); -} - -@end - -static AudioComponentDescription PanDescription(void) { - AudioComponentDescription description = {0}; - description.componentType = kAudioUnitType_Effect; - description.componentSubType = 'nscn'; - description.componentManufacturer = 'NSCa'; - return description; -} - -@implementation NSCAudioPannerNode { - AVAudioUnitEffect *_unit; - // Connections into the panner mix here: clamped-max, two channels. - NSCChannelMixerNode *_input; - float _positionX, _positionY, _positionZ; - float _orientationX, _orientationY, _orientationZ; - float _pan; - int _distanceModel; - int _panningModel; - float _refDistance, _maxDistance, _rolloffFactor; - float _coneInnerAngle, _coneOuterAngle, _coneOuterGain; - dispatch_source_t _automationTimer; - CFTimeInterval _automationAnchorHostTime; - double _automationAnchorAudioTime; - BOOL _automationUsesHostTime; -} - -- (instancetype)initWithContext:(NSCAudioContext *)context { - return [self initWithContext:context positionX:0.0 positionY:0.0 positionZ:0.0 panningModel:0]; -} - -- (instancetype)initWithContext:(NSCAudioContext *)context positionX:(double)positionX positionY:(double)positionY positionZ:(double)positionZ { - return [self initWithContext:context positionX:positionX positionY:positionY positionZ:positionZ panningModel:0]; -} - -- (instancetype)initWithContext:(NSCAudioContext *)context - positionX:(double)positionX - positionY:(double)positionY - positionZ:(double)positionZ - panningModel:(int)panningModel { - static dispatch_once_t once; - dispatch_once(&once, ^{ - [AUAudioUnit registerSubclass:[NSCPanUnit class] asComponentDescription:PanDescription() name:@"NativeScript: panner" version:1]; - }); - double sr = context.sampleRate > 0 ? context.sampleRate : 44100.0; - AVAudioFormat *stereo = [[AVAudioFormat alloc] initStandardFormatWithSampleRate:sr channels:2]; - pendingPanFormat = stereo; - // A registered in-process unit instantiates synchronously. - AVAudioUnitEffect *unit = [[AVAudioUnitEffect alloc] initWithAudioComponentDescription:PanDescription()]; - pendingPanFormat = nil; - if (![unit.AUAudioUnit isKindOfClass:[NSCPanUnit class]]) return nil; - NSCChannelMixerNode *input = [[NSCChannelMixerNode alloc] initWithContext:context mode:NSCMixModeSum channels:2 discrete:NO]; - if (!input) return nil; - [input setClamp:YES]; - if ([context isKindOfClass:[NSCOfflineAudioContext class]]) [(NSCOfflineAudioContext *)context willConnect]; - @try { [context.engine attachNode:unit]; } @catch (NSException *e) { return nil; } - - if (self = [super initWithContext:context node:unit]) { - _unit = unit; - _input = input; - ((NSCPanUnit *)unit.AUAudioUnit).render->inputChannels = [input mixedChannels]; - NSCConnectAdding(context, input.avNode, 0, unit, 0, stereo); - _positionX = (float)positionX; _positionY = (float)positionY; _positionZ = (float)positionZ; - _pan = 0.0f; - _positionXParam = [[NSCAudioParam alloc] initWithContext:context defaultValue:positionX]; - _positionYParam = [[NSCAudioParam alloc] initWithContext:context defaultValue:positionY]; - _positionZParam = [[NSCAudioParam alloc] initWithContext:context defaultValue:positionZ]; - _orientationXParam = [[NSCAudioParam alloc] initWithContext:context defaultValue:1.0]; - _orientationYParam = [[NSCAudioParam alloc] initWithContext:context defaultValue:0.0]; - _orientationZParam = [[NSCAudioParam alloc] initWithContext:context defaultValue:0.0]; - for (NSCAudioParam *param in @[ _positionXParam, _positionYParam, _positionZParam, _orientationXParam, _orientationYParam, _orientationZParam ]) param.owner = self; - _orientationX = 1.0f; _orientationY = 0.0f; _orientationZ = 0.0f; - _panningModel = panningModel == 1 ? 1 : 0; - _distanceModel = 0; - _refDistance = 1.0f; - _maxDistance = 10000.0f; - _rolloffFactor = 1.0f; - _coneInnerAngle = 360.0f; - _coneOuterAngle = 360.0f; - _coneOuterGain = 0.0f; - _automationAnchorHostTime = 0; - _automationAnchorAudioTime = 0.0; - _automationUsesHostTime = NO; - - [self installAudioParamHooks]; - [self applySpatial]; + float scale = (float)sqrt(0.5 / (energy / (positions * 2))); + vDSP_vsmul(db->data, 1, &scale, db->data, 1, (vDSP_Length)positions * 2 * db->taps); + cache[@(rate)] = [NSValue valueWithPointer:db]; + return db; } - return self; } -- (void)dealloc { - [self stopAutomationLink]; - [self clearAudioParamHooks]; - NSCAudioContext *ctx = self.context; - AVAudioEngine *engine = ctx.engine; - if (engine && _unit && [ctx isNode:_unit attachedToEngine:engine]) { - @try { [engine disconnectNodeOutput:_unit]; } @catch (NSException *e) {} - @try { [ctx detachNode:_unit fromEngine:engine]; } @catch (NSException *e) {} - } +static const float *HRIR(HRTFDatabase *db, int position, int ear) { + return db->data + ((size_t)position * 2 + ear) * db->taps; } -- (instancetype)initWithContextAndParams:(NSCAudioContext *)context - :(NSNumber *)positionX - :(NSNumber *)positionY - :(NSNumber *)positionZ - :(NSNumber *)orientationX - :(NSNumber *)orientationY - :(NSNumber *)orientationZ - :(NSNumber *)pan - :(NSNumber *)distanceModel - :(NSNumber *)panningModel - :(NSNumber *)refDistance - :(NSNumber *)maxDistance - :(NSNumber *)rolloffFactor - :(NSNumber *)coneInnerAngle - :(NSNumber *)coneOuterAngle - :(NSNumber *)coneOuterGain { - double px = positionX ? positionX.doubleValue : 0.0; - double py = positionY ? positionY.doubleValue : 0.0; - double pz = positionZ ? positionZ.doubleValue : 0.0; - int pm = panningModel ? panningModel.intValue : 0; - if (self = [self initWithContext:context positionX:px positionY:py positionZ:pz panningModel:pm]) { - if (orientationX || orientationY || orientationZ) { - [self setOrientation:orientationX :orientationY :orientationZ]; - } - if (pan) [self setPan:pan]; - if (distanceModel) [self setDistanceModel:distanceModel]; - if (refDistance) [self setRefDistance:refDistance]; - if (maxDistance) [self setMaxDistance:maxDistance]; - if (rolloffFactor) [self setRolloffFactor:rolloffFactor]; - if (coneInnerAngle) [self setConeInnerAngle:coneInnerAngle]; - if (coneOuterAngle) [self setConeOuterAngle:coneOuterAngle]; - if (coneOuterGain) [self setConeOuterGain:coneOuterGain]; - [self applySpatial]; +// Adds `weight` times the HRIR pair nearest azimuth `az` (0 to 180) at elevation row `e`, interpolated. +static void AddRow(HRTFDatabase *db, int e, double az, double weight, BOOL swap, float *left, float *right) { + int count = NSCHRIRAzimuthCount[e], first = db->offsets[e]; + double step = 360.0 / NSCHRIRCircle[e]; + int lo = MAX(0, MIN((int)(az / step), count - 1)); + int hi = MIN(lo + 1, count - 1); + double f = hi > lo ? MAX(0.0, MIN(1.0, az / step - lo)) : 0.0; + float wl = (float)(weight * (1.0 - f)), wh = (float)(weight * f); + vDSP_vsma(HRIR(db, first + lo, swap ? 1 : 0), 1, &wl, left, 1, left, 1, db->taps); + vDSP_vsma(HRIR(db, first + lo, swap ? 0 : 1), 1, &wl, right, 1, right, 1, db->taps); + if (wh > 0.0f) { + vDSP_vsma(HRIR(db, first + hi, swap ? 1 : 0), 1, &wh, left, 1, left, 1, db->taps); + vDSP_vsma(HRIR(db, first + hi, swap ? 0 : 1), 1, &wh, right, 1, right, 1, db->taps); } - return self; } -#pragma mark - AudioParam hooks (param-driven automation) - -- (void)installAudioParamHooks { - __weak typeof(self) weakSelf = self; - void (^hook)(NSCAudioParam *) = ^(NSCAudioParam *p) { - __strong typeof(weakSelf) s = weakSelf; - if (!s) return; - [s applySpatial]; - [s ensureAutomationLink]; - }; - _positionXParam.onScheduleChanged = hook; - _positionYParam.onScheduleChanged = hook; - _positionZParam.onScheduleChanged = hook; - _orientationXParam.onScheduleChanged = hook; - _orientationYParam.onScheduleChanged = hook; - _orientationZParam.onScheduleChanged = hook; +// The ear responses for a Web Audio azimuth (-180 to 180, right positive) and elevation. +static void HRTFKernel(HRTFDatabase *db, double azimuth, double elevation, float *left, float *right) { + memset(left, 0, db->taps * sizeof(float)); + memset(right, 0, db->taps * sizeof(float)); + BOOL swap = azimuth < 0.0; + double az = fabs(azimuth); + double el = MAX(NSCHRIRElevation[0], MIN(elevation, NSCHRIRElevation[NSC_HRIR_ELEVATIONS - 1])); + int e = 0; + while (e + 1 < NSC_HRIR_ELEVATIONS && NSCHRIRElevation[e + 1] <= el) e++; + int e2 = MIN(e + 1, NSC_HRIR_ELEVATIONS - 1); + double span = NSCHRIRElevation[e2] - NSCHRIRElevation[e]; + double f = span > 0.0 ? (el - NSCHRIRElevation[e]) / span : 0.0; + AddRow(db, e, az, 1.0 - f, swap, left, right); + if (f > 0.0) AddRow(db, e2, az, f, swap, left, right); +} + +#pragma mark - Render state + +#define PAN_MAX_TAPS 512 +#define PAN_FRAMES 128 + +enum { PX, PY, PZ, OX, OY, OZ, LPX, LPY, LPZ, LFX, LFY, LFZ, LUX, LUY, LUZ, PARAMS }; + +// Owned by the render block; settings are written on the main thread. +@interface NSCPannerState : NSObject { +@public + NSCAudioParam *params[PARAMS]; + double rate; + _Atomic int distanceModel; + _Atomic int panningModel; + _Atomic double refDistance, maxDistance, rolloffFactor; + _Atomic double coneInnerAngle, coneOuterAngle, coneOuterGain; + _Atomic double pan; + HRTFDatabase *hrtf; + // HRTF: the kernels in use, the ones being faded to, and input history per channel. + float kernel[2][PAN_MAX_TAPS], next[2][PAN_MAX_TAPS]; + double kernelAzimuth, kernelElevation; + BOOL hasKernel; + float history[2][PAN_MAX_TAPS + PAN_FRAMES]; } +@end -- (void)clearAudioParamHooks { - _positionXParam.onScheduleChanged = nil; - _positionYParam.onScheduleChanged = nil; - _positionZParam.onScheduleChanged = nil; - _orientationXParam.onScheduleChanged = nil; - _orientationYParam.onScheduleChanged = nil; - _orientationZParam.onScheduleChanged = nil; -} +@implementation NSCPannerState +@end -- (BOOL)hasFutureAutomation { - double t = [self currentTimeForApply]; - return [_positionXParam hasEventsAfter:t] - || [_positionYParam hasEventsAfter:t] - || [_positionZParam hasEventsAfter:t] - || [_orientationXParam hasEventsAfter:t] - || [_orientationYParam hasEventsAfter:t] - || [_orientationZParam hasEventsAfter:t]; +// Spec: distance gain. +static double DistanceGain(NSCPannerState *s, double distance) { + double ref = atomic_load_explicit(&s->refDistance, memory_order_relaxed); + double max = atomic_load_explicit(&s->maxDistance, memory_order_relaxed); + double rolloff = atomic_load_explicit(&s->rolloffFactor, memory_order_relaxed); + switch (atomic_load_explicit(&s->distanceModel, memory_order_relaxed)) { + case 1: { + double d = MAX(MIN(distance, max), ref); + rolloff = MIN(rolloff, 1.0); + return max == ref ? 1.0 - rolloff : 1.0 - rolloff * (d - ref) / (max - ref); + } + case 2: + return ref == 0.0 ? 0.0 : pow(MAX(distance, ref) / ref, -rolloff); + default: + return ref / (ref + rolloff * (MAX(distance, ref) - ref)); + } } -- (void)ensureAutomationLink { - if (![NSThread isMainThread]) { - __weak typeof(self) weakSelf = self; - dispatch_async(dispatch_get_main_queue(), ^{ [weakSelf ensureAutomationLink]; }); +// Spec: cone gain. +static double ConeGain(NSCPannerState *s, V3 source, V3 orientation, V3 listener) { + double inner = atomic_load_explicit(&s->coneInnerAngle, memory_order_relaxed); + double outer = atomic_load_explicit(&s->coneOuterAngle, memory_order_relaxed); + if ((orientation.x == 0.0 && orientation.y == 0.0 && orientation.z == 0.0) || (inner == 360.0 && outer == 360.0)) return 1.0; + V3 toListener = Norm(Sub(listener, source)); + double angle = fabs(180.0 * acos(MAX(-1.0, MIN(1.0, Dot(toListener, Norm(orientation))))) / M_PI); + double absInner = fabs(inner) / 2.0, absOuter = fabs(outer) / 2.0; + double outerGain = atomic_load_explicit(&s->coneOuterGain, memory_order_relaxed); + if (angle <= absInner) return 1.0; + if (angle >= absOuter) return outerGain; + double x = (angle - absInner) / (absOuter - absInner); + return (1.0 - x) + outerGain * x; +} + +// Spec: azimuth and elevation of the source as the listener hears it. +static void AzimuthElevation(V3 source, V3 listener, V3 forward, V3 up, double *azimuth, double *elevation) { + V3 sl = Sub(source, listener); + if (sl.x == 0.0 && sl.y == 0.0 && sl.z == 0.0) { + *azimuth = 0.0; + *elevation = 0.0; return; } - if (_automationTimer) return; - if (![self hasFutureAutomation]) return; - dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, - dispatch_get_main_queue()); - uint64_t intervalNs = (uint64_t)(NSEC_PER_SEC / 60.0); - uint64_t leewayNs = (uint64_t)(NSEC_PER_SEC / 240.0); - NSCAudioContext *ctx = self.context; - double now = ctx ? ctx.currentTime : 0.0; - if (now <= 0.0) { - _automationUsesHostTime = YES; - _automationAnchorHostTime = CACurrentMediaTime(); - _automationAnchorAudioTime = 0.0; + sl = Norm(sl); + V3 right = Norm(Cross(forward, up)); + V3 f = Norm(forward); + V3 u = Cross(right, f); + double upProjection = Dot(sl, u); + V3 projected = Norm(Sub(sl, (V3){ u.x * upProjection, u.y * upProjection, u.z * upProjection })); + double az = 180.0 * acos(MAX(-1.0, MIN(1.0, Dot(projected, right)))) / M_PI; + if (Dot(projected, f) < 0.0) az = 360.0 - az; + az = az >= 0.0 && az <= 270.0 ? 90.0 - az : 450.0 - az; + double el = 90.0 - 180.0 * acos(MAX(-1.0, MIN(1.0, Dot(sl, u)))) / M_PI; + if (el > 90.0) el = 180.0 - el; + else if (el < -90.0) el = -180.0 - el; + *azimuth = az; + *elevation = el; +} + +static void Spatial(NSCPannerState *s, double v[PARAMS], double *gain, double *azimuth, double *elevation) { + V3 source = { v[PX], v[PY], v[PZ] }, orientation = { v[OX], v[OY], v[OZ] }; + V3 listener = { v[LPX], v[LPY], v[LPZ] }, forward = { v[LFX], v[LFY], v[LFZ] }, up = { v[LUX], v[LUY], v[LUZ] }; + AzimuthElevation(source, listener, forward, up, azimuth, elevation); + double pan = atomic_load_explicit(&s->pan, memory_order_relaxed); + if (pan != 0.0) *azimuth = MAX(-1.0, MIN(1.0, pan)) * 90.0; + *gain = DistanceGain(s, Len(Sub(source, listener))) * ConeGain(s, source, orientation, listener); +} + +static void EqualPower(double azimuth, double gain, BOOL mono, float inL, float inR, float *outL, float *outR) { + azimuth = MAX(-180.0, MIN(180.0, azimuth)); + if (azimuth < -90.0) azimuth = -180.0 - azimuth; + else if (azimuth > 90.0) azimuth = 180.0 - azimuth; + if (mono) { + double x = (azimuth + 90.0) / 180.0; + *outL = (float)(inL * cos(x * M_PI_2) * gain); + *outR = (float)(inL * sin(x * M_PI_2) * gain); + } else if (azimuth <= 0.0) { + double x = (azimuth + 90.0) / 90.0; + *outL = (float)((inL + inR * cos(x * M_PI_2)) * gain); + *outR = (float)(inR * sin(x * M_PI_2) * gain); } else { - _automationUsesHostTime = NO; - _automationAnchorHostTime = CACurrentMediaTime(); - _automationAnchorAudioTime = now; + double x = azimuth / 90.0; + *outL = (float)(inL * cos(x * M_PI_2) * gain); + *outR = (float)((inR + inL * sin(x * M_PI_2)) * gain); } - dispatch_source_set_timer(timer, dispatch_time(DISPATCH_TIME_NOW, 0), intervalNs, leewayNs); - __weak typeof(self) weakSelf = self; - dispatch_source_set_event_handler(timer, ^{ - __strong typeof(weakSelf) s = weakSelf; - if (!s) return; - [s applySpatial]; - if (![s hasFutureAutomation]) [s stopAutomationLink]; - }); - _automationTimer = timer; - dispatch_resume(timer); } -- (void)stopAutomationLink { - if (_automationTimer) { - dispatch_source_cancel(_automationTimer); - _automationTimer = nil; +// Each ear convolves its input channel (both the mono one) with its HRIR; a kernel change fades +// across the quantum. Chromium's HRTFPanner works the same way. +static void RenderHRTF(NSCPannerState *s, UInt32 frames, float *const *in, UInt32 inChannels, float *const *out, const double *gain, double azimuth, double elevation) { + HRTFDatabase *db = s->hrtf; + int taps = MIN(db->taps, PAN_MAX_TAPS); + BOOL change = !s->hasKernel || fabs(azimuth - s->kernelAzimuth) > 1e-3 || fabs(elevation - s->kernelElevation) > 1e-3; + if (change) { + HRTFKernel(db, azimuth, elevation, s->next[0], s->next[1]); + if (!s->hasKernel) memcpy(s->kernel, s->next, sizeof(s->kernel)); + s->kernelAzimuth = azimuth; + s->kernelElevation = elevation; + s->hasKernel = YES; + } + float a[PAN_FRAMES], b[PAN_FRAMES]; + for (int ear = 0; ear < 2; ear++) { + float *h = s->history[ear]; + memcpy(h + taps - 1, in[MIN((UInt32)ear, inChannels - 1)], frames * sizeof(float)); + vDSP_conv(h, 1, s->kernel[ear] + taps - 1, -1, a, 1, frames, (vDSP_Length)taps); + if (change) { + vDSP_conv(h, 1, s->next[ear] + taps - 1, -1, b, 1, frames, (vDSP_Length)taps); + for (UInt32 k = 0; k < frames; k++) { + float x = (float)(k + 1) / frames; + a[k] = a[k] * (1.0f - x) + b[k] * x; + } + } + for (UInt32 k = 0; k < frames; k++) out[ear][k] = (float)(a[k] * gain[k]); + memmove(h, h + frames, (taps - 1) * sizeof(float)); } - _automationUsesHostTime = NO; - _automationAnchorHostTime = 0; - _automationAnchorAudioTime = 0.0; + if (change) memcpy(s->kernel, s->next, sizeof(s->kernel)); } -#pragma mark - Spatial state apply +#pragma mark - The listener's params -- (double)currentTimeForApply { - NSCAudioContext *ctx = self.context; - double t = ctx ? ctx.currentTime : 0.0; - if (t > 0.0) { - _automationUsesHostTime = NO; - _automationAnchorHostTime = CACurrentMediaTime(); - _automationAnchorAudioTime = t; - return t; - } +// Owns the AudioListener params: audio connected to them renders before every panner. +@interface NSCListenerOwner : NSCAudioNode +@end - if (!_automationTimer) return t; +@implementation NSCListenerOwner - double hostNow = CACurrentMediaTime(); - if (!_automationUsesHostTime) { - _automationUsesHostTime = YES; - _automationAnchorHostTime = hostNow; - _automationAnchorAudioTime = 0.0; - return 0.0; +- (void)attachParamSink:(AVAudioNode *)sink { + for (NSCAudioNode *node in [self.context allNodeWrappers]) { + if ([node isKindOfClass:[NSCAudioPannerNode class]]) [((NSCAudioPannerNode *)node).port connectEarly:sink format:self.context.format]; } - - double synthetic = _automationAnchorAudioTime + (hostNow - _automationAnchorHostTime); - return synthetic >= 0.0 ? synthetic : 0.0; } -- (void)readListenerStateAtTime:(double)t - positionX:(double *)listenerX - positionY:(double *)listenerY - positionZ:(double *)listenerZ - forwardX:(double *)forwardX - forwardY:(double *)forwardY - forwardZ:(double *)forwardZ - upX:(double *)upX - upY:(double *)upY - upZ:(double *)upZ { - *listenerX = 0.0; - *listenerY = 0.0; - *listenerZ = 0.0; - *forwardX = 0.0; - *forwardY = 0.0; - *forwardZ = -1.0; - *upX = 0.0; - *upY = 1.0; - *upZ = 0.0; - - NSCAudioContext *ctx = self.context; - if (!ctx) return; - - *listenerX = [[ctx getListenerPositionXParam] valueAtTime:t]; - *listenerY = [[ctx getListenerPositionYParam] valueAtTime:t]; - *listenerZ = [[ctx getListenerPositionZParam] valueAtTime:t]; - *forwardX = [[ctx getListenerForwardXParam] valueAtTime:t]; - *forwardY = [[ctx getListenerForwardYParam] valueAtTime:t]; - *forwardZ = [[ctx getListenerForwardZParam] valueAtTime:t]; - *upX = [[ctx getListenerUpXParam] valueAtTime:t]; - *upY = [[ctx getListenerUpYParam] valueAtTime:t]; - *upZ = [[ctx getListenerUpZParam] valueAtTime:t]; +@end + +NSCAudioNode *NSCMakeListenerOwner(NSCAudioContext *context) { + return [[NSCListenerOwner alloc] initWithContext:context node:nil]; } -- (double)coneAndDistanceGainForListenerX:(double)listenerX - listenerY:(double)listenerY - listenerZ:(double)listenerZ { - double dx = (double)_positionX - listenerX; - double dy = (double)_positionY - listenerY; - double dz = (double)_positionZ - listenerZ; - double dist = sqrt(dx * dx + dy * dy + dz * dz); - - double ref = fmax(1e-6, (double)_refDistance); - double maxd = fmax(ref, (double)_maxDistance); - double rf = fmax(0.0, (double)_rolloffFactor); - double d = fmin(fmax(dist, ref), maxd); - - double distGain = 1.0; - switch (_distanceModel) { - default: - case 0: // inverse - distGain = ref / (ref + rf * (d - ref)); - break; - case 1: // linear - if (maxd <= ref) distGain = dist > maxd ? 0.0 : 1.0; - else distGain = 1.0 - rf * (d - ref) / (maxd - ref); - break; - case 2: // exponential - distGain = pow(d / ref, -rf); - break; - } - distGain = NSCClampDouble(distGain, 0.0, 1.0); - - double sx = listenerX - (double)_positionX; - double sy = listenerY - (double)_positionY; - double sz = listenerZ - (double)_positionZ; - double slen = sqrt(sx * sx + sy * sy + sz * sz); - if (slen <= 1e-12) return distGain; - - double ox = (double)_orientationX; - double oy = (double)_orientationY; - double oz = (double)_orientationZ; - NSCNormalizeVector3(&ox, &oy, &oz, 1.0, 0.0, 0.0); - - double dot = (ox * sx + oy * sy + oz * sz) / slen; - dot = NSCClampDouble(dot, -1.0, 1.0); - double angDeg = acos(dot) * 180.0 / M_PI; - - double inner = NSCClampDouble((double)_coneInnerAngle, 0.0, 360.0) * 0.5; - double outer = NSCClampDouble((double)_coneOuterAngle, 0.0, 360.0) * 0.5; - if (outer < inner) inner = outer; - double outGainV = NSCClampDouble((double)_coneOuterGain, 0.0, 1.0); - - double coneGain = 1.0; - if (angDeg <= inner) { - coneGain = 1.0; - } else if (angDeg >= outer) { - coneGain = outGainV; - } else { - double denom = outer - inner; - if (denom <= 1e-12) coneGain = outGainV; - else { - double tt = (angDeg - inner) / denom; - coneGain = (1.0 - tt) + tt * outGainV; - } - } +#pragma mark - The node - return distGain * coneGain; +@implementation NSCAudioPannerNode { + NSCPannerState *_state; } -- (double)resolvedPanForListenerX:(double)listenerX - listenerY:(double)listenerY - listenerZ:(double)listenerZ - forwardX:(double)forwardX - forwardY:(double)forwardY - forwardZ:(double)forwardZ - upX:(double)upX - upY:(double)upY - upZ:(double)upZ { - if (fabs((double)_pan) > 1e-12) { - return NSCClampDouble((double)_pan, -1.0, 1.0); - } - - double fx = forwardX; - double fy = forwardY; - double fz = forwardZ; - NSCNormalizeVector3(&fx, &fy, &fz, 0.0, 0.0, -1.0); - - double ux = upX; - double uy = upY; - double uz = upZ; - NSCNormalizeVector3(&ux, &uy, &uz, 0.0, 1.0, 0.0); - - double rxv = fy * uz - fz * uy; - double ryv = fz * ux - fx * uz; - double rzv = fx * uy - fy * ux; - NSCNormalizeVector3(&rxv, &ryv, &rzv, 1.0, 0.0, 0.0); - - double relX = (double)_positionX - listenerX; - double relY = (double)_positionY - listenerY; - double relZ = (double)_positionZ - listenerZ; - - double localX = relX * rxv + relY * ryv + relZ * rzv; - double localZ = relX * fx + relY * fy + relZ * fz; - double azimuth = NSCWrapPannerAzimuthDegrees(atan2(localX, localZ) * 180.0 / M_PI); - return NSCClampDouble(azimuth / 90.0, -1.0, 1.0); +- (instancetype)initWithContext:(NSCAudioContext *)context { + return [self initWithContextAndParams:context :nil :nil :nil :nil :nil :nil :nil :nil :nil :nil :nil :nil :nil :nil :nil]; } -- (void)applySpatial { - double t = [self currentTimeForApply]; - - _positionX = (float)[_positionXParam valueAtTime:t]; - _positionY = (float)[_positionYParam valueAtTime:t]; - _positionZ = (float)[_positionZParam valueAtTime:t]; - _orientationX = (float)[_orientationXParam valueAtTime:t]; - _orientationY = (float)[_orientationYParam valueAtTime:t]; - _orientationZ = (float)[_orientationZParam valueAtTime:t]; - - double listenerX = 0.0; - double listenerY = 0.0; - double listenerZ = 0.0; - double forwardX = 0.0; - double forwardY = 0.0; - double forwardZ = -1.0; - double upX = 0.0; - double upY = 1.0; - double upZ = 0.0; - [self readListenerStateAtTime:t - positionX:&listenerX - positionY:&listenerY - positionZ:&listenerZ - forwardX:&forwardX - forwardY:&forwardY - forwardZ:&forwardZ - upX:&upX - upY:&upY - upZ:&upZ]; - - double gain = [self coneAndDistanceGainForListenerX:listenerX - listenerY:listenerY - listenerZ:listenerZ]; - double panVal = [self resolvedPanForListenerX:listenerX - listenerY:listenerY - listenerZ:listenerZ - forwardX:forwardX - forwardY:forwardY - forwardZ:forwardZ - upX:upX - upY:upY - upZ:upZ]; - - PanRender *r = ((NSCPanUnit *)_unit.AUAudioUnit).render; - atomic_store_explicit(&r->gain, (float)gain, memory_order_relaxed); - atomic_store_explicit(&r->azimuth, (float)(panVal * 90.0), memory_order_relaxed); +- (instancetype)initWithContextAndParams:(NSCAudioContext *)context + :(NSNumber *)positionX + :(NSNumber *)positionY + :(NSNumber *)positionZ + :(NSNumber *)orientationX + :(NSNumber *)orientationY + :(NSNumber *)orientationZ + :(NSNumber *)pan + :(NSNumber *)distanceModel + :(NSNumber *)panningModel + :(NSNumber *)refDistance + :(NSNumber *)maxDistance + :(NSNumber *)rolloffFactor + :(NSNumber *)coneInnerAngle + :(NSNumber *)coneOuterAngle + :(NSNumber *)coneOuterGain { + if (!(self = [super initWithContext:context outputChannels:2])) return nil; + NSCPannerState *s = [NSCPannerState new]; + _state = s; + s->rate = context.sampleRate; + _positionXParam = [[NSCAudioParam alloc] initWithContext:context defaultValue:positionX ? positionX.doubleValue : 0.0]; + _positionYParam = [[NSCAudioParam alloc] initWithContext:context defaultValue:positionY ? positionY.doubleValue : 0.0]; + _positionZParam = [[NSCAudioParam alloc] initWithContext:context defaultValue:positionZ ? positionZ.doubleValue : 0.0]; + _orientationXParam = [[NSCAudioParam alloc] initWithContext:context defaultValue:orientationX ? orientationX.doubleValue : 1.0]; + _orientationYParam = [[NSCAudioParam alloc] initWithContext:context defaultValue:orientationY ? orientationY.doubleValue : 0.0]; + _orientationZParam = [[NSCAudioParam alloc] initWithContext:context defaultValue:orientationZ ? orientationZ.doubleValue : 0.0]; + NSArray *own = @[ _positionXParam, _positionYParam, _positionZParam, _orientationXParam, _orientationYParam, _orientationZParam ]; + NSArray *listener = @[ [context getListenerPositionXParam], [context getListenerPositionYParam], [context getListenerPositionZParam], + [context getListenerForwardXParam], [context getListenerForwardYParam], [context getListenerForwardZParam], + [context getListenerUpXParam], [context getListenerUpYParam], [context getListenerUpZParam] ]; + for (NSUInteger i = 0; i < own.count; i++) { + own[i].owner = self; + s->params[i] = own[i]; + } + for (NSUInteger i = 0; i < listener.count; i++) { + s->params[own.count + i] = listener[i]; + if (listener[i].inputSink) [self.port connectEarly:(AVAudioNode *)listener[i].inputSink format:context.format]; + } + atomic_init(&s->distanceModel, distanceModel ? distanceModel.intValue : 0); + atomic_init(&s->panningModel, panningModel && panningModel.intValue == 1 ? 1 : 0); + atomic_init(&s->refDistance, refDistance ? refDistance.doubleValue : 1.0); + atomic_init(&s->maxDistance, maxDistance ? maxDistance.doubleValue : 10000.0); + atomic_init(&s->rolloffFactor, rolloffFactor ? rolloffFactor.doubleValue : 1.0); + atomic_init(&s->coneInnerAngle, coneInnerAngle ? coneInnerAngle.doubleValue : 360.0); + atomic_init(&s->coneOuterAngle, coneOuterAngle ? coneOuterAngle.doubleValue : 360.0); + atomic_init(&s->coneOuterGain, coneOuterGain ? coneOuterGain.doubleValue : 0.0); + atomic_init(&s->pan, pan ? MAX(-1.0, MIN(1.0, pan.doubleValue)) : 0.0); + if (atomic_load(&s->panningModel) == 1) s->hrtf = HRTFDatabaseForRate(s->rate); + [self setChannelConfig:2 mode:1 interpretation:0]; + [self setProcess:^UInt32(int64_t start, UInt32 total, float *const *inAll, UInt32 inChannels, float *const *outAll, UInt32 outChannels) { + for (UInt32 at = 0; at < total; at += PAN_FRAMES) { + UInt32 frames = MIN(total - at, (UInt32)PAN_FRAMES); + int64_t frame = start + at; + float *in[2] = { inAll[0] + at, inAll[MIN(1u, inChannels - 1)] + at }; + float *out[2] = { outAll[0] + at, outAll[1] + at }; + double values[PARAMS][frames]; + BOOL automated = NO; + for (int p = 0; p < PARAMS; p++) automated |= [s->params[p] fillValuesFromFrame:(double)frame sampleRate:s->rate frameCount:frames into:values[p]]; + double gains[frames], azimuth = 0.0, elevation = 0.0; + double v[PARAMS]; + for (int p = 0; p < PARAMS; p++) v[p] = values[p][0]; + Spatial(s, v, &gains[0], &azimuth, &elevation); + BOOL hrtf = atomic_load_explicit(&s->panningModel, memory_order_relaxed) == 1 && s->hrtf; + BOOL mono = inChannels == 1; + if (hrtf) { + // The HRIRs follow the source per quantum; distance and cone gain per frame. + for (UInt32 k = 1; k < frames; k++) { + if (!automated) { gains[k] = gains[0]; continue; } + double az, el; + for (int p = 0; p < PARAMS; p++) v[p] = values[p][k]; + Spatial(s, v, &gains[k], &az, &el); + } + RenderHRTF(s, frames, in, inChannels, out, gains, azimuth, elevation); + continue; + } + double az = azimuth, gain = gains[0]; + for (UInt32 k = 0; k < frames; k++) { + if (automated && k > 0) { + double el; + for (int p = 0; p < PARAMS; p++) v[p] = values[p][k]; + Spatial(s, v, &gain, &az, &el); + } + EqualPower(az, gain, mono, in[0][k], in[mono ? 0 : 1][k], &out[0][k], &out[1][k]); + } + } + return 2; + }]; + return self; } #pragma mark - Source attach / connect - (void)attachSource:(NSCAudioNode *)source output:(NSNumber *)output input:(NSNumber *)input { - [_input handleConnectFrom:source output:output input:nil]; + [self handleConnectFrom:source output:output input:nil]; } - (void)detachSource:(NSCAudioNode *)source { - [_input handleDisconnectFrom:source output:nil input:nil]; + [self handleDisconnectFrom:source output:nil input:nil]; } - (void)disconnectPanner { [self disconnect]; } -- (void)handleConnectFrom:(NSCAudioNode *)source output:(NSNumber *)output input:(NSNumber *)input { - [_input handleConnectFrom:source output:output input:nil]; -} - -- (void)handleDisconnectFrom:(NSCAudioNode *)source output:(NSNumber *)output input:(NSNumber *)input { - [_input handleDisconnectFrom:source output:output input:nil]; -} - #pragma mark - Setters / getters -- (void)setPan:(NSNumber *)p { - _pan = (float)NSCClampDouble([p doubleValue], -1.0, 1.0); - [self applySpatial]; -} - -- (void)setDistanceModel:(NSNumber *)v { _distanceModel = v.intValue; [self applySpatial]; } -- (NSNumber *)getDistanceModel { return @(_distanceModel); } +- (void)setPan:(NSNumber *)p { atomic_store(&_state->pan, MAX(-1.0, MIN(1.0, p.doubleValue))); } +- (void)setDistanceModel:(NSNumber *)v { atomic_store(&_state->distanceModel, v.intValue); } +- (NSNumber *)getDistanceModel { return @(atomic_load(&_state->distanceModel)); } - (void)setPanningModel:(NSNumber *)v { - int newPM = v.intValue == 1 ? 1 : 0; - if (newPM == _panningModel) return; - - // HRTF renders as equalpower. - _panningModel = newPM; - [self applySpatial]; - NSCLogDebug(@"NSCAudioPannerNode: setPanningModel -> %d", _panningModel); -} -- (NSNumber *)getPanningModel { return @(_panningModel); } - -- (void)setRefDistance:(NSNumber *)v { _refDistance = [v floatValue]; [self applySpatial]; } -- (NSNumber *)getRefDistance { return @((double)_refDistance); } -- (void)setMaxDistance:(NSNumber *)v { _maxDistance = [v floatValue]; [self applySpatial]; } -- (NSNumber *)getMaxDistance { return @((double)_maxDistance); } -- (void)setRolloffFactor:(NSNumber *)v { _rolloffFactor = [v floatValue]; [self applySpatial]; } -- (NSNumber *)getRolloffFactor { return @((double)_rolloffFactor); } - - - - (void)setConeInnerAngle:(NSNumber *)v { _coneInnerAngle = [v floatValue]; NSCLogDebug(@"NSCAudioPannerNode: setConeInnerAngle -> %f", _coneInnerAngle); [self applySpatial]; } - - (NSNumber *)getConeInnerAngle { return @((double)_coneInnerAngle); } - - (void)setConeOuterAngle:(NSNumber *)v { _coneOuterAngle = [v floatValue]; NSCLogDebug(@"NSCAudioPannerNode: setConeOuterAngle -> %f", _coneOuterAngle); [self applySpatial]; } - - (NSNumber *)getConeOuterAngle { return @((double)_coneOuterAngle); } - - (void)setConeOuterGain:(NSNumber *)v { _coneOuterGain = [v floatValue]; NSCLogDebug(@"NSCAudioPannerNode: setConeOuterGain -> %f", _coneOuterGain); [self applySpatial]; } - - (NSNumber *)getConeOuterGain { return @((double)_coneOuterGain); } + int model = v.intValue == 1 ? 1 : 0; + if (model == 1 && !_state->hrtf) _state->hrtf = HRTFDatabaseForRate(_state->rate); + atomic_store(&_state->panningModel, model); +} +- (NSNumber *)getPanningModel { return @(atomic_load(&_state->panningModel)); } + +- (void)setRefDistance:(NSNumber *)v { atomic_store(&_state->refDistance, v.doubleValue); } +- (NSNumber *)getRefDistance { return @(atomic_load(&_state->refDistance)); } +- (void)setMaxDistance:(NSNumber *)v { atomic_store(&_state->maxDistance, v.doubleValue); } +- (NSNumber *)getMaxDistance { return @(atomic_load(&_state->maxDistance)); } +- (void)setRolloffFactor:(NSNumber *)v { atomic_store(&_state->rolloffFactor, v.doubleValue); } +- (NSNumber *)getRolloffFactor { return @(atomic_load(&_state->rolloffFactor)); } +- (void)setConeInnerAngle:(NSNumber *)v { atomic_store(&_state->coneInnerAngle, v.doubleValue); } +- (NSNumber *)getConeInnerAngle { return @(atomic_load(&_state->coneInnerAngle)); } +- (void)setConeOuterAngle:(NSNumber *)v { atomic_store(&_state->coneOuterAngle, v.doubleValue); } +- (NSNumber *)getConeOuterAngle { return @(atomic_load(&_state->coneOuterAngle)); } +- (void)setConeOuterGain:(NSNumber *)v { atomic_store(&_state->coneOuterGain, v.doubleValue); } +- (NSNumber *)getConeOuterGain { return @(atomic_load(&_state->coneOuterGain)); } - (void)setPosition:(NSNumber *)x :(NSNumber *)y :(NSNumber *)z { - double now = self.context ? self.context.currentTime : 0.0; - [self.positionXParam setValueAtTime:x :@(now)]; - [self.positionYParam setValueAtTime:y :@(now)]; - [self.positionZParam setValueAtTime:z :@(now)]; - NSCLogDebug(@"NSCAudioPannerNode: setPosition -> x=%f y=%f z=%f", [x doubleValue], [y doubleValue], [z doubleValue]); - [self applySpatial]; + [self.positionXParam setValue:x]; + [self.positionYParam setValue:y]; + [self.positionZParam setValue:z]; } - (void)setOrientation:(NSNumber *)x :(NSNumber *)y :(NSNumber *)z { - double now = self.context ? self.context.currentTime : 0.0; - [self.orientationXParam setValueAtTime:x :@(now)]; - [self.orientationYParam setValueAtTime:y :@(now)]; - [self.orientationZParam setValueAtTime:z :@(now)]; - NSCLogDebug(@"NSCAudioPannerNode: setOrientation -> x=%f y=%f z=%f", [x doubleValue], [y doubleValue], [z doubleValue]); - [self applySpatial]; -} - -- (void)attachParamSink:(AVAudioNode *)sink { - [super attachParamSink:sink]; - [self ensureAutomationLink]; -} - -- (void)applyAutomation { - [self applySpatial]; + [self.orientationXParam setValue:x]; + [self.orientationYParam setValue:y]; + [self.orientationZParam setValue:z]; } @end diff --git a/packages/audio-context/platforms/ios/src/NSCAudioParam.h b/packages/audio-context/platforms/ios/src/NSCAudioParam.h index 02132138..732f2e07 100644 --- a/packages/audio-context/platforms/ios/src/NSCAudioParam.h +++ b/packages/audio-context/platforms/ios/src/NSCAudioParam.h @@ -38,6 +38,11 @@ typedef struct { - (void)setValue:(NSNumber *)value; - (void)setValueAtTime:(NSNumber *)value :(NSNumber *)time; - (void)linearRampToValueAtTime:(NSNumber *)value :(NSNumber *)time; +- (void)exponentialRampToValueAtTime:(NSNumber *)value :(NSNumber *)time; +- (void)setTargetAtTime:(NSNumber *)target :(NSNumber *)startTime :(NSNumber *)timeConstant; +- (void)setValueCurveAtTime:(NSData *)values :(NSNumber *)startTime :(NSNumber *)duration; +/// The value at the context's current time. +- (double)computedValue; - (void)cancelScheduledValues:(NSNumber *)time; - (void)cancelAndHoldAtTime:(NSNumber *)heldValue :(NSNumber *)time; - (NSArray *)getValuesForRange:(double)startTime :(double)sampleRate :(NSInteger)frameCount; diff --git a/packages/audio-context/platforms/ios/src/NSCAudioParam.m b/packages/audio-context/platforms/ios/src/NSCAudioParam.m index 783dee2b..2debecd2 100644 --- a/packages/audio-context/platforms/ios/src/NSCAudioParam.m +++ b/packages/audio-context/platforms/ios/src/NSCAudioParam.m @@ -3,13 +3,20 @@ typedef NS_ENUM(NSInteger, ParamEventType) { ParamEventTypeSet = 0, - ParamEventTypeLinearRamp = 1 + ParamEventTypeLinearRamp = 1, + ParamEventTypeExpRamp = 2, + // value: target, aux: time constant. + ParamEventTypeTarget = 3, + // curve values from time for aux seconds. + ParamEventTypeCurve = 4, }; @interface ParamEvent : NSObject @property (nonatomic) ParamEventType type; @property (nonatomic) double time; @property (nonatomic) double value; +@property (nonatomic) double aux; +@property (nonatomic, strong) NSData *curve; - (instancetype)initWithType:(ParamEventType)type time:(double)time value:(double)value; @end @@ -28,6 +35,9 @@ - (instancetype)initWithType:(ParamEventType)type time:(double)time value:(doubl ParamEventType type; double time; double value; + double aux; + const float *curve; + NSUInteger curveLength; } NSCParamEventSnapshot; @implementation NSCAudioParam { @@ -114,6 +124,43 @@ - (void)linearRampToValueAtTime:(NSNumber *)value :(NSNumber *)time { [self notifyScheduleChanged]; } +- (void)exponentialRampToValueAtTime:(NSNumber *)value :(NSNumber *)time { + [_lock lock]; + ParamEvent *ev = [[ParamEvent alloc] initWithType:ParamEventTypeExpRamp time:time.doubleValue value:value.doubleValue]; + NSCAudioParam_insertSorted(_events, ev); + [_lock unlock]; + [self notifyScheduleChanged]; +} + +- (void)setTargetAtTime:(NSNumber *)target :(NSNumber *)startTime :(NSNumber *)timeConstant { + [_lock lock]; + ParamEvent *ev = [[ParamEvent alloc] initWithType:ParamEventTypeTarget time:startTime.doubleValue value:target.doubleValue]; + ev.aux = timeConstant.doubleValue; + NSCAudioParam_insertSorted(_events, ev); + [_lock unlock]; + [self notifyScheduleChanged]; +} + +- (void)setValueCurveAtTime:(NSData *)values :(NSNumber *)startTime :(NSNumber *)duration { + if (values.length < 2 * sizeof(float)) return; + [_lock lock]; + const float *v = (const float *)values.bytes; + ParamEvent *ev = [[ParamEvent alloc] initWithType:ParamEventTypeCurve time:startTime.doubleValue value:v[values.length / sizeof(float) - 1]]; + ev.aux = duration.doubleValue; + ev.curve = [values copy]; + NSCAudioParam_insertSorted(_events, ev); + // The curve's last value holds from its end, as a set would. + ParamEvent *end = [[ParamEvent alloc] initWithType:ParamEventTypeSet time:startTime.doubleValue + duration.doubleValue value:ev.value]; + NSCAudioParam_insertSorted(_events, end); + [_lock unlock]; + [self notifyScheduleChanged]; +} + +- (double)computedValue { + double now = _context ? _context.currentTime : 0.0; + return [self valueAtTime:now]; +} + - (void)cancelScheduledValues:(NSNumber *)time { [_lock lock]; double t = time.doubleValue; @@ -127,25 +174,32 @@ - (void)cancelScheduledValues:(NSNumber *)time { [self notifyScheduleChanged]; } +// Holds the value automation reaches at `time`; a ramp running then ends there with it. - (void)cancelAndHoldAtTime:(NSNumber *)heldValue :(NSNumber *)time { - - [_lock lock]; double t = time.doubleValue; - double hv = heldValue.doubleValue; + double hv = [self scheduledValueAtTime:t]; + [_lock lock]; + ParamEventType cut = ParamEventTypeSet; + for (ParamEvent *e in _events) { + if (e.time >= t) { cut = e.type; break; } + } NSIndexSet *toRemove = [_events indexesOfObjectsPassingTest:^BOOL(ParamEvent *obj, NSUInteger idx, BOOL *stop) { return obj.time >= t; }]; - if (toRemove.count > 0) { - [_events removeObjectsAtIndexes:toRemove]; - } - - ParamEvent *ev = [[ParamEvent alloc] initWithType:ParamEventTypeSet time:t value:hv]; - [_events addObject:ev]; - _currentValueInternal = hv; + if (toRemove.count > 0) [_events removeObjectsAtIndexes:toRemove]; + ParamEventType held = cut == ParamEventTypeLinearRamp || cut == ParamEventTypeExpRamp ? cut : ParamEventTypeSet; + NSCAudioParam_insertSorted(_events, [[ParamEvent alloc] initWithType:held time:t value:hv]); [_lock unlock]; [self notifyScheduleChanged]; } +- (double)scheduledValueAtTime:(double)t { + double v = 0.0; + double rate = _context ? _context.sampleRate : 0.0; + [self fillScheduled:t byFrame:NO sampleRate:(rate > 0.0 ? rate : 1.0) frameCount:1 into:&v]; + return v; +} + - (NSMutableData *)inputData { if (_inputData) return _inputData; NSMutableData *data = [NSMutableData dataWithLength:sizeof(NSCParamInputBlock)]; @@ -228,6 +282,69 @@ - (BOOL)fillValues:(double)start return AddInput(in, first, frameCount, outValues, kRate) || automated; } +// The value at time t of the spec's automation timeline. +static double EvaluateAt(const NSCParamEventSnapshot *e, NSUInteger count, double def, double t) { + // The last event at or before t, and the one after it. + NSInteger prev = -1; + NSUInteger lo = 0, hi = count; + while (lo < hi) { + NSUInteger mid = (lo + hi) >> 1; + if (e[mid].time <= t) lo = mid + 1; else hi = mid; + } + prev = (NSInteger)lo - 1; + NSUInteger next = lo; + // The value an event leaves behind, at its own time. + double base = def, baseTime = 0.0; + for (NSInteger k = 0; k <= prev; k++) { + const NSCParamEventSnapshot *ev = &e[k]; + switch (ev->type) { + case ParamEventTypeTarget: { + // Settles from the value before it; the next event starts from wherever it got. + double endT = (NSUInteger)(k + 1) < count ? MIN(e[k + 1].time, t) : t; + double v0 = base; + base = ev->aux > 0.0 ? ev->value + (v0 - ev->value) * exp(-(endT - ev->time) / ev->aux) : ev->value; + baseTime = endT; + if ((NSUInteger)(k + 1) < count && e[k + 1].time <= t) continue; + return base; + } + case ParamEventTypeCurve: { + double dur = ev->aux; + double endT = ev->time + dur; + if (t < endT && k == prev) { + NSUInteger n = ev->curveLength; + double pos = dur > 0.0 ? (t - ev->time) / dur * (double)(n - 1) : (double)(n - 1); + NSUInteger i0 = (NSUInteger)MAX(0.0, floor(pos)); + if (i0 >= n - 1) return ev->curve[n - 1]; + double f = pos - i0; + return ev->curve[i0] + (ev->curve[i0 + 1] - ev->curve[i0]) * f; + } + base = ev->value; + baseTime = endT; + break; + } + default: + base = ev->value; + baseTime = ev->time; + break; + } + } + if (next < count) { + const NSCParamEventSnapshot *n = &e[next]; + double t0 = prev >= 0 ? baseTime : 0.0, t1 = n->time; + if (prev >= 0 && e[prev].type == ParamEventTypeTarget) t0 = e[prev].time; + if (n->type == ParamEventTypeLinearRamp) { + double r = t1 <= t0 ? 1.0 : MAX(0.0, MIN(1.0, (t - t0) / (t1 - t0))); + return base + (n->value - base) * r; + } + if (n->type == ParamEventTypeExpRamp) { + if (base * n->value <= 0.0) return base; + double r = t1 <= t0 ? 1.0 : MAX(0.0, MIN(1.0, (t - t0) / (t1 - t0))); + return base * pow(n->value / base, r); + } + } + return base; +} + // byFrame: frame i is at (start + i) / sampleRate, so an event on a frame lands exactly on it. - (BOOL)fillScheduled:(double)start byFrame:(BOOL)byFrame @@ -265,62 +382,21 @@ - (BOOL)fillScheduled:(double)start evts[i].type = e.type; evts[i].time = e.time; evts[i].value = e.value; + evts[i].aux = e.aux; + evts[i].curve = (const float *)e.curve.bytes; + evts[i].curveLength = e.curve.length / sizeof(float); } [_lock unlock]; + // Curves and targets read their data, which the events keep; snapshot them under the lock. if (kRate) { - double v = def; - NSInteger firstAfter = (NSInteger)evtCount; - for (NSUInteger i = 0; i < evtCount; ++i) { - if (evts[i].time > startTime) { firstAfter = (NSInteger)i; break; } - } - if (firstAfter == 0) v = def; - else if (firstAfter >= (NSInteger)evtCount) v = evts[evtCount - 1].value; - else { - double prevT = evts[firstAfter - 1].time; - double prevV = evts[firstAfter - 1].value; - ParamEventType nextType = evts[firstAfter].type; - double nextT = evts[firstAfter].time; - double nextV = evts[firstAfter].value; - if (nextType == ParamEventTypeLinearRamp) { - double ratio = nextT <= prevT ? 1.0 : (startTime - prevT) / (nextT - prevT); - if (ratio < 0.0) ratio = 0.0; if (ratio > 1.0) ratio = 1.0; - v = prevV + (nextV - prevV) * ratio; - } else { - v = prevV; - } - } + double v = EvaluateAt(evts, evtCount, def, startTime); for (NSInteger i = 0; i < frameCount; ++i) outValues[i] = v; - if (evts != stackEvents) free(evts); - return YES; - } - - NSInteger nextIdx = 0; - NSInteger prevIdx = -1; - for (NSInteger i = 0; i < frameCount; ++i) { - double t = byFrame ? (start + (double)i) / sampleRate : startTime + (double)i / sampleRate; - while (nextIdx < (NSInteger)evtCount && evts[nextIdx].time <= t) { - prevIdx = nextIdx; - nextIdx += 1; - } - double value; - if (prevIdx < 0) value = def; - else if (nextIdx >= (NSInteger)evtCount) value = evts[prevIdx].value; - else { - double prevT = evts[prevIdx].time; - double prevV = evts[prevIdx].value; - ParamEventType nextType = evts[nextIdx].type; - double nextT = evts[nextIdx].time; - double nextV = evts[nextIdx].value; - if (nextType == ParamEventTypeLinearRamp) { - double ratio = nextT <= prevT ? 1.0 : (t - prevT) / (nextT - prevT); - if (ratio < 0.0) ratio = 0.0; if (ratio > 1.0) ratio = 1.0; - value = prevV + (nextV - prevV) * ratio; - } else { - value = prevV; - } + } else { + for (NSInteger i = 0; i < frameCount; ++i) { + double t = byFrame ? (start + (double)i) / sampleRate : startTime + (double)i / sampleRate; + outValues[i] = EvaluateAt(evts, evtCount, def, t); } - outValues[i] = value; } if (evts != stackEvents) free(evts); return YES; diff --git a/packages/audio-context/platforms/ios/src/NSCAudioWorkletNode.m b/packages/audio-context/platforms/ios/src/NSCAudioWorkletNode.m index 6a8fd8bb..45fbeef4 100644 --- a/packages/audio-context/platforms/ios/src/NSCAudioWorkletNode.m +++ b/packages/audio-context/platforms/ios/src/NSCAudioWorkletNode.m @@ -39,6 +39,10 @@ float *inQ; float *outQ; BOOL inSilent[16]; + // Each input's computed channels this quantum, from its port's last mix (ports retained). + NSInteger inQuantum[16]; + const _Atomic UInt32 *inMixed[16]; + CFTypeRef inPortRefs[16]; // One render call's pulled inputs and rendered outputs, `maxFrames` per channel. float *pulled; float *rendered; @@ -76,7 +80,7 @@ static BOOL PushRequest(WorkletRender *r, uint64_t requestFrame, double time) { memcpy(slot + FRAME, &frame, sizeof frame); ((uint32_t *)slot)[ALIVE] = 1; for (NSInteger i = 0; i < r->inputs; i++) { - uint32_t count = r->inSilent[i] ? 0 : (uint32_t)r->inChannels[i]; + uint32_t count = r->inSilent[i] ? 0 : (uint32_t)MAX(1, MIN(r->inQuantum[i], MAX_CHANNELS)); ((uint32_t *)slot)[r->inputCounts + i] = count; for (uint32_t c = 0; c < count; c++) { memcpy(slot + r->inputData + (i * MAX_CHANNELS + c) * QUANTUM, InQ(r, i, c), QUANTUM * sizeof(float)); @@ -188,21 +192,19 @@ static void EndQuantum(WorkletRender *r) { } r->nextFrame += QUANTUM; r->position = 0; - for (NSInteger i = 0; i < r->inputs; i++) r->inSilent[i] = YES; + for (NSInteger i = 0; i < r->inputs; i++) { + r->inSilent[i] = YES; + r->inQuantum[i] = 0; + } } -// Web Audio "speakers" mixing from the port's channels; AVAudioMixerNode pans equal-power instead. +// The port mixed to the computed channels and fills the rest with silence. static void CopyInput(WorkletRender *r, NSInteger i, NSInteger at, NSInteger from, NSInteger n) { - NSInteger want = r->inChannels[i], have = r->inPort[i]; - if (have == 2 && want == 1) { - float *dst = InQ(r, i, 0) + at; - const float *left = Pulled(r, i, 0) + from, *right = Pulled(r, i, 1) + from; - for (NSInteger k = 0; k < n; k++) dst[k] = 0.5f * (left[k] + right[k]); - return; - } - for (NSInteger c = 0; c < want; c++) { - memcpy(InQ(r, i, c) + at, Pulled(r, i, MIN(c, have - 1)) + from, n * sizeof(float)); - } + for (NSInteger c = 0; c < r->inPort[i]; c++) memcpy(InQ(r, i, c) + at, Pulled(r, i, c) + from, n * sizeof(float)); +} + +static NSInteger MixedChannels(WorkletRender *r, NSInteger i) { + return r->inMixed[i] ? (NSInteger)atomic_load_explicit(r->inMixed[i], memory_order_acquire) : r->inChannels[i]; } static void DownmixOutputs(WorkletRender *r, AUAudioFrameCount frames) { @@ -247,8 +249,9 @@ static void Process(WorkletRender *r, const AudioTimeStamp *ts, AUAudioFrameCoun // The context renders one quantum per call; a short last one is padded. for (NSInteger i = 0; i < r->inputs; i++) { r->inSilent[i] = silent[i]; + r->inQuantum[i] = MixedChannels(r, i); CopyInput(r, i, 0, 0, MIN(frames, QUANTUM)); - for (NSInteger c = 0; c < r->inChannels[i]; c++) { + for (NSInteger c = 0; c < r->inPort[i]; c++) { memset(InQ(r, i, c) + frames, 0, (QUANTUM - MIN(frames, QUANTUM)) * sizeof(float)); } } @@ -262,7 +265,10 @@ static void Process(WorkletRender *r, const AudioTimeStamp *ts, AUAudioFrameCoun while (done < frames) { AUAudioFrameCount n = (AUAudioFrameCount)MIN((NSInteger)(QUANTUM - r->position), (NSInteger)(frames - done)); for (NSInteger i = 0; i < r->inputs; i++) { - if (!silent[i]) r->inSilent[i] = NO; + if (!silent[i]) { + r->inSilent[i] = NO; + r->inQuantum[i] = MAX(r->inQuantum[i], MixedChannels(r, i)); + } CopyInput(r, i, r->position, done, n); } for (NSInteger o = 0; o < r->outputs; o++) { @@ -370,6 +376,7 @@ - (void)dealloc { free(r->inQ); free(r->outQ); if (r->params) CFRelease(r->params); + for (NSInteger i = 0; i < MAX_PORTS; i++) if (r->inPortRefs[i]) CFRelease(r->inPortRefs[i]); free(r); } @@ -525,8 +532,8 @@ - (nullable instancetype)initWithContext:(NSCAudioContext *)context NSMutableArray *outFormats = [NSMutableArray array]; for (NSInteger i = 0; i < inputs; i++) { inCounts[i] = MAX(1, MIN(inputChannels[i].integerValue, MAX_CHANNELS)); - // Each input's channel mixer gives it exactly channelCount channels. - [inFormats addObject:ChannelFormat(sampleRate, inCounts[i])]; + // Wide enough for any computedNumberOfChannels; the port mixes per the channel config. + [inFormats addObject:ChannelFormat(sampleRate, MAX_CHANNELS)]; } for (NSInteger o = 0; o < outputs; o++) { outCounts[o] = MAX(1, MIN(outputChannels[o].integerValue, MAX_CHANNELS)); @@ -586,7 +593,7 @@ - (nullable instancetype)initWithContext:(NSCAudioContext *)context r->outQ = calloc((size_t)MAX(outputs, 1) * MAX_CHANNELS * QUANTUM, sizeof(float)); r->position = 0; r->lowWater = UINT32_MAX; - r->offline = context.engine.isInManualRenderingMode; + r->offline = context.isOffline; r->sampleRate = sampleRate; NSMutableArray *params = [NSMutableArray array]; @@ -607,10 +614,13 @@ - (nullable instancetype)initWithContext:(NSCAudioContext *)context AVAudioEngine *engine = context.engine; if ([context isKindOfClass:[NSCOfflineAudioContext class]]) [(NSCOfflineAudioContext *)context willConnect]; [engine attachNode:unit]; + if (engine.isRunning) NSCEnsureAllocated(unit); NSMutableArray *ports = [NSMutableArray array]; for (NSInteger i = 0; i < inputs; i++) { - NSCChannelMixerNode *port = [[NSCChannelMixerNode alloc] initWithContext:context mode:NSCMixModeSum channels:inCounts[i] discrete:NO]; + NSCChannelMixerNode *port = [[NSCChannelMixerNode alloc] initWithContext:context mode:NSCMixModeSum channels:MAX_CHANNELS discrete:NO]; if (!port) continue; + r->inMixed[i] = [port mixedChannels]; + r->inPortRefs[i] = CFBridgingRetain(port); @try { [engine connect:port.avNode to:unit fromBus:0 toBus:(AVAudioNodeBus)i format:inFormats[i]]; } @catch (NSException *e) { @@ -634,6 +644,7 @@ - (nullable instancetype)initWithContext:(NSCAudioContext *)context tapUnit.render = r; tapUnit.output = o; [engine attachNode:tap]; + if (engine.isRunning) NSCEnsureAllocated(tap); [taps addObject:tap]; [points addObject:[[AVAudioConnectionPoint alloc] initWithNode:tap bus:0]]; } @@ -655,6 +666,7 @@ - (nullable instancetype)initWithContext:(NSCAudioContext *)context _paramMixer = mixer; _paramFormat = paramFormat; } + [self channelConfigChanged]; return self; } @@ -693,6 +705,12 @@ - (void)attachParamSink:(AVAudioNode *)sink { } } +- (void)channelConfigChanged { + for (NSCChannelMixerNode *port in _inputPorts) { + [port configureCount:self.channelCount mode:self.channelCountMode discrete:self.channelInterpretation == 1]; + } +} + - (void)handleConnectFrom:(NSCAudioNode *)source output:(NSNumber *)output input:(NSNumber *)input { NSInteger index = input ? input.integerValue : 0; if (index < 0 || index >= (NSInteger)_inputPorts.count) return; @@ -712,7 +730,7 @@ - (void)handleDisconnectFrom:(NSCAudioNode *)source output:(NSNumber *)output in - (void)handleConnectedTo:(NSCAudioNode *)destination output:(NSNumber *)output input:(NSNumber *)input { [super handleConnectedTo:destination output:output input:input]; NSCAudioContext *ctx = self.context; - if (!ctx || ctx.engine.isInManualRenderingMode) return; + if (!ctx || ctx.isOffline) return; if (!_active) { _active = YES; [ctx incrementActiveCount]; diff --git a/packages/audio-context/platforms/ios/src/NSCCanvasAudioContextUmbrella.h b/packages/audio-context/platforms/ios/src/NSCCanvasAudioContextUmbrella.h index 4928c165..f283f1a0 100644 --- a/packages/audio-context/platforms/ios/src/NSCCanvasAudioContextUmbrella.h +++ b/packages/audio-context/platforms/ios/src/NSCCanvasAudioContextUmbrella.h @@ -22,6 +22,7 @@ #import "NSCConvolverNode.h" #import "NSCDynamicsCompressorNode.h" #import "NSCChannelMixerNode.h" +#import "NSCProcessorNode.h" #import "NSCChannelSplitterNode.h" #import "NSCChannelMergerNode.h" #import "NSCPeriodicWave.h" diff --git a/packages/audio-context/platforms/ios/src/NSCChannelMixerNode.h b/packages/audio-context/platforms/ios/src/NSCChannelMixerNode.h index 5a245b99..129648c0 100644 --- a/packages/audio-context/platforms/ios/src/NSCChannelMixerNode.h +++ b/packages/audio-context/platforms/ios/src/NSCChannelMixerNode.h @@ -1,5 +1,6 @@ #import #import +#import #import "NSCAudioNode.h" NS_ASSUME_NONNULL_BEGIN @@ -34,12 +35,17 @@ typedef NS_ENUM(NSInteger, NSCMixMode) { - (void)setClamp:(BOOL)clamp; - (void)setDiscrete:(BOOL)discrete; /// The channels the last render mixed to; read on the render thread after pulling this node. -- (const UInt32 *)mixedChannels; +- (const _Atomic UInt32 *)mixedChannels; +/// Sum mode: mixes to `channels` (at most 8) without changing the output format. +- (void)setMixChannels:(NSInteger)channels; +/// Web Audio channelCount / channelCountMode (0 max, 1 clamped-max, 2 explicit) / interpretation. +- (void)configureCount:(NSInteger)count mode:(NSInteger)mode discrete:(BOOL)discrete; /// Connects `node`'s bus 0 to a bus rendered before the others; its audio is not mixed. - (void)connectEarly:(AVAudioNode *)node format:(AVAudioFormat *)format; /// Pass mode: connects `node`'s `bus` as the audio this node plays. - (void)connectMain:(AVAudioNode *)node bus:(AVAudioNodeBus)bus format:(AVAudioFormat *)format; +- (void)connectMain:(AVAudioNode *)node bus:(AVAudioNodeBus)bus format:(AVAudioFormat *)format logical:(nullable const _Atomic UInt32 *)logical; @end diff --git a/packages/audio-context/platforms/ios/src/NSCChannelMixerNode.m b/packages/audio-context/platforms/ios/src/NSCChannelMixerNode.m index 4c9ea740..b9cc703b 100644 --- a/packages/audio-context/platforms/ios/src/NSCChannelMixerNode.m +++ b/packages/audio-context/platforms/ios/src/NSCChannelMixerNode.m @@ -11,7 +11,7 @@ typedef struct { NSCMixMode mode; _Atomic BOOL discrete; - UInt32 channels; + _Atomic UInt32 channels; // Sum mode: mix to at most the widest connection's channels (clamped-max). _Atomic int clamp; // Pick mode: the channel of bus 0 this node plays. @@ -21,13 +21,15 @@ _Atomic int busChannels[MIX_BUSSES]; _Atomic int target[MIX_BUSSES]; _Atomic int early[MIX_BUSSES]; + // The source's own channel count when it plays fewer than its bus carries. + _Atomic(const _Atomic UInt32 *) logical[MIX_BUSSES]; UInt32 maxFrames; float *pulled; float *mixed; float *outs; AudioBufferList *abl; double lastSampleTime; - UInt32 mixedChannels; + _Atomic UInt32 mixedChannels; BOOL silent; } MixRender; @@ -80,18 +82,27 @@ static void MixAdd(float *const *src, UInt32 n, float *const *dst, UInt32 m, UIn static float *Mixed(MixRender *r, UInt32 c) { return r->mixed + c * r->maxFrames; } +// A bus's channels as its source plays them. +static UInt32 BusChannels(MixRender *r, int b) { + UInt32 n = (UInt32)MAX(1, MIN(atomic_load_explicit(&r->busChannels[b], memory_order_relaxed), MIX_CHANNELS)); + const _Atomic UInt32 *cell = atomic_load_explicit(&r->logical[b], memory_order_acquire); + UInt32 logical = cell ? atomic_load_explicit(cell, memory_order_relaxed) : 0; + return logical >= 1 && logical < n ? logical : n; +} + static void Mix(MixRender *r, const AudioTimeStamp *ts, AUAudioFrameCount frames, AURenderPullInputBlock pull) { - UInt32 C = r->channels; + UInt32 C = atomic_load_explicit(&r->channels, memory_order_relaxed); if (r->mode == NSCMixModeSum && atomic_load_explicit(&r->clamp, memory_order_relaxed)) { UInt32 widest = 1; for (int b = 0; b < MIX_BUSSES; b++) { if (!atomic_load_explicit(&r->used[b], memory_order_acquire) || atomic_load_explicit(&r->early[b], memory_order_relaxed)) continue; - widest = MAX(widest, (UInt32)atomic_load_explicit(&r->busChannels[b], memory_order_relaxed)); + widest = MAX(widest, BusChannels(r, b)); } C = MIN(C, widest); } + if (r->mode == NSCMixModePick) C = 1; for (UInt32 c = 0; c < MIX_CHANNELS; c++) memset(Mixed(r, c), 0, frames * sizeof(float)); - r->mixedChannels = r->mode == NSCMixModePass ? 0 : C; + UInt32 mixedCount = r->mode == NSCMixModePass ? 0 : C; r->silent = YES; float *mixed[MIX_CHANNELS]; for (UInt32 c = 0; c < MIX_CHANNELS; c++) mixed[c] = Mixed(r, c); @@ -110,11 +121,13 @@ static void Mix(MixRender *r, const AudioTimeStamp *ts, AUAudioFrameCount frames } AudioUnitRenderActionFlags flags = 0; OSStatus status = pull ? pull(&flags, ts, frames, b, abl) : kAudioUnitErr_NoConnection; - if (r->mode == NSCMixModePass && b == 0) r->mixedChannels = n; + UInt32 played = BusChannels(r, b); + if (r->mode == NSCMixModePass && b == 0) mixedCount = played; if (early || status != noErr || (flags & kAudioUnitRenderAction_OutputIsSilence)) continue; r->silent = NO; float *src[MIX_CHANNELS]; for (UInt32 c = 0; c < n; c++) src[c] = abl->mBuffers[c].mData ? (float *)abl->mBuffers[c].mData : r->pulled + c * r->maxFrames; + n = played; if (r->mode == NSCMixModePass) { if (b == 0) MixAdd(src, n, mixed, n, frames, YES); } else if (r->mode == NSCMixModePick) { @@ -128,6 +141,7 @@ static void Mix(MixRender *r, const AudioTimeStamp *ts, AUAudioFrameCount frames } } } + atomic_store_explicit(&r->mixedChannels, mixedCount, memory_order_release); } // Bus formats for the unit being instantiated; set around the synchronous instantiation. @@ -216,7 +230,7 @@ - (AUInternalRenderBlock)internalRenderBlock { if (c < MIX_CHANNELS) dst[c] = (float *)out->mBuffers[c].mData; } float *src[MIX_CHANNELS]; - UInt32 n = r->mixedChannels; + UInt32 n = atomic_load_explicit(&r->mixedChannels, memory_order_relaxed); for (UInt32 c = 0; c < n; c++) src[c] = Mixed(r, c); if (n > 0 && !r->silent) MixAdd(src, n, dst, k, frames, NO); else *flags |= kAudioUnitRenderAction_OutputIsSilence; @@ -256,6 +270,7 @@ @implementation NSCChannelMixerNode { NSCMixMode _mode; // One per connection: source node, its bus, this node's bus. NSMutableArray *_links; + AVAudioSourceNode *_silence; } - (instancetype)initWithContext:(NSCAudioContext *)context mode:(NSCMixMode)mode channels:(NSInteger)channels discrete:(BOOL)discrete { @@ -290,6 +305,15 @@ - (instancetype)initWithContext:(NSCAudioContext *)context mode:(NSCMixMode)mode _links = [NSMutableArray array]; if ([context isKindOfClass:[NSCOfflineAudioContext class]]) [(NSCOfflineAudioContext *)context willConnect]; [context.engine attachNode:unit]; + if (context.engine.isRunning) NSCEnsureAllocated(unit); + // The engine skips an effect with no input. + _silence = [[AVAudioSourceNode alloc] initWithFormat:context.format renderBlock:^OSStatus(BOOL *isSilence, const AudioTimeStamp *ts, AVAudioFrameCount frames, AudioBufferList *out) { + for (UInt32 c = 0; c < out->mNumberBuffers; c++) memset(out->mBuffers[c].mData, 0, out->mBuffers[c].mDataByteSize); + *isSilence = YES; + return noErr; + }]; + [context.engine attachNode:_silence]; + [self connectNode:_silence bus:0 toBus:MIX_BUSSES - 1 format:context.format target:-1 early:YES]; return self; } @@ -297,11 +321,26 @@ - (MixRender *)render { return ((NSCChannelMixUnit *)_unit.AUAudioUnit).render; } -- (const UInt32 *)mixedChannels { +- (const _Atomic UInt32 *)mixedChannels { MixRender *r = [self render]; return r ? &r->mixedChannels : NULL; } +- (const _Atomic UInt32 *)logicalChannelCellForOutput:(NSInteger)output { + return [self mixedChannels]; +} + +- (void)setMixChannels:(NSInteger)channels { + MixRender *r = [self render]; + if (r) atomic_store(&r->channels, (UInt32)MAX(1, MIN(channels, (NSInteger)MIX_CHANNELS))); +} + +- (void)configureCount:(NSInteger)count mode:(NSInteger)mode discrete:(BOOL)discrete { + [self setMixChannels:mode == 0 ? MIX_CHANNELS : count]; + [self setClamp:mode != 2]; + [self setDiscrete:discrete]; +} + - (void)setDiscrete:(BOOL)discrete { MixRender *r = [self render]; if (r) atomic_store(&r->discrete, discrete); @@ -350,14 +389,20 @@ - (void)forgetBus:(NSInteger)b { atomic_store(&r->used[b], 0); atomic_store(&r->early[b], 0); atomic_store(&r->target[b], -1); + atomic_store(&r->logical[b], NULL); for (NSInteger i = (NSInteger)_links.count - 1; i >= 0; i--) { if ([_links[i][2] integerValue] == b) [_links removeObjectAtIndex:(NSUInteger)i]; } } - (BOOL)connectNode:(AVAudioNode *)node bus:(AVAudioNodeBus)from toBus:(NSInteger)b format:(AVAudioFormat *)format target:(NSInteger)target early:(BOOL)early { + return [self connectNode:node bus:from toBus:b format:format target:target early:early logical:NULL]; +} + +- (BOOL)connectNode:(AVAudioNode *)node bus:(AVAudioNodeBus)from toBus:(NSInteger)b format:(AVAudioFormat *)format target:(NSInteger)target early:(BOOL)early logical:(const _Atomic UInt32 *)logical { MixRender *r = [self render]; if (b < 0 || !r) return NO; + atomic_store(&r->logical[b], logical); atomic_store(&r->busChannels[b], (int)MAX(1u, MIN(format.channelCount, (AVAudioChannelCount)MIX_CHANNELS))); atomic_store(&r->target[b], (int)target); atomic_store(&r->early[b], early ? 1 : 0); @@ -375,8 +420,12 @@ - (void)connectEarly:(AVAudioNode *)node format:(AVAudioFormat *)format { } - (void)connectMain:(AVAudioNode *)node bus:(AVAudioNodeBus)bus format:(AVAudioFormat *)format { + [self connectMain:node bus:bus format:format logical:NULL]; +} + +- (void)connectMain:(AVAudioNode *)node bus:(AVAudioNodeBus)bus format:(AVAudioFormat *)format logical:(const _Atomic UInt32 *)logical { [self forgetBus:0]; - [self connectNode:node bus:bus toBus:0 format:format target:-1 early:NO]; + [self connectNode:node bus:bus toBus:0 format:format target:-1 early:NO logical:logical]; } - (void)handleConnectFrom:(NSCAudioNode *)source output:(NSNumber *)output input:(NSNumber *)input { @@ -394,7 +443,8 @@ - (void)handleConnectFrom:(NSCAudioNode *)source output:(NSNumber *)output input } AVAudioFormat *format = [source formatForOutput:(AVAudioNodeBus)MAX(0, output ? output.intValue : 0)]; if (format.channelCount > MIX_CHANNELS) format = self.context.format; - if ([self connectNode:node bus:from toBus:[self freeBus] format:format target:target early:NO]) { + NSInteger outputIndex = MAX(0, output ? output.intValue : 0); + if ([self connectNode:node bus:from toBus:[self freeBus] format:format target:target early:NO logical:[source logicalChannelCellForOutput:outputIndex]]) { [source handleConnectedTo:self output:output input:input]; } } diff --git a/packages/audio-context/platforms/ios/src/NSCChannelSplitterNode.m b/packages/audio-context/platforms/ios/src/NSCChannelSplitterNode.m index ccbb39e6..9b41fb2a 100644 --- a/packages/audio-context/platforms/ios/src/NSCChannelSplitterNode.m +++ b/packages/audio-context/platforms/ios/src/NSCChannelSplitterNode.m @@ -36,6 +36,10 @@ - (void)eachOutputNode:(NSNumber *)output block:(void (NS_NOESCAPE ^)(AVAudioNod } } +- (const _Atomic UInt32 *)logicalChannelCellForOutput:(NSInteger)output { + return output >= 0 && output < (NSInteger)_outputs.count ? [_outputs[(NSUInteger)output] mixedChannels] : NULL; +} + - (AVAudioFormat *)formatForOutput:(AVAudioNodeBus)bus { NSCChannelMixerNode *output = bus < _outputs.count ? _outputs[bus] : _outputs.firstObject; return output ? [output formatForOutput:0] : [super formatForOutput:bus]; diff --git a/packages/audio-context/platforms/ios/src/NSCConstantSourceNode.m b/packages/audio-context/platforms/ios/src/NSCConstantSourceNode.m index 39fcb423..c659ec23 100644 --- a/packages/audio-context/platforms/ios/src/NSCConstantSourceNode.m +++ b/packages/audio-context/platforms/ios/src/NSCConstantSourceNode.m @@ -109,6 +109,7 @@ - (instancetype)initWithContext:(NSCAudioContext *)context offset:(double)offset _offsetCell = offsetCell; _offsetParam = offsetParam; offsetParam.owner = self; + [self setLogicalChannels:1]; [context.engine attachNode:source]; } return self; diff --git a/packages/audio-context/platforms/ios/src/NSCConvolverNode.h b/packages/audio-context/platforms/ios/src/NSCConvolverNode.h index 9703f51a..b4452195 100644 --- a/packages/audio-context/platforms/ios/src/NSCConvolverNode.h +++ b/packages/audio-context/platforms/ios/src/NSCConvolverNode.h @@ -1,18 +1,17 @@ #import -#import "NSCAudioNode.h" +#import "NSCProcessorNode.h" #import "NSCAudioBuffer.h" NS_ASSUME_NONNULL_BEGIN @class NSCAudioContext; -@interface NSCConvolverNode : NSCAudioNode +@interface NSCConvolverNode : NSCProcessorNode @property (nonatomic, strong, nullable) NSCAudioBuffer *buffer; @property (nonatomic) BOOL normalize; -- (instancetype)initWithContext:(NSCAudioContext *)context NS_DESIGNATED_INITIALIZER; -- (instancetype)initWithContext:(NSCAudioContext *)context node:(nullable AVAudioNode *)node NS_UNAVAILABLE; +- (instancetype)initWithContext:(NSCAudioContext *)context; @end diff --git a/packages/audio-context/platforms/ios/src/NSCConvolverNode.m b/packages/audio-context/platforms/ios/src/NSCConvolverNode.m index 4b4a9c3c..3aa0cc8f 100644 --- a/packages/audio-context/platforms/ios/src/NSCConvolverNode.m +++ b/packages/audio-context/platforms/ios/src/NSCConvolverNode.m @@ -1,19 +1,181 @@ #import "NSCAudioContext.h" +#import +#import + +#define CONV_BLOCK 128 +#define CONV_FFT 256 +#define CONV_LOG2 8 + +// Uniformly partitioned overlap-save convolution, a quantum per partition, so no latency. +// Spectra are vDSP packed: 128 real then 128 imaginary, DC and Nyquist in bin 0. +typedef struct { + int irChannels; + int parts; + float *H; + float *fdl; + float prev[2][CONV_BLOCK]; + int head; +} ConvKernel; + +static float *Spectrum(float *base, int index) { return base + (size_t)index * CONV_FFT; } + +static void ForwardFFT(FFTSetup setup, const float *time, float *spectrum) { + DSPSplitComplex split = { spectrum, spectrum + CONV_BLOCK }; + vDSP_ctoz((const DSPComplex *)time, 2, &split, 1, CONV_BLOCK); + vDSP_fft_zrip(setup, &split, 1, CONV_LOG2, kFFTDirection_Forward); +} + +// acc += a * b, keeping the packed DC and Nyquist bins apart. +static void MultiplyAdd(const float *a, const float *b, float *acc) { + float dc = acc[0] + a[0] * b[0], ny = acc[CONV_BLOCK] + a[CONV_BLOCK] * b[CONV_BLOCK]; + DSPSplitComplex A = { (float *)a, (float *)a + CONV_BLOCK }, B = { (float *)b, (float *)b + CONV_BLOCK }, C = { acc, acc + CONV_BLOCK }; + vDSP_zvma(&A, 1, &B, 1, &C, 1, &C, 1, CONV_BLOCK); + acc[0] = dc; + acc[CONV_BLOCK] = ny; +} + +static void FreeKernel(ConvKernel *k) { + if (!k) return; + free(k->H); + free(k->fdl); + free(k); +} + +// The spec's equal-power normalization scale. +static float NormalizationScale(AVAudioPCMBuffer *pcm) { + double power = 0.0; + AVAudioChannelCount channels = pcm.format.channelCount; + AVAudioFrameCount length = pcm.frameLength; + for (AVAudioChannelCount c = 0; c < channels; c++) { + float sum = 0.0f; + vDSP_svesq(pcm.floatChannelData[c], 1, &sum, length); + power += sum; + } + power = sqrt(power / ((double)channels * MAX(1u, length))); + if (!isfinite(power) || power < 0.000125) power = 0.000125; + double scale = 1.0 / power * 0.00125 * 44100.0 / pcm.format.sampleRate; + if (channels == 4) scale *= 0.5; + return (float)scale; +} + +static ConvKernel *MakeKernel(FFTSetup setup, AVAudioPCMBuffer *pcm, BOOL normalize) { + AVAudioChannelCount channels = pcm.format.channelCount; + if (!pcm.floatChannelData || (channels != 1 && channels != 2 && channels != 4)) return NULL; + ConvKernel *k = calloc(1, sizeof(ConvKernel)); + k->irChannels = (int)channels; + k->parts = (int)MAX(1u, (pcm.frameLength + CONV_BLOCK - 1) / CONV_BLOCK); + k->H = calloc((size_t)channels * k->parts * CONV_FFT, sizeof(float)); + k->fdl = calloc((size_t)2 * k->parts * CONV_FFT, sizeof(float)); + if (!k->H || !k->fdl) { + FreeKernel(k); + return NULL; + } + // vDSP's forward transforms are twice the DFT and its inverse N times the inverse DFT. + float scale = (normalize ? NormalizationScale(pcm) : 1.0f) / (4.0f * CONV_FFT); + float block[CONV_FFT]; + for (AVAudioChannelCount c = 0; c < channels; c++) { + const float *ir = pcm.floatChannelData[c]; + for (int p = 0; p < k->parts; p++) { + memset(block, 0, sizeof(block)); + AVAudioFrameCount from = (AVAudioFrameCount)p * CONV_BLOCK; + AVAudioFrameCount n = MIN((AVAudioFrameCount)CONV_BLOCK, pcm.frameLength - from); + vDSP_vsmul(ir + from, 1, &scale, block, 1, n); + ForwardFFT(setup, block, Spectrum(k->H, (int)c * k->parts + p)); + } + } + return k; +} + +// One quantum: in[0..inputs) through the response into out[0..outputs). +static UInt32 Convolve(FFTSetup setup, ConvKernel *k, const float *const *in, UInt32 inputs, float *const *out) { + float window[CONV_FFT], acc[2][CONV_FFT], time[CONV_FFT]; + int P = k->parts; + k->head = (k->head + 1) % P; + for (UInt32 c = 0; c < 2; c++) { + const float *x = in[MIN(c, inputs - 1)]; + memcpy(window, k->prev[c], sizeof(k->prev[c])); + memcpy(window + CONV_BLOCK, x, CONV_BLOCK * sizeof(float)); + memcpy(k->prev[c], x, CONV_BLOCK * sizeof(float)); + ForwardFFT(setup, window, Spectrum(k->fdl, (int)c * P + k->head)); + } + // Output channel o sums input i through response channel `paths[o][i]`. + int irs = k->irChannels; + UInt32 outputs = irs == 1 && inputs == 1 ? 1 : 2; + int paths[2][2] = { { -1, -1 }, { -1, -1 } }; + if (irs == 1) { paths[0][0] = 0; paths[1][1] = 0; } + else if (irs == 2) { paths[0][0] = 0; paths[1][inputs == 1 ? 0 : 1] = 1; } + else { paths[0][0] = 0; paths[0][1] = 2; paths[1][0] = 1; paths[1][1] = 3; } + for (UInt32 o = 0; o < outputs; o++) { + memset(acc[o], 0, sizeof(acc[o])); + for (UInt32 i = 0; i < 2; i++) { + int h = paths[o][i]; + if (h < 0) continue; + for (int p = 0; p < P; p++) { + int slot = (k->head - p + P) % P; + MultiplyAdd(Spectrum(k->fdl, (int)i * P + slot), Spectrum(k->H, h * P + p), acc[o]); + } + } + DSPSplitComplex split = { acc[o], acc[o] + CONV_BLOCK }; + vDSP_fft_zrip(setup, &split, 1, CONV_LOG2, kFFTDirection_Inverse); + vDSP_ztoc(&split, 1, (DSPComplex *)time, 2, CONV_BLOCK); + memcpy(out[o], time + CONV_BLOCK, CONV_BLOCK * sizeof(float)); + } + return outputs; +} + +// Owned by the render block, so kernels outlive any render still using them. +@interface NSCConvolverState : NSObject { +@public + _Atomic(ConvKernel *) kernel; + FFTSetup setup; + NSMutableArray *kernels; +} +@end + +@implementation NSCConvolverState +- (instancetype)init { + if ((self = [super init])) { + setup = vDSP_create_fftsetup(CONV_LOG2, kFFTRadix2); + kernels = [NSMutableArray array]; + } + return self; +} +- (void)dealloc { + for (NSValue *v in kernels) FreeKernel((ConvKernel *)v.pointerValue); + if (setup) vDSP_destroy_fftsetup(setup); +} +@end @implementation NSCConvolverNode { - AVAudioUnitReverb *_reverb; + NSCConvolverState *_state; } - (instancetype)initWithContext:(NSCAudioContext *)context { - AVAudioUnitReverb *r = [[AVAudioUnitReverb alloc] init]; - [r loadFactoryPreset:AVAudioUnitReverbPresetMediumHall]; - r.wetDryMix = 50.0; - [context.engine attachNode:r]; - if (self = [super initWithContext:context node:r]) { - _reverb = r; - _normalize = YES; - } + if (!(self = [super initWithContext:context outputChannels:2])) return nil; + _normalize = YES; + _state = [NSCConvolverState new]; + [self setChannelConfig:2 mode:1 interpretation:0]; + NSCConvolverState *st = _state; + [self setProcess:^UInt32(int64_t frame, UInt32 frames, float *const *in, UInt32 inChannels, float *const *out, UInt32 outChannels) { + ConvKernel *k = atomic_load_explicit(&st->kernel, memory_order_acquire); + if (!k) return 1; + UInt32 inputs = MIN(inChannels, 2u), wrote = 1; + for (UInt32 at = 0; at + CONV_BLOCK <= frames; at += CONV_BLOCK) { + const float *ins[2] = { in[0] + at, in[MIN(1u, inputs - 1)] + at }; + float *outs[2] = { out[0] + at, out[1] + at }; + wrote = Convolve(st->setup, k, ins, inputs, outs); + } + return wrote; + }]; return self; } +- (void)setBuffer:(NSCAudioBuffer *)buffer { + _buffer = buffer; + AVAudioPCMBuffer *pcm = [buffer getBuffer]; + ConvKernel *kernel = pcm ? MakeKernel(_state->setup, pcm, _normalize) : NULL; + if (kernel) [_state->kernels addObject:[NSValue valueWithPointer:kernel]]; + atomic_store_explicit(&_state->kernel, kernel, memory_order_release); +} + @end diff --git a/packages/audio-context/platforms/ios/src/NSCDynamicsCompressorNode.h b/packages/audio-context/platforms/ios/src/NSCDynamicsCompressorNode.h index c5718563..034b6744 100644 --- a/packages/audio-context/platforms/ios/src/NSCDynamicsCompressorNode.h +++ b/packages/audio-context/platforms/ios/src/NSCDynamicsCompressorNode.h @@ -1,24 +1,25 @@ #import #import -#import "NSCAudioNode.h" +#import "NSCParamEffectNode.h" #import "NSCAudioParam.h" NS_ASSUME_NONNULL_BEGIN @class NSCAudioContext; -@interface NSCDynamicsCompressorNode : NSCAudioNode +/// Web Audio's compressor: Chromium's kernel with 6 ms of look-ahead and makeup gain. +@interface NSCDynamicsCompressorNode : NSCParamEffectNode @property (nonatomic, readonly) NSCAudioParam *thresholdParam; @property (nonatomic, readonly) NSCAudioParam *kneeParam; @property (nonatomic, readonly) NSCAudioParam *ratioParam; @property (nonatomic, readonly) NSCAudioParam *attackParam; @property (nonatomic, readonly) NSCAudioParam *releaseParam; -@property (nonatomic, readonly) NSCAudioParam *reductionParam; +/// The gain reduction in dB the last render applied. +@property (nonatomic, readonly) double reduction; -- (instancetype)initWithContext:(NSCAudioContext *)context NS_DESIGNATED_INITIALIZER; -- (instancetype)initWithContext:(NSCAudioContext *)context node:(nullable AVAudioNode *)node NS_UNAVAILABLE; +- (instancetype)initWithContext:(NSCAudioContext *)context; @end diff --git a/packages/audio-context/platforms/ios/src/NSCDynamicsCompressorNode.m b/packages/audio-context/platforms/ios/src/NSCDynamicsCompressorNode.m index 21336d3e..fb439340 100644 --- a/packages/audio-context/platforms/ios/src/NSCDynamicsCompressorNode.m +++ b/packages/audio-context/platforms/ios/src/NSCDynamicsCompressorNode.m @@ -1,240 +1,24 @@ -#import -#import - +#import "NSCDynamicsCompressorNode.h" #import "NSCAudioContext.h" -@implementation NSCDynamicsCompressorNode { - AVAudioUnitEffect *_compressor; - dispatch_source_t _automationTimer; - CFTimeInterval _automationAnchorHostTime; - double _automationAnchorAudioTime; - BOOL _automationUsesHostTime; -} +@implementation NSCDynamicsCompressorNode - (instancetype)initWithContext:(NSCAudioContext *)context { - AudioComponentDescription description; - description.componentType = kAudioUnitType_Effect; - description.componentSubType = kAudioUnitSubType_DynamicsProcessor; - description.componentManufacturer = kAudioUnitManufacturer_Apple; - description.componentFlags = 0; - description.componentFlagsMask = 0; - - AVAudioUnitEffect *compressor = [[AVAudioUnitEffect alloc] initWithAudioComponentDescription:description]; - AVAudioNode *node = compressor; - if (compressor) { - [context.engine attachNode:compressor]; - } else { - AVAudioMixerNode *fallback = [[AVAudioMixerNode alloc] init]; - [context.engine attachNode:fallback]; - node = fallback; - } - - if (self = [super initWithContext:context node:node]) { - _compressor = compressor; - - _thresholdParam = [[NSCAudioParam alloc] initWithContext:context defaultValue:-24.0]; - _kneeParam = [[NSCAudioParam alloc] initWithContext:context defaultValue:30.0]; - _ratioParam = [[NSCAudioParam alloc] initWithContext:context defaultValue:12.0]; - _attackParam = [[NSCAudioParam alloc] initWithContext:context defaultValue:0.003]; - _releaseParam = [[NSCAudioParam alloc] initWithContext:context defaultValue:0.25]; - _reductionParam = [[NSCAudioParam alloc] initWithContext:context defaultValue:0.0]; - - _automationAnchorHostTime = 0; - _automationAnchorAudioTime = 0.0; - _automationUsesHostTime = NO; - - [self installAudioParamHooks]; - [self applyCompressorParams]; + NSCAudioParam *threshold = [[NSCAudioParam alloc] initWithContext:context defaultValue:-24.0]; + NSCAudioParam *knee = [[NSCAudioParam alloc] initWithContext:context defaultValue:30.0]; + NSCAudioParam *ratio = [[NSCAudioParam alloc] initWithContext:context defaultValue:12.0]; + NSCAudioParam *attack = [[NSCAudioParam alloc] initWithContext:context defaultValue:0.003]; + NSCAudioParam *release = [[NSCAudioParam alloc] initWithContext:context defaultValue:0.25]; + if (self = [super initWithContext:context kind:NSCParamEffectKindCompressor params:@[ threshold, knee, ratio, attack, release ] maxDelayTime:0.0]) { + _thresholdParam = threshold; + _kneeParam = knee; + _ratioParam = ratio; + _attackParam = attack; + _releaseParam = release; } - return self; } -- (BOOL)setCompressorParam:(AudioUnitParameterID)param value:(AudioUnitParameterValue)value { - if (!_compressor) return NO; -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wdeprecated-declarations" - AudioUnit unit = _compressor.audioUnit; -#pragma clang diagnostic pop - if (!unit) return NO; - OSStatus status = AudioUnitSetParameter(unit, param, kAudioUnitScope_Global, 0, value, 0); - return status == noErr; -} - -- (BOOL)getCompressorParam:(AudioUnitParameterID)param value:(AudioUnitParameterValue *)value { - if (!_compressor || !value) return NO; -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wdeprecated-declarations" - AudioUnit unit = _compressor.audioUnit; -#pragma clang diagnostic pop - if (!unit) return NO; - OSStatus status = AudioUnitGetParameter(unit, param, kAudioUnitScope_Global, 0, value); - return status == noErr; -} - -- (void)dealloc { - [self stopAutomationLink]; - [self clearAudioParamHooks]; -} - -- (void)installAudioParamHooks { - __weak typeof(self) weakSelf = self; - void (^hook)(NSCAudioParam *) = ^(NSCAudioParam *p) { - __strong typeof(weakSelf) s = weakSelf; - if (!s) return; - [s applyCompressorParams]; - [s ensureAutomationLink]; - }; - - _thresholdParam.onScheduleChanged = hook; - _kneeParam.onScheduleChanged = hook; - _ratioParam.onScheduleChanged = hook; - _attackParam.onScheduleChanged = hook; - _releaseParam.onScheduleChanged = hook; -} - -- (void)clearAudioParamHooks { - _thresholdParam.onScheduleChanged = nil; - _kneeParam.onScheduleChanged = nil; - _ratioParam.onScheduleChanged = nil; - _attackParam.onScheduleChanged = nil; - _releaseParam.onScheduleChanged = nil; -} - -- (double)currentTimeForApply { - NSCAudioContext *ctx = self.context; - double t = ctx ? ctx.currentTime : 0.0; - if (t > 0.0) { - _automationUsesHostTime = NO; - _automationAnchorHostTime = CACurrentMediaTime(); - _automationAnchorAudioTime = t; - return t; - } - - if (!_automationTimer) return t; - - double hostNow = CACurrentMediaTime(); - if (!_automationUsesHostTime) { - _automationUsesHostTime = YES; - _automationAnchorHostTime = hostNow; - _automationAnchorAudioTime = 0.0; - return 0.0; - } - - double synthetic = _automationAnchorAudioTime + (hostNow - _automationAnchorHostTime); - return synthetic >= 0.0 ? synthetic : 0.0; -} - -- (BOOL)hasFutureAutomation { - double t = [self currentTimeForApply]; - return [_thresholdParam hasEventsAfter:t] - || [_kneeParam hasEventsAfter:t] - || [_ratioParam hasEventsAfter:t] - || [_attackParam hasEventsAfter:t] - || [_releaseParam hasEventsAfter:t]; -} - -- (void)ensureAutomationLink { - if (![NSThread isMainThread]) { - __weak typeof(self) weakSelf = self; - dispatch_async(dispatch_get_main_queue(), ^{ [weakSelf ensureAutomationLink]; }); - return; - } - - if (_automationTimer) return; - if (![self hasFutureAutomation]) return; - - dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, - dispatch_get_main_queue()); - uint64_t intervalNs = (uint64_t)(NSEC_PER_SEC / 60.0); - uint64_t leewayNs = (uint64_t)(NSEC_PER_SEC / 240.0); - - NSCAudioContext *ctx = self.context; - double now = ctx ? ctx.currentTime : 0.0; - if (now <= 0.0) { - _automationUsesHostTime = YES; - _automationAnchorHostTime = CACurrentMediaTime(); - _automationAnchorAudioTime = 0.0; - } else { - _automationUsesHostTime = NO; - _automationAnchorHostTime = CACurrentMediaTime(); - _automationAnchorAudioTime = now; - } - - dispatch_source_set_timer(timer, dispatch_time(DISPATCH_TIME_NOW, 0), intervalNs, leewayNs); - __weak typeof(self) weakSelf = self; - dispatch_source_set_event_handler(timer, ^{ - __strong typeof(weakSelf) s = weakSelf; - if (!s) return; - [s applyCompressorParams]; - if (![s hasFutureAutomation]) [s stopAutomationLink]; - }); - - _automationTimer = timer; - dispatch_resume(timer); -} - -- (void)stopAutomationLink { - if (_automationTimer) { - dispatch_source_cancel(_automationTimer); - _automationTimer = nil; - } - _automationUsesHostTime = NO; - _automationAnchorHostTime = 0; - _automationAnchorAudioTime = 0.0; -} - -- (void)applyCompressorParams { - if (!_compressor) return; - - double t = [self currentTimeForApply]; - - double threshold = [_thresholdParam valueAtTime:t]; - double knee = [_kneeParam valueAtTime:t]; - double ratio = [_ratioParam valueAtTime:t]; - double attack = [_attackParam valueAtTime:t]; - double release = [_releaseParam valueAtTime:t]; - - if (threshold < -100.0) threshold = -100.0; - if (threshold > 0.0) threshold = 0.0; - - if (knee < 0.0) knee = 0.0; - if (knee > 40.0) knee = 40.0; - - if (ratio < 1.0) ratio = 1.0; - if (ratio > 50.0) ratio = 50.0; - - if (attack < 0.0001) attack = 0.0001; - if (attack > 1.0) attack = 1.0; - - if (release < 0.001) release = 0.001; - if (release > 5.0) release = 5.0; - - double effectiveHeadroom = knee; - if (ratio > 1.0) { - double normalized = (ratio - 1.0) / 19.0; - if (normalized < 0.0) normalized = 0.0; - if (normalized > 1.0) normalized = 1.0; - effectiveHeadroom = knee * (1.0 - (0.7 * normalized)); - if (effectiveHeadroom < 1.0) effectiveHeadroom = 1.0; - } - - [self setCompressorParam:kDynamicsProcessorParam_Threshold value:(AudioUnitParameterValue)threshold]; - [self setCompressorParam:kDynamicsProcessorParam_HeadRoom value:(AudioUnitParameterValue)effectiveHeadroom]; - [self setCompressorParam:kDynamicsProcessorParam_ExpansionRatio value:(AudioUnitParameterValue)1.0f]; - [self setCompressorParam:kDynamicsProcessorParam_ExpansionThreshold value:(AudioUnitParameterValue)-120.0f]; - [self setCompressorParam:kDynamicsProcessorParam_AttackTime value:(AudioUnitParameterValue)attack]; - [self setCompressorParam:kDynamicsProcessorParam_ReleaseTime value:(AudioUnitParameterValue)release]; - - AudioUnitParameterValue compressionAmount = 0; - if ([self getCompressorParam:kDynamicsProcessorParam_CompressionAmount value:&compressionAmount]) { - double reductionDb = -(double)compressionAmount; - [_reductionParam setValueAtTime:@(reductionDb) :@(t)]; - } -} - -- (void)applyAutomation { - [self applyCompressorParams]; -} +- (double)reduction { return [self meteredReduction]; } @end diff --git a/packages/audio-context/platforms/ios/src/NSCHRTFKemar.h b/packages/audio-context/platforms/ios/src/NSCHRTFKemar.h new file mode 100644 index 00000000..a6424437 --- /dev/null +++ b/packages/audio-context/platforms/ios/src/NSCHRTFKemar.h @@ -0,0 +1,19 @@ +// C view of the shared MIT KEMAR set in src-native/common/hrtf_kemar.h. +#import + +#define NSC_HRIR_ELEVATIONS 14 + +#ifdef __cplusplus +extern "C" { +#endif +extern const int NSCHRIRTaps; +extern const double NSCHRIRRate; +extern const int *const NSCHRIRElevation; +// Azimuths per elevation, 360 / NSCHRIRCircle[row] degrees apart from 0 up to 180. +extern const int *const NSCHRIRAzimuthCount; +extern const int *const NSCHRIRCircle; +// Per elevation, then azimuth: NSCHRIRTaps left samples, then NSCHRIRTaps right. +extern const int16_t *const NSCHRIRData; +#ifdef __cplusplus +} +#endif diff --git a/packages/audio-context/platforms/ios/src/NSCHRTFKemar.mm b/packages/audio-context/platforms/ios/src/NSCHRTFKemar.mm new file mode 100644 index 00000000..3e82115c --- /dev/null +++ b/packages/audio-context/platforms/ios/src/NSCHRTFKemar.mm @@ -0,0 +1,11 @@ +#import "NSCHRTFKemar.h" +#include "hrtf_kemar.h" + +static_assert(kemar::kRows == NSC_HRIR_ELEVATIONS, "KEMAR elevation rows"); + +const int NSCHRIRTaps = kemar::kLength; +const double NSCHRIRRate = kemar::kRate; +const int *const NSCHRIRElevation = kemar::kElevation; +const int *const NSCHRIRAzimuthCount = kemar::kAzimuths; +const int *const NSCHRIRCircle = kemar::kCircle; +const int16_t *const NSCHRIRData = kemar::kData; diff --git a/packages/audio-context/platforms/ios/src/NSCIIRFilterNode.h b/packages/audio-context/platforms/ios/src/NSCIIRFilterNode.h index f3c886f1..217f654e 100644 --- a/packages/audio-context/platforms/ios/src/NSCIIRFilterNode.h +++ b/packages/audio-context/platforms/ios/src/NSCIIRFilterNode.h @@ -1,16 +1,15 @@ #import -#import "NSCAudioNode.h" +#import "NSCProcessorNode.h" NS_ASSUME_NONNULL_BEGIN @class NSCAudioContext; -@interface NSCIIRFilterNode : NSCAudioNode +@interface NSCIIRFilterNode : NSCProcessorNode - (instancetype)initWithContext:(NSCAudioContext *)context feedforward:(NSArray *)feedforward - feedback:(NSArray *)feedback NS_DESIGNATED_INITIALIZER; -- (instancetype)initWithContext:(NSCAudioContext *)context node:(nullable AVAudioNode *)node NS_UNAVAILABLE; + feedback:(NSArray *)feedback; - (void)getFrequencyResponse:(NSData *)frequencyHzData magResponse:(NSMutableData *)magResponse diff --git a/packages/audio-context/platforms/ios/src/NSCIIRFilterNode.m b/packages/audio-context/platforms/ios/src/NSCIIRFilterNode.m index 34d33099..4858d6aa 100644 --- a/packages/audio-context/platforms/ios/src/NSCIIRFilterNode.m +++ b/packages/audio-context/platforms/ios/src/NSCIIRFilterNode.m @@ -8,22 +8,56 @@ static inline NSUInteger NSCIIRNormalizeFloatByteOffset(NSInteger byteOffset, NS return offset; } +#define IIR_CHANNELS 8 +#define IIR_ORDER 20 + +// Direct form I: x and y histories per channel, newest first. +typedef struct { + double b[IIR_ORDER], a[IIR_ORDER]; + int nb, na; + double x[IIR_CHANNELS][IIR_ORDER], y[IIR_CHANNELS][IIR_ORDER]; +} IIRState; + @implementation NSCIIRFilterNode { NSArray *_feedforward; NSArray *_feedback; - AVAudioMixerNode *_mixer; + NSMutableData *_state; } - (instancetype)initWithContext:(NSCAudioContext *)context feedforward:(NSArray *)feedforward feedback:(NSArray *)feedback { - AVAudioMixerNode *mixer = [[AVAudioMixerNode alloc] init]; - [context.engine attachNode:mixer]; - if (self = [super initWithContext:context node:mixer]) { - _mixer = mixer; - _feedforward = [feedforward copy]; - _feedback = [feedback copy]; - } + if (!(self = [super initWithContext:context outputChannels:2])) return nil; + _feedforward = [feedforward copy]; + _feedback = [feedback copy]; + _state = [NSMutableData dataWithLength:sizeof(IIRState)]; + IIRState *st = (IIRState *)_state.mutableBytes; + double a0 = feedback.count > 0 ? feedback[0].doubleValue : 1.0; + if (a0 == 0.0) a0 = 1.0; + st->nb = (int)MIN(feedforward.count, (NSUInteger)IIR_ORDER); + st->na = (int)MIN(feedback.count, (NSUInteger)IIR_ORDER); + for (int k = 0; k < st->nb; k++) st->b[k] = feedforward[k].doubleValue / a0; + for (int k = 0; k < st->na; k++) st->a[k] = feedback[k].doubleValue / a0; + NSMutableData *keep = _state; + [self setProcess:^UInt32(int64_t frame, UInt32 frames, float *const *in, UInt32 inChannels, float *const *out, UInt32 outChannels) { + IIRState *s = (IIRState *)keep.mutableBytes; + UInt32 channels = MIN(inChannels, MIN(outChannels, (UInt32)IIR_CHANNELS)); + for (UInt32 c = 0; c < channels; c++) { + double *x = s->x[c], *y = s->y[c]; + for (UInt32 n = 0; n < frames; n++) { + memmove(x + 1, x, (IIR_ORDER - 1) * sizeof(double)); + x[0] = in[c][n]; + double v = 0.0; + for (int k = 0; k < s->nb; k++) v += s->b[k] * x[k]; + for (int k = 1; k < s->na; k++) v -= s->a[k] * y[k - 1]; + if (!isfinite(v)) v = 0.0; + memmove(y + 1, y, (IIR_ORDER - 1) * sizeof(double)); + y[0] = v; + out[c][n] = (float)v; + } + } + return channels; + }]; return self; } @@ -79,6 +113,11 @@ - (void)getFrequencyResponseMagResponsePhaseResponseWithByteOffsets:(NSData *)fr const double twoPiOverSr = 2.0 * M_PI / sr; for (NSInteger i = 0; i < n; ++i) { + if (!(freqs[i] >= 0.0f && freqs[i] <= sr * 0.5)) { + mag[i] = NAN; + phase[i] = NAN; + continue; + } double w = twoPiOverSr * (double)freqs[i]; double numR = 0, numI = 0, denR = 0, denI = 0; for (NSUInteger k = 0; k < ffCount; ++k) { diff --git a/packages/audio-context/platforms/ios/src/NSCParamEffectNode.h b/packages/audio-context/platforms/ios/src/NSCParamEffectNode.h index 0d019eda..9681ffc5 100644 --- a/packages/audio-context/platforms/ios/src/NSCParamEffectNode.h +++ b/packages/audio-context/platforms/ios/src/NSCParamEffectNode.h @@ -12,6 +12,8 @@ typedef NS_ENUM(NSInteger, NSCParamEffectKind) { NSCParamEffectKindDelay = 1, /// params: frequency, Q, gain, detune. NSCParamEffectKindBiquad = 2, + /// params: threshold, knee, ratio, attack, release. + NSCParamEffectKindCompressor = 3, }; /// A node whose inputs sum in a mixer feeding an audio unit that applies its params per frame: @@ -31,6 +33,12 @@ typedef NS_ENUM(NSInteger, NSCParamEffectKind) { /// A delay only: moves the delay's input onto a writer so it can sit in a cycle; the delay then /// reads only earlier render calls, clamping delayTime to at least one call. YES once split. - (BOOL)breakCycle; +/// Undoes breakCycle once the delay is no longer on a cycle. +- (void)healCycle; +@property (nonatomic, readonly) BOOL isSplit; + +/// A compressor: the gain reduction in dB the last render applied. +- (double)meteredReduction; /// The biquad's filter type, read by the render thread. - (void)setFilterType:(NSInteger)type; diff --git a/packages/audio-context/platforms/ios/src/NSCParamEffectNode.m b/packages/audio-context/platforms/ios/src/NSCParamEffectNode.m index 39ec42e3..e34f48a8 100644 --- a/packages/audio-context/platforms/ios/src/NSCParamEffectNode.m +++ b/packages/audio-context/platforms/ios/src/NSCParamEffectNode.m @@ -8,7 +8,7 @@ #define MAX_CHANNELS 32 #define MAX_FRAMES 4096 -#define MAX_PARAMS 4 +#define MAX_PARAMS 5 // Renders a param's inputs into its input block, outputting silence; not a public kind. static const NSCParamEffectKind KindSink = (NSCParamEffectKind)99; @@ -42,6 +42,12 @@ // Biquad: x1, x2, y1, y2 per channel. double *state; _Atomic NSInteger filterType; + // Compressor: the look-ahead line per channel, and the reduction in dB. + float *preDelay; + int lookahead; + int preDelayPos; + double reduction; + _Atomic float meter; // The context's timeline cell (retained). CFTypeRef timelineCell; const double *timeline; @@ -234,6 +240,47 @@ static void ProcessBiquad(EffectRender *r, AUAudioFrameCount frames) { } } +// Chromium's DynamicsCompressorKernel, as on Android: one envelope for every channel, k-rate params. +static double CompressorReduction(double level, double t, double k, double ratio) { + double over = level - t, compressed = level; + if (k > 0.0) { + double half = 0.5 * k; + if (over >= half) compressed = t + over / ratio; + else if (over > -half) compressed = level + (1.0 / ratio - 1.0) * (over + half) * (over + half) / (2.0 * k); + } else if (over > 0.0) { + compressed = t + over / ratio; + } + return MAX(0.0, level - compressed); +} + +static void ProcessCompressor(EffectRender *r, AUAudioFrameCount frames) { + double sr = r->sampleRate; + double t = r->values[0][0], k = MAX(0.0, r->values[1][0]), ratio = MAX(1.0, r->values[2][0]); + double attackCoeff = exp(-1.0 / (MAX(r->values[3][0], 1.0 / sr) * sr)); + double releaseCoeff = exp(-1.0 / (MAX(r->values[4][0], 1.0 / sr) * sr)); + // The spec's makeup gain: 0.6 of the reduction at 0 dB. + double makeup = pow(10.0, 0.6 * CompressorReduction(0.0, t, k, ratio) / 20.0); + int lookahead = r->lookahead; + double current = r->reduction; + for (AUAudioFrameCount f = 0; f < frames; f++) { + double peak = 0.0; + for (UInt32 c = 0; c < r->channels; c++) peak = MAX(peak, fabs((double)r->pulled[c * r->maxFrames + f])); + double target = CompressorReduction(20.0 * log10(MAX(1.0e-12, peak)), t, k, ratio); + double coeff = target > current ? attackCoeff : releaseCoeff; + current = coeff * current + (1.0 - coeff) * target; + float gain = (float)(makeup * pow(10.0, -current / 20.0)); + for (UInt32 c = 0; c < r->channels; c++) { + float *slot = r->preDelay + c * lookahead + r->preDelayPos; + float delayed = *slot; + *slot = r->pulled[c * r->maxFrames + f]; + r->rendered[c * r->maxFrames + f] = delayed * gain; + } + if (++r->preDelayPos == lookahead) r->preDelayPos = 0; + } + r->reduction = current; + atomic_store_explicit(&r->meter, (float)-current, memory_order_relaxed); +} + static void WriteParamInput(EffectRender *r, const AudioTimeStamp *ts, AUAudioFrameCount frames, BOOL silent) { NSCParamInputBlock *in = r->input; if (!in || !ts || !(ts->mFlags & kAudioTimeStampSampleTimeValid)) return; @@ -285,6 +332,11 @@ - (AUAudioUnitBusArray *)inputBusses { return _inputBusses; } - (AUAudioUnitBusArray *)outputBusses { return _outputBusses; } - (BOOL)canProcessInPlace { return NO; } +// Connecting re-sets a bus's format; an allocated unit keeps its channel count. +- (BOOL)shouldChangeToFormat:(AVAudioFormat *)format forBus:(AUAudioUnitBus *)bus { + return !self.renderResourcesAllocated || format.channelCount == bus.format.channelCount; +} + // The delay line outlives render resources: an offline context stops the engine to connect. - (BOOL)allocateRenderResourcesAndReturnError:(NSError **)outError { if (![super allocateRenderResourcesAndReturnError:outError]) return NO; @@ -319,12 +371,22 @@ - (BOOL)allocateRenderResourcesAndReturnError:(NSError **)outError { free(r->state); r->state = calloc((size_t)channels * 4, sizeof(double)); } + if (r->kind == NSCParamEffectKindCompressor) { + int lookahead = MAX(1, (int)lround(0.006 * rate)); + if (!r->preDelay || lookahead != r->lookahead || channels != r->channels) { + free(r->preDelay); + r->preDelay = calloc((size_t)channels * lookahead, sizeof(float)); + r->lookahead = lookahead; + r->preDelayPos = 0; + } + } r->channels = channels; r->sampleRate = rate; r->pullList->mNumberBuffers = channels; for (UInt32 c = 0; c < channels; c++) r->pullList->mBuffers[c].mNumberChannels = 1; if (!r->pulled || !r->rendered || !r->values[MAX_PARAMS - 1]) return NO; if ((r->kind == NSCParamEffectKindDelay && !r->line) || (r->kind == NSCParamEffectKindBiquad && !r->state)) return NO; + if (r->kind == NSCParamEffectKindCompressor && !r->preDelay) return NO; return YES; } @@ -381,6 +443,7 @@ - (AUInternalRenderBlock)internalRenderBlock { if (split && r->line) ProcessSplitDelay(r, (int64_t)llround(frame), frames); else if (r->kind == NSCParamEffectKindDelay && r->line) ProcessDelay(r, frames); else if (r->kind == NSCParamEffectKindBiquad && r->state && r->paramCount == 4) ProcessBiquad(r, frames); + else if (r->kind == NSCParamEffectKindCompressor && r->preDelay && r->paramCount == 5) ProcessCompressor(r, frames); else ProcessGain(r, frames); for (UInt32 c = 0; c < out->mNumberBuffers; c++) { @@ -401,6 +464,7 @@ - (void)dealloc { for (NSInteger p = 0; p < MAX_PARAMS; p++) free(r->values[p]); free(r->line); free(r->state); + free(r->preDelay); free(r->pullList); for (NSInteger p = 0; p < r->paramCount; p++) CFRelease(r->params[p]); if (r->timelineCell) CFRelease(r->timelineCell); @@ -466,20 +530,18 @@ static AudioComponentDescription EffectDescription(void) { NSMutableData *data = [param inputData]; au.render->inputData = CFBridgingRetain(data); au.render->input = (NSCParamInputBlock *)data.mutableBytes; - AVAudioMixerNode *mixer = [[AVAudioMixerNode alloc] init]; if ([context isKindOfClass:[NSCOfflineAudioContext class]]) [(NSCOfflineAudioContext *)context willConnect]; - [engine attachNode:mixer]; [engine attachNode:sink]; - @try { - [engine connect:mixer to:sink format:format]; - } @catch (NSException *e) { - NSCLogError(@"NSCParamEffectNode: the param input did not connect: %@", e); + if (engine.isRunning) NSCEnsureAllocated(sink); + // Audio into a param mixes to mono with the speakers rules. + NSCChannelMixerNode *port = [[NSCChannelMixerNode alloc] initWithContext:context mode:NSCMixModeSum channels:format.channelCount discrete:NO]; + [port setMixChannels:1]; + if (!port || !NSCConnectAdding(context, port.avNode, 0, sink, 0, format)) { [engine detachNode:sink]; - [engine detachNode:mixer]; return nil; } param.inputSink = sink; - param.inputNode = [[NSCAudioNode alloc] initWithContext:context node:mixer]; + param.inputNode = port; return param.inputNode; } @@ -487,15 +549,10 @@ static AudioComponentDescription EffectDescription(void) { @implementation NSCParamEffectNode { AVAudioUnitEffect *_unit; - AVAudioMixerNode *_mixer; - // Connections into this node go to this wrapper of its mixer. - NSCAudioNode *_input; - // clamped-max or explicit: new connections mix to channelCount here first. + // Connections mix here, per channelCount, channelCountMode and channelInterpretation. NSCChannelMixerNode *_port; - NSMutableArray *_ports; - // A delay in a cycle: its input mixer feeds this instead of _unit. + // A delay in a cycle: its input port feeds this instead of _unit, which plays _silence. AVAudioUnitEffect *_writer; - // ...and _unit takes silence, as the engine skips an effect with no input. AVAudioSourceNode *_silence; } @@ -519,16 +576,11 @@ - (instancetype)initWithContext:(NSCAudioContext *)context for (NSCAudioParam *param in params) param.owner = self; AVAudioEngine *engine = context.engine; if ([context isKindOfClass:[NSCOfflineAudioContext class]]) [(NSCOfflineAudioContext *)context willConnect]; - AVAudioMixerNode *mixer = [[AVAudioMixerNode alloc] init]; [engine attachNode:unit]; - [engine attachNode:mixer]; - @try { - [engine connect:mixer to:unit format:format]; - } @catch (NSException *e) { - NSCLogError(@"NSCParamEffectNode: the input mixer did not connect: %@", e); - } - _mixer = mixer; - _input = [[NSCAudioNode alloc] initWithContext:context node:mixer]; + if (engine.isRunning) NSCEnsureAllocated(unit); + _port = [[NSCChannelMixerNode alloc] initWithContext:context mode:NSCMixModeSum channels:format.channelCount discrete:NO]; + if (_port) NSCConnectAdding(context, _port.avNode, 0, unit, 0, format); + [self channelConfigChanged]; return self; } @@ -548,68 +600,76 @@ - (BOOL)breakCycle { wu.render->sharedOwner = CFBridgingRetain(au); if ([context isKindOfClass:[NSCOfflineAudioContext class]]) [(NSCOfflineAudioContext *)context willConnect]; [engine attachNode:writer]; - NSCDisconnectRemoving(context, _mixer, @0, _unit, nil); + if (engine.isRunning) NSCEnsureAllocated(writer); + NSCDisconnectRemoving(context, _port.avNode, @0, _unit, nil); EffectRender *r = au.render; if (r->line) memset(r->line, 0, (size_t)r->channels * (size_t)r->lineLength * sizeof(float)); atomic_store_explicit(&r->split, 1, memory_order_release); - AVAudioSourceNode *silence = [[AVAudioSourceNode alloc] initWithFormat:format renderBlock:^OSStatus(BOOL *isSilence, const AudioTimeStamp *ts, AVAudioFrameCount frames, AudioBufferList *out) { + // The engine skips an effect with no input. + _silence = [[AVAudioSourceNode alloc] initWithFormat:format renderBlock:^OSStatus(BOOL *isSilence, const AudioTimeStamp *ts, AVAudioFrameCount frames, AudioBufferList *out) { for (UInt32 c = 0; c < out->mNumberBuffers; c++) memset(out->mBuffers[c].mData, 0, out->mBuffers[c].mDataByteSize); *isSilence = YES; return noErr; }]; - [engine attachNode:silence]; - NSCConnectAdding(context, silence, 0, _unit, 0, format); - _silence = silence; - NSCConnectAdding(context, _mixer, 0, writer, 0, format); + [engine attachNode:_silence]; + NSCConnectAdding(context, _silence, 0, _unit, 0, format); + NSCConnectAdding(context, _port.avNode, 0, writer, 0, format); // The main mixer pulls the writer every render. NSCConnectAdding(context, writer, 0, main, main.nextAvailableInputBus, format); _writer = writer; return YES; } +// Undoes breakCycle once no path leads from this delay back to its input. +- (void)healCycle { + if (!_writer) return; + NSCAudioContext *context = self.context; + AVAudioEngine *engine = context.engine; + if (!engine || NSCHasPath(engine, _unit, _port.avNode)) return; + AVAudioFormat *format = EffectFormat(context); + NSCParamEffectUnit *au = (NSCParamEffectUnit *)_unit.AUAudioUnit; + NSCDisconnectRemoving(context, _port.avNode, @0, _writer, nil); + @try { [engine disconnectNodeOutput:_writer]; } @catch (NSException *e) {} + @try { [engine disconnectNodeOutput:_silence]; } @catch (NSException *e) {} + [context detachNode:_writer fromEngine:engine]; + [context detachNode:_silence fromEngine:engine]; + _writer = nil; + _silence = nil; + atomic_store_explicit(&au.render->split, 0, memory_order_release); + NSCConnectAdding(context, _port.avNode, 0, _unit, 0, format); +} + +- (BOOL)isSplit { return _writer != nil; } + - (void)setFilterType:(NSInteger)type { NSCParamEffectUnit *au = (NSCParamEffectUnit *)_unit.AUAudioUnit; if ([au isKindOfClass:[NSCParamEffectUnit class]]) atomic_store_explicit(&au.render->filterType, type, memory_order_relaxed); } -// The sink feeds silence into this node's input mixer, so it renders before this unit reads the param. +// The sink renders early in this node's input port, before this unit reads the param. - (void)attachParamSink:(AVAudioNode *)sink { - NSCAudioContext *context = self.context; - AVAudioEngine *engine = context.engine; - if ([context isKindOfClass:[NSCOfflineAudioContext class]]) [(NSCOfflineAudioContext *)context willConnect]; - @try { - [engine connect:sink to:_mixer fromBus:0 toBus:_mixer.nextAvailableInputBus format:EffectFormat(context)]; - } @catch (NSException *e) { - NSCLogError(@"NSCParamEffectNode: the param input did not connect: %@", e); - } + [_port connectEarly:sink format:EffectFormat(self.context)]; } -- (void)channelConfigChanged { - if (self.channelCountMode == 0) { - _port = nil; - return; - } - NSInteger count = MAX(1, MIN(self.channelCount, (NSInteger)8)); - if (!_port || _port.channels != count) { - NSCAudioContext *context = self.context; - NSCChannelMixerNode *port = [[NSCChannelMixerNode alloc] initWithContext:context mode:NSCMixModeSum channels:count discrete:NO]; - if (!port || !NSCConnectAdding(context, port.avNode, 0, _mixer, _mixer.nextAvailableInputBus, EffectFormat(context))) return; - if (!_ports) _ports = [NSMutableArray array]; - [_ports addObject:port]; - _port = port; - } - [_port setDiscrete:self.channelInterpretation == 1]; - [_port setClamp:self.channelCountMode == 1]; +- (double)meteredReduction { + NSCParamEffectUnit *au = (NSCParamEffectUnit *)_unit.AUAudioUnit; + if (![au isKindOfClass:[NSCParamEffectUnit class]]) return 0.0; + return atomic_load_explicit(&au.render->meter, memory_order_relaxed); +} + +- (NSCChannelMixerNode *)channelPort { return _port; } + +- (const _Atomic UInt32 *)logicalChannelCellForOutput:(NSInteger)output { + return [_port mixedChannels]; } // Each connection takes the mixer's next free bus, so inputs sum. - (void)handleConnectFrom:(NSCAudioNode *)source output:(NSNumber *)output input:(NSNumber *)input { - [(_port ?: _input) handleConnectFrom:source output:output input:nil]; + [_port handleConnectFrom:source output:output input:nil]; } - (void)handleDisconnectFrom:(NSCAudioNode *)source output:(NSNumber *)output input:(NSNumber *)input { - [_input handleDisconnectFrom:source output:output input:nil]; - for (NSCChannelMixerNode *port in _ports) [port handleDisconnectFrom:source output:output input:nil]; + [_port handleDisconnectFrom:source output:output input:nil]; } @end diff --git a/packages/audio-context/platforms/ios/src/NSCPeriodicWave.h b/packages/audio-context/platforms/ios/src/NSCPeriodicWave.h index 8e2a0688..2a1984d0 100644 --- a/packages/audio-context/platforms/ios/src/NSCPeriodicWave.h +++ b/packages/audio-context/platforms/ios/src/NSCPeriodicWave.h @@ -1,4 +1,8 @@ #import +#import + +#define NSC_WAVE_TABLE_SIZE 4096 +#define NSC_WAVE_TABLES 12 NS_ASSUME_NONNULL_BEGIN @@ -18,6 +22,25 @@ NS_ASSUME_NONNULL_BEGIN imagByteOffset:(NSInteger)imagByteOffset NS_DESIGNATED_INITIALIZER; - (instancetype)init NS_UNAVAILABLE; +/// A built-in oscillator type's wave: square, sawtooth or triangle. ++ (nullable instancetype)waveForType:(NSString *)type; +/// Band-limited tables: table j holds harmonics up to 2^j; read on the render thread. +- (const float *_Nonnull const *_Nonnull)tables; + @end NS_ASSUME_NONNULL_END + +/// The wave at `phase` (radians, 0 to 2 pi) with no harmonic above `nyquist / frequency`. +static inline float NSCWaveSample(const float *const *tables, double phase, double frequency, double nyquist) { + double limit = fabs(frequency) > 0.0 ? nyquist / fabs(frequency) : 1e9; + int j = limit >= 1.0 ? (int)floor(log2(limit)) : 0; + j = j < 0 ? 0 : (j >= NSC_WAVE_TABLES ? NSC_WAVE_TABLES - 1 : j); + const float *t = tables[j]; + double at = phase / (2.0 * M_PI) * NSC_WAVE_TABLE_SIZE; + int i0 = (int)at; + double f = at - i0; + i0 &= NSC_WAVE_TABLE_SIZE - 1; + int i1 = (i0 + 1) & (NSC_WAVE_TABLE_SIZE - 1); + return (float)(t[i0] + (t[i1] - t[i0]) * f); +} diff --git a/packages/audio-context/platforms/ios/src/NSCPeriodicWave.m b/packages/audio-context/platforms/ios/src/NSCPeriodicWave.m index 56ba707e..54d81eea 100644 --- a/packages/audio-context/platforms/ios/src/NSCPeriodicWave.m +++ b/packages/audio-context/platforms/ios/src/NSCPeriodicWave.m @@ -7,7 +7,86 @@ static inline NSUInteger NSCPeriodicWaveNormalizeFloatByteOffset(NSInteger byteO return offset; } -@implementation NSCPeriodicWave +#import + +@implementation NSCPeriodicWave { + float *_tables[NSC_WAVE_TABLES]; + dispatch_once_t _built; +} + ++ (instancetype)waveForType:(NSString *)type { + static NSMutableDictionary *cache; + static dispatch_once_t once; + dispatch_once(&once, ^{ cache = [NSMutableDictionary dictionary]; }); + @synchronized (cache) { + NSCPeriodicWave *wave = cache[type]; + if (wave) return wave; + // The Fourier series the spec gives for each built-in type. + NSUInteger n = NSC_WAVE_TABLE_SIZE / 2; + NSMutableData *real = [NSMutableData dataWithLength:n * sizeof(float)]; + NSMutableData *imag = [NSMutableData dataWithLength:n * sizeof(float)]; + float *b = (float *)imag.mutableBytes; + for (NSUInteger k = 1; k < n; k++) { + double pk = M_PI * k; + if ([type isEqualToString:@"square"]) b[k] = (float)(k % 2 ? 4.0 / pk : 0.0); + else if ([type isEqualToString:@"sawtooth"]) b[k] = (float)((k % 2 ? 2.0 : -2.0) / pk); + else if ([type isEqualToString:@"triangle"]) b[k] = (float)(8.0 * sin(pk / 2.0) / (pk * pk)); + else return nil; + } + wave = [[NSCPeriodicWave alloc] initWithReal:real imag:imag disableNormalization:NO]; + cache[type] = wave; + return wave; + } +} + +- (const float *const *)tables { + dispatch_once(&_built, ^{ [self buildTables]; }); + return (const float *const *)_tables; +} + +// Inverse DFTs of the coefficients up to each table's harmonic limit, scaled by the full table's peak. +- (void)buildTables { + NSUInteger count = MIN(_real.length, _imag.length) / sizeof(float); + const float *a = (const float *)_real.bytes, *b = (const float *)_imag.bytes; + NSUInteger N = NSC_WAVE_TABLE_SIZE, half = N / 2; + vDSP_DFT_Setup setup = vDSP_DFT_zrop_CreateSetup(NULL, N, vDSP_DFT_INVERSE); + float *re = calloc(half, sizeof(float)), *im = calloc(half, sizeof(float)); + float *ore = calloc(half, sizeof(float)), *oim = calloc(half, sizeof(float)); + float scale = 1.0f; + for (int pass = 0; pass < 2; pass++) { + for (int j = NSC_WAVE_TABLES - 1; j >= 0; j--) { + NSUInteger limit = (NSUInteger)1 << j; + if (pass == 0 && j != NSC_WAVE_TABLES - 1) continue; + memset(re, 0, half * sizeof(float)); + memset(im, 0, half * sizeof(float)); + // x[n] = sum a_k cos + b_k sin: packed so the inverse real DFT returns it. + for (NSUInteger k = 1; k < MIN(count, half) && k <= limit; k++) { + re[k] = a[k]; + im[k] = -b[k]; + } + float *table = _tables[j] ?: (_tables[j] = calloc(N, sizeof(float))); + vDSP_DFT_Execute(setup, re, im, ore, oim); + DSPSplitComplex split = { ore, oim }; + vDSP_ztoc(&split, 1, (DSPComplex *)table, 2, half); + // vDSP's inverse real DFT returns twice the series. + float half_ = 0.5f; + vDSP_vsmul(table, 1, &half_, table, 1, N); + if (pass == 0) { + float peak = 0.0f; + vDSP_maxmgv(table, 1, &peak, N); + scale = !_disableNormalization && peak > 0.0f ? 1.0f / peak : 1.0f; + } else { + vDSP_vsmul(table, 1, &scale, table, 1, N); + } + } + } + free(re); free(im); free(ore); free(oim); + vDSP_DFT_DestroySetup(setup); +} + +- (void)dealloc { + for (int j = 0; j < NSC_WAVE_TABLES; j++) free(_tables[j]); +} - (instancetype)initWithReal:(NSData *)real imag:(NSData *)imag disableNormalization:(BOOL)disableNormalization { return [self initWithReal:real diff --git a/packages/audio-context/platforms/ios/src/NSCProcessorNode.h b/packages/audio-context/platforms/ios/src/NSCProcessorNode.h new file mode 100644 index 00000000..1a42b38f --- /dev/null +++ b/packages/audio-context/platforms/ios/src/NSCProcessorNode.h @@ -0,0 +1,31 @@ +#import +#import +#import +#import "NSCAudioNode.h" + +NS_ASSUME_NONNULL_BEGIN + +@class NSCAudioContext; +@class NSCChannelMixerNode; + +/// Renders `frames` from context frame `frame`: `in` holds the input's own channels (its +/// computedNumberOfChannels), `out` has room for `outChannels`. Returns the channels it wrote. +typedef UInt32 (^NSCProcessBlock)(int64_t frame, UInt32 frames, float *const _Nonnull *_Nonnull in, UInt32 inChannels, float *const _Nonnull *_Nonnull out, UInt32 outChannels); + +/// A node whose inputs mix per its channel config into a block run on the render thread. +@interface NSCProcessorNode : NSCAudioNode + +- (nullable instancetype)initWithContext:(NSCAudioContext *)context outputChannels:(NSInteger)outputChannels NS_DESIGNATED_INITIALIZER; +- (instancetype)initWithContext:(NSCAudioContext *)context node:(nullable AVAudioNode *)node NS_UNAVAILABLE; + +@property (nonatomic, readonly) NSCChannelMixerNode *port; +@property (nonatomic, readonly) NSInteger outputChannels; + +/// Swaps the block the render thread runs. +- (void)setProcess:(NSCProcessBlock)process; +/// Renders even with nothing connected to the output, as an AnalyserNode does. +- (void)keepPulled; + +@end + +NS_ASSUME_NONNULL_END diff --git a/packages/audio-context/platforms/ios/src/NSCProcessorNode.m b/packages/audio-context/platforms/ios/src/NSCProcessorNode.m new file mode 100644 index 00000000..7817e746 --- /dev/null +++ b/packages/audio-context/platforms/ios/src/NSCProcessorNode.m @@ -0,0 +1,271 @@ +#import "NSCProcessorNode.h" +#import +#import "NSCAudioContext.h" +#import "NSCAudioLog.h" +#import "NSCChannelMixerNode.h" + +#define PROC_IN_CHANNELS 8 +#define PROC_MAX_FRAMES 4096 + +typedef struct { + UInt32 maxFrames; + UInt32 outChannels; + float *pulled; + float *outs; + AudioBufferList *abl; + const _Atomic UInt32 *inLogical; + _Atomic UInt32 outLogical; + _Atomic(void *) process; + const double *timeline; + double nextFrame; + double lastSampleTime; + BOOL lastSilent; +} ProcRender; + +static AVAudioFormat *ProcFormat(double rate, NSInteger channels) { + if (channels <= 2) return [[AVAudioFormat alloc] initStandardFormatWithSampleRate:rate channels:(AVAudioChannelCount)MAX(1, channels)]; + AVAudioChannelLayout *layout = [AVAudioChannelLayout layoutWithLayoutTag:kAudioChannelLayoutTag_DiscreteInOrder | (AudioChannelLayoutTag)channels]; + return [[AVAudioFormat alloc] initStandardFormatWithSampleRate:rate channelLayout:layout]; +} + +static AVAudioFormat *pendingIn; +static AVAudioFormat *pendingOut; + +@interface NSCProcessorUnit : AUAudioUnit +@property (nonatomic, readonly) ProcRender *render; +@end + +@implementation NSCProcessorUnit { + AUAudioUnitBusArray *_inputBusses; + AUAudioUnitBusArray *_outputBusses; + ProcRender *_render; +} + +- (instancetype)initWithComponentDescription:(AudioComponentDescription)description options:(AudioComponentInstantiationOptions)options error:(NSError **)outError { + if (!(self = [super initWithComponentDescription:description options:options error:outError])) return nil; + AUAudioUnitBus *input = [[AUAudioUnitBus alloc] initWithFormat:pendingIn error:outError]; + AUAudioUnitBus *output = [[AUAudioUnitBus alloc] initWithFormat:pendingOut error:outError]; + if (!input || !output) return nil; + _inputBusses = [[AUAudioUnitBusArray alloc] initWithAudioUnit:self busType:AUAudioUnitBusTypeInput busses:@[ input ]]; + _outputBusses = [[AUAudioUnitBusArray alloc] initWithAudioUnit:self busType:AUAudioUnitBusTypeOutput busses:@[ output ]]; + _render = calloc(1, sizeof(ProcRender)); + _render->abl = calloc(1, sizeof(AudioBufferList) + (PROC_IN_CHANNELS - 1) * sizeof(AudioBuffer)); + _render->outChannels = pendingOut.channelCount; + _render->lastSampleTime = -1.0; + atomic_init(&_render->outLogical, 1); + self.maximumFramesToRender = PROC_MAX_FRAMES; + return self; +} + +- (AUAudioUnitBusArray *)inputBusses { return _inputBusses; } +- (AUAudioUnitBusArray *)outputBusses { return _outputBusses; } +- (BOOL)canProcessInPlace { return NO; } + +- (BOOL)shouldChangeToFormat:(AVAudioFormat *)format forBus:(AUAudioUnitBus *)bus { + if (bus.busType == AUAudioUnitBusTypeInput) return format.channelCount == PROC_IN_CHANNELS; + return format.channelCount == _render->outChannels; +} + +- (BOOL)allocateRenderResourcesAndReturnError:(NSError **)outError { + if (![super allocateRenderResourcesAndReturnError:outError]) return NO; + ProcRender *r = _render; + UInt32 frames = MAX((UInt32)self.maximumFramesToRender, 128u); + if (frames > r->maxFrames) { + free(r->pulled); + free(r->outs); + r->pulled = calloc((size_t)PROC_IN_CHANNELS * frames, sizeof(float)); + r->outs = calloc((size_t)MAX(r->outChannels, 2u) * frames, sizeof(float)); + r->maxFrames = frames; + } + return r->pulled && r->outs; +} + +- (AUInternalRenderBlock)internalRenderBlock { + ProcRender *r = _render; + return ^AUAudioUnitStatus(AudioUnitRenderActionFlags *flags, const AudioTimeStamp *ts, AUAudioFrameCount frames, NSInteger bus, AudioBufferList *out, const AURenderEvent *events, AURenderPullInputBlock pull) { + if (!r->pulled || frames > r->maxFrames) return kAudioUnitErr_TooManyFramesToProcess; + BOOL timed = ts && (ts->mFlags & kAudioTimeStampSampleTimeValid); + double sampleTime = timed ? ts->mSampleTime : -2.0; + UInt32 C = r->outChannels; + float *outs[16]; + for (UInt32 c = 0; c < C && c < 16; c++) outs[c] = r->outs + c * r->maxFrames; + // A repeated pull for the same timestamp (fan-out) plays what the first rendered. + if (sampleTime < 0.0 || sampleTime != r->lastSampleTime) { + AudioBufferList *abl = r->abl; + abl->mNumberBuffers = PROC_IN_CHANNELS; + for (UInt32 c = 0; c < PROC_IN_CHANNELS; c++) { + abl->mBuffers[c].mNumberChannels = 1; + abl->mBuffers[c].mData = r->pulled + c * r->maxFrames; + abl->mBuffers[c].mDataByteSize = frames * sizeof(float); + } + AudioUnitRenderActionFlags pullFlags = 0; + OSStatus status = pull ? pull(&pullFlags, ts, frames, 0, abl) : kAudioUnitErr_NoConnection; + BOOL silent = status != noErr || (pullFlags & kAudioUnitRenderAction_OutputIsSilence); + float *ins[PROC_IN_CHANNELS]; + for (UInt32 c = 0; c < PROC_IN_CHANNELS; c++) { + float *mine = r->pulled + c * r->maxFrames; + if (silent || !abl->mBuffers[c].mData) memset(mine, 0, frames * sizeof(float)); + else if (abl->mBuffers[c].mData != mine) memcpy(mine, abl->mBuffers[c].mData, frames * sizeof(float)); + ins[c] = mine; + } + UInt32 inChannels = r->inLogical ? atomic_load_explicit(r->inLogical, memory_order_acquire) : 1; + inChannels = MAX(1u, MIN(inChannels, (UInt32)PROC_IN_CHANNELS)); + double frame = timed ? NSCContextFrame(ts->mSampleTime, r->timeline) : r->nextFrame; + r->nextFrame = frame + frames; + for (UInt32 c = 0; c < C; c++) memset(outs[c], 0, frames * sizeof(float)); + NSCProcessBlock process = (__bridge NSCProcessBlock)atomic_load_explicit(&r->process, memory_order_acquire); + UInt32 wrote = process ? process((int64_t)llround(frame), frames, ins, inChannels, outs, C) : 0; + if (!process) { + for (UInt32 c = 0; c < MIN(inChannels, C); c++) memcpy(outs[c], ins[c], frames * sizeof(float)); + wrote = MIN(inChannels, C); + } + wrote = MAX(1u, MIN(wrote, C)); + // Up-mix a mono result to the bus with the speakers rule; a wider bus gets silence. + if (wrote == 1 && C == 2) memcpy(outs[1], outs[0], frames * sizeof(float)); + atomic_store_explicit(&r->outLogical, wrote, memory_order_release); + r->lastSampleTime = sampleTime; + } + for (UInt32 c = 0; c < out->mNumberBuffers; c++) { + float *from = outs[MIN(c, C - 1)]; + if (out->mBuffers[c].mData) memcpy(out->mBuffers[c].mData, from, frames * sizeof(float)); + else out->mBuffers[c].mData = from; + out->mBuffers[c].mDataByteSize = frames * sizeof(float); + } + return noErr; + }; +} + +- (void)dealloc { + ProcRender *r = _render; + if (!r) return; + void *process = atomic_load(&r->process); + if (process) CFRelease(process); + free(r->pulled); + free(r->outs); + free(r->abl); + free(r); +} + +@end + +static AudioComponentDescription ProcDescription(void) { + AudioComponentDescription description = {0}; + description.componentType = kAudioUnitType_Effect; + description.componentSubType = 'nscx'; + description.componentManufacturer = 'NSCa'; + return description; +} + +@implementation NSCProcessorNode { + AVAudioUnitEffect *_unit; + NSCChannelMixerNode *_port; + // Pulls the unit each quantum without playing it. + NSCChannelMixerNode *_drain; + NSMutableArray *_retired; + NSMutableData *_timelineKeep; +} + +- (instancetype)initWithContext:(NSCAudioContext *)context outputChannels:(NSInteger)outputChannels { + static dispatch_once_t once; + dispatch_once(&once, ^{ + [AUAudioUnit registerSubclass:[NSCProcessorUnit class] asComponentDescription:ProcDescription() name:@"NativeScript: processor" version:1]; + }); + double rate = context.sampleRate > 0 ? context.sampleRate : 44100.0; + outputChannels = MAX(1, MIN(outputChannels, (NSInteger)16)); + AVAudioFormat *inFormat = ProcFormat(rate, PROC_IN_CHANNELS); + pendingIn = inFormat; + pendingOut = ProcFormat(rate, outputChannels); + // A registered in-process unit instantiates synchronously. + AVAudioUnitEffect *unit = [[AVAudioUnitEffect alloc] initWithAudioComponentDescription:ProcDescription()]; + pendingIn = nil; + pendingOut = nil; + NSCProcessorUnit *au = (NSCProcessorUnit *)unit.AUAudioUnit; + if (![au isKindOfClass:[NSCProcessorUnit class]]) { + NSCLogError(@"NSCProcessorNode: could not instantiate the processor audio unit"); + return nil; + } + NSCChannelMixerNode *port = [[NSCChannelMixerNode alloc] initWithContext:context mode:NSCMixModeSum channels:PROC_IN_CHANNELS discrete:NO]; + if (!port) return nil; + if ([context isKindOfClass:[NSCOfflineAudioContext class]]) [(NSCOfflineAudioContext *)context willConnect]; + @try { [context.engine attachNode:unit]; } @catch (NSException *e) { return nil; } + if (context.engine.isRunning) NSCEnsureAllocated(unit); + if (!(self = [super initWithContext:context node:unit])) return nil; + _unit = unit; + _port = port; + _outputChannels = outputChannels; + _retired = [NSMutableArray array]; + _timelineKeep = context.timelineCell; + au.render->inLogical = [port mixedChannels]; + au.render->timeline = (const double *)_timelineKeep.bytes; + NSCConnectAdding(context, port.avNode, 0, unit, 0, inFormat); + [self channelConfigChanged]; + return self; +} + +- (ProcRender *)render { + return ((NSCProcessorUnit *)_unit.AUAudioUnit).render; +} + +- (void)setProcess:(NSCProcessBlock)process { + ProcRender *r = [self render]; + if (!r) return; + id copied = [process copy]; + void *old = atomic_exchange(&r->process, copied ? (void *)CFBridgingRetain(copied) : NULL); + // The render thread may still be running the old block. + if (old) [_retired addObject:CFBridgingRelease(old)]; +} + +- (NSCChannelMixerNode *)channelPort { return _port; } + +- (const _Atomic UInt32 *)logicalChannelCellForOutput:(NSInteger)output { + ProcRender *r = [self render]; + return r ? &r->outLogical : NULL; +} + +- (void)handleConnectFrom:(NSCAudioNode *)source output:(NSNumber *)output input:(NSNumber *)input { + [_port handleConnectFrom:source output:output input:nil]; +} + +- (void)handleDisconnectFrom:(NSCAudioNode *)source output:(NSNumber *)output input:(NSNumber *)input { + [_port handleDisconnectFrom:source output:output input:nil]; +} + +// Param inputs render before this node reads its params. +- (void)attachParamSink:(AVAudioNode *)sink { + [_port connectEarly:sink format:self.context.format]; +} + +- (void)keepPulled { + NSCAudioContext *ctx = self.context; + AVAudioEngine *engine = ctx.engine; + if (!engine) return; + if (!_drain) { + _drain = [[NSCChannelMixerNode alloc] initWithContext:ctx mode:NSCMixModeSum channels:1 discrete:NO]; + AVAudioMixerNode *main = engine.mainMixerNode; + if (!_drain || !NSCConnectAdding(ctx, _drain.avNode, 0, main, main.nextAvailableInputBus, ctx.format)) return; + } + [_drain connectEarly:_unit format:[_unit outputFormatForBus:0]]; +} + +- (void)disconnect { + [super disconnect]; + if (_drain) [self keepPulled]; +} + +- (void)disconnectOutput:(NSNumber *)output { + [super disconnectOutput:output]; + if (_drain) [self keepPulled]; +} + +- (void)detachHelpers { + NSCAudioContext *ctx = self.context; + AVAudioEngine *engine = ctx.engine; + if (!engine) return; + for (AVAudioNode *node in @[ _unit ?: (id)[NSNull null], _drain.avNode ?: (id)[NSNull null] ]) { + if ((id)node == [NSNull null] || ![ctx isNode:node attachedToEngine:engine]) continue; + @try { [engine disconnectNodeOutput:node]; } @catch (NSException *e) {} + @try { [ctx detachNode:node fromEngine:engine]; } @catch (NSException *e) {} + } +} + +@end diff --git a/packages/audio-context/platforms/ios/src/NSCStereoPannerNode.h b/packages/audio-context/platforms/ios/src/NSCStereoPannerNode.h index 47abb191..0d10689b 100644 --- a/packages/audio-context/platforms/ios/src/NSCStereoPannerNode.h +++ b/packages/audio-context/platforms/ios/src/NSCStereoPannerNode.h @@ -1,18 +1,17 @@ #import #import -#import "NSCAudioNode.h" +#import "NSCProcessorNode.h" #import "NSCAudioParam.h" NS_ASSUME_NONNULL_BEGIN @class NSCAudioContext; -@interface NSCStereoPannerNode : NSCAudioNode +@interface NSCStereoPannerNode : NSCProcessorNode @property (nonatomic, readonly) NSCAudioParam *panParam; -- (instancetype)initWithContext:(NSCAudioContext *)context pan:(double)pan NS_DESIGNATED_INITIALIZER; -- (instancetype)initWithContext:(NSCAudioContext *)context node:(nullable AVAudioNode *)node NS_UNAVAILABLE; +- (instancetype)initWithContext:(NSCAudioContext *)context pan:(double)pan; @end diff --git a/packages/audio-context/platforms/ios/src/NSCStereoPannerNode.m b/packages/audio-context/platforms/ios/src/NSCStereoPannerNode.m index 3e1cd748..0d28be2e 100644 --- a/packages/audio-context/platforms/ios/src/NSCStereoPannerNode.m +++ b/packages/audio-context/platforms/ios/src/NSCStereoPannerNode.m @@ -1,127 +1,38 @@ -#import #import "NSCAudioContext.h" -@implementation NSCStereoPannerNode { - dispatch_source_t _automationTimer; - CFTimeInterval _automationAnchorHostTime; - double _automationAnchorAudioTime; - BOOL _automationUsesHostTime; -} +// Web Audio's equal-power stereo panning, with pan read per frame. +@implementation NSCStereoPannerNode - (instancetype)initWithContext:(NSCAudioContext *)context pan:(double)pan { - AVAudioMixerNode *mixer = [[AVAudioMixerNode alloc] init]; - [context.engine attachNode:mixer]; - if (self = [super initWithContext:context node:mixer]) { - mixer.pan = (float)MAX(-1.0, MIN(1.0, pan)); - _panParam = [[NSCAudioParam alloc] initWithContext:context defaultValue:pan]; - _panParam.owner = self; - _automationAnchorHostTime = 0; - _automationAnchorAudioTime = 0.0; - _automationUsesHostTime = NO; - - __weak typeof(self) weakSelf = self; - void (^hook)(NSCAudioParam *) = ^(NSCAudioParam *p) { - __strong typeof(weakSelf) s = weakSelf; - if (!s) return; - double now = s.context ? s.context.currentTime : 0.0; - double v = [p valueAtTime:now]; - if (v < -1.0) v = -1.0; - if (v > 1.0) v = 1.0; - ((AVAudioMixerNode *)s.avNode).pan = (float)v; - [s ensureAutomationLink]; - }; - _panParam.onScheduleChanged = hook; - double init = _panParam.value; - mixer.pan = (float)MAX(-1.0, MIN(1.0, init)); - } + if (!(self = [super initWithContext:context outputChannels:2])) return nil; + NSCAudioParam *param = [[NSCAudioParam alloc] initWithContext:context defaultValue:pan]; + _panParam = param; + param.owner = self; + double rate = context.sampleRate; + [self setProcess:^UInt32(int64_t frame, UInt32 frames, float *const *in, UInt32 inChannels, float *const *out, UInt32 outChannels) { + double p[frames]; + BOOL automated = [param fillValuesFromFrame:(double)frame sampleRate:rate frameCount:frames into:p]; + BOOL mono = inChannels == 1; + for (UInt32 k = 0; k < frames; k++) { + double v = automated ? p[k] : p[0]; + v = isfinite(v) ? MAX(-1.0, MIN(1.0, v)) : 0.0; + if (mono) { + double x = (v + 1.0) * 0.5; + out[0][k] = in[0][k] * (float)cos(x * M_PI_2); + out[1][k] = in[0][k] * (float)sin(x * M_PI_2); + } else if (v <= 0.0) { + double x = v + 1.0; + out[0][k] = in[0][k] + in[1][k] * (float)cos(x * M_PI_2); + out[1][k] = in[1][k] * (float)sin(x * M_PI_2); + } else { + double x = v; + out[0][k] = in[0][k] * (float)cos(x * M_PI_2); + out[1][k] = in[1][k] + in[0][k] * (float)sin(x * M_PI_2); + } + } + return 2; + }]; return self; } -- (double)currentTimeForApply { - NSCAudioContext *ctx = self.context; - double t = ctx ? ctx.currentTime : 0.0; - if (t > 0.0) { - _automationUsesHostTime = NO; - _automationAnchorHostTime = CACurrentMediaTime(); - _automationAnchorAudioTime = t; - return t; - } - - if (!_automationTimer) return t; - - double hostNow = CACurrentMediaTime(); - if (!_automationUsesHostTime) { - _automationUsesHostTime = YES; - _automationAnchorHostTime = hostNow; - _automationAnchorAudioTime = 0.0; - return 0.0; - } - - double synthetic = _automationAnchorAudioTime + (hostNow - _automationAnchorHostTime); - return synthetic >= 0.0 ? synthetic : 0.0; -} - -- (BOOL)hasFutureAutomation { - double t = [self currentTimeForApply]; - return [_panParam hasEventsAfter:t]; -} - -- (void)ensureAutomationLink { - if (![NSThread isMainThread]) { - __weak typeof(self) weakSelf = self; - dispatch_async(dispatch_get_main_queue(), ^{ [weakSelf ensureAutomationLink]; }); - return; - } - if (_automationTimer) return; - if (![self hasFutureAutomation]) return; - dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue()); - uint64_t intervalNs = (uint64_t)(NSEC_PER_SEC / 60.0); - uint64_t leewayNs = (uint64_t)(NSEC_PER_SEC / 240.0); - NSCAudioContext *ctx = self.context; - double now = ctx ? ctx.currentTime : 0.0; - if (now <= 0.0) { - _automationUsesHostTime = YES; - _automationAnchorHostTime = CACurrentMediaTime(); - _automationAnchorAudioTime = 0.0; - } else { - _automationUsesHostTime = NO; - _automationAnchorHostTime = CACurrentMediaTime(); - _automationAnchorAudioTime = now; - } - dispatch_source_set_timer(timer, dispatch_time(DISPATCH_TIME_NOW, 0), intervalNs, leewayNs); - __weak typeof(self) weakSelf = self; - dispatch_source_set_event_handler(timer, ^{ - __strong typeof(weakSelf) s = weakSelf; - if (!s) return; - double t = [s currentTimeForApply]; - double v = [s.panParam valueAtTime:t]; - if (v < -1.0) v = -1.0; - if (v > 1.0) v = 1.0; - ((AVAudioMixerNode *)s.avNode).pan = (float)v; - if (![s hasFutureAutomation]) [s stopAutomationLink]; - }); - _automationTimer = timer; - dispatch_resume(timer); -} - -- (void)stopAutomationLink { - if (_automationTimer) { - dispatch_source_cancel(_automationTimer); - _automationTimer = nil; - } - _automationUsesHostTime = NO; - _automationAnchorHostTime = 0; - _automationAnchorAudioTime = 0.0; -} - -- (void)attachParamSink:(AVAudioNode *)sink { - [super attachParamSink:sink]; - [self ensureAutomationLink]; -} - -- (void)applyAutomation { - double v = [_panParam valueAtTime:[self currentTimeForApply]]; - ((AVAudioMixerNode *)self.avNode).pan = (float)MAX(-1.0, MIN(1.0, v)); -} - @end diff --git a/packages/audio-context/platforms/ios/src/NSCWaveShaperNode.h b/packages/audio-context/platforms/ios/src/NSCWaveShaperNode.h index 8bdc37cb..006f2c45 100644 --- a/packages/audio-context/platforms/ios/src/NSCWaveShaperNode.h +++ b/packages/audio-context/platforms/ios/src/NSCWaveShaperNode.h @@ -1,16 +1,15 @@ #import -#import "NSCAudioNode.h" +#import "NSCProcessorNode.h" NS_ASSUME_NONNULL_BEGIN @class NSCAudioContext; -@interface NSCWaveShaperNode : NSCAudioNode +@interface NSCWaveShaperNode : NSCProcessorNode @property (nonatomic, copy) NSString *oversample; // "none" | "2x" | "4x" -- (instancetype)initWithContext:(NSCAudioContext *)context NS_DESIGNATED_INITIALIZER; -- (instancetype)initWithContext:(NSCAudioContext *)context node:(nullable AVAudioNode *)node NS_UNAVAILABLE; +- (instancetype)initWithContext:(NSCAudioContext *)context; - (void)setCurveFromData:(nullable NSData *)floatData; - (void)setCurveFromDataWithByteOffset:(nullable NSData *)floatData :(NSInteger)byteOffset; diff --git a/packages/audio-context/platforms/ios/src/NSCWaveShaperNode.m b/packages/audio-context/platforms/ios/src/NSCWaveShaperNode.m index e0779fbd..840a0775 100644 --- a/packages/audio-context/platforms/ios/src/NSCWaveShaperNode.m +++ b/packages/audio-context/platforms/ios/src/NSCWaveShaperNode.m @@ -1,4 +1,8 @@ #import "NSCAudioContext.h" +#import + +#define WS_CHANNELS 8 +#define WS_TAPS 32 static inline NSUInteger NSCWaveShaperNormalizeFloatByteOffset(NSInteger byteOffset, NSUInteger length) { NSUInteger offset = byteOffset > 0 ? (NSUInteger)byteOffset : 0; @@ -7,33 +11,118 @@ static inline NSUInteger NSCWaveShaperNormalizeFloatByteOffset(NSInteger byteOff return offset; } +// One 2x resampling stage: a windowed-sinc half-band low-pass, with history per channel. +typedef struct { + float up[WS_CHANNELS][WS_TAPS]; + float down[WS_CHANNELS][WS_TAPS]; +} WSStage; + +typedef struct { + // A curve: its length in the first 4 bytes, then the floats from byte 16. + _Atomic(const void *) curve; + _Atomic int oversample; + WSStage stages[2]; + float kernel[WS_TAPS]; +} WSState; + +static void MakeKernel(float *k) { + double sum = 0.0; + for (int i = 0; i < WS_TAPS; i++) { + double n = i - (WS_TAPS - 1) / 2.0; + double sinc = n == 0.0 ? 1.0 : sin(M_PI * n * 0.5) / (M_PI * n * 0.5); + double w = 0.42 - 0.5 * cos(2 * M_PI * i / (WS_TAPS - 1)) + 0.08 * cos(4 * M_PI * i / (WS_TAPS - 1)); + k[i] = (float)(sinc * w); + sum += k[i]; + } + for (int i = 0; i < WS_TAPS; i++) k[i] = (float)(k[i] / sum); +} + +static float Fir(float *hist, const float *k, float x) { + memmove(hist, hist + 1, (WS_TAPS - 1) * sizeof(float)); + hist[WS_TAPS - 1] = x; + float y = 0.0f; + for (int i = 0; i < WS_TAPS; i++) y += hist[i] * k[i]; + return y; +} + +static float Shape(const float *curve, UInt32 n, float x) { + if (!curve || n == 0) return x; + double v = (n - 1) * 0.5 * ((double)x + 1.0); + if (!(v > 0.0)) return curve[0]; + if (v >= n - 1) return curve[n - 1]; + UInt32 k = (UInt32)v; + double f = v - k; + return (float)((1.0 - f) * curve[k] + f * curve[k + 1]); +} + +// Up-samples x by 2^level, shapes, and down-samples back. +static float ShapeOversampled(WSState *s, int level, int c, const float *curve, UInt32 n, float x) { + if (level == 0) return Shape(curve, n, x); + WSStage *st = &s->stages[level - 1]; + float a = Fir(st->up[c], s->kernel, 2.0f * x); + float b = Fir(st->up[c], s->kernel, 0.0f); + float ya = ShapeOversampled(s, level - 1, c, curve, n, a); + float yb = ShapeOversampled(s, level - 1, c, curve, n, b); + Fir(st->down[c], s->kernel, ya); + return Fir(st->down[c], s->kernel, yb); +} + @implementation NSCWaveShaperNode { - AVAudioMixerNode *_mixer; + NSMutableData *_state; NSData *_curve; + NSMutableArray *_curves; } - (instancetype)initWithContext:(NSCAudioContext *)context { - - AVAudioMixerNode *mixer = [[AVAudioMixerNode alloc] init]; - [context.engine attachNode:mixer]; - if (self = [super initWithContext:context node:mixer]) { - _mixer = mixer; - _oversample = @"none"; - } + if (!(self = [super initWithContext:context outputChannels:2])) return nil; + _oversample = @"none"; + _curves = [NSMutableArray array]; + _state = [NSMutableData dataWithLength:sizeof(WSState)]; + WSState *s = (WSState *)_state.mutableBytes; + MakeKernel(s->kernel); + NSMutableData *keep = _state; + [self setProcess:^UInt32(int64_t frame, UInt32 frames, float *const *in, UInt32 inChannels, float *const *out, UInt32 outChannels) { + WSState *st = (WSState *)keep.mutableBytes; + const void *packed = atomic_load_explicit(&st->curve, memory_order_acquire); + UInt32 n = packed ? *(const UInt32 *)packed : 0; + const float *curve = packed ? (const float *)((const uint8_t *)packed + 16) : NULL; + int level = atomic_load_explicit(&st->oversample, memory_order_relaxed); + UInt32 channels = MIN(inChannels, MIN(outChannels, (UInt32)WS_CHANNELS)); + for (UInt32 c = 0; c < channels; c++) { + for (UInt32 k = 0; k < frames; k++) out[c][k] = curve ? ShapeOversampled(st, level, (int)c, curve, n, in[c][k]) : in[c][k]; + } + return channels; + }]; return self; } +- (void)setOversample:(NSString *)oversample { + _oversample = [oversample isEqualToString:@"2x"] || [oversample isEqualToString:@"4x"] ? [oversample copy] : @"none"; + WSState *s = (WSState *)_state.mutableBytes; + int level = [_oversample isEqualToString:@"4x"] ? 2 : [_oversample isEqualToString:@"2x"] ? 1 : 0; + atomic_store(&s->oversample, level); +} + - (void)setCurveFromData:(NSData *)floatData { [self setCurveFromDataWithByteOffset:floatData :0]; } - (void)setCurveFromDataWithByteOffset:(NSData *)floatData :(NSInteger)byteOffset { + WSState *s = (WSState *)_state.mutableBytes; if (!floatData) { _curve = nil; + atomic_store(&s->curve, NULL); return; } NSUInteger offsetBytes = NSCWaveShaperNormalizeFloatByteOffset(byteOffset, floatData.length); - _curve = [floatData subdataWithRange:NSMakeRange(offsetBytes, floatData.length - offsetBytes)]; + NSData *curve = [floatData subdataWithRange:NSMakeRange(offsetBytes, floatData.length - offsetBytes)]; + _curve = curve; + NSMutableData *packed = [NSMutableData dataWithLength:16]; + *(UInt32 *)packed.mutableBytes = (UInt32)(curve.length / sizeof(float)); + [packed appendData:curve]; + // The render thread may still read an earlier curve. + [_curves addObject:packed]; + atomic_store(&s->curve, packed.bytes); } - (NSData *)curve { return _curve; } diff --git a/packages/audio-context/project.json b/packages/audio-context/project.json index 03b43220..15a29604 100644 --- a/packages/audio-context/project.json +++ b/packages/audio-context/project.json @@ -21,6 +21,11 @@ "input": "packages/audio-context/platforms/", "output": "./platforms/" }, + { + "glob": "**/*", + "input": "packages/audio-context/src-native/common/", + "output": "./src-native/common/" + }, { "glob": "Package.swift", "input": "nativescript-v8/", diff --git a/packages/audio-context/src-native/android/audiocontext/src/main/cpp/CMakeLists.txt b/packages/audio-context/src-native/android/audiocontext/src/main/cpp/CMakeLists.txt index bf88b45a..af1bdfc2 100644 --- a/packages/audio-context/src-native/android/audiocontext/src/main/cpp/CMakeLists.txt +++ b/packages/audio-context/src-native/android/audiocontext/src/main/cpp/CMakeLists.txt @@ -38,6 +38,8 @@ target_include_directories(native-audio PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/thir find_library(log-lib log) target_include_directories(native-audio PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}) +# Shared with the iOS plugin (hrtf_kemar.h). +target_include_directories(native-audio PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../../../../../common) if (HAS_OBOE) target_link_libraries(native-audio PRIVATE oboe ${log-lib} android) diff --git a/packages/audio-context/src-native/android/audiocontext/src/main/cpp/audio_context.cpp b/packages/audio-context/src-native/android/audiocontext/src/main/cpp/audio_context.cpp index f3be9aee..992f867e 100644 --- a/packages/audio-context/src-native/android/audiocontext/src/main/cpp/audio_context.cpp +++ b/packages/audio-context/src-native/android/audiocontext/src/main/cpp/audio_context.cpp @@ -2,6 +2,7 @@ #include "audio_internal.h" #include +#include namespace { @@ -91,45 +92,172 @@ static inline double defaultListenerParamValueForType(int paramType) { } void NativeEngine::registerContextStart(const std::string &contextId, int64_t startNanos) { - std::lock_guard lock(contextMutex_); - contextStartNanos_[contextId] = startNanos; + auto clock = std::make_shared(); + clock->baseNs = startNanos; + { + std::lock_guard lock(contextMutex_); + contextClocks_[contextId] = clock; + } + if (offline_) return; + // Held at 0 until the first quantum it renders. + clock->pausedAtNs.store(startNanos, std::memory_order_relaxed); + Command cmd; + cmd.type = CMD_CONTEXT_START; + cmd.clock = clock; + enqueueCommand(std::move(cmd)); } void NativeEngine::unregisterContextStart(const std::string &contextId) { std::lock_guard lock(contextMutex_); - contextStartNanos_.erase(contextId); + auto it = contextClocks_.find(contextId); + if (it == contextClocks_.end()) return; + const auto clock = it->second; + contextClocks_.erase(it); + for (auto n = nodeClocks_.begin(); n != nodeClocks_.end();) { + if (n->second == clock) n = nodeClocks_.erase(n); + else ++n; + } + clocksDirty_.store(true, std::memory_order_release); +} + +void NativeEngine::setNodeContext(const std::string &id, const std::string &contextId) { + std::lock_guard lock(contextMutex_); + auto it = contextClocks_.find(contextId); + if (it == contextClocks_.end()) return; + nodeClocks_[id] = it->second; + clocksDirty_.store(true, std::memory_order_release); +} + +void NativeEngine::forgetNode(const std::string &id) { + { + std::lock_guard lock(contextMutex_); + if (nodeClocks_.erase(id)) clocksDirty_.store(true, std::memory_order_release); + } + std::lock_guard lock(scheduledEventsMutex_); + paramSlots_.erase(id); +} + +void NativeEngine::suspendContext(const std::string &contextId) { + std::shared_ptr clock; + bool all = true; + { + std::lock_guard lock(contextMutex_); + auto it = contextClocks_.find(contextId); + if (it == contextClocks_.end() || it->second->suspended) return; + clock = it->second; + clock->suspended = true; + for (const auto &kv: contextClocks_) all = all && kv.second->suspended; + } + if (offline_) return; + Command cmd; + cmd.type = CMD_CONTEXT_SUSPEND; + cmd.clock = clock; + enqueueCommand(std::move(cmd)); +#ifdef HAS_OBOE + // Resolves once the render thread has taken the suspend, so currentTime has stopped. + for (int i = 0; i < 250; i++) { + { + std::lock_guard cl(commandMutex_); + if (pendingCommands_.empty()) break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } + if (!all) return; + std::lock_guard lock(mutex_); + stopStream(); +#endif +} + +void NativeEngine::resumeContext(const std::string &contextId) { + std::shared_ptr clock; + { + std::lock_guard lock(contextMutex_); + auto it = contextClocks_.find(contextId); + if (it == contextClocks_.end()) return; + clock = it->second; + clock->suspended = false; + } + if (offline_) return; + Command cmd; + cmd.type = CMD_CONTEXT_RESUME; + cmd.clock = clock; + enqueueCommand(std::move(cmd)); +#ifdef HAS_OBOE + std::lock_guard lock(mutex_); + ensureStream(); +#endif +} + +int64_t NativeEngine::callNowNs(const std::string &id) { + const int64_t now = nowNs_.load(std::memory_order_relaxed); + if (offline_) return now; + std::lock_guard lock(contextMutex_); + auto it = nodeClocks_.find(id); + const ContextClock *clock = nullptr; + if (it != nodeClocks_.end()) clock = it->second.get(); + else { + auto c = contextClocks_.find(id); + if (c != contextClocks_.end()) clock = c->second.get(); + } + if (!clock) return now; + const int64_t paused = clock->pausedAtNs.load(std::memory_order_relaxed); + return (paused != 0 ? paused : now) - clock->offsetNs.load(std::memory_order_relaxed); +} + +double NativeEngine::paramComputedValue(const std::string &id, int type) { + std::lock_guard lock(scheduledEventsMutex_); + auto &slots = paramSlots_[id]; + for (const auto &slot: slots) { + if (slot->type == type) return slot->value.load(std::memory_order_relaxed); + } + slots.push_back(std::make_unique(type, std::numeric_limits::quiet_NaN())); + return std::numeric_limits::quiet_NaN(); +} + +void NativeEngine::holdParamValue(const std::string &id, int type, double value) { + std::lock_guard lock(scheduledEventsMutex_); + auto it = paramSlots_.find(id); + if (it == paramSlots_.end()) return; + for (const auto &slot: it->second) { + if (slot->type != type) continue; + slot->value.store(value, std::memory_order_relaxed); + slot->holdNs.store(nowNs_.load(std::memory_order_relaxed), std::memory_order_relaxed); + } } void NativeEngine::scheduleGainEvent(const std::string &gainId, int type, int rate, double value, int64_t timeNs) { + const int64_t callNs = callNowNs(gainId); std::lock_guard lock(scheduledEventsMutex_); auto &vec = scheduledGainEvents_[gainId]; ParamEvent ev{type, rate, timeNs, value}; - ev.callNs = nowNs_.load(std::memory_order_relaxed); + ev.callNs = callNs; insertSortedByTime(vec, ev); } void NativeEngine::schedulePannerEvent(const std::string &pannerId, int paramType, int type, int rate, double value, int64_t timeNs) { + const int64_t callNs = callNowNs(pannerId); std::lock_guard lock(scheduledEventsMutex_); auto &map = scheduledPannerEvents_[pannerId]; auto &vec = map[paramType]; ParamEvent ev{type, rate, timeNs, value}; - ev.callNs = nowNs_.load(std::memory_order_relaxed); + ev.callNs = callNs; insertSortedByTime(vec, ev); } void NativeEngine::scheduleListenerEvent(const std::string &contextId, int paramType, int type, int rate, double value, int64_t timeNs) { + const int64_t callNs = callNowNs(contextId); std::lock_guard lock(scheduledEventsMutex_); auto &map = scheduledListenerEvents_[contextId]; auto &vec = map[paramType]; ParamEvent ev{type, rate, timeNs, value}; - ev.callNs = nowNs_.load(std::memory_order_relaxed); + ev.callNs = callNs; insertSortedByTime(vec, ev); } @@ -146,7 +274,7 @@ std::shared_ptr> NativeEngine::compressorMeter(const std::str void NativeEngine::scheduleParamEvent(int target, const std::string &id, int paramType, const ParamEvent &e) { ParamEvent event = e; - event.callNs = nowNs_.load(std::memory_order_relaxed); + event.callNs = callNowNs(id); std::lock_guard lock(scheduledEventsMutex_); if (target == 0) insertSortedByTime(scheduledGainEvents_[id], event); else if (target == 1) insertSortedByTime(scheduledPannerEvents_[id][paramType], event); @@ -386,17 +514,15 @@ NativeEngine::getIIRCoefficients(const std::string &iirId) { } int64_t NativeEngine::getContextCurrentTimeNanos(const std::string &contextId) { + std::lock_guard lock(contextMutex_); + auto it = contextClocks_.find(contextId); + if (it == contextClocks_.end()) return 0; + const ContextClock &clock = *it->second; int64_t audioNs = offline_ ? nowNs_.load(std::memory_order_relaxed) : g_audioTimeNanos.load(std::memory_order_relaxed); - if (audioNs == 0) { - audioNs = std::chrono::duration_cast( - std::chrono::steady_clock::now().time_since_epoch()).count(); - } - std::lock_guard lock(contextMutex_); - auto it = contextStartNanos_.find(contextId); - if (it == contextStartNanos_.end()) return 0; - int64_t startNs = it->second; - int64_t diff = audioNs - startNs; + const int64_t paused = clock.pausedAtNs.load(std::memory_order_relaxed); + if (paused != 0) audioNs = paused; + const int64_t diff = audioNs - clock.offsetNs.load(std::memory_order_relaxed) - clock.baseNs; return diff < 0 ? 0 : diff; } @@ -459,6 +585,7 @@ void NativeEngine::endedNotifierLoop() { if (endedStop_) break; batch.swap(endedQueue_); } + for (const auto &id: batch) forgetNode(id); for (const auto &id: batch) { if (!audioContextClassGlobalRef || !onNativeTrackEndedMethod) break; jstring js = env->NewStringUTF(id.c_str()); @@ -1036,9 +1163,9 @@ void NativeEngine::stopTrack(const std::string &id) { int64_t NativeEngine::contextTimeToNanos(const std::string &contextId, double when) { if (!std::isfinite(when) || when <= 0.0) return 0; std::lock_guard lock(contextMutex_); - auto it = contextStartNanos_.find(contextId); - if (it == contextStartNanos_.end()) return 0; - return it->second + static_cast(std::llround(when * 1e9)); + auto it = contextClocks_.find(contextId); + if (it == contextClocks_.end()) return 0; + return it->second->baseNs + static_cast(std::llround(when * 1e9)); } void NativeEngine::startOscillatorAt(const std::string &id, const std::string &type, diff --git a/packages/audio-context/src-native/android/audiocontext/src/main/cpp/audio_context.h b/packages/audio-context/src-native/android/audiocontext/src/main/cpp/audio_context.h index 4969efc8..128a2d01 100644 --- a/packages/audio-context/src-native/android/audiocontext/src/main/cpp/audio_context.h +++ b/packages/audio-context/src-native/android/audiocontext/src/main/cpp/audio_context.h @@ -150,6 +150,32 @@ class NativeEngine { int64_t getContextCurrentTimeNanos(const std::string &contextId); + // A realtime context's nodes stop rendering and its clock stops; others play on. + void suspendContext(const std::string &contextId); + + void resumeContext(const std::string &contextId); + + // Node `id` belongs to `contextId`; nodes connected to it inherit that. + void setNodeContext(const std::string &id, const std::string &contextId); + + // Drops what setNodeContext and paramComputedValue kept for a released node. + void forgetNode(const std::string &id); + + // The value param (id, type) had on the last quantum rendered, or a value set since; NaN if unknown. + double paramComputedValue(const std::string &id, int type); + + void holdParamValue(const std::string &id, int type, double value); + + // A context's clock: the render clock less the time it spent suspended (or not yet started). + struct ContextClock { + int64_t baseNs = 0; + std::atomic offsetNs{0}; + // The render time it stopped at; 0 while running. + std::atomic pausedAtNs{0}; + // Suspend requested by the app (or closed). + bool suspended = false; + }; + enum PannerDistanceModel { DISTANCE_INVERSE = 0, DISTANCE_LINEAR = 1, DISTANCE_EXPONENTIAL = 2 }; @@ -240,6 +266,8 @@ class NativeEngine { int mixChannels = 1; std::vector inMix; bool inActive[kWorkletMaxPorts] = {}; + // Each input's computed channels this quantum. + int inCount[kWorkletMaxPorts] = {}; // The quantum playing: outputs x kWorkletMaxChannels x 128. std::vector outQ; uint64_t nextFrame = 0; @@ -380,7 +408,11 @@ class NativeEngine { // A source's detune param, in targetId. CMD_ATTACH_DETUNE, // A buffer source's loop flag and points. - CMD_SET_SOURCE_LOOP + CMD_SET_SOURCE_LOOP, + // A context's clock starts, stops or restarts at this quantum. + CMD_CONTEXT_START, + CMD_CONTEXT_SUSPEND, + CMD_CONTEXT_RESUME }; // Graph node kinds; AudioContext.java's NODE_* match. @@ -468,6 +500,7 @@ class NativeEngine { bool periodicDisableNormalization = false; std::string periodicWaveId; std::vector waveShaperCurve; + std::shared_ptr clock; std::string waveShaperOversample; std::vector paramIds; std::shared_ptr convolver; @@ -551,6 +584,8 @@ class NativeEngine { int low = 0; bool onStack = false; int pending = 0; + // Its context's clock; null plays on the engine clock. + std::shared_ptr clock; }; struct ParamInput { @@ -893,8 +928,25 @@ class NativeEngine { std::thread endedThread_; bool endedStop_ = false; - std::unordered_map contextStartNanos_; + // The context's virtual 'now' on the clock of the node or context `id`, for ramps that start at the call. + int64_t callNowNs(const std::string &id); + + std::unordered_map> contextClocks_; + std::unordered_map> nodeClocks_; + std::atomic clocksDirty_{false}; std::mutex contextMutex_; + // The render clock at the start of the quantum being rendered. + int64_t quantumStartNs_ = 0; + + struct ParamSlot { + int type; + std::atomic value; + // Render results from before this time don't replace a value the app set. + std::atomic holdNs{0}; + ParamSlot(int t, double v) : type(t), value(v) {} + }; + // Guarded by scheduledEventsMutex_. + std::unordered_map>> paramSlots_; }; #endif // AUDIO_CONTEXT_H diff --git a/packages/audio-context/src-native/android/audiocontext/src/main/cpp/audio_graph.cpp b/packages/audio-context/src-native/android/audiocontext/src/main/cpp/audio_graph.cpp index dac83cd6..1c9aaf93 100644 --- a/packages/audio-context/src-native/android/audiocontext/src/main/cpp/audio_graph.cpp +++ b/packages/audio-context/src-native/android/audiocontext/src/main/cpp/audio_graph.cpp @@ -221,7 +221,6 @@ NativeEngine::GraphNode *NativeEngine::ensureNode(const std::string &id, int kin node->worklet = w->second; node->inputs = w->second->inputs; node->outputs = w->second->outputs; - node->countMode = COUNT_EXPLICIT; } break; } @@ -441,6 +440,35 @@ void NativeEngine::rebuildOrder() { } } + // Each node's context clock; connections never cross contexts, so it spreads along them. + { + std::lock_guard lock(contextMutex_); + for (GraphNode *n: nodes) { + auto it = nodeClocks_.find(n->id); + n->clock = it != nodeClocks_.end() ? it->second : nullptr; + } + } + std::vector spread; + for (GraphNode *n: nodes) { + if (n->clock) spread.push_back(n); + } + std::vector> linked(nodes.size()); + for (GraphNode *n: nodes) { + for (GraphNode *d: deps[static_cast(n->index)]) { + linked[static_cast(n->index)].push_back(d); + linked[static_cast(d->index)].push_back(n); + } + } + while (!spread.empty()) { + GraphNode *n = spread.back(); + spread.pop_back(); + for (GraphNode *m: linked[static_cast(n->index)]) { + if (m->clock) continue; + m->clock = n->clock; + spread.push_back(m); + } + } + // Tarjan's strongly connected components: a cycle plays only through a DelayNode. int counter = 0; std::vector stack; @@ -571,8 +599,8 @@ bool NativeEngine::mixInput(GraphNode &n, int input, int channels, int mode, int bool NativeEngine::evalParam(const std::string &id, int type, double fallback, int64_t startNs, double frameNs, double *out) { bool constant; + std::lock_guard lock(scheduledEventsMutex_); { - std::lock_guard lock(scheduledEventsMutex_); const std::vector *ev = nullptr; if (type == kTargetGainParam) { auto it = scheduledGainEvents_.find(id); @@ -602,6 +630,15 @@ bool NativeEngine::evalParam(const std::string &id, int type, double fallback, i for (int f = 0; f < Q; f++) out[f] += monoAt(ch, b.channels, f); constant = false; } + if (!paramSlots_.empty()) { + auto it = paramSlots_.find(id); + if (it != paramSlots_.end()) { + for (const auto &slot: it->second) { + if (slot->type != type || quantumStartNs_ < slot->holdNs.load(std::memory_order_relaxed)) continue; + slot->value.store(out[Q - 1], std::memory_order_relaxed); + } + } + } return constant; } @@ -1090,10 +1127,12 @@ void NativeEngine::renderWorklet(GraphNode &n, int64_t startNs, double frameNs) } WorkletNode &w = *n.worklet; for (int i = 0; i < w.inputs && i < n.inputs; i++) { - const bool active = mixInput(n, i, w.inChannels[i], COUNT_EXPLICIT, n.interpretation); + // computedNumberOfChannels from this quantum's connections and the channel config. + const bool active = mixInput(n, i, std::min(n.channelCount, kWorkletMaxChannels), n.countMode, n.interpretation); w.inActive[i] = active; if (!active) continue; const Bus &in = n.inBus[static_cast(i)]; + w.inCount[i] = std::min(in.channels, w.mixChannels); for (int c = 0; c < std::min(in.channels, w.mixChannels); c++) { std::memcpy(w.inMix.data() + static_cast((i * w.mixChannels + c) * Q), in.channel(c), Q * sizeof(float)); } @@ -1381,15 +1420,33 @@ void NativeEngine::renderConvolver(GraphNode &n) { void NativeEngine::renderQuantum(float *out, int64_t startNs) { const int channels = std::max(1, streamChannels_); const double frameNs = 1e9 / (streamSampleRate_ > 0 ? static_cast(streamSampleRate_) : 48000.0); + if (clocksDirty_.exchange(false, std::memory_order_acquire)) orderDirty_ = true; if (orderDirty_) { rebuildOrder(); orderDirty_ = false; } endedScratch_.clear(); - for (GraphNode *n: order_) processNode(*n, startNs, frameNs); + // A suspended context's nodes hold still; the others render at their context's time. + auto paused = [](const GraphNode &n) { + return n.clock && n.clock->pausedAtNs.load(std::memory_order_relaxed) != 0; + }; + auto nodeNs = [startNs](const GraphNode &n) { + return n.clock ? startNs - n.clock->offsetNs.load(std::memory_order_relaxed) : startNs; + }; + for (GraphNode *n: order_) { + if (paused(*n)) { + for (auto &b: n->inBus) b.active = false; + for (auto &b: n->outBus) { + b.active = false; + b.silence(); + } + continue; + } + processNode(*n, nodeNs(*n), frameNs); + } // A cycle's DelayNode takes its input once everything feeding it has rendered. for (GraphNode *n: order_) { - if (n->delayInCycle && !n->muted) renderDelay(*n, startNs, frameNs, true, false); + if (n->delayInCycle && !n->muted && !paused(*n)) renderDelay(*n, nodeNs(*n), frameNs, true, false); } std::fill(out, out + Q * channels, 0.0f); diff --git a/packages/audio-context/src-native/android/audiocontext/src/main/cpp/audio_jni.cpp b/packages/audio-context/src-native/android/audiocontext/src/main/cpp/audio_jni.cpp index 2a1e346b..d144d572 100644 --- a/packages/audio-context/src-native/android/audiocontext/src/main/cpp/audio_jni.cpp +++ b/packages/audio-context/src-native/android/audiocontext/src/main/cpp/audio_jni.cpp @@ -13,6 +13,7 @@ #include #include #include +#include #ifdef HAS_OBOE @@ -433,6 +434,7 @@ Java_org_nativescript_audiocontext_AudioContext_nativeReleaseGain(JNIEnv *env, j NativeEngine::Command cmd; cmd.type = NativeEngine::CMD_FREE_GAIN; cmd.id = gid ? gid : std::string(); + NativeEngine::getInstance().forgetNode(cmd.id); NativeEngine::getInstance().enqueueCommand(std::move(cmd)); if (gid) env->ReleaseStringUTFChars(jgainId, gid); } @@ -1209,6 +1211,7 @@ Java_org_nativescript_audiocontext_AudioContext_nativeReleasePanner(JNIEnv *env, NativeEngine::Command cmd; cmd.type = NativeEngine::CMD_FREE_PANNER; cmd.id = pid ? pid : std::string(); + NativeEngine::getInstance().forgetNode(cmd.id); NativeEngine::getInstance().enqueueCommand(std::move(cmd)); if (pid) env->ReleaseStringUTFChars(jpannerId, pid); } @@ -1772,11 +1775,10 @@ Java_org_nativescript_audiocontext_AudioContext_nativeGetMonotonicTimeNanos(JNIE jobject thiz) { (void) env; (void) thiz; - int64_t audioNs = g_audioTimeNanos.load(std::memory_order_relaxed); - if (audioNs != 0) return static_cast(audioNs); - int64_t nowNs = std::chrono::duration_cast( - std::chrono::steady_clock::now().time_since_epoch()).count(); - return static_cast(nowNs); + // A context's clock starts on its first rendered quantum, so any base on this clock works. + timespec ts{}; + clock_gettime(CLOCK_MONOTONIC, &ts); + return static_cast(ts.tv_sec) * 1000000000LL + static_cast(ts.tv_nsec); } extern "C" JNIEXPORT void JNICALL @@ -2009,3 +2011,38 @@ Java_org_nativescript_audiocontext_AudioContext_nativeReplaceSource(JNIEnv *env, if (cmd.id.empty()) return; NativeEngine::getInstance().enqueueCommand(std::move(cmd)); } + +extern "C" JNIEXPORT void JNICALL +Java_org_nativescript_audiocontext_AudioContext_nativeSuspendContext(JNIEnv *env, jobject thiz, + jstring jcontextId) { + NativeEngine::Scope scope__(engineFor(env, jcontextId)); + NativeEngine::getInstance().suspendContext(jstringToStd(env, jcontextId)); +} + +extern "C" JNIEXPORT void JNICALL +Java_org_nativescript_audiocontext_AudioContext_nativeResumeContext(JNIEnv *env, jobject thiz, + jstring jcontextId) { + NativeEngine::Scope scope__(engineFor(env, jcontextId)); + NativeEngine::getInstance().resumeContext(jstringToStd(env, jcontextId)); +} + +extern "C" JNIEXPORT void JNICALL +Java_org_nativescript_audiocontext_AudioContext_nativeSetNodeContext(JNIEnv *env, jobject thiz, + jstring jid, jstring jcontextId) { + NativeEngine::Scope scope__(engineFor(env, jcontextId)); + NativeEngine::getInstance().setNodeContext(jstringToStd(env, jid), jstringToStd(env, jcontextId)); +} + +extern "C" JNIEXPORT jdouble JNICALL +Java_org_nativescript_audiocontext_AudioContext_nativeParamComputedValue(JNIEnv *env, jobject thiz, + jstring jid, jint type) { + NativeEngine::Scope scope__(engineFor(env, jid)); + return NativeEngine::getInstance().paramComputedValue(jstringToStd(env, jid), type); +} + +extern "C" JNIEXPORT void JNICALL +Java_org_nativescript_audiocontext_AudioContext_nativeHoldParamValue(JNIEnv *env, jobject thiz, + jstring jid, jint type, jdouble value) { + NativeEngine::Scope scope__(engineFor(env, jid)); + NativeEngine::getInstance().holdParamValue(jstringToStd(env, jid), type, value); +} diff --git a/packages/audio-context/src-native/android/audiocontext/src/main/cpp/audio_render.cpp b/packages/audio-context/src-native/android/audiocontext/src/main/cpp/audio_render.cpp index 86ef6e3d..24cd72fb 100644 --- a/packages/audio-context/src-native/android/audiocontext/src/main/cpp/audio_render.cpp +++ b/packages/audio-context/src-native/android/audiocontext/src/main/cpp/audio_render.cpp @@ -158,8 +158,9 @@ NativeEngine::onAudioReady(oboe::AudioStream *stream, void *audioData, int32_t n if (offline_) { // Offline renders one quantum per call, at nowNs_. + quantumStartNs_ = nowNs_.load(std::memory_order_relaxed) + kFrameTimeSlackNs; drainCommands(); - renderQuantum(out, nowNs_.load(std::memory_order_relaxed) + kFrameTimeSlackNs); + renderQuantum(out, quantumStartNs_); return oboe::DataCallbackResult::Continue; } @@ -171,8 +172,6 @@ NativeEngine::onAudioReady(oboe::AudioStream *stream, void *audioData, int32_t n int64_t clock = renderClockNs_; if (clock == 0 || now - clock > kClockBehindNs || clock - now > kClockAheadNs) clock = now; renderClockNs_ = clock + std::llround(static_cast(numFrames) * 1e9 / rate); - g_audioTimeNanos.store(clock, std::memory_order_relaxed); - nowNs_.store(clock, std::memory_order_relaxed); const size_t quantumSamples = static_cast(kQuantum * channels); if (quantum_.size() != quantumSamples) { @@ -183,9 +182,14 @@ NativeEngine::onAudioReady(oboe::AudioStream *stream, void *audioData, int32_t n int written = 0; while (written < numFrames) { if (quantumPos_ >= kQuantum) { - drainCommands(); const int64_t startNs = clock + std::llround(static_cast(written) * 1e9 / rate); - renderQuantum(quantum_.data(), startNs + kFrameTimeSlackNs); + quantumStartNs_ = startNs + kFrameTimeSlackNs; + drainCommands(); + // 'Now' is the next quantum: what's queued from here on applies there. + const int64_t next = startNs + std::llround(static_cast(kQuantum) * 1e9 / rate); + g_audioTimeNanos.store(next, std::memory_order_relaxed); + nowNs_.store(next, std::memory_order_relaxed); + renderQuantum(quantum_.data(), quantumStartNs_); quantumPos_ = 0; } const int n = std::min(numFrames - written, kQuantum - quantumPos_); @@ -601,6 +605,24 @@ void NativeEngine::applyCommand(Command &c) { if (bufferInUse(c.id)) idleFrees_.push_back(c.id); else releaseBufferData(c.id); break; + case CMD_CONTEXT_START: + if (!c.clock) break; + c.clock->offsetNs.store(quantumStartNs_ - c.clock->baseNs, std::memory_order_relaxed); + c.clock->pausedAtNs.store(0, std::memory_order_relaxed); + break; + case CMD_CONTEXT_SUSPEND: + if (c.clock && c.clock->pausedAtNs.load(std::memory_order_relaxed) == 0) { + c.clock->pausedAtNs.store(quantumStartNs_, std::memory_order_relaxed); + } + break; + case CMD_CONTEXT_RESUME: { + if (!c.clock) break; + const int64_t paused = c.clock->pausedAtNs.load(std::memory_order_relaxed); + if (paused == 0) break; + c.clock->offsetNs.fetch_add(quantumStartNs_ - paused, std::memory_order_relaxed); + c.clock->pausedAtNs.store(0, std::memory_order_relaxed); + break; + } case CMD_RESUME: ensureStream(); break; diff --git a/packages/audio-context/src-native/android/audiocontext/src/main/cpp/audio_worklet.cpp b/packages/audio-context/src-native/android/audiocontext/src/main/cpp/audio_worklet.cpp index 919dffef..47f4571f 100644 --- a/packages/audio-context/src-native/android/audiocontext/src/main/cpp/audio_worklet.cpp +++ b/packages/audio-context/src-native/android/audiocontext/src/main/cpp/audio_worklet.cpp @@ -183,10 +183,10 @@ bool NativeEngine::workletPush(WorkletNode &w, uint64_t frame, int64_t paramNs, std::memcpy(slot, &frameValue, sizeof frameValue); words[ALIVE] = 1; - // The mixer already rendered each input at its own channelCount. + // The mixer already rendered each input at its computed channel count. const int stride = w.mixChannels; for (int i = 0; i < w.inputs; i++) { - const int want = w.inChannels[i]; + const int want = w.inCount[i]; const uint32_t count = withInputs && w.inActive[i] ? static_cast(want) : 0u; words[w.inputCounts + i] = count; const float *mix = w.inMix.data() + static_cast(i * stride * kQuantum); diff --git a/packages/audio-context/src-native/android/audiocontext/src/main/java/org/nativescript/audiocontext/AudioContext.java b/packages/audio-context/src-native/android/audiocontext/src/main/java/org/nativescript/audiocontext/AudioContext.java index f02c3b16..597485c8 100644 --- a/packages/audio-context/src-native/android/audiocontext/src/main/java/org/nativescript/audiocontext/AudioContext.java +++ b/packages/audio-context/src-native/android/audiocontext/src/main/java/org/nativescript/audiocontext/AudioContext.java @@ -887,6 +887,59 @@ private Set getOrCreateContextSet(ConcurrentHashMap> private void addToContextSet(ConcurrentHashMap> map, String contextId, String value) { if (contextId == null || value == null || value.isEmpty()) return; getOrCreateContextSet(map, contextId).add(value); + // Graph nodes take their realtime context's clock, so a suspended context's nodes hold. + boolean node = map == contextTracksMap || map == contextGains || map == contextBiquads || map == contextPanners || map == contextIirs; + if (node && nativeAvailable && !isOfflineId(contextId)) { + try { + nativeSetNodeContext(value, contextId); + } catch (Throwable ignored) { + } + } + } + + private native void nativeSetNodeContext(String id, String contextId); + + private native void nativeSuspendContext(String contextId); + + private native void nativeResumeContext(String contextId); + + private native double nativeParamComputedValue(String id, int type); + + private native void nativeHoldParamValue(String id, int type, double value); + + double getParamComputedValue(String id, int type) { + if (!nativeAvailable || id == null) return Double.NaN; + return nativeParamComputedValue(id, type); + } + + void holdParamValue(String id, int type, double value) { + if (nativeAvailable && id != null) nativeHoldParamValue(id, type, value); + } + + // Suspends one realtime context; the stream stops once every context is suspended. + public void suspendAsync(String contextId, @Nullable AsyncCallback cb) { + runContextAsync(contextId, true, cb); + } + + public void resumeAsync(String contextId, @Nullable AsyncCallback cb) { + runContextAsync(contextId, false, cb); + } + + private void runContextAsync(String contextId, boolean suspend, @Nullable AsyncCallback cb) { + final Looper callerLooper = captureCallerLooper(); + decodeExecutor.submit(() -> { + boolean ok = true; + try { + if (nativeAvailable) { + if (suspend) nativeSuspendContext(contextId); + else nativeResumeContext(contextId); + } + } catch (Throwable t) { + ok = false; + } + final boolean result = ok; + if (cb != null) dispatch(callerLooper, () -> cb.onComplete(result)); + }); } boolean isDestinationNode(String nodeId) { @@ -972,6 +1025,8 @@ void connectParam(AudioNode source, int output, @Nullable AudioParam param) { String src = nodeId(source); Integer target = param == null ? null : paramTarget(param); if (!nativeAvailable || src == null || target == null || param.getId() == null) return; + // Audio drives the param, so it records its rendered value. + nativeParamComputedValue(param.getId(), target); nativeConnect(src, kindOf(source, src), portsOf(source), output, param.getId(), 0, 1, 0, target); } @@ -1769,6 +1824,8 @@ public void closeAsync(@Nullable String contextId, @Nullable AsyncCallback cb) { decodeExecutor.submit(() -> { boolean ok = true; try { + // A closed context's clock stops. + if (nativeAvailable && contextId != null && !isOfflineId(contextId)) nativeSuspendContext(contextId); if (nativeAvailable && (contextId == null || openRealtimeContexts.isEmpty())) nativeSuspend(); } catch (Throwable t) { ok = false; diff --git a/packages/audio-context/src-native/android/audiocontext/src/main/java/org/nativescript/audiocontext/AudioContextInstance.java b/packages/audio-context/src-native/android/audiocontext/src/main/java/org/nativescript/audiocontext/AudioContextInstance.java index ac541999..da49c277 100644 --- a/packages/audio-context/src-native/android/audiocontext/src/main/java/org/nativescript/audiocontext/AudioContextInstance.java +++ b/packages/audio-context/src-native/android/audiocontext/src/main/java/org/nativescript/audiocontext/AudioContextInstance.java @@ -90,11 +90,11 @@ public boolean setSinkId(String deviceId) { } public void resumeAsync(@androidx.annotation.Nullable AudioContext.AsyncCallback cb) { - AudioContext.getInstance().resumeAsync(cb); + AudioContext.getInstance().resumeAsync(id, cb); } public void suspendAsync(@androidx.annotation.Nullable AudioContext.AsyncCallback cb) { - AudioContext.getInstance().suspendAsync(cb); + AudioContext.getInstance().suspendAsync(id, cb); } public void closeAsync(@androidx.annotation.Nullable AudioContext.AsyncCallback cb) { diff --git a/packages/audio-context/src-native/android/audiocontext/src/main/java/org/nativescript/audiocontext/AudioParam.java b/packages/audio-context/src-native/android/audiocontext/src/main/java/org/nativescript/audiocontext/AudioParam.java index 72620cb8..5c70809b 100644 --- a/packages/audio-context/src-native/android/audiocontext/src/main/java/org/nativescript/audiocontext/AudioParam.java +++ b/packages/audio-context/src-native/android/audiocontext/src/main/java/org/nativescript/audiocontext/AudioParam.java @@ -79,6 +79,7 @@ public Type getType() { } public void setValue(double v) { + AudioContext.getInstance().holdParamValue(id, targetCode(), v); if (owner != null) { switch (type) { case PANNER_POSITION_X: @@ -154,7 +155,26 @@ public double getValue() { return AudioContext.getInstance().getGain(id); } + // The engine's param code: -1 for a gain-style param, else the panner or listener param type. + private int targetCode() { + int ordinal = type.ordinal(); + int first = Type.PANNER_POSITION_X.ordinal(); + if (ordinal >= first && ordinal <= Type.LISTENER_UP_Z.ordinal()) return 5 + ordinal - first; + return -1; + } + + /** The value automation and connected audio gave on the last rendered quantum, or one set since; NaN before either. */ + public double getComputedValue() { + return AudioContext.getInstance().getParamComputedValue(id, targetCode()); + } + + // Automated params record their rendered value from here on. + private void track() { + AudioContext.getInstance().getParamComputedValue(id, targetCode()); + } + public void setValueAtTime(double v, double t) { + track(); if (owner != null) { AudioContext.getInstance().schedulePannerSet(owner.getId(), this.type.ordinal(), this.automationRate, v, t); if (t <= 0.0) setValue(v); @@ -170,6 +190,7 @@ public void setValueAtTime(double v, double t) { } public void linearRampToValueAtTime(double v, double t) { + track(); if (owner != null) { AudioContext.getInstance().schedulePannerRamp(owner.getId(), this.type.ordinal(), this.automationRate, v, t); if (t <= 0.0) setValue(v); @@ -204,6 +225,7 @@ public void setValueCurveAtTime(java.nio.FloatBuffer values, double t, double du } private void schedule(int type, double v, double t, double timeConstant, double duration, java.nio.FloatBuffer curve) { + track(); if (owner != null) { AudioContext.getInstance().scheduleParamEvent(1, owner.getId(), this.type.ordinal(), type, this.automationRate, t, v, timeConstant, duration, curve); } else if (contextOwner != null) { diff --git a/packages/audio-context/src-native/android/audiocontext/src/main/cpp/hrtf_kemar.h b/packages/audio-context/src-native/common/hrtf_kemar.h similarity index 100% rename from packages/audio-context/src-native/android/audiocontext/src/main/cpp/hrtf_kemar.h rename to packages/audio-context/src-native/common/hrtf_kemar.h diff --git a/packages/audio-context/typings/android.d.ts b/packages/audio-context/typings/android.d.ts index 4a1c32c8..cfc95285 100644 --- a/packages/audio-context/typings/android.d.ts +++ b/packages/audio-context/typings/android.d.ts @@ -475,6 +475,7 @@ declare module org { public setValueCurveAtTime(values: java.nio.FloatBuffer, t: number, duration: number): void; public setValueAtTime(v: number, t: number): void; public getValue(): number; + public getComputedValue(): number; public getValuesForRange(out: number, this_: number, startTime: number): androidNative.Array; } export module AudioParam { diff --git a/packages/audio-context/typings/objc!NSCCanvasAudioContext.d.ts b/packages/audio-context/typings/objc!NSCCanvasAudioContext.d.ts index c89d4360..96e8b542 100644 --- a/packages/audio-context/typings/objc!NSCCanvasAudioContext.d.ts +++ b/packages/audio-context/typings/objc!NSCCanvasAudioContext.d.ts @@ -83,6 +83,10 @@ declare class NSCAudioBufferSourceNode extends NSCAudioScheduledSourceNode { buffer: NSCAudioBuffer; + loopStart: number; + + loopEnd: number; + loop: boolean; constructor(o: { context: NSCAudioContext; buffer: NSCAudioBuffer }); @@ -427,6 +431,14 @@ declare class NSCAudioParam extends NSObject { linearRampToValueAtTime(value: number, time: number): void; + exponentialRampToValueAtTime(value: number, time: number): void; + + setTargetAtTime(target: number, startTime: number, timeConstant: number): void; + + setValueCurveAtTime(values: NSData, startTime: number, duration: number): void; + + computedValue(): number; + setValue(value: number): void; setValueAtTime(value: number, time: number): void; @@ -581,7 +593,7 @@ declare class NSCDynamicsCompressorNode extends NSCAudioNode { readonly ratioParam: NSCAudioParam; - readonly reductionParam: NSCAudioParam; + readonly reduction: number; readonly releaseParam: NSCAudioParam; diff --git a/tools/demo/canvas/spec/audio-api.ts b/tools/demo/canvas/spec/audio-api.ts index e34ce91c..071271b1 100644 --- a/tools/demo/canvas/spec/audio-api.ts +++ b/tools/demo/canvas/spec/audio-api.ts @@ -8,7 +8,7 @@ declare const global: any; const RATE = 48000; const Q = 128; -const androidTest = (name: string, body: TestBody) => (global.isAndroid ? test(name, body) : skip(name, 'not yet on this platform')); +const nativeTest = (name: string, body: TestBody) => (global.isAndroid || global.isIOS ? test(name, body) : skip(name, 'not yet on this platform')); const offline = (channels = 1, length = Q): any => new OfflineAudioContext(channels, length, RATE); @@ -26,7 +26,7 @@ function errorName(e: any) { export function registerAudioApiSpec() { suite('audio.api', () => { - androidTest('nodes report numberOfInputs and numberOfOutputs', () => { + nativeTest('nodes report numberOfInputs and numberOfOutputs', () => { const context = offline(); const io = (node: any) => `${node.numberOfInputs}/${node.numberOfOutputs}`; equal(io(context.createConstantSource()), '0/1', 'constant source'); @@ -37,9 +37,11 @@ export function registerAudioApiSpec() { equal(io(context.createGain()), '1/1', 'gain'); equal(io(context.createChannelSplitter({ numberOfOutputs: 3 })), '1/3', 'splitter'); equal(io(context.createChannelMerger({ numberOfInputs: 3 })), '3/1', 'merger'); + equal(io(context.createChannelMerger(2)), '2/1', 'merger from a number'); + equal(io(context.createChannelSplitter(2)), '1/2', 'splitter from a number'); }); - androidTest('ChannelSplitterNode and ChannelMergerNode keep their channel config', () => { + nativeTest('ChannelSplitterNode and ChannelMergerNode keep their channel config', () => { const context = offline(); const splitter = context.createChannelSplitter({ numberOfOutputs: 4 }); equal(splitter.channelCount, 4); @@ -55,7 +57,7 @@ export function registerAudioApiSpec() { throws(() => context.createChannelSplitter({ numberOfOutputs: 33 }), 'IndexSizeError'); }); - androidTest('stereo-only nodes reject more than two channels and max mode', () => { + nativeTest('stereo-only nodes reject more than two channels and max mode', () => { const context = offline(); for (const node of [context.createPanner(), context.createStereoPanner(), context.createConvolver(), context.createDynamicsCompressor()]) { node.channelCount = 1; @@ -66,7 +68,7 @@ export function registerAudioApiSpec() { } }); - androidTest('channelCount 0 or above 32 is NotSupportedError', () => { + nativeTest('channelCount 0 or above 32 is NotSupportedError', () => { const gain = offline().createGain(); throws(() => (gain.channelCount = 0), 'NotSupportedError'); throws(() => (gain.channelCount = 33), 'NotSupportedError'); @@ -74,7 +76,7 @@ export function registerAudioApiSpec() { equal(gain.channelCount, 32); }); - androidTest('destination reports maxChannelCount and limits channelCount', () => { + nativeTest('destination reports maxChannelCount and limits channelCount', () => { const context = offline(2); equal(context.destination.maxChannelCount, 2); throws(() => (context.destination.channelCount = 1), 'InvalidStateError', 'an offline destination is fixed'); @@ -87,7 +89,7 @@ export function registerAudioApiSpec() { } }); - androidTest('start and stop validate their arguments and order', () => { + nativeTest('start and stop validate their arguments and order', () => { const context = offline(); const source = context.createConstantSource(); throws(() => source.stop(), 'InvalidStateError', 'stop before start'); @@ -103,7 +105,7 @@ export function registerAudioApiSpec() { source.stop(2); }); - androidTest('ended fires once, after the call to stop returns', async () => { + nativeTest('ended fires once, after the call to stop returns', async () => { const context = offline(); const source = context.createConstantSource(); let ended = 0; @@ -119,7 +121,7 @@ export function registerAudioApiSpec() { equal(ended, 1, 'once'); }); - androidTest('ended fires on a buffer source whose listener came before its buffer', async () => { + nativeTest('ended fires on a buffer source whose listener came before its buffer', async () => { const context = offline(1, Q * 8); const source = context.createBufferSource(); let ended = 0; @@ -134,7 +136,7 @@ export function registerAudioApiSpec() { equal(ended, 1, 'once'); }); - androidTest('AudioBufferSourceNode.buffer can only be set once', () => { + nativeTest('AudioBufferSourceNode.buffer can only be set once', () => { const context = offline(); const buffer = context.createBuffer(1, Q, RATE); const source = context.createBufferSource({ buffer }); @@ -143,7 +145,7 @@ export function registerAudioApiSpec() { throws(() => (source.buffer = buffer), 'InvalidStateError'); }); - androidTest('OfflineAudioContext validates its arguments', () => { + nativeTest('OfflineAudioContext validates its arguments', () => { throws(() => new OfflineAudioContext(0, Q, RATE), 'NotSupportedError', 'no channels'); throws(() => new OfflineAudioContext(33, Q, RATE), 'NotSupportedError', '33 channels'); throws(() => new OfflineAudioContext(1, 0, RATE), 'NotSupportedError', 'zero length'); @@ -152,7 +154,7 @@ export function registerAudioApiSpec() { equal(new OfflineAudioContext(2, Q, 3000).length, Q); }); - androidTest('OfflineAudioContext fires complete with the rendered buffer', async () => { + nativeTest('OfflineAudioContext fires complete with the rendered buffer', async () => { const context = offline(); let fromHandler: any = null; let fromListener: any = null; @@ -164,7 +166,7 @@ export function registerAudioApiSpec() { equal(fromHandler.renderedBuffer, rendered, 'renderedBuffer is the resolved buffer'); }); - androidTest('createBuffer takes numberOfChannels, length and sampleRate', () => { + nativeTest('createBuffer takes numberOfChannels, length and sampleRate', () => { const context = offline(); const buffer = context.createBuffer(2, 100, 22050); equal(buffer.numberOfChannels, 2); @@ -173,7 +175,7 @@ export function registerAudioApiSpec() { equal(context.createBuffer({ numberOfChannels: 1, length: 10, sampleRate: RATE }).length, 10, 'the options form still works'); }); - androidTest('AudioBuffer validates its options and channel indices', () => { + nativeTest('AudioBuffer validates its options and channel indices', () => { throws(() => new AudioBuffer({ numberOfChannels: 1, length: 0, sampleRate: RATE }), 'NotSupportedError', 'zero length'); throws(() => new AudioBuffer({ numberOfChannels: 0, length: 1, sampleRate: RATE }), 'NotSupportedError', 'no channels'); throws(() => new AudioBuffer({ numberOfChannels: 33, length: 1, sampleRate: RATE }), 'NotSupportedError', '33 channels'); @@ -185,12 +187,12 @@ export function registerAudioApiSpec() { throws(() => buffer.copyToChannel(new Float32Array(4), 2), 'IndexSizeError'); }); - androidTest('AudioContext validates sampleRate and latencyHint', () => { + nativeTest('AudioContext validates sampleRate and latencyHint', () => { throws(() => new AudioContext({ sampleRate: 1000 }), 'NotSupportedError'); throws(() => new AudioContext({ latencyHint: 'fast' as any }), 'TypeError'); }); - androidTest('a closed AudioContext rejects close, resume and suspend', async () => { + nativeTest('a closed AudioContext rejects close, resume and suspend', async () => { const context: any = new AudioContext(); await context.close(); equal(errorName(await rejects(context.close())), 'InvalidStateError', 'close'); @@ -198,7 +200,7 @@ export function registerAudioApiSpec() { equal(errorName(await rejects(context.suspend())), 'InvalidStateError', 'suspend'); }); - androidTest('getOutputTimestamp returns contextTime and performanceTime', async () => { + nativeTest('getOutputTimestamp returns contextTime and performanceTime', async () => { const context: any = new AudioContext(); try { const stamp = context.getOutputTimestamp(); @@ -209,7 +211,7 @@ export function registerAudioApiSpec() { } }); - androidTest('decodeAudioData failure is an EncodingError and reaches errorCallback', async () => { + nativeTest('decodeAudioData failure is an EncodingError and reaches errorCallback', async () => { const context = offline(); let callbackError: any = null; const error = await rejects( @@ -221,14 +223,14 @@ export function registerAudioApiSpec() { equal(errorName(callbackError), 'EncodingError'); }); - androidTest('DelayNode maxDelayTime must be in (0, 180)', () => { + nativeTest('DelayNode maxDelayTime must be in (0, 180)', () => { const context = offline(); throws(() => context.createDelay(0), 'NotSupportedError'); throws(() => context.createDelay(180), 'NotSupportedError'); equal(context.createDelay(10).maxDelayTime, 10); }); - androidTest('IIRFilterNode validates its coefficients', () => { + nativeTest('IIRFilterNode validates its coefficients', () => { const context = offline(); throws(() => context.createIIRFilter([], [1]), 'NotSupportedError', 'empty feedforward'); throws(() => context.createIIRFilter(new Array(21).fill(1), [1]), 'NotSupportedError', '21 feedforward'); @@ -239,7 +241,7 @@ export function registerAudioApiSpec() { throws(() => node.getFrequencyResponse(new Float32Array(2), new Float32Array(1), new Float32Array(2)), 'InvalidAccessError'); }); - androidTest('AnalyserNode validates its attributes', () => { + nativeTest('AnalyserNode validates its attributes', () => { const analyser = offline().createAnalyser(); throws(() => (analyser.fftSize = 1000), 'IndexSizeError', 'not a power of two'); throws(() => (analyser.fftSize = 16), 'IndexSizeError', 'too small'); @@ -252,7 +254,7 @@ export function registerAudioApiSpec() { throws(() => offline().createAnalyser({ minDecibels: -10, maxDecibels: -20 }), 'IndexSizeError', 'options'); }); - androidTest('PannerNode validates distance and cone attributes', () => { + nativeTest('PannerNode validates distance and cone attributes', () => { const context = offline(); const panner = context.createPanner(); throws(() => (panner.refDistance = -1), 'RangeError'); @@ -264,13 +266,13 @@ export function registerAudioApiSpec() { equal(panner.refDistance, 0); }); - androidTest('PeriodicWave real and imag must match and hold two terms', () => { + nativeTest('PeriodicWave real and imag must match and hold two terms', () => { const context = offline(); throws(() => context.createPeriodicWave([0, 1], [0, 1, 0]), 'IndexSizeError', 'mismatch'); throws(() => context.createPeriodicWave([0], [0]), 'IndexSizeError', 'one term'); }); - androidTest('WaveShaperNode.curve copies and needs two points', () => { + nativeTest('WaveShaperNode.curve copies and needs two points', () => { const shaper = offline().createWaveShaper(); throws(() => (shaper.curve = new Float32Array(1)), 'InvalidStateError'); const curve = new Float32Array([-1, 0, 1]); @@ -281,14 +283,14 @@ export function registerAudioApiSpec() { equal(shaper.curve[1], 0, 'the getter copies'); }); - androidTest('ConvolverNode.buffer must match the context sampleRate', () => { + nativeTest('ConvolverNode.buffer must match the context sampleRate', () => { const context = offline(); const convolver = context.createConvolver(); throws(() => (convolver.buffer = new AudioBuffer({ numberOfChannels: 1, length: 4, sampleRate: 44100 })), 'NotSupportedError'); convolver.buffer = new AudioBuffer({ numberOfChannels: 1, length: 4, sampleRate: RATE }); }); - androidTest("OscillatorNode type 'custom' comes only from a PeriodicWave", () => { + nativeTest("OscillatorNode type 'custom' comes only from a PeriodicWave", () => { const context = offline(); const wave = context.createPeriodicWave([0, 1], [0, 0]); const oscillator = context.createOscillator(); @@ -303,7 +305,7 @@ export function registerAudioApiSpec() { throws(() => context.createOscillator({ type: 'custom' }), 'InvalidStateError', 'custom without a wave'); }); - androidTest('BiquadFilterNode.getFrequencyResponse follows the filter', () => { + nativeTest('BiquadFilterNode.getFrequencyResponse follows the filter', () => { const context = offline(); const filter = context.createBiquadFilter(); const nyquist = RATE / 2; @@ -323,7 +325,7 @@ export function registerAudioApiSpec() { throws(() => filter.getFrequencyResponse(freqs, new Float32Array(4), phase), 'InvalidAccessError'); }); - androidTest('AudioParams report defaultValue, minValue and maxValue', () => { + nativeTest('AudioParams report defaultValue, minValue and maxValue', () => { const context = offline(); const range = (p: any) => [p.defaultValue, p.minValue, p.maxValue].join(','); const FLT = 3.4028234663852886e38; @@ -346,7 +348,7 @@ export function registerAudioApiSpec() { equal(range(compressor.release), '0.25,0,1', 'release'); }); - androidTest('fixed k-rate params keep their automationRate', () => { + nativeTest('fixed k-rate params keep their automationRate', () => { const context = offline(); const threshold = context.createDynamicsCompressor().threshold; equal(threshold.automationRate, 'k-rate'); @@ -361,7 +363,7 @@ export function registerAudioApiSpec() { if (playbackRate) equal(playbackRate.automationRate, 'k-rate', 'playbackRate'); }); - androidTest('DynamicsCompressorNode.reduction is a number', () => { + nativeTest('DynamicsCompressorNode.reduction is a number', () => { const reduction = offline().createDynamicsCompressor().reduction; equal(typeof reduction, 'number'); equal(reduction, 0, 'idle'); diff --git a/tools/demo/canvas/spec/audio-dsp.ts b/tools/demo/canvas/spec/audio-dsp.ts index c7e8fde7..e34f6124 100644 --- a/tools/demo/canvas/spec/audio-dsp.ts +++ b/tools/demo/canvas/spec/audio-dsp.ts @@ -8,7 +8,7 @@ declare const global: any; const RATE = 48000; const Q = 128; -const androidTest = (name: string, body: TestBody) => (global.isAndroid ? test(name, body) : skip(name, 'not yet on this platform')); +const nativeTest = (name: string, body: TestBody) => (global.isAndroid || global.isIOS ? test(name, body) : skip(name, 'not yet on this platform')); const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); @@ -37,7 +37,7 @@ function onset(data: Float32Array, threshold: number) { export function registerAudioDspSpec() { suite('audio.dsp.convolver', () => { - androidTest('a response longer than 32768 frames convolves exactly', async () => { + nativeTest('a response longer than 32768 frames convolves exactly', async () => { const length = 50000; const response = Float32Array.from({ length }, (_, i) => Math.sin(i * 0.013) * Math.exp(-i / 20000)); const impulses: [number, number][] = [ @@ -66,7 +66,7 @@ export function registerAudioDspSpec() { ok(diff < 1e-4, `frame ${at} differs by ${diff}`); }); - androidTest('a realtime convolver plays the far end of a long response on time', async () => { + nativeTest('a realtime convolver plays the far end of a long response on time', async () => { const context = new AudioContext(); const rate = context.sampleRate; const response = new Float32Array(Math.round(rate * 1.2)); @@ -116,7 +116,7 @@ export function registerAudioDspSpec() { return [rendered.getChannelData(0), rendered.getChannelData(1)]; } - androidTest('HRTF: a source on the right reaches the right ear first and louder', async () => { + nativeTest('HRTF: a source on the right reaches the right ear first and louder', async () => { const [left, right] = await hrtf(1, 0, 0); ok(energy(right) > 4 * energy(left), `right ${energy(right)}, left ${energy(left)}`); const l = onset(left, 0.02); @@ -124,7 +124,7 @@ export function registerAudioDspSpec() { ok(r >= 0 && l - r > 10, `onsets: left ${l}, right ${r}`); }); - androidTest('HRTF: left and right mirror each other', async () => { + nativeTest('HRTF: left and right mirror each other', async () => { const [rightL, rightR] = await hrtf(1, 0, -0.5); const [leftL, leftR] = await hrtf(-1, 0, -0.5); let diff = 0; @@ -132,14 +132,14 @@ export function registerAudioDspSpec() { ok(diff < 1e-6 && energy(rightR) > 0, `differs by ${diff}`); }); - androidTest('HRTF: a source straight ahead reaches both ears alike', async () => { + nativeTest('HRTF: a source straight ahead reaches both ears alike', async () => { const [left, right] = await hrtf(0, 0, -1); let diff = 0; for (let i = 0; i < left.length; i++) diff = Math.max(diff, Math.abs(left[i] - right[i])); ok(diff < 1e-6 && energy(left) > 0.1, `differs by ${diff}, energy ${energy(left)}`); }); - androidTest('HRTF: elevation changes the response', async () => { + nativeTest('HRTF: elevation changes the response', async () => { const [levelL] = await hrtf(0, 0, -1); const [aboveL] = await hrtf(0, 1, -0.2); let diff = 0; @@ -147,13 +147,13 @@ export function registerAudioDspSpec() { ok(diff > 0.01, `differs by ${diff}`); }); - androidTest('HRTF: the response rings on after a one-frame input', async () => { + nativeTest('HRTF: the response rings on after a one-frame input', async () => { const [left, right] = await hrtf(1, 0, 0); ok(energy(right, Q, 2 * Q) + energy(left, Q, 2 * Q) > 0, 'second quantum'); ok(energy(right, 3 * Q) + energy(left, 3 * Q) === 0, 'silent after the tail'); }); - androidTest('StereoPannerNode pans by pan alone, wherever the listener is', async () => { + nativeTest('StereoPannerNode pans by pan alone, wherever the listener is', async () => { const context: any = new OfflineAudioContext(2, Q * 2, RATE); context.listener.positionX.value = 5; context.listener.positionZ.value = 3; @@ -182,7 +182,7 @@ export function registerAudioDspSpec() { return (await context.startRendering()).getChannelData(0); } - androidTest('exponentialRampToValueAtTime follows the exponential curve', async () => { + nativeTest('exponentialRampToValueAtTime follows the exponential curve', async () => { const end = (Q * 4) / RATE; const got = await automate((g) => { g.setValueAtTime(0.01, 0); @@ -195,7 +195,7 @@ export function registerAudioDspSpec() { closeTo(got[Q * 5], 1, 1e-6, 'after the ramp'); }); - androidTest('setTargetAtTime approaches its target exponentially', async () => { + nativeTest('setTargetAtTime approaches its target exponentially', async () => { const start = Q / RATE; const tau = 0.002; const got = await automate((g) => { @@ -209,7 +209,7 @@ export function registerAudioDspSpec() { } }); - androidTest('setValueCurveAtTime interpolates its values over the duration', async () => { + nativeTest('setValueCurveAtTime interpolates its values over the duration', async () => { const curve = new Float32Array([0, 1, 0.5]); const duration = (Q * 2) / RATE; const got = await automate((g) => g.setValueCurveAtTime(curve, Q / RATE, duration)); @@ -220,7 +220,7 @@ export function registerAudioDspSpec() { closeTo(got[Q * 4], 0.5, 1e-6, 'held after'); }); - androidTest('a ramp with no event before it starts from the current value', async () => { + nativeTest('a ramp with no event before it starts from the current value', async () => { const got = await automate((g) => { g.value = 1; g.linearRampToValueAtTime(0, (Q * 4) / RATE); @@ -237,7 +237,7 @@ export function registerAudioDspSpec() { return count; } - androidTest('OscillatorNode.detune shifts the frequency by cents', async () => { + nativeTest('OscillatorNode.detune shifts the frequency by cents', async () => { const context = new OfflineAudioContext(1, RATE / 10, RATE); const oscillator: any = context.createOscillator({ frequency: 400 }); oscillator.detune.value = 1200; @@ -248,7 +248,7 @@ export function registerAudioDspSpec() { ok(Math.abs(count - 80) <= 1, `${count} cycles in 0.1s`); }); - androidTest('AudioBufferSourceNode.detune scales the playback rate', async () => { + nativeTest('AudioBufferSourceNode.detune scales the playback rate', async () => { const context = new OfflineAudioContext(1, Q * 4, RATE); const ramp = Float32Array.from({ length: Q * 8 }, (_, i) => i / (Q * 8)); const source: any = context.createBufferSource(); @@ -260,7 +260,7 @@ export function registerAudioDspSpec() { closeTo(data[100], ramp[200], 1e-6, 'twice as fast'); }); - androidTest('AudioBufferSourceNode loops between loopStart and loopEnd', async () => { + nativeTest('AudioBufferSourceNode loops between loopStart and loopEnd', async () => { const context = new OfflineAudioContext(1, Q * 4, RATE); const data = Float32Array.from({ length: Q }, (_, i) => i); const source: any = context.createBufferSource(); @@ -277,7 +277,7 @@ export function registerAudioDspSpec() { ok(bad < 0, `frame ${bad}: ${got[bad]}, want ${want(bad)}`); }); - androidTest('a custom PeriodicWave is normalized to a peak of 1 unless disabled', async () => { + nativeTest('a custom PeriodicWave is normalized to a peak of 1 unless disabled', async () => { const peak = async (disableNormalization: boolean) => { const context = new OfflineAudioContext(1, RATE / 10, RATE); const wave = context.createPeriodicWave(new Float32Array([5, 0, 0]), new Float32Array([0, 3, 1]), { disableNormalization }); @@ -295,7 +295,7 @@ export function registerAudioDspSpec() { }); suite('audio.dsp.nodes', () => { - androidTest("WaveShaperNode oversample '2x' and '4x' shape at a higher rate", async () => { + nativeTest("WaveShaperNode oversample '2x' and '4x' shape at a higher rate", async () => { const render = async (oversample: string) => { const context = new OfflineAudioContext(1, Q * 16, RATE); const shaper = context.createWaveShaper(); @@ -321,7 +321,7 @@ export function registerAudioDspSpec() { } }); - androidTest('DynamicsCompressorNode.reduction meters the gain reduction', async () => { + nativeTest('DynamicsCompressorNode.reduction meters the gain reduction', async () => { const context = new OfflineAudioContext(1, RATE / 4, RATE); const compressor: any = context.createDynamicsCompressor(); const source = context.createConstantSource({ offset: 1 }); @@ -333,7 +333,7 @@ export function registerAudioDspSpec() { ok(compressor.reduction < -10, `reduction ${compressor.reduction}`); }); - androidTest('DynamicsCompressorNode looks 6 ms ahead and applies makeup gain', async () => { + nativeTest('DynamicsCompressorNode looks 6 ms ahead and applies makeup gain', async () => { const context = new OfflineAudioContext(1, Q * 8, RATE); const compressor = context.createDynamicsCompressor(); const source = context.createConstantSource({ offset: 0.01 }); @@ -347,7 +347,7 @@ export function registerAudioDspSpec() { closeTo(data[lookahead + Q], 0.01 * Math.pow(10, (0.6 * 22) / 20), 1e-5, 'made up'); }); - androidTest('AnalyserNode windows with Blackman and converts bytes as the spec says', async () => { + nativeTest('AnalyserNode windows with Blackman and converts bytes as the spec says', async () => { const context = new OfflineAudioContext(1, 4096, RATE); const analyser = context.createAnalyser({ fftSize: 1024, smoothingTimeConstant: 0 }); // Bin 32 exactly, so the window's gain alone sets the peak. diff --git a/tools/demo/canvas/spec/audio-nodes.ts b/tools/demo/canvas/spec/audio-nodes.ts new file mode 100644 index 00000000..e92318d2 --- /dev/null +++ b/tools/demo/canvas/spec/audio-nodes.ts @@ -0,0 +1,364 @@ +import { AudioBuffer, AudioContext, ConvolverNode, OfflineAudioContext } from '@nativescript/audio-context'; +import { suite, test, equal, closeTo, ok, throws } from './harness'; + +// Node behaviour the spec pins down: channel rules, the DSP nodes, automation and the context clock. + +const RATE = 48000; +const Q = 128; + +function constant(context: any, offset: number, when = 0) { + const source = context.createConstantSource({ offset }); + source.start(when); + return source; +} + +function bufferOf(...channels: Float32Array[]) { + const out = new AudioBuffer({ numberOfChannels: channels.length, length: channels[0].length, sampleRate: RATE }); + channels.forEach((data, c) => out.copyToChannel(data, c)); + return out; +} + +/** A source playing `channels` (one value each) for the whole render. */ +function stereoSource(context: any, values: number[], length: number) { + const source = context.createBufferSource(); + source.buffer = bufferOf(...values.map((v) => new Float32Array(length).fill(v))); + source.start(0); + return source; +} + +async function until(context: AudioContext, time: number) { + const deadline = Date.now() + 5000; + while (context.currentTime < time) { + if (Date.now() > deadline) throw new Error(`currentTime stalled at ${context.currentTime}`); + await new Promise((resolve) => setTimeout(resolve, 5)); + } +} + +export function registerAudioNodesSpec() { + suite('audio.nodes.context', () => { + test('a realtime context runs from construction, its clock from 0', async () => { + const context = new AudioContext(); + const first = context.currentTime; + await until(context, 0.1); + const rate = context.sampleRate; + await context.close(); + ok(first < 0.05, `starts near 0, at ${first}`); + ok(rate >= 8000, `sampleRate ${rate} still readable after close`); + ok(context.currentTime >= 0.1, `currentTime ${context.currentTime} after close`); + }); + + test('honours a sampleRate option and rejects one out of range', async () => { + const context = new AudioContext({ sampleRate: 44100 }); + const rate = context.sampleRate; + await context.close(); + equal(rate, 44100, 'sampleRate'); + throws(() => new AudioContext({ sampleRate: 1000 }), 'NotSupportedError'); + }); + + test('getOutputTimestamp trails currentTime', async () => { + const context = new AudioContext(); + await until(context, 0.1); + const stamp = (context as any).getOutputTimestamp(); + const now = context.currentTime; + await context.close(); + ok(stamp.contextTime <= now && stamp.contextTime >= 0, `contextTime ${stamp.contextTime}, currentTime ${now}`); + ok(stamp.performanceTime > 0, `performanceTime ${stamp.performanceTime}`); + }); + + test('MediaStream nodes throw NotSupportedError', async () => { + const context: any = new AudioContext(); + throws(() => context.createMediaStreamDestination(), 'NotSupportedError'); + await context.close(); + }); + + test('a DelayNode in a realtime cycle delays by one 128-frame quantum at least', async () => { + const context = new AudioContext(); + const analyser = context.createAnalyser({ fftSize: 32768 }); + analyser.connect(context.destination); + const delay = context.createDelay(1); + delay.delayTime.value = 0; + const loop = context.createGain(); + loop.gain.value = 0.5; + const impulse = new Float32Array(Q * 4); + impulse[0] = 1; + const source: any = context.createBufferSource(); + const buffer = context.createBuffer({ numberOfChannels: 1, length: impulse.length, sampleRate: context.sampleRate }); + buffer.copyToChannel(impulse, 0); + source.buffer = buffer; + source.connect(delay); + delay.connect(loop); + loop.connect(delay); + delay.connect(analyser); + source.start(); + await until(context, context.currentTime + 0.3); + const data = new Float32Array(32768); + analyser.getFloatTimeDomainData(data); + await context.close(); + const peaks: number[] = []; + for (let i = 0; i < data.length; i++) if (Math.abs(data[i]) > 1e-3) peaks.push(i); + ok(peaks.length >= 3, `echoes ${peaks.length}`); + for (let k = 1; k < 3; k++) equal(peaks[k] - peaks[k - 1], Q, `echo ${k} spacing`); + closeTo(data[peaks[1]] / data[peaks[0]], 0.5, 1e-4, 'decay per pass'); + }); + + test('a split DelayNode reads its input directly again once the cycle is gone', async () => { + const context = new OfflineAudioContext(1, Q * 4, RATE); + const delay = context.createDelay(1); + delay.delayTime.value = 0; + const loop = context.createGain(); + constant(context, 1).connect(delay); + delay.connect(loop); + loop.connect(delay); + loop.disconnect(); + delay.connect(context.destination); + const samples = (await context.startRendering()).getChannelData(0); + equal(samples[0], 1, 'no quantum of delay on the first frame'); + }); + }); + + suite('audio.nodes.channels', () => { + test('channel rules: panners, convolver and compressor at most 2, never max', () => { + const context = new OfflineAudioContext(2, Q, RATE); + for (const node of [context.createPanner(), context.createStereoPanner(), context.createConvolver(), context.createDynamicsCompressor()] as any[]) { + equal(node.channelCountMode, 'clamped-max', `${node.constructor.name} default mode`); + throws(() => (node.channelCount = 3), 'NotSupportedError', `${node.constructor.name} channelCount 3`); + throws(() => (node.channelCountMode = 'max'), 'NotSupportedError', `${node.constructor.name} max`); + node.channelCount = 1; + node.channelCountMode = 'explicit'; + } + }); + + test('channel rules: splitter and merger are fixed', () => { + const context = new OfflineAudioContext(2, Q, RATE); + const splitter: any = context.createChannelSplitter({ numberOfOutputs: 4 }); + equal(splitter.channelCount, 4, 'splitter channelCount'); + throws(() => (splitter.channelCount = 2), 'InvalidStateError'); + throws(() => (splitter.channelCountMode = 'max'), 'InvalidStateError'); + throws(() => (splitter.channelInterpretation = 'speakers'), 'InvalidStateError'); + const merger: any = context.createChannelMerger({ numberOfInputs: 2 }); + throws(() => (merger.channelCount = 2), 'InvalidStateError'); + throws(() => (merger.channelCountMode = 'max'), 'InvalidStateError'); + equal(merger.numberOfInputs, 2, 'merger inputs'); + equal(splitter.numberOfOutputs, 4, 'splitter outputs'); + }); + + for (const kind of ['gain', 'delay', 'biquad', 'waveshaper', 'iir', 'stereo', 'analyser']) { + test(`${kind}: channelCount 1 explicit down-mixes a stereo input`, async () => { + const context = new OfflineAudioContext(2, Q * 2, RATE); + const c: any = context; + const node: any = + kind === 'gain' + ? c.createGain() + : kind === 'delay' + ? c.createDelay() + : kind === 'biquad' + ? c.createBiquadFilter({ type: 'allpass', frequency: RATE / 2 }) + : kind === 'waveshaper' + ? c.createWaveShaper() + : kind === 'iir' + ? c.createIIRFilter([1], [1]) + : kind === 'stereo' + ? c.createStereoPanner() + : c.createAnalyser(); + node.channelCount = 1; + node.channelCountMode = 'explicit'; + stereoSource(context, [1, 0.5], Q * 2).connect(node); + node.connect(context.destination); + const out = await context.startRendering(); + const l = out.getChannelData(0)[Q]; + const r = out.getChannelData(1)[Q]; + // Mono 0.75 up-mixed; the stereo panner pans that mono centre: 0.75 cos(pi/4) each side. + const want = kind === 'stereo' ? 0.75 * Math.SQRT1_2 : 0.75; + closeTo(l, want, 1e-5, 'left'); + closeTo(r, want, 1e-5, 'right'); + }); + } + + test('a stereo source with equal channels pans as stereo, not as mono', async () => { + const context = new OfflineAudioContext(2, Q, RATE); + const panner = context.createPanner({ positionX: 1, positionZ: -1 } as any); + stereoSource(context, [1, 1], Q).connect(panner); + panner.connect(context.destination); + const out = await context.startRendering(); + // Azimuth 45: L = 1 cos(pi/4), R = 1 + 1 sin(pi/4), times 1/sqrt(2) for distance. + closeTo(out.getChannelData(0)[10], 0.5, 1e-5, 'left'); + closeTo(out.getChannelData(1)[10], (1 + Math.SQRT1_2) * Math.SQRT1_2, 1e-5, 'right'); + }); + + test('a mono source pans as mono', async () => { + const context = new OfflineAudioContext(2, Q, RATE); + const panner = context.createPanner({ positionX: 1, positionZ: -1 } as any); + constant(context, 1).connect(panner); + panner.connect(context.destination); + const out = await context.startRendering(); + closeTo(out.getChannelData(0)[10], 0.2706, 1e-4, 'left'); + closeTo(out.getChannelData(1)[10], 0.6533, 1e-4, 'right'); + }); + }); + + suite('audio.nodes.dsp', () => { + test('HRTF puts a source on the right in the right ear, on the left in the left', async () => { + const render = async (x: number) => { + const context = new OfflineAudioContext(2, Q * 16, RATE); + const panner = context.createPanner({ panningModel: 'HRTF', positionX: x, positionZ: 0 } as any); + const noise = new Float32Array(Q * 16).map((_, i) => Math.sin(i * 0.37) * 0.5 + Math.sin(i * 1.3) * 0.5); + const source: any = context.createBufferSource(); + source.buffer = bufferOf(noise); + source.start(0); + source.connect(panner); + panner.connect(context.destination); + const out = await context.startRendering(); + const energy = (c: number) => out.getChannelData(c).reduce((sum, v) => sum + v * v, 0); + return [energy(0), energy(1)]; + }; + const [rl, rr] = await render(1); + const [ll, lr] = await render(-1); + ok(rr > rl * 2, `right source: left ${rl}, right ${rr}`); + ok(ll > lr * 2, `left source: left ${ll}, right ${lr}`); + closeTo(rl / rr, lr / ll, 0.05, 'mirror images'); + }); + + test('ConvolverOptions.buffer and disableNormalization apply in the constructor', async () => { + const context = new OfflineAudioContext(1, Q * 2, RATE); + const response = bufferOf(Float32Array.from({ length: 10 }, (_, i) => (i === 3 ? 0.5 : 0))); + const convolver = new ConvolverNode(context, { buffer: response, disableNormalization: true }); + equal(convolver.normalize, false, 'normalize'); + ok(convolver.buffer != null, 'buffer'); + const impulse = new Float32Array(Q * 2); + impulse[0] = 1; + const source: any = context.createBufferSource(); + source.buffer = bufferOf(impulse); + source.start(0); + source.connect(convolver); + convolver.connect(context.destination); + const samples = (await context.startRendering()).getChannelData(0); + closeTo(samples[3], 0.5, 1e-6, 'the response, unscaled'); + throws(() => (convolver.buffer = new AudioBuffer({ numberOfChannels: 3, length: 4, sampleRate: RATE })), 'NotSupportedError'); + }); + + test('IIRFilterNode filters with its coefficients', async () => { + const context = new OfflineAudioContext(1, Q, RATE); + const filter = context.createIIRFilter([0.5, 0.5], [1, -0.5]); + const impulse = new Float32Array(Q); + impulse[0] = 1; + const source: any = context.createBufferSource(); + source.buffer = bufferOf(impulse); + source.start(0); + source.connect(filter); + filter.connect(context.destination); + const y = (await context.startRendering()).getChannelData(0); + // y[n] = 0.5 x[n] + 0.5 x[n-1] + 0.5 y[n-1] + closeTo(y[0], 0.5, 1e-6, 'y0'); + closeTo(y[1], 0.75, 1e-6, 'y1'); + closeTo(y[2], 0.375, 1e-6, 'y2'); + }); + + test('WaveShaperNode maps its input through the curve', async () => { + const context = new OfflineAudioContext(1, Q, RATE); + const shaper = context.createWaveShaper({ curve: [0, 0.5, 1] } as any); + constant(context, 0.5).connect(shaper); + shaper.connect(context.destination); + const y = (await context.startRendering()).getChannelData(0); + closeTo(y[0], 0.75, 1e-6, 'curve at 0.5'); + throws(() => ((shaper as any).curve = new Float32Array(1)), 'InvalidStateError'); + }); + + test('StereoPannerNode pans a mono input fully left', async () => { + const context = new OfflineAudioContext(2, Q, RATE); + const pan = context.createStereoPanner({ pan: -1 }); + constant(context, 1).connect(pan); + pan.connect(context.destination); + const out = await context.startRendering(); + closeTo(out.getChannelData(0)[0], 1, 1e-6, 'left'); + closeTo(out.getChannelData(1)[0], 0, 1e-6, 'right'); + }); + + test('AnalyserNode reports a bin-centred sine at |X|/N with the Blackman window', async () => { + const context = new OfflineAudioContext(1, Q * 64, RATE); + const analyser = context.createAnalyser({ fftSize: 2048, smoothingTimeConstant: 0 }); + const oscillator = context.createOscillator({ frequency: (64 * RATE) / 2048 }); + oscillator.connect(analyser); + analyser.connect(context.destination); + oscillator.start(0); + const bins = new Float32Array(1024); + context.suspend((Q * 32) / RATE).then(() => { + analyser.getFloatFrequencyData(bins); + context.resume(); + }); + await context.startRendering(); + closeTo(bins[64], 20 * Math.log10(0.21), 0.1, 'peak bin dB'); + throws(() => (analyser.fftSize = 100), 'IndexSizeError'); + }); + + test('a custom PeriodicWave plays its harmonics', async () => { + const context = new OfflineAudioContext(1, Q * 4, RATE); + const wave = context.createPeriodicWave(new Float32Array(2), Float32Array.from([0, 1]), { disableNormalization: true }); + const oscillator = context.createOscillator({ frequency: 375 }); + oscillator.setPeriodicWave(wave); + oscillator.connect(context.destination); + oscillator.start(0); + const y = (await context.startRendering()).getChannelData(0); + // 375 Hz is 128 frames a cycle: a quarter in, the sine peaks. + closeTo(y[32], 1, 1e-3, 'sin at a quarter cycle'); + equal(oscillator.type, 'custom', 'type'); + }); + + test('AudioBufferSourceNode loops between loopStart and loopEnd', async () => { + const context = new OfflineAudioContext(1, 64, RATE); + const source: any = context.createBufferSource(); + source.buffer = bufferOf(Float32Array.from({ length: 16 }, (_, i) => i)); + source.loop = true; + source.loopStart = 4 / RATE; + source.loopEnd = 8 / RATE; + source.start(0); + source.connect(context.destination); + const y = (await context.startRendering()).getChannelData(0); + equal(y[7], 7, 'plays to the loop end'); + equal(y[8], 4, 'then from loopStart'); + equal(y[12], 4, 'again'); + }); + }); + + suite('audio.nodes.params', () => { + test('exponentialRampToValueAtTime ramps exponentially', async () => { + const context = new OfflineAudioContext(1, Q * 2, RATE); + const source = constant(context, 1); + source.offset.setValueAtTime(1, 0); + source.offset.exponentialRampToValueAtTime(4, Q / RATE); + source.connect(context.destination); + const y = (await context.startRendering()).getChannelData(0); + closeTo(y[Q / 2], 2, 1e-4, 'geometric midpoint'); + closeTo(y[Q], 4, 1e-4, 'the target from its time'); + }); + + test('setTargetAtTime approaches its target with the time constant', async () => { + const context = new OfflineAudioContext(1, Q * 2, RATE); + const source = constant(context, 0); + source.offset.setTargetAtTime(1, 0, Q / RATE); + source.connect(context.destination); + const y = (await context.startRendering()).getChannelData(0); + closeTo(y[Q], 1 - Math.exp(-1), 1e-4, 'one time constant in'); + }); + + test('setValueCurveAtTime interpolates the curve', async () => { + const context = new OfflineAudioContext(1, Q * 2, RATE); + const source = constant(context, 0); + source.offset.setValueCurveAtTime([0, 1, 0], 0, Q / RATE); + source.connect(context.destination); + const y = (await context.startRendering()).getChannelData(0); + closeTo(y[Q / 2], 1, 1e-4, 'middle of the curve'); + closeTo(y[Q / 4], 0.5, 1e-4, 'between points'); + equal(y[Q + 10], 0, 'holds the last value'); + }); + + test('AudioParam methods reject negative times; start twice is an error', () => { + const context = new OfflineAudioContext(1, Q, RATE); + const source = context.createConstantSource(); + throws(() => source.offset.setValueAtTime(1, -1), 'RangeError'); + throws(() => source.offset.exponentialRampToValueAtTime(0, 1), 'RangeError'); + throws(() => source.stop(), 'InvalidStateError'); + source.start(0); + throws(() => source.start(0), 'InvalidStateError'); + }); + }); +} diff --git a/tools/demo/canvas/spec/audio-scheduling.ts b/tools/demo/canvas/spec/audio-scheduling.ts index e55adefa..c3eb13c3 100644 --- a/tools/demo/canvas/spec/audio-scheduling.ts +++ b/tools/demo/canvas/spec/audio-scheduling.ts @@ -55,6 +55,32 @@ const loud = (rms: number) => rms > 0.5; export function registerAudioSchedulingSpec() { suite('audio.scheduling', () => { + // The analyser holds the last 32768 frames, so it sees the whole short burst. + for (const kind of ['constant', 'buffer', 'oscillator']) { + test(`${kind} source stopped 20 ms after start plays 20 ms`, async () => { + const { context, analyser } = await runningContext(); + analyser.fftSize = 32768; + const source: any = kind === 'constant' ? context.createConstantSource({ offset: 1 }) : kind === 'buffer' ? context.createBufferSource() : context.createOscillator({ type: 'square', frequency: 50 }); + if (kind === 'buffer') { + source.buffer = squareBuffer(context, 1); + } + source.connect(analyser); + const t0 = context.currentTime; + source.start(); + source.stop(t0 + 0.02); + await until(context, t0 + 0.3); + const data = new Float32Array(32768); + analyser.getFloatTimeDomainData(data); + const rate = context.sampleRate; + await context.close(); + let loudFrames = 0; + for (let i = 0; i < data.length; i++) if (Math.abs(data[i]) > 0.5) loudFrames++; + const expected = 0.02 * rate; + // Up to a render call either side: start() takes effect at the next one. + ok(loudFrames > expected * 0.4 && loudFrames < expected + 1100, `${loudFrames} loud frames, expected about ${expected}`); + }); + } + test('buffer source sounds only between start(when) and stop(when)', async () => { const { context, analyser } = await runningContext(); const source: any = context.createBufferSource(); @@ -304,6 +330,58 @@ export function registerAudioSchedulingSpec() { ok(quiet(rms), `silent in the next context, rms ${rms}`); }); + test('suspend and resume act on one realtime context, not the others', async () => { + const watch = (context: AudioContext) => { + const analyser = context.createAnalyser({ fftSize: FFT }); + const oscillator = context.createOscillator({ frequency: 441 }); + oscillator.connect(analyser).connect(context.destination); + oscillator.start(); + return analyser; + }; + const snapshot = (analyser: any) => { + const data = new Float32Array(FFT); + analyser.getFloatTimeDomainData(data); + return data; + }; + const same = (a: Float32Array, b: Float32Array) => a.every((v, i) => v === b[i]); + const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); + const a = new AudioContext(); + const b = new AudioContext(); + try { + const outA = watch(a); + const outB = watch(b); + await Promise.all([a.resume(), b.resume()]); + await until(a, a.currentTime + 0.1); + await until(b, b.currentTime + 0.1); + + await a.suspend(); + const [frozenA, runningB, heardA, heardB] = [a.currentTime, b.currentTime, snapshot(outA), snapshot(outB)]; + await wait(300); + ok(a.state === 'suspended' && b.state === 'running', `states ${a.state}, ${b.state}`); + ok(a.currentTime === frozenA, `the suspended clock moved from ${frozenA} to ${a.currentTime}`); + ok(b.currentTime > runningB + 0.15, `the other clock went from ${runningB} to ${b.currentTime}`); + ok(same(heardA, snapshot(outA)), 'the suspended context renders nothing'); + ok(!same(heardB, snapshot(outB)), 'the other context keeps rendering'); + + await a.resume(); + const resumedA = a.currentTime; + await wait(300); + ok(a.currentTime > resumedA + 0.15, `the resumed clock went from ${resumedA} to ${a.currentTime}`); + + await Promise.all([a.suspend(), b.suspend()]); + const [heldA, heldB] = [a.currentTime, b.currentTime]; + await wait(300); + ok(a.currentTime === heldA && b.currentTime === heldB, `held clocks moved: ${heldA} to ${a.currentTime}, ${heldB} to ${b.currentTime}`); + + await Promise.all([a.resume(), b.resume()]); + const [againA, againB] = [a.currentTime, b.currentTime]; + await wait(300); + ok(a.currentTime > againA + 0.15 && b.currentTime > againB + 0.15, `both clocks resume: ${againA} to ${a.currentTime}, ${againB} to ${b.currentTime}`); + } finally { + await Promise.all([a.close(), b.close()]); + } + }); + test('oscillator sounds only between start(when) and stop(when)', async () => { const { context, analyser } = await runningContext(); const oscillator = context.createOscillator({ type: 'square', frequency: 440 }); diff --git a/tools/demo/canvas/spec/audio-worklet.ts b/tools/demo/canvas/spec/audio-worklet.ts index b0514ecb..d86382c7 100644 --- a/tools/demo/canvas/spec/audio-worklet.ts +++ b/tools/demo/canvas/spec/audio-worklet.ts @@ -133,7 +133,7 @@ export function registerAudioWorkletSpec() { fed.connect(context.destination); const samples = (await context.startRendering()).getChannelData(0); equal(samples[0], 0, 'empty until the source starts'); - equal(samples[Q], 2, 'channelCount channels once it plays'); + equal(samples[Q], 1, "the source's channels once it plays (channelCountMode 'max')"); const other = await offline(Q * 3); const unconnected = new AudioWorkletNode(other, 'input-count', { outputChannelCount: [1] }); @@ -145,6 +145,26 @@ export function registerAudioWorkletSpec() { ); }); + test('an input has computedNumberOfChannels for its channelCountMode', async () => { + // [channelCountMode, channelCount, the source's channels, the input's channels] + const cases: [string, number, number, number][] = [ + ['max', 1, 2, 2], + ['max', 2, 1, 1], + ['clamped-max', 1, 2, 1], + ['explicit', 4, 1, 4], + ]; + for (const [channelCountMode, channelCount, channels, expected] of cases) { + const context = await offline(Q * 2); + const node = new AudioWorkletNode(context, 'input-count', { channelCount, channelCountMode, outputChannelCount: [1] } as any); + const merger = context.createChannelMerger(channels); + for (let c = 0; c < channels; c++) constant(context, 1).connect(merger, 0, c); + merger.connect(node); + node.connect(context.destination); + const samples = (await context.startRendering()).getChannelData(0); + equal(samples[Q], expected, `${channelCountMode} ${channelCount} from ${channels} channels`); + } + }); + test('feeds each input separately', async () => { const context = await offline(); const node = new AudioWorkletNode(context, 'sum-inputs', { ...MONO, numberOfInputs: 2, outputChannelCount: [1] }); @@ -230,8 +250,7 @@ export function registerAudioWorkletSpec() { } // Mono up-mixes by copying and down-mixes by averaging, with no pan law. - test('a mono source plays at full level in a realtime context', () => - realtimeLevel((context, analyser) => new AudioWorkletNode(context, 'constant', { numberOfInputs: 0, outputChannelCount: [1] }).connect(analyser), 0.25)); + test('a mono source plays at full level in a realtime context', () => realtimeLevel((context, analyser) => new AudioWorkletNode(context, 'constant', { numberOfInputs: 0, outputChannelCount: [1] }).connect(analyser), 0.25)); test('processes an input in a realtime context', () => realtimeLevel((context, analyser) => { diff --git a/tools/demo/canvas/spec/index.ts b/tools/demo/canvas/spec/index.ts index dce760f7..2258d5d9 100644 --- a/tools/demo/canvas/spec/index.ts +++ b/tools/demo/canvas/spec/index.ts @@ -27,6 +27,7 @@ import { registerAudioOfflineRenderSpec } from './audio-offline-render'; import { registerAudioGraphSpec } from './audio-graph'; import { registerAudioApiSpec } from './audio-api'; import { registerAudioDspSpec } from './audio-dsp'; +import { registerAudioNodesSpec } from './audio-nodes'; import { registerMediaSpec } from './media'; import { registerLifecycleSpec } from './lifecycle'; import { registerOffscreenCanvasSpec } from './offscreen'; @@ -59,6 +60,7 @@ export async function runSpecTests(group: SpecGroup = 'all') { registerAudioGraphSpec(); registerAudioApiSpec(); registerAudioDspSpec(); + registerAudioNodesSpec(); registerAudioWorkletSpec(); if ((typeof __WINDOWS__ !== 'undefined' && __WINDOWS__) || (typeof __LINUX__ !== 'undefined' && __LINUX__)) { registerAudioSpec();