Skip to content

Use web worker for Quantize and Score steps #129

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion typescript/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"importHelpers": true,
"module": "es2015",
"module": "es2020",
"moduleResolution": "node",
"noFallthroughCasesInSwitch": true,
"noImplicitAny": true,
Expand Down
40 changes: 20 additions & 20 deletions typescript/utils/image_utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,7 @@
* limitations under the License.
*/

import {QuantizerCelebi} from '../quantize/quantizer_celebi.js';
import {Score} from '../score/score.js';

import {argbFromRgb} from './color_utils.js';
import {rankedColorsFromImageBytes} from './image_utils_converter.js';

/**
* Get the source color from an image.
Expand All @@ -29,7 +26,8 @@ import {argbFromRgb} from './color_utils.js';
export async function sourceColorFromImage(image: HTMLImageElement) {
// Convert Image data to Pixel Array
const imageBytes = await new Promise<Uint8ClampedArray>((resolve, reject) => {
const canvas = document.createElement('canvas');
const element = document.createElement('canvas');
const canvas = 'OffscreenCanvas' in window ? element.transferControlToOffscreen() : element;
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does it make any sense to use transferControlToOffscreen() without using this canvas in the web worker? 🤔

If not, does it make any sense to move the callback function code into the web worker? 🤔

const context = canvas.getContext('2d');
if (!context) {
reject(new Error('Could not get canvas context'));
Expand All @@ -38,6 +36,7 @@ export async function sourceColorFromImage(image: HTMLImageElement) {
const callback = () => {
canvas.width = image.width;
canvas.height = image.height;
// @ts-ignore
context.drawImage(image, 0, 0);
let rect = [0, 0, image.width, image.height];
const area = image.dataset['area'];
Expand All @@ -48,6 +47,7 @@ export async function sourceColorFromImage(image: HTMLImageElement) {
});
}
const [sx, sy, sw, sh] = rect;
// @ts-ignore
resolve(context.getImageData(sx, sy, sw, sh).data);
};
if (image.complete) {
Expand All @@ -57,23 +57,23 @@ export async function sourceColorFromImage(image: HTMLImageElement) {
}
});

// Convert Image data to Pixel Array
const pixels: number[] = [];
for (let i = 0; i < imageBytes.length; i += 4) {
const r = imageBytes[i];
const g = imageBytes[i + 1];
const b = imageBytes[i + 2];
const a = imageBytes[i + 3];
if (a < 255) {
continue;
}
const argb = argbFromRgb(r, g, b);
pixels.push(argb);
let ranked: number[];

if (window.Worker) {
const worker = new Worker(new URL('./image_utils_worker.js', import.meta.url), {type: 'module'});

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If I create a new web worker here, do I have to destroy it somehow afterwards? 🤔


worker.postMessage(imageBytes);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The second argument of postMessage is an optional array of transferable objects, which are objects that can be transferred from one context to another with zero-copy. The imageBytes is a Uint8ClampedArray that is not a transferable type. This means that we can't just write:

worker.postMessage(imageBytes, [imageBytes]);

The supported types of transferable objects are ArrayBuffer, MessagePort, and ImageBitmap.

So to fix this, we need to pass the underlying ArrayBuffer of the imageBytes as the first argument, and [imageBytes.buffer] as the second argument. This way, we are transferring the ownership of the ArrayBuffer to the worker, and avoiding unnecessary copying:

worker.postMessage(imageBytes.buffer, [imageBytes.buffer]);

But in this case, we need in the web worker to use:

const imageBytes = new Uint8ClampedArray(event.data);

instead of:

const imageBytes = event.data;

Does it make any sense? Does new Uint8ClampedArray(event.data) create a copy? 🤔

Can we write

worker.postMessage(imageBytes, [imageBytes.buffer]);

instead of

worker.postMessage(imageBytes.buffer, [imageBytes.buffer]);

Is that even correct? The browser doesn't give any errors. But does it work? Does such a code make any sense at all?


ranked = await new Promise((resolve) => {
worker.onmessage = (event) => {
const ranked = event.data;
resolve(ranked);
};
});
} else {
ranked = rankedColorsFromImageBytes(imageBytes);
}

// Convert Pixels to Material Colors
const result = QuantizerCelebi.quantize(pixels, 128);
const ranked = Score.score(result);
const top = ranked[0];
return top;
}
48 changes: 48 additions & 0 deletions typescript/utils/image_utils_converter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
/**
* @license
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import {QuantizerCelebi} from '../quantize/quantizer_celebi.js';
import {Score} from '../score/score.js';

import {argbFromRgb} from './color_utils.js';

/**
* Get ranked colors from image bytes.
*
* @param imageBytes The image bytes
* @return Ranked colors - the colors most suitable for creating a UI theme
*/
export function rankedColorsFromImageBytes(imageBytes: Uint8ClampedArray) {
// Convert Image data to Pixel Array
const pixels: number[] = [];
for (let i = 0; i < imageBytes.length; i += 4) {
const r = imageBytes[i];
const g = imageBytes[i + 1];
const b = imageBytes[i + 2];
const a = imageBytes[i + 3];
if (a < 255) {
continue;
}
const argb = argbFromRgb(r, g, b);
pixels.push(argb);
}

// Convert Pixels to Material Colors
const result = QuantizerCelebi.quantize(pixels, 128);
const ranked = Score.score(result);
return ranked;
}
24 changes: 24 additions & 0 deletions typescript/utils/image_utils_worker.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/**
* @license
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import {rankedColorsFromImageBytes} from './image_utils_converter.js';

self.onmessage = (event) => {
const imageBytes = event.data;
const ranked = rankedColorsFromImageBytes(imageBytes);
self.postMessage(ranked);
}