Repository navigation
Expand file tree
/
Copy pathtranscode.js
More file actions
64 lines (52 loc) · 1.67 KB
/
Copy pathtranscode.js
File metadata and controls
64 lines (52 loc) · 1.67 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
let workerPromise = null;
let workerClient = null;
class CmdClient {
constructor(port) {
this.port = port;
this.messageCounter = 0;
this.pendingMessages = {};
this.port.addEventListener('message', this._handleMessage.bind(this));
}
send(what, transfer=[]) {
const msgId = ++this.messageCounter;
return new Promise((resolve, reject) => {
this.pendingMessages[msgId] = { resolve, reject };
this.port.postMessage({ ...what, msgId }, transfer);
});
}
_handleMessage(event) {
const data = event.data;
if (data && data.replyFor) {
const { replyFor, value, error } = data;
const handlers = this.pendingMessages[replyFor];
if (handlers) {
if (error !== undefined) {
handlers.reject(error);
} else {
handlers.resolve(value);
}
delete this.pendingMessages[replyFor];
}
}
}
}
async function loadWorker() {
const worker = new Worker(new URL('./worker.js', import.meta.url));
workerClient = new CmdClient(worker);
const module = await WebAssembly.compileStreaming(
fetch(new URL('./transcode.wasm', import.meta.url))
);
await workerClient.send({cmd: 'init', module});
return;
}
function ensure() {
// lazy load but avoid race conditions and loading the worker twice
if (!workerPromise) {
workerPromise = loadWorker();
}
return workerPromise;
}
export async function transcode(data) {
await ensure();
return await workerClient.send({cmd: 'transcode', data}, [data]);
}