-
Notifications
You must be signed in to change notification settings - Fork 141
/
worker.ts
88 lines (78 loc) · 2.28 KB
/
worker.ts
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
import { Runner, env } from '@paddlejs/paddlejs-core';
import { GLHelper } from '@paddlejs/paddlejs-backend-webgl';
import map from './map.json';
const webWorker: Worker = self as any;
const WEBGL_ATTRIBUTES = {
alpha: false,
antialias: false,
premultipliedAlpha: false,
preserveDrawingBuffer: false,
depth: false,
stencil: false,
failIfMajorPerformanceCaveat: true,
powerPreference: 'high-performance'
};
let runner = null;
webWorker.addEventListener('message', async msg => {
const {
event,
data
} = msg.data;
switch (event) {
case 'init':
await initEvent(data);
break;
case 'predict':
await predictEvent(data);
break;
default:
break;
}
});
async function initEvent(config) {
await init(config);
}
async function init(config) {
const offscreenCanvasFor2D = new OffscreenCanvas(1, 1);
// 用来作为 core mediaprocessor 里的 canvas getContext('2d')
env.set('canvas2d', offscreenCanvasFor2D);
env.set('fetch', (path, params) => {
return new Promise(function (resolve) {
fetch(path, {
method: 'get',
headers: params
}).then(response => {
if (params.type === 'arrayBuffer') {
return response.arrayBuffer();
}
return response.json();
}).then(data => resolve(data));
});
});
runner = new Runner(config);
const offscreenCanvas = new OffscreenCanvas(1, 1);
const gl = offscreenCanvas.getContext('webgl2', WEBGL_ATTRIBUTES);
// set gl context
GLHelper.setWebGLRenderingContext(gl);
// set gl version
GLHelper.setWebglVersion(2);
await runner.init();
webWorker.postMessage({
event: 'init'
});
}
async function predictEvent(imageBitmap: ImageBitmap) {
const res = await runner.predict(imageBitmap);
const maxItem = getMaxItem(res);
webWorker.postMessage({
event: 'predict',
data: map[maxItem]
});
}
// 获取数组中的最大值索引
function getMaxItem(datas: number[] = []) {
const max: number = Math.max.apply(null, datas);
const index: number = datas.indexOf(max);
return index;
}
export default null as any;