-
Notifications
You must be signed in to change notification settings - Fork 40
Expand file tree
/
Copy pathindex.ts
More file actions
186 lines (148 loc) · 5.12 KB
/
index.ts
File metadata and controls
186 lines (148 loc) · 5.12 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
import invariant from 'invariant';
import {
EventEmitter,
Renderer,
} from '@elemaudio/core';
// NEEDS WASM_ASYNC COMPILATION FLAG IN THE WASM BUILD SCRIPT
import Module from './elementary-wasm.cjs';
export default class OfflineRenderer extends EventEmitter {
private _module: any;
private _native: any;
private _renderer: Renderer;
private _numInputChannels: number;
private _numOutputChannels: number;
private _blockSize: number;
async initialize(options) {
// Default option assignment
const config = Object.assign({
numInputChannels: 0,
numOutputChannels: 2,
sampleRate: 44100,
blockSize: 512,
virtualFileSystem: {},
}, options);
// Unpack
const {
numInputChannels,
numOutputChannels,
sampleRate,
blockSize,
virtualFileSystem,
} = config;
this._numInputChannels = numInputChannels;
this._numOutputChannels = numOutputChannels;
this._blockSize = blockSize;
try {
this._module = await Module();
this._native = new this._module.ElementaryAudioProcessor(numInputChannels, numOutputChannels);
this._native.prepare(sampleRate, blockSize);
} catch (e) {
if (e instanceof WebAssembly.RuntimeError) {
throw new Error('Failed to load the Elementary WASM backend. Running Elementary within Node.js requires Node v18, or Node v16 with --experimental-wasm-eh enabled.');
}
throw e;
}
const validVFS = typeof virtualFileSystem === 'object' &&
virtualFileSystem !== null &&
Object.keys(virtualFileSystem).length > 0;
if (validVFS) {
for (let [key, val] of Object.entries(virtualFileSystem)) {
let result = this._native.addSharedResource(key, val);
if (!result.success) {
this.emit('error', new Error(result.message));
}
}
}
this._renderer = new Renderer((batch) => {
return this._native.postMessageBatch(batch);
});
}
async render(...args) {
const {result, ...stats} = await this._renderer.render(...args);
if (!result.success) {
return Promise.reject(result);
}
return Promise.resolve(stats);
}
createRef(kind, props, children) {
return this._renderer.createRef(kind, props, children);
}
process(inputs: Array<Float32Array>, outputs: Array<Float32Array>) {
if (!Array.isArray(inputs) || inputs.length !== this._numInputChannels)
throw new Error(`Invalid input data; expected an array of ${this._numInputChannels} Float32Array buffers.`);
if (!Array.isArray(outputs) || outputs.length !== this._numOutputChannels)
throw new Error(`Invalid output data; expected an array of ${this._numOutputChannels} Float32Array buffers.`);
// Nothing to do
if (outputs.length === 0) {
return;
}
// Process internal.
//
// We step through the desired output buffer in blocks to ensure we
// process the event queue regularly. If the user wants smaller block sizes
// they can configure it as such or simply call `process` multiple times themselves.
for (let k = 0; k < outputs[0].length; k += this._blockSize) {
// Write the input data to the internal memory
inputs.forEach((buf, i) => {
const internalData = this._native.getInputBufferData(i);
for (let j = 0; j < this._blockSize; ++j) {
internalData[j] = (k + j) < buf.length ? buf[k + j] : 0;
}
});
this._native.process(this._blockSize);
this._native.processQueuedEvents((evtBatch) => {
evtBatch.forEach(({type, event}) => {
this.emit(type, event);
});
});
// Write the internal memory to a new output buffer and return
outputs.forEach((buf, i) => {
const internalData = this._native.getOutputBufferData(i);
for (let j = 0; j < this._blockSize; ++j) {
if (k + j < buf.length) {
buf[k + j] = internalData[j];
}
}
});
}
}
updateVirtualFileSystem(vfs) {
const valid = typeof vfs === 'object' && vfs !== null;
invariant(valid, "Virtual file system must be an object mapping string type keys to Array<Float32Array> | Float32Array type values");
Object.keys(vfs).forEach(function(key) {
const validValue = typeof vfs[key] === 'object' &&
(Array.isArray(vfs[key]) || (vfs[key] instanceof Float32Array));
invariant(validValue, "Virtual file system must be an object mapping string type keys to Array<Float32Array> | Float32Array type values");
});
for (let [key, val] of Object.entries(vfs)) {
let result = this._native.addSharedResource(key, val);
if (!result.success) {
return result;
}
}
return {
success: true,
message: 'Ok',
};
}
pruneVirtualFileSystem() {
this._native.pruneSharedResources();
}
listVirtualFileSystem() {
return this._native.listSharedResources();
}
reset() {
this._native.reset();
}
gc() {
let pruned = this._native.gc();
this._renderer.prune(pruned);
return pruned;
}
setCurrentTime(t) {
this._native.setCurrentTime(t);
}
setCurrentTimeMs(t) {
this._native.setCurrentTimeMs(t);
}
}