-
Notifications
You must be signed in to change notification settings - Fork 284
Expand file tree
/
Copy pathAlphaSynthAudioWorkletOutput.ts
More file actions
302 lines (270 loc) · 11.1 KB
/
Copy pathAlphaSynthAudioWorkletOutput.ts
File metadata and controls
302 lines (270 loc) · 11.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
import { Environment } from '@coderline/alphatab/Environment';
import { Logger } from '@coderline/alphatab/Logger';
import type { Settings } from '@coderline/alphatab/Settings';
import { AlphaSynthWebAudioOutputBase } from '@coderline/alphatab/platform/javascript/AlphaSynthWebAudioOutputBase';
import { BrowserUiFacade } from '@coderline/alphatab/platform/javascript/BrowserUiFacade';
import type {
IAlphaSynthWorkerMessage,
IAlphaTabWorker
} from '@coderline/alphatab/platform/worker/AlphaTabWorkerProtocol';
import { SynthConstants } from '@coderline/alphatab/synth/SynthConstants';
import { CircularSampleBuffer } from '@coderline/alphatab/synth/ds/CircularSampleBuffer';
/**
* @target web
* @internal
*/
type AudioWorkletProcessorMessagePort<T> = Omit<IAlphaTabWorker<T>, 'terminate'> & Pick<MessagePort, 'start'>;
/**
* @target web
* @internal
*/
interface AudioWorkletProcessor {
readonly port: AudioWorkletProcessorMessagePort<IAlphaSynthWorkerMessage>;
process(inputs: Float32Array[][], outputs: Float32Array[][], parameters: Record<string, Float32Array>): boolean;
}
/**
* @target web
* @internal
*/
declare let AudioWorkletProcessor: {
prototype: AudioWorkletProcessor;
new (options?: AudioWorkletNodeOptions): AudioWorkletProcessor;
};
/**
* @target web
* @internal
*/
interface AudioWorkletNode<T> extends AudioNode {
readonly port: AudioWorkletProcessorMessagePort<T>;
}
// Bug 646: Safari 14.1 is buggy regarding audio worklets
// globalThis cannot be used to access registerProcessor or samplerate
// we need to really use them as globals
/**
* @target web
* @internal
*/
declare let registerProcessor: any;
/**
* @target web
* @internal
*/
declare let sampleRate: number;
/**
* This class implements a HTML5 Web Audio API based audio output device
* for alphaSynth using the modern Audio Worklets.
* @target web
* @internal
*/
export class AlphaSynthWebWorklet {
private static _isRegistered = false;
public static init() {
if (AlphaSynthWebWorklet._isRegistered) {
return;
}
AlphaSynthWebWorklet._isRegistered = true;
registerProcessor(
'alphatab',
class AlphaSynthWebWorkletProcessor extends AudioWorkletProcessor {
public static readonly BufferSize: number = 4096;
private _outputBuffer: Float32Array = new Float32Array(0);
private _circularBuffer!: CircularSampleBuffer;
private _bufferCount: number = 0;
private _requestedBufferCount: number = 0;
private _isStopped = false;
constructor(options: AudioWorkletNodeOptions) {
super(options);
Logger.debug('WebAudio', 'creating processor');
this._bufferCount = Math.floor(
(options.processorOptions.bufferTimeInMilliseconds * sampleRate) /
1000 /
AlphaSynthWebWorkletProcessor.BufferSize
);
this._circularBuffer = new CircularSampleBuffer(
AlphaSynthWebWorkletProcessor.BufferSize * this._bufferCount
);
this.port.addEventListener('message', e => this._handleMessage(e));
this.port.start();
}
private _handleMessage(e: MessageEvent<IAlphaSynthWorkerMessage>) {
const data = e.data;
const cmd = data.cmd;
switch (cmd) {
case 'alphaSynth.output.addSamples':
const f: Float32Array = data.samples;
this._circularBuffer.write(f, 0, f.length);
this._requestedBufferCount--;
break;
case 'alphaSynth.output.resetSamples':
this._circularBuffer.clear();
break;
case 'alphaSynth.output.stop':
this._isStopped = true;
break;
}
}
public override process(
_inputs: Float32Array[][],
outputs: Float32Array[][],
_parameters: Record<string, Float32Array>
): boolean {
if (outputs.length !== 1 && outputs[0].length !== 2) {
return false;
}
const left: Float32Array = outputs[0][0];
const right: Float32Array = outputs[0][1];
if (!left || !right) {
return true;
}
const samples: number = left.length + right.length;
let buffer = this._outputBuffer;
if (buffer.length !== samples) {
buffer = new Float32Array(samples);
this._outputBuffer = buffer;
}
const samplesFromBuffer = this._circularBuffer.read(
buffer,
0,
Math.min(buffer.length, this._circularBuffer.count)
);
let s: number = 0;
const min = Math.min(left.length, samplesFromBuffer);
for (let i: number = 0; i < min; i++) {
left[i] = buffer[s++];
right[i] = buffer[s++];
}
if (samplesFromBuffer < left.length) {
for (let i = samplesFromBuffer; i < left.length; i++) {
left[i] = 0;
right[i] = 0;
}
}
this.port.postMessage({
cmd: 'alphaSynth.output.samplesPlayed',
samples: samplesFromBuffer / SynthConstants.AudioChannels
});
this._requestBuffers();
return this._circularBuffer.count > 0 || !this._isStopped;
}
private _requestBuffers(): void {
// if we fall under the half of buffers
// we request one half
const halfBufferCount = (this._bufferCount / 2) | 0;
const halfSamples: number = halfBufferCount * AlphaSynthWebWorkletProcessor.BufferSize;
// Issue #631: it can happen that requestBuffers is called multiple times
// before we already get samples via addSamples, therefore we need to
// remember how many buffers have been requested, and consider them as available.
const bufferedSamples =
this._circularBuffer.count +
this._requestedBufferCount * AlphaSynthWebWorkletProcessor.BufferSize;
if (bufferedSamples < halfSamples) {
for (let i: number = 0; i < halfBufferCount; i++) {
this.port.postMessage({
cmd: 'alphaSynth.output.sampleRequest'
});
}
this._requestedBufferCount += halfBufferCount;
}
}
}
);
}
}
/**
* This class implements a HTML5 Web Audio API based audio output device
* for alphaSynth. It can be controlled via a JS API.
* @target web
* @internal
*/
export class AlphaSynthAudioWorkletOutput extends AlphaSynthWebAudioOutputBase {
private _worklet: AudioWorkletNode<IAlphaSynthWorkerMessage> | null = null;
private _bufferTimeInMilliseconds: number = 0;
private readonly _settings: Settings;
private _boundHandleMessage: (e: MessageEvent<IAlphaSynthWorkerMessage>) => void;
private _pendingEvents?: IAlphaSynthWorkerMessage[];
public constructor(settings: Settings) {
super();
this._settings = settings;
this._boundHandleMessage = e => this._handleMessage(e);
}
public override open(bufferTimeInMilliseconds: number) {
super.open(bufferTimeInMilliseconds);
this._bufferTimeInMilliseconds = bufferTimeInMilliseconds;
this.onReady();
}
public override play(): void {
super.play();
const ctx = this.context!;
// create a script processor node which will replace the silence with the generated audio
BrowserUiFacade.createAlphaSynthAudioWorklet(ctx, this._settings).then(
() => {
this._worklet = new AudioWorkletNode(ctx!, 'alphatab', {
numberOfOutputs: 1,
outputChannelCount: [2],
processorOptions: {
bufferTimeInMilliseconds: this._bufferTimeInMilliseconds
}
}) as AudioWorkletNode<IAlphaSynthWorkerMessage>;
this._worklet.port.addEventListener('message', this._boundHandleMessage);
this._worklet.port.start();
this.source!.connect(this._worklet);
this.source!.start(0);
this._worklet.connect(ctx!.destination);
const pending = this._pendingEvents;
if (pending) {
for (const e of pending) {
this._worklet.port.postMessage(e);
}
this._pendingEvents = undefined;
}
},
(reason: any) => {
Logger.error('WebAudio', `Audio Worklet creation failed: reason=${reason}`);
}
);
}
private _handleMessage(e: MessageEvent<IAlphaSynthWorkerMessage>) {
const data = e.data;
const cmd = data.cmd;
switch (cmd) {
case 'alphaSynth.output.samplesPlayed':
this.onSamplesPlayed(data.samples);
break;
case 'alphaSynth.output.sampleRequest':
this.onSampleRequest();
break;
}
}
public override pause(): void {
super.pause();
if (this._worklet) {
this._worklet.port.postMessage({
cmd: 'alphaSynth.output.stop'
});
this._worklet.port.removeEventListener('message', this._boundHandleMessage);
this._worklet.disconnect();
}
this._worklet = null;
this._pendingEvents = undefined;
}
private _postWorkerMessage(message: IAlphaSynthWorkerMessage) {
const worklet = this._worklet;
if (worklet) {
worklet.port.postMessage(message);
} else {
this._pendingEvents ??= [];
this._pendingEvents.push(message);
}
}
public addSamples(f: Float32Array): void {
this._postWorkerMessage({
cmd: 'alphaSynth.output.addSamples',
samples: Environment.prepareForPostMessage(f)
});
}
public resetSamples(): void {
this._postWorkerMessage({
cmd: 'alphaSynth.output.resetSamples'
});
}
}