Files
marco/app/services/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

189 lines
5.0 KiB
JavaScript

import Service from '@ember/service';
// We use the special Vite query parameter to load this as a web worker
import Worker from '../workers/image-processor?worker';
/**
* Scale `width`/`height` down to fit within `maxDimension` while preserving
* aspect ratio. Never upscales.
*
* @param {number} width
* @param {number} height
* @param {number} maxDimension
* @returns {{ width: number, height: number }}
*/
export function fitWithin(width, height, maxDimension) {
if (width <= maxDimension && height <= maxDimension) {
return { width, height };
}
if (width >= height) {
return {
width: maxDimension,
height: Math.round(height * (maxDimension / width)),
};
}
return {
width: Math.round(width * (maxDimension / height)),
height: maxDimension,
};
}
export default class ImageProcessorService extends Service {
_worker = null;
_callbacks = new Map();
_msgId = 0;
constructor() {
super(...arguments);
this._initWorker();
}
_initWorker() {
if (!this._worker && typeof Worker !== 'undefined') {
try {
this._worker = new Worker();
this._worker.onmessage = this._handleMessage.bind(this);
this._worker.onerror = this._handleError.bind(this);
} catch (e) {
console.warn('Failed to initialize image-processor worker:', e);
}
}
}
_handleMessage(e) {
const {
id,
success,
mainBlob,
mainDim,
thumbBlob,
thumbDim,
blurhash,
error,
} = e.data;
const resolver = this._callbacks.get(id);
if (resolver) {
this._callbacks.delete(id);
if (success) {
resolver.resolve({ mainBlob, mainDim, thumbBlob, thumbDim, blurhash });
} else {
resolver.reject(new Error(error));
}
}
}
_handleError(error) {
console.error('Image Processor Worker Error:', error);
// Reject all pending jobs
for (const [, resolver] of this._callbacks.entries()) {
resolver.reject(new Error('Worker crashed'));
}
this._callbacks.clear();
// Restart the worker for future jobs
this._worker.terminate();
this._worker = null;
this._initWorker();
}
_getImageDimensions(file) {
return new Promise((resolve, reject) => {
const img = new Image();
const url = URL.createObjectURL(file);
img.onload = () => {
const dimensions = { width: img.width, height: img.height };
URL.revokeObjectURL(url);
resolve(dimensions);
};
img.onerror = () => {
URL.revokeObjectURL(url);
reject(new Error('Could not read image dimensions'));
};
img.src = url;
});
}
/**
* Process a photo in a single worker pass: decode the original once, resize
* it to the main and thumbnail dimensions, and (optionally) generate a
* BlurHash from a tiny downscale.
*
* @param {File|Blob} file
* @param {object} options
* @param {number} options.maxDimension Longest edge of the main image.
* @param {number} options.quality JPEG quality of the main image.
* @param {number} options.thumbMaxDimension Longest edge of the thumbnail.
* @param {number} options.thumbQuality JPEG quality of the thumbnail.
* @param {boolean} [options.computeBlurhash]
* @returns {Promise<{ mainBlob: Blob, mainDim: string, thumbBlob: Blob, thumbDim: string, blurhash: string|null }>}
*/
async processPhoto(file, options = {}) {
const {
maxDimension,
quality,
thumbMaxDimension,
thumbQuality,
computeBlurhash = false,
} = options;
if (!this._worker) {
// Fallback if worker initialization failed (e.g. incredibly old browsers)
throw new Error('Image processor worker is not available.');
}
try {
// 1. Get dimensions safely on the main thread.
const { width: origWidth, height: origHeight } =
await this._getImageDimensions(file);
// 2. Calculate aspect-ratio preserving dimensions for both outputs.
const { width: mainWidth, height: mainHeight } = fitWithin(
origWidth,
origHeight,
maxDimension
);
const { width: thumbWidth, height: thumbHeight } = fitWithin(
origWidth,
origHeight,
thumbMaxDimension
);
// 3. Send to worker for processing.
return new Promise((resolve, reject) => {
const id = ++this._msgId;
this._callbacks.set(id, { resolve, reject });
this._worker.postMessage({
type: 'PROCESS_PHOTO',
id,
file,
origWidth,
origHeight,
mainWidth,
mainHeight,
quality,
thumbWidth,
thumbHeight,
thumbQuality,
computeBlurhash,
});
});
} catch (e) {
throw new Error(`Failed to process image: ${e.message}`, { cause: e });
}
}
willDestroy() {
super.willDestroy(...arguments);
if (this._worker) {
this._worker.terminate();
this._worker = null;
}
this._callbacks.clear();
}
}