human/demo/index-worker.js

45 lines
1.9 KiB
JavaScript
Raw Normal View History

// load Human using IIFE script as Chome Mobile does not support Modules as Workers
// import Human from '../dist/human.esm.js';
self.importScripts('../dist/human.js');
2020-10-14 02:52:30 +02:00
2020-10-18 20:14:05 +02:00
let busy = false;
// @ts-ignore // Human is registered as global namespace using IIFE script
// eslint-disable-next-line no-undef, new-cap
const human = new Human.default();
2020-10-15 21:25:58 +02:00
2020-12-08 15:00:44 +01:00
function log(...msg) {
const dt = new Date();
const ts = `${dt.getHours().toString().padStart(2, '0')}:${dt.getMinutes().toString().padStart(2, '0')}:${dt.getSeconds().toString().padStart(2, '0')}.${dt.getMilliseconds().toString().padStart(3, '0')}`;
2020-10-15 21:25:58 +02:00
// eslint-disable-next-line no-console
2020-12-08 15:00:44 +01:00
if (msg) console.log(ts, 'Human:', ...msg);
}
2020-10-15 21:25:58 +02:00
2020-10-14 02:52:30 +02:00
onmessage = async (msg) => {
2020-10-18 20:14:05 +02:00
if (busy) return;
busy = true;
2021-05-30 18:03:34 +02:00
// received from index.js using:
2020-10-16 00:16:05 +02:00
// worker.postMessage({ image: image.data.buffer, width: canvas.width, height: canvas.height, config }, [image.data.buffer]);
const image = new ImageData(new Uint8ClampedArray(msg.data.image), msg.data.width, msg.data.height);
2020-10-15 21:25:58 +02:00
let result = {};
try {
2020-11-09 12:32:11 +01:00
result = await human.detect(image, msg.data.userConfig);
2020-10-15 21:25:58 +02:00
} catch (err) {
result.error = err.message;
2020-11-05 14:21:23 +01:00
log('worker thread error:', err.message);
2020-10-15 21:25:58 +02:00
}
2021-06-04 19:51:01 +02:00
if (result.canvas) { // convert canvas to imageData and send it by reference
const ctx = result.canvas.getContext('2d');
const img = ctx?.getImageData(0, 0, result.canvas.width, result.canvas.height);
result.canvas = null; // must strip original canvas from return value as it cannot be transfered from worker thread
// @ts-ignore tslint wrong type matching for worker
if (img) postMessage({ result, image: img.data.buffer, width: msg.data.width, height: msg.data.height }, [img?.data.buffer]);
// @ts-ignore tslint wrong type matching for worker
else postMessage({ result });
} else {
// @ts-ignore tslint wrong type matching for worker
postMessage({ result });
}
2020-10-18 20:14:05 +02:00
busy = false;
2020-10-14 02:52:30 +02:00
};