Files
marco/app/workers/image-processor.js
raucao 6b37db7d42
CI / Lint (pull_request) Successful in 54s
CI / Test (pull_request) Successful in 1m14s
Release Drafter / Update release notes draft (pull_request) Successful in 17s
Speed up photo processing without noticeable quality loss
Photo processing was slow on most devices because blurhash was encoded
from the full-resolution image, the original file was decoded up to five
times, and the Android fallback path skipped native resizing.

- Encode blurhash from a <=64px canvas instead of full resolution
- Process main image, thumbnail and blurhash in a single worker pass,
  decoding the original only once and deriving the thumbnail from the
  resized main image
- Retry createImageBitmap via an in-memory Blob before falling back to
  stepped software scaling, and validate the browser honored the resize
- Avoid the redundant full-resolution canvas and release intermediate
  canvases during stepped scaling
- Swap the preview to the processed thumbnail and decode it async
- Lower main image JPEG quality to 0.85

Adds unit tests for the image-processor service and documents the design
in doc/dev/photo-upload-performance.md.
2026-11-28 02:52:57 +04:00

264 lines
8.7 KiB
JavaScript

import { encode } from 'blurhash';
// BlurHash 4x3 only encodes 12 low-frequency color components, so encoding from
// a tiny canvas produces a visually identical hash to encoding the full-size
// image — at a fraction of the cost. Marco renders the hash at 32x18
// (see app/components/blurhash.gjs), so 64px on the long edge is plenty.
const BLURHASH_MAX_DIMENSION = 64;
// Draw a decoded bitmap into a fresh OffscreenCanvas at the exact target size,
// then release the bitmap.
function drawBitmapToCanvas(bitmap, targetWidth, targetHeight) {
const canvas = new OffscreenCanvas(targetWidth, targetHeight);
const ctx = canvas.getContext('2d');
if (!ctx) {
throw new Error('Failed to get 2d context from OffscreenCanvas');
}
ctx.imageSmoothingEnabled = true;
ctx.imageSmoothingQuality = 'high';
ctx.drawImage(bitmap, 0, 0, targetWidth, targetHeight);
bitmap.close();
return canvas;
}
// Software scaling fallback used when the browser cannot (or refuses to) resize
// natively. Steps down by halves with bilinear filtering, releasing each
// intermediate canvas immediately, then makes one high-quality pass to the
// exact target. Avoids the old full-resolution duplicate canvas.
function steppedScale(source, targetWidth, targetHeight) {
const canHalve =
source.width * 0.5 > targetWidth && source.height * 0.5 > targetHeight;
// Close enough to the target that a single pass is best quality.
if (!canHalve) {
return drawBitmapToCanvas(source, targetWidth, targetHeight);
}
// First halving straight from the decoded bitmap — no full-size copy.
let currentCanvas = new OffscreenCanvas(
Math.floor(source.width * 0.5),
Math.floor(source.height * 0.5)
);
let ctx = currentCanvas.getContext('2d');
ctx.imageSmoothingEnabled = true;
ctx.imageSmoothingQuality = 'medium';
ctx.drawImage(source, 0, 0, currentCanvas.width, currentCanvas.height);
source.close();
// Step down by halves until the next halving would undershoot the target.
while (
currentCanvas.width * 0.5 > targetWidth &&
currentCanvas.height * 0.5 > targetHeight
) {
const nextCanvas = new OffscreenCanvas(
Math.floor(currentCanvas.width * 0.5),
Math.floor(currentCanvas.height * 0.5)
);
const nextCtx = nextCanvas.getContext('2d');
nextCtx.imageSmoothingEnabled = true;
nextCtx.imageSmoothingQuality = 'medium';
nextCtx.drawImage(currentCanvas, 0, 0, nextCanvas.width, nextCanvas.height);
// Release the previous canvas' backing store immediately.
currentCanvas.width = 0;
currentCanvas.height = 0;
currentCanvas = nextCanvas;
}
// Final high-quality resize to the exact target.
const finalCanvas = new OffscreenCanvas(targetWidth, targetHeight);
const finalCtx = finalCanvas.getContext('2d');
finalCtx.imageSmoothingEnabled = true;
finalCtx.imageSmoothingQuality = 'high';
finalCtx.drawImage(currentCanvas, 0, 0, targetWidth, targetHeight);
currentCanvas.width = 0;
currentCanvas.height = 0;
return finalCanvas;
}
// Decode the original file once and resize it to the target dimensions.
//
// Strategy:
// 1. Try native/hardware resizing directly from the File.
// 2. If that throws (Android's `content://` File descriptor bug in workers),
// retry via an in-memory Blob so the browser can still DCT-scale natively.
// 3. Validate the browser actually honored the resize request; if not — or if
// both attempts failed — fall back to stepped software scaling, reusing the
// already-decoded bitmap where possible.
async function decodeResized(file, targetWidth, targetHeight, needsResize) {
const resizeOptions = needsResize
? {
resizeWidth: targetWidth,
resizeHeight: targetHeight,
resizeQuality: 'high',
}
: {};
const isExactTarget = (bitmap) =>
bitmap.width === targetWidth && bitmap.height === targetHeight;
// 1. Happy path: decode + resize straight from the File.
try {
const bitmap = await createImageBitmap(file, resizeOptions);
return isExactTarget(bitmap)
? drawBitmapToCanvas(bitmap, targetWidth, targetHeight)
: steppedScale(bitmap, targetWidth, targetHeight);
} catch (fileError) {
console.warn(
'Hardware resize from File failed, retrying via in-memory Blob:',
fileError
);
}
// 2. Android workaround: read into memory and retry native resizing.
const buffer = await file.arrayBuffer();
const blob = new Blob([buffer], { type: file.type });
try {
const bitmap = await createImageBitmap(blob, resizeOptions);
return isExactTarget(bitmap)
? drawBitmapToCanvas(bitmap, targetWidth, targetHeight)
: steppedScale(bitmap, targetWidth, targetHeight);
} catch (blobError) {
console.warn(
'Hardware resize from Blob failed, falling back to stepped software scaling:',
blobError
);
}
// 3. Last resort: decode at full size and scale in steps.
const source = await createImageBitmap(blob);
return steppedScale(source, targetWidth, targetHeight);
}
// Derive the thumbnail from the already-resized main canvas — the original file
// is never decoded a second time.
async function deriveThumbnail(mainCanvas, thumbWidth, thumbHeight) {
// Main image is already thumbnail-sized; reuse it as-is.
if (mainCanvas.width === thumbWidth && mainCanvas.height === thumbHeight) {
return mainCanvas;
}
try {
const bitmap = await createImageBitmap(mainCanvas, {
resizeWidth: thumbWidth,
resizeHeight: thumbHeight,
resizeQuality: 'high',
});
return bitmap.width === thumbWidth && bitmap.height === thumbHeight
? drawBitmapToCanvas(bitmap, thumbWidth, thumbHeight)
: steppedScale(bitmap, thumbWidth, thumbHeight);
} catch (thumbError) {
console.warn(
'Native thumbnail resize failed, scaling from canvas:',
thumbError
);
const bitmap = await createImageBitmap(mainCanvas);
return steppedScale(bitmap, thumbWidth, thumbHeight);
}
}
// Encode a BlurHash from a tiny, aspect-preserving downscale of the source.
function computeBlurhash(source) {
const scale = Math.min(
1,
BLURHASH_MAX_DIMENSION / Math.max(source.width, source.height)
);
const width = Math.max(1, Math.round(source.width * scale));
const height = Math.max(1, Math.round(source.height * scale));
const canvas = new OffscreenCanvas(width, height);
const ctx = canvas.getContext('2d', { willReadFrequently: true });
ctx.imageSmoothingEnabled = true;
ctx.imageSmoothingQuality = 'high';
ctx.drawImage(source, 0, 0, width, height);
const imageData = ctx.getImageData(0, 0, width, height);
return encode(imageData.data, width, height, 4, 3);
}
self.onmessage = async (e) => {
// Ignore internal browser/Vite/extension pings that don't match our job signature.
if (e.data?.type !== 'PROCESS_PHOTO') return;
const {
id,
file,
origWidth,
origHeight,
mainWidth,
mainHeight,
quality,
thumbWidth,
thumbHeight,
thumbQuality,
computeBlurhash: shouldComputeBlurhash,
} = e.data;
try {
// 1. Decode + resize the original exactly once for the main image.
const needsResize = origWidth !== mainWidth || origHeight !== mainHeight;
const mainCanvas = await decodeResized(
file,
mainWidth,
mainHeight,
needsResize
);
// 2. Derive the thumbnail from the main canvas (no second decode).
const thumbCanvas = await deriveThumbnail(
mainCanvas,
thumbWidth,
thumbHeight
);
// 3. Generate BlurHash from a tiny canvas, if requested.
let blurhash = null;
if (shouldComputeBlurhash) {
try {
blurhash = computeBlurhash(thumbCanvas);
} catch (blurhashError) {
console.warn(
'Could not generate blurhash (possible canvas fingerprinting protection):',
blurhashError
);
}
}
const mainDim = `${mainCanvas.width}x${mainCanvas.height}`;
const thumbDim = `${thumbCanvas.width}x${thumbCanvas.height}`;
// 4. Compress both images to JPEG concurrently.
const [mainBlob, thumbBlob] = await Promise.all([
mainCanvas.convertToBlob({ type: 'image/jpeg', quality }),
thumbCanvas.convertToBlob({ type: 'image/jpeg', quality: thumbQuality }),
]);
// Release canvas backing stores now that the blobs are materialized.
mainCanvas.width = 0;
mainCanvas.height = 0;
if (thumbCanvas !== mainCanvas) {
thumbCanvas.width = 0;
thumbCanvas.height = 0;
}
// 5. Send results back to the main thread.
self.postMessage({
id,
success: true,
mainBlob,
mainDim,
thumbBlob,
thumbDim,
blurhash,
});
} catch (error) {
self.postMessage({
id,
success: false,
error: error.message,
});
}
};