-
Notifications
You must be signed in to change notification settings - Fork 0
/
opus.js
348 lines (301 loc) · 6.42 KB
/
opus.js
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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
(function () {
'use strict';
var ENABLE_LOG = false;
var ENABLE_CONCURRENCY = true;
var MAX_CONCURRENCY = 4;
var DEFAULT_CONCURRENCY = 2;
var STATE_INIT = 0;
var STATE_LOADING = 1;
var STATE_READY = 2;
var IDLE_TIMEOUT = 500;
var HARDWARE_CONCURRANCY = Math.min(MAX_CONCURRENCY, (navigator["hardwareConcurrency"] || DEFAULT_CONCURRENCY));
var LIBRARY_URL = (window["WebAssembly"] ? "opus.wasm.js" : "opus.asm.js");
var DEPENDENCY_URL = (window["WebAssembly"] ? "opus.wasm.wasm" : "opus.asm.js.mem");
var _state = STATE_INIT;
var _queue = [];
var _pending = [];
var _counter = 0;
var _workers = [];
var _isConcurrent = true;
var _idleTimer = null;
var _hotLoad = false;
var _workerURL = null;
if (_isConcurrent)
{
window.OpusDecoder = function (buffer, callback)
{
_queue.unshift([_counter++, buffer, callback]);
if (_state == STATE_READY)
ProcessNext();
else if (_state == STATE_INIT)
Initialise();
};
window.OpusDecoder["Initialise"] = function (n)
{
// NOTE this method is specifically called when we want to hot load
// audio files during gameplay, so we should avoid auto killing the
// decoder if this has been called
_hotLoad = true;
Initialise(n);
};
window.OpusDecoder["Destroy"] = function ()
{
Destroy();
};
window.OpusDecoder["type"] = "concurrent";
}
// logging functions, not normally enabled
function log ()
{
if (ENABLE_LOG)
console.log.apply(console, arguments);
}
function startProfile ()
{
if (ENABLE_LOG)
console.profile("audio");
}
function snapshotProfile (n)
{
if (ENABLE_LOG)
console.takeHeapSnapshot(n);
}
function delayedSnapshotProfile (n, t)
{
if (ENABLE_LOG)
setTimeout(snapshotProfile, t, n);
}
function delayedEndProfile (t)
{
if (ENABLE_LOG)
setTimeout(endProfile, t);
}
function endProfile ()
{
if (ENABLE_LOG)
console.profileEnd("audio");
}
// loader functions
function IsWKWebView ()
{
var isIOS = /(iphone|ipod|ipad)/i.test(navigator.userAgent);
var isCordova = !!window["cordova"];
return isIOS && isCordova;
}
function Initialise (n)
{
if (_state != STATE_INIT)
return;
_state = STATE_LOADING;
if (_isConcurrent)
{
log("Initialising multi-worker opus decoder");
startProfile();
snapshotProfile("init")
GetWorkerURL(function (err, url) {
if (err)
throw new Error(err);
var count = n || HARDWARE_CONCURRANCY;
while (count--)
CreateWorker(url);
_state = STATE_READY;
ProcessNext();
});
}
}
function Destroy ()
{
if (_state != STATE_READY)
return;
log("Destroying opus decoder");
CancelIdleTimer();
for (var i = 0, l = _workers.length; i < l; i++)
_workers[i].terminate();
_state = STATE_INIT;
_queue.length = 0;
_pending.length = 0;
_counter = 0;
_workers.length = 0;
snapshotProfile("destroy");
delayedEndProfile(5000);
delayedSnapshotProfile("after completion", 5000);
}
function ProcessNext ()
{
var job;
var buffer;
var callback;
var id;
var worker;
if (_isConcurrent)
{
// jobs are dispatched round robin to workers, so this is isn't 100%
// efficient ( some workers could recieve short files and others long ones )
var L = _workers.length;
if (_queue.length)
{
CancelIdleTimer();
while (_queue.length)
{
job = _queue.pop();
id = job[0];
buffer = job[1];
callback = job[2];
worker = _workers[id % L];
worker.postMessage({
"id": id,
"buffer": buffer
}, [ buffer ]);
_pending.push([id, callback]);
}
}
}
}
function ReadLocalFile (url, cb)
{
var path = window["cordova"]["file"]["applicationDirectory"] + "www/" + url;
window["resolveLocalFileSystemURL"](path, function (entry)
{
entry["file"](function (file)
{
var reader = new FileReader();
reader.onload = function ()
{
cb(null, reader.result);
};
reader.onerror = function ()
{
cb("Failed to read " + path);
};
reader.readAsArrayBuffer(file);
})
});
}
function GetWorkerURL (cb)
{
// NOTE if we're running on WKWebView we need to take a slightly round
// about way to load the worker
if (IsWKWebView())
{
if (_workerURL)
{
cb(null, _workerURL);
}
else
{
ReadLocalFile(LIBRARY_URL, function (err, workContent)
{
if (err)
cb(err);
else
{
_workerURL = URL.createObjectURL(new Blob([ "self[\"IS_WKWEBVIEW\"] = true;\n", workContent ]));
cb(null, _workerURL);
}
});
}
}
else
{
cb(null, LIBRARY_URL);
}
}
function CreateWorker (url)
{
var worker = new Worker(url);
_workers.push(worker);
worker.onmessage = OnWorkerMessage;
}
function RequestFile (url, worker, id)
{
ReadLocalFile(url, function (err, data) {
if (err)
{
worker.postMessage({
"type": "request",
"id": id,
"error": err
});
}
else
{
worker.postMessage({
"type": "request",
"id": id,
"buffer": data
}, [ data ]);
}
});
}
function CompleteJobWithID (id, err, buffer, time)
{
var job;
for (var i = 0, l = _pending.length; i < l; i++)
{
if (_pending[i][0] == id)
{
job = _pending[i];
_pending.splice(i, 1);
break;
}
}
if (!job)
throw new Error("No job with ID " + id);
job[1](err, buffer, time);
if (_pending.length == 0)
{
StartIdleTimer();
}
}
var OnWorkerMessage = function OnWorkerMessage (e)
{
var data = e.data;
var id = data["id"];
var worker = this;
switch (data["type"])
{
case "request":
RequestFile(data["url"], worker, id);
break;
case "error":
CompleteJobWithID(id, data["value"], null);
break;
case "complete":
CompleteJobWithID(id, null, data["value"], data["time"]);
break;
}
}
function StartIdleTimer ()
{
// NOTE hotload requires the decoder to be called at various points
// during gameplay, not just during initialisation, so we should avoid
// destroying the workers after the initial batch
if (_hotLoad)
return;
if (_idleTimer)
{
CancelIdleTimer();
}
log("Starting idle timer");
snapshotProfile("idle");
_idleTimer = setTimeout(TriggerIdle, IDLE_TIMEOUT);
}
function CancelIdleTimer ()
{
if (_idleTimer)
{
log("Cancelling idle timer");
clearTimeout(_idleTimer);
_idleTimer = null;
}
}
var TriggerIdle = function TriggerIdle ()
{
if (_idleTimer)
{
log("Completing idle timer");
_idleTimer = null;
Destroy();
}
}
})();