-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebp-worker.mjs
60 lines (57 loc) · 1.55 KB
/
webp-worker.mjs
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
import webp from 'webp-wasm';
import * as u8 from 'u8-encoder';
import { QueueManager } from 'queue-manager-async';
const encodeWebp = async (imageData, opts) => {
const outputBuffer = await webp.encode(imageData, opts);
const uint8Array = new Uint8Array(outputBuffer.buffer, outputBuffer.byteOffset, outputBuffer.byteLength);
return uint8Array;
};
const decodeWebp = async (encodedData) => {
const arrayBuffer = encodedData.buffer.slice(encodedData.byteOffset, encodedData.byteOffset + encodedData.byteLength);
const imageData = await webp.decode(arrayBuffer);
return imageData;
};
const queueManager = new QueueManager();
globalThis.onmessage = async (e) => {
await queueManager.waitForTurn(async () => {
let error, result;
try {
const b = e.data;
const o = u8.decode(b);
const {
method,
args,
} = o;
switch (method) {
case 'encode': {
const {
imageData,
opts,
} = args;
result = await encodeWebp(imageData, opts);
break;
}
case 'decode': {
const {
encodedData,
} = args;
result = await decodeWebp(encodedData);
break;
}
default: {
throw new Error('unknown method: ' + method);
}
}
} catch(err) {
console.error(err);
error = err;
}
let b;
if (!error) {
b = u8.encode({ error: null, result });
} else {
b = u8.encode({ error, result: null });
}
postMessage(b, [b.buffer]);
});
};