-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
342 lines (296 loc) · 8.98 KB
/
index.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
import { Queue } from './utils';
const worker = new Worker(
/* webpackChunkName: "rs-worker" */ new URL('./worker.js', import.meta.url)
);
/**
* @type { HTMLCanvasElement }
*/
const canvas = document.querySelector('#canvas');
// const bridgeCanvas = document.querySelector('#bridge');
let bridgeCanvas;
const video = document.querySelector('#video');
// const btnInitWasm = document.getElementById("btn_init_wasm");
const btn1 = document.getElementById("btn1");
const btn2 = document.getElementById("btn2");
const btn3 = document.getElementById("btn_select_file");
const btn4 = document.getElementById("btn_reset");
const btn5 = document.getElementById("btn_redraw");
const range1 = document.getElementById("low_threshold");
const range2 = document.getElementById("high_threshold");
const btn6 = document.getElementById('btn_pause');
const btnVideo = document.getElementById('btn_video');
const btnImage = document.getElementById('btn_image');
const imageControls = document.querySelector('.image.controls');
const videoControls = document.querySelector('.video.controls');
const brightRange = document.querySelector('#brightness');
const stats = new Stats();
let isPaused = false;
let isReady = false;
let threshold_low = 100;
let threshold_high = 200;
let brightness = 50;
const taskQueue = new Queue();
function checkReady() {
if (!isReady) {
throw alert('Please click `init wasm` firstly.');
}
}
worker.addEventListener('message', e => {
if (e.data === 'worker_created') {
console.log('========== worker successfully initialized ==========');
initWasm();
initWorkerImpl();
initInteractions();
}
});
function initWorkerImpl() {
worker.onmessage = ({ data }) => {
if (data.error) {
console.error(data);
return;
}
const { type } = data;
switch (type) {
case 'WASM_INIT_DONE':
console.log('========== wasm successfully initialized ==========');
const offscreen = canvas.transferControlToOffscreen();
worker.postMessage({ type: "CANVAS", data: offscreen }, [offscreen]);
isReady = true;
// btnInitWasm.removeEventListener('click', initWasm);
break;
case 'FRAME_RENDERED':
stats.end();
break;
default: {
break;
}
}
};
}
function initWasm() {
fetch(`${process.env.ASSET_PATH}rs_js_bg.wasm`)
.then((response) => response.arrayBuffer())
.then((bytes) => {
worker.postMessage({ type: "INIT", data: bytes }, [bytes]);
});
}
function initInteractions() {
// btnInitWasm.addEventListener('click', initWasm);
btn1.addEventListener('click', e => {
checkReady();
const imgUrl = 'https://upload.wikimedia.org/wikipedia/commons/5/55/John_William_Waterhouse_A_Mermaid.jpg';
drawOriginalImage(imgUrl);
worker.postMessage({ type: "DRAW_IMAGE", data: imgUrl });
taskQueue.push({ type: "DRAW_IMAGE", data: imgUrl });
});
btn2.addEventListener('click', e => {
checkReady();
const imgUrl = `${process.env.ASSET_PATH}2.png`;
const img = new Image();
img.onload = () => {
drawOriginalImage(img);
window.createImageBitmap(img).then(imgBitmap => {
worker.postMessage({ type: "DRAW_EDGE", data: {
bitmap: imgBitmap,
low: threshold_low,
high: threshold_high
}}, [imgBitmap]);
});
window.createImageBitmap(img).then(bitmapCopy => {
taskQueue.push({
type: "DRAW_EDGE",
data: {
bitmap: bitmapCopy,
low: threshold_low,
high: threshold_high
},
transfer: [bitmapCopy],
})
});
}
img.src = imgUrl;
});
btn3.addEventListener('click', e => {
checkReady();
const fileInput = document.createElement('input');
fileInput.type = 'file';
fileInput.accept = 'image/*';
fileInput.onchange = loadFileAsUrl;
fileInput.click();
});
btn4.addEventListener('click', e => {
checkReady();
const canvas = document.body.querySelector('#original');
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
worker.postMessage({ type: "RESET" });
});
range1.value = threshold_low;
range2.value = threshold_high;
range1.addEventListener('change', e => {
threshold_low = +e.target.value;
});
range2.addEventListener('change', e => {
threshold_high = +e.target.value
});
btn5.addEventListener('click', async e => {
const task = await taskQueue.head();
if (!task) {
return;
}
worker.postMessage({
type: task.type,
data: task.type === 'DRAW_EDGE' ? {
...task.data,
low: threshold_low,
high: threshold_high
} : task.data,
}, task.transfer);
});
btn6.addEventListener('click', e => {
isPaused = !isPaused;
});
let stopVideo;
btnVideo.addEventListener('click', e => {
stopVideo = initCamera();
imageControls.classList.add('hidden');
videoControls.classList.remove('hidden');
})
btnImage.addEventListener('click', e => {
if (!stopVideo) {
return;
}
imageControls.classList.remove('hidden');
videoControls.classList.add('hidden');
stopVideo();
setTimeout(() => {
worker.postMessage({ type: "RESET" });
}, 50);
})
brightRange.value = brightness;
brightRange.addEventListener('change', e => {
brightness = +e.target.value;
})
}
function drawOriginalImage(img) {
const canvas = document.body.querySelector('#original');
const ctx = canvas.getContext('2d');
if (typeof img === 'string') {
const image = new Image();
image.onload = function() {
ctx.canvas.width = image.width;
ctx.canvas.height = image.height;
ctx.drawImage(image, 0, 0);
}
image.src = img;
} else if (img instanceof HTMLImageElement) {
ctx.canvas.width = img.width;
ctx.canvas.height = img.height;
ctx.drawImage(img, 0, 0);
}
}
function loadFileAsUrl(e) {
const file = e.target.files[0];
const reader = new FileReader();
reader.onload = function(e) {
const url = e.target.result;
drawOriginalImage(url);
const img = new Image();
img.onload = () => {
window.createImageBitmap(img).then(imgBitmap => {
worker.postMessage({ type: "DRAW_EDGE", data: {
bitmap: imgBitmap,
low: threshold_low,
high: threshold_high
}}, [imgBitmap]);
window.createImageBitmap(img).then(bitmapCopy => {
taskQueue.push({
type: "DRAW_EDGE",
data: {
bitmap: bitmapCopy,
low: threshold_low,
high: threshold_high
},
transfer: [bitmapCopy]
})
})
})
}
img.src = url;
}
reader.readAsDataURL(file);
}
function initCamera() {
/** @type { MediaStream } */
let _stream = null;
function stopVideo() {
if (!_stream) {
return;
}
_stream.getTracks().forEach(track => track.stop());
_stream = null;
stats.dom.parentNode.removeChild(stats.dom);
}
navigator.mediaDevices.getUserMedia({ video: true })
.then(stream => {
video.srcObject = _stream = stream;
const videoTrack = stream.getVideoTracks()[0];
const { width, height } = videoTrack.getSettings();
bridgeCanvas = new OffscreenCanvas(width, height);
/* handle visibility change */
document.addEventListener('visibilitychange', e => {
if (document.hidden && _stream) {
_stream.getTracks().forEach(track => track.stop());
_stream = null;
} else {
navigator.mediaDevices.getUserMedia({ video: true })
.then(stream => {
video.srcObject = _stream = stream;
});
}
});
/* init stats */
stats.showPanel(0); // 0: fps, 1: ms, 2: mb, 3+: custom
stats.dom.style.position = 'absolute';
document.body.querySelector('.left').appendChild(stats.dom);
/* init frame renderer ticker */
function onFrame() {
if (!isPaused && _stream) {
getImgbitmapFromVideo(video, width, height).then(bitmap => {
stats.begin();
worker.postMessage({
type: 'VIDEO_FRAME',
data: {
bitmap,
brightness,
},
}, [bitmap]);
});
}
requestAnimationFrame(onFrame);
}
requestAnimationFrame(onFrame);
})
.catch(err => {
console.error(err);
});
return stopVideo;
}
/**
* @deprecated not transferable
*/
function getVideoFrameData(video, w, h) {
/**@type {CanvasRenderingContext2D} */
const ctx = bridgeCanvas.getContext('2d');
canvas.width = w;
canvas.height = h;
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
return ctx.getImageData(0, 0, canvas.width, canvas.height);
}
function getImgbitmapFromVideo(video, w, h) {
const ctx = bridgeCanvas.getContext('2d');
ctx.canvas.width = w;
ctx.canvas.height = h;
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
return window.createImageBitmap(ctx.canvas);
}