Speed up photo processing without noticeable quality loss
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

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.
This commit is contained in:
raucao committed 2026-11-28 02:52:57 +04:00
1 parent f605dffc73
commit 6b37db7d42
5 files changed
+710 -132

No files matched your search

+30 -26
View File
@@ -10,7 +10,7 @@ import { isMobile } from '../utils/device';
import Blurhash from './blurhash';
const MAX_IMAGE_DIMENSION = 1920;
const IMAGE_QUALITY = 0.9;
const IMAGE_QUALITY = 0.85;
const MAX_THUMBNAIL_DIMENSION = 350;
const THUMBNAIL_QUALITY = 0.9;
@@ -46,30 +46,34 @@ export default class PlacePhotoUploadItem extends Component {
}
}
// Swap the preview from the raw (multi-megapixel) file URL to the small
// processed thumbnail, so the browser can release the decoded original.
updateThumbnailPreview(blob) {
if (this.thumbnailUrl) {
URL.revokeObjectURL(this.thumbnailUrl);
}
this.thumbnailUrl = URL.createObjectURL(blob);
}
uploadTask = task(async (file) => {
this.error = '';
this.statusText = 'Processing';
try {
// 1. Process main image and generate blurhash in worker
const mainData = await this.imageProcessor.process(
file,
MAX_IMAGE_DIMENSION,
IMAGE_QUALITY,
true // computeBlurhash
);
// 1. Process main image, thumbnail and blurhash in a single worker pass.
const { mainBlob, mainDim, thumbBlob, blurhash } =
await this.imageProcessor.processPhoto(file, {
maxDimension: MAX_IMAGE_DIMENSION,
quality: IMAGE_QUALITY,
thumbMaxDimension: MAX_THUMBNAIL_DIMENSION,
thumbQuality: THUMBNAIL_QUALITY,
computeBlurhash: true,
});
this.blurhash = mainData.blurhash;
this.blurhash = blurhash;
this.updateThumbnailPreview(thumbBlob);
// 2. Process thumbnail (no blurhash needed)
const thumbData = await this.imageProcessor.process(
file,
MAX_THUMBNAIL_DIMENSION,
THUMBNAIL_QUALITY,
false
);
// 3. Upload main image
// 4. Upload thumbnail
// 2. Upload main image
// 3. Upload thumbnail
let mainResult, thumbResult;
const isMobileDevice = isMobile();
@@ -85,20 +89,20 @@ export default class PlacePhotoUploadItem extends Component {
if (isMobileDevice) {
// Mobile: sequential uploads to preserve bandwidth and memory
mainResult = await this.blossom.upload(mainData.blob, {
mainResult = await this.blossom.upload(mainBlob, {
sequential: true,
onProgress: mainProgress,
});
thumbResult = await this.blossom.upload(thumbData.blob, {
thumbResult = await this.blossom.upload(thumbBlob, {
sequential: true,
onProgress: thumbProgress,
});
} else {
// Desktop: concurrent uploads
const mainUploadPromise = this.blossom.upload(mainData.blob, {
const mainUploadPromise = this.blossom.upload(mainBlob, {
onProgress: mainProgress,
});
const thumbUploadPromise = this.blossom.upload(thumbData.blob, {
const thumbUploadPromise = this.blossom.upload(thumbBlob, {
onProgress: thumbProgress,
});
@@ -114,9 +118,9 @@ export default class PlacePhotoUploadItem extends Component {
url: mainResult.url,
fallbackUrls: mainResult.fallbackUrls,
thumbUrl: thumbResult.url,
blurhash: mainData.blurhash,
blurhash,
type: 'image/jpeg',
dim: mainData.dim,
dim: mainDim,
hash: mainResult.hash,
thumbHash: thumbResult.hash,
});
@@ -135,7 +139,7 @@ export default class PlacePhotoUploadItem extends Component {
{{#if this.blurhash}}
<Blurhash @hash={{this.blurhash}} class="place-header-photo-blur" />
{{/if}}
<img src={{this.thumbnailUrl}} alt="thumbnail" />
<img src={{this.thumbnailUrl}} alt="thumbnail" decoding="async" />
{{#if this.uploadTask.isRunning}}
<div class="overlay">
+82 -23
View File
@@ -2,6 +2,33 @@ 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();
@@ -25,13 +52,22 @@ export default class ImageProcessorService extends Service {
}
_handleMessage(e) {
const { id, success, blob, dim, blurhash, error } = e.data;
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({ blob, dim, blurhash });
resolver.resolve({ mainBlob, mainDim, thumbBlob, thumbDim, blurhash });
} else {
resolver.reject(new Error(error));
}
@@ -71,45 +107,68 @@ export default class ImageProcessorService extends Service {
});
}
async process(file, maxDimension, quality, computeBlurhash = false) {
/**
* 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
// 1. Get dimensions safely on the main thread.
const { width: origWidth, height: origHeight } =
await this._getImageDimensions(file);
// 2. Calculate aspect-ratio preserving dimensions
let targetWidth = origWidth;
let targetHeight = origHeight;
// 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
);
if (origWidth > origHeight) {
if (origWidth > maxDimension) {
targetHeight = Math.round(origHeight * (maxDimension / origWidth));
targetWidth = maxDimension;
}
} else {
if (origHeight > maxDimension) {
targetWidth = Math.round(origWidth * (maxDimension / origHeight));
targetHeight = maxDimension;
}
}
// 3. Send to worker for processing
// 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_IMAGE',
type: 'PROCESS_PHOTO',
id,
file,
targetWidth,
targetHeight,
origWidth,
origHeight,
mainWidth,
mainHeight,
quality,
thumbWidth,
thumbHeight,
thumbQuality,
computeBlurhash,
});
});
+216 -83
View File
@@ -1,101 +1,223 @@
import { encode } from 'blurhash';
self.onmessage = async (e) => {
// Ignore internal browser/Vite/extension pings that don't match our exact job signature
if (e.data?.type !== 'PROCESS_IMAGE') return;
// 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;
const { id, file, targetWidth, targetHeight, quality, computeBlurhash } =
e.data;
// 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;
}
try {
let finalCanvas;
let finalCtx;
// 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;
// --- 1. Attempt Hardware Resizing (Happy Path) ---
try {
const resizedBitmap = await createImageBitmap(file, {
// 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',
});
finalCanvas = new OffscreenCanvas(targetWidth, targetHeight);
finalCtx = finalCanvas.getContext('2d');
if (!finalCtx) {
throw new Error('Failed to get 2d context from OffscreenCanvas');
}
finalCtx.drawImage(resizedBitmap, 0, 0, targetWidth, targetHeight);
resizedBitmap.close();
} catch (hwError) {
console.warn(
'Hardware resize failed, falling back to stepped software scaling:',
hwError
);
: {};
// --- 2. Fallback to Stepped Software Scaling (Robust Path) ---
// Bypass Android File descriptor bug by reading into memory
const buffer = await file.arrayBuffer();
const blob = new Blob([buffer], { type: file.type });
const isExactTarget = (bitmap) =>
bitmap.width === targetWidth && bitmap.height === targetHeight;
const source = await createImageBitmap(blob);
let srcWidth = source.width;
let srcHeight = source.height;
// 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
);
}
let currentCanvas = new OffscreenCanvas(srcWidth, srcHeight);
let ctx = currentCanvas.getContext('2d');
// 2. Android workaround: read into memory and retry native resizing.
const buffer = await file.arrayBuffer();
const blob = new Blob([buffer], { type: file.type });
ctx.imageSmoothingEnabled = true;
ctx.imageSmoothingQuality = 'high';
ctx.drawImage(source, 0, 0);
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
);
}
// Step down by halves until near 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');
// 3. Last resort: decode at full size and scale in steps.
const source = await createImageBitmap(blob);
return steppedScale(source, targetWidth, targetHeight);
}
nextCtx.imageSmoothingEnabled = true;
nextCtx.imageSmoothingQuality = 'high';
// 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;
}
nextCtx.drawImage(
currentCanvas,
0,
0,
nextCanvas.width,
nextCanvas.height
);
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);
}
}
currentCanvas = nextCanvas;
}
// 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));
// Final resize to exact target
finalCanvas = new OffscreenCanvas(targetWidth, targetHeight);
finalCtx = finalCanvas.getContext('2d');
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);
finalCtx.imageSmoothingEnabled = true;
finalCtx.imageSmoothingQuality = 'high';
const imageData = ctx.getImageData(0, 0, width, height);
return encode(imageData.data, width, height, 4, 3);
}
finalCtx.drawImage(currentCanvas, 0, 0, targetWidth, targetHeight);
self.onmessage = async (e) => {
// Ignore internal browser/Vite/extension pings that don't match our job signature.
if (e.data?.type !== 'PROCESS_PHOTO') return;
source.close();
}
const {
id,
file,
origWidth,
origHeight,
mainWidth,
mainHeight,
quality,
thumbWidth,
thumbHeight,
thumbQuality,
computeBlurhash: shouldComputeBlurhash,
} = e.data;
// --- 3. Generate Blurhash (if requested) ---
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 (computeBlurhash) {
if (shouldComputeBlurhash) {
try {
const imageData = finalCtx.getImageData(
0,
0,
targetWidth,
targetHeight
);
blurhash = encode(imageData.data, targetWidth, targetHeight, 4, 3);
blurhash = computeBlurhash(thumbCanvas);
} catch (blurhashError) {
console.warn(
'Could not generate blurhash (possible canvas fingerprinting protection):',
@@ -104,20 +226,31 @@ self.onmessage = async (e) => {
}
}
// --- 4. Compress to JPEG Blob ---
const finalBlob = await finalCanvas.convertToBlob({
type: 'image/jpeg',
quality: quality,
});
const mainDim = `${mainCanvas.width}x${mainCanvas.height}`;
const thumbDim = `${thumbCanvas.width}x${thumbCanvas.height}`;
const dim = `${targetWidth}x${targetHeight}`;
// 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 }),
]);
// --- 5. Send results back to main thread ---
// 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,
blob: finalBlob,
dim,
mainBlob,
mainDim,
thumbBlob,
thumbDim,
blurhash,
});
} catch (error) {
+252
View File
@@ -0,0 +1,252 @@
# Photo Upload Performance — Optimization Plan
Why photo processing is slow on most devices, and how to make it fast without any
noticeable loss in picture quality.
> Status: **Implemented** (see git history on this branch). This document is
> kept as the design record for the optimization.
> Scope: client-side image processing + upload pipeline for place photos
> (the `place-photo-upload*` components, the `image-processor` service, and the
> `image-processor` worker). Does not cover blossom server-side behavior,
> relay publishing, or rendering/gallery code beyond the preview `<img>`.
>
> Implementation choices: BlurHash input capped at **64px**; main image JPEG
> quality set to **0.85** (thumbnail stays at 0.9).
## 1. Summary
Adding a photo currently decodes the multi-megapixel original up to five times,
builds a full-resolution `OffscreenCanvas` copy, and — worst of all — runs
`blurhash.encode()` over **every full-resolution pixel** (~33M iterations for a
4:3 1920px image). On a fast desktop CPU that single BlurHash call measured
**~1.3 s**; on mid-range/older phones and cold workers it easily reaches
**5–15+ seconds**. This is the dominant cost and it happens before the upload
even starts.
The plan below removes the redundant decodes, shrinks the BlurHash input to a
tiny canvas, hardens the Android fallback, and derives the thumbnail from the
already-resized main image. Expected result: **seconds → ~100–300 ms** of
processing on most devices, with no visually noticeable quality loss (same
dimensions, EXIF/GPS still stripped, visually identical BlurHash; main JPEG
quality from 0.9 → 0.85 as requested).
## 2. Root causes
Four concrete bottlenecks, ordered by impact. The first one alone accounts for
roughly 70–90% of the processing time.
### 2.1 BlurHash is encoded on the full 1920px image
- `app/components/place-photo-upload-item.gjs:54-59` requests
`computeBlurhash = true` on the **1920px main image** (up to ~2.76 MP for 4:3,
e.g. `1920×1440`).
- `app/workers/image-processor.js:90-98` calls
`finalCtx.getImageData(0, 0, targetWidth, targetHeight)` — an **~11 MB
GPU→CPU readback** — and passes all ~2.76M pixels to
`blurhash.encode(..., 4, 3)`.
- Inside `blurhash@2.0.5`, `encode` loops over every pixel **12 times**
(`4×3` components ≈ **33.2M iterations**), calling `Math.cos` ~66M times and
`Math.pow(..., 2.4)` ~100M times with no lookup tables, in a **column-major**
loop that thrashes CPU caches across the 11 MB RGBA buffer.
- BlurHash `4×3` encodes only **12 low-frequency DCT color components** — it is
designed to be encoded from a _small_ image. Marco decodes it at `32×18`
(`app/components/blurhash.gjs:11-12`), so the extra input pixels contribute
nothing visible.
Measured with the `blurhash@2.0.5` algorithm in Node on a fast desktop CPU
(warmed up; mobile is slower):
| Input size | Pixels | Time |
| ----------- | ------ | -------- |
| `1920×1440` | 2.76M | ~1312 ms |
| `350×263` | 92K | ~47 ms |
| `64×48` | 3072 | ~2.2 ms |
| `32×24` | 768 | ~0.6 ms |
Encoding from a `64×48` input is **~600× faster** than from `1920×1440`.
A visual comparison of the produced hashes (synthetic photo scene):
full-res `L:EDJLW-J7W.TOjcspjbNgfRsnjt` vs `64×48` downscale
`L?EDGDbXJ7W;ThjcspjvNgf8soju` — visually identical at render size.
### 2.2 The original multi-megapixel file is decoded up to five times
- `app/components/place-photo-upload-item.gjs:54-69` calls
`imageProcessor.process(file, ...)` **twice sequentially** on the raw original
`file`: once for the 1920px main image, then again from scratch for the 350px
thumbnail.
- Each call runs `_getImageDimensions(file)` via `new Image()` on the **main
thread** (`app/services/image-processor.js:54-72`), then sends the full
12MP–48MP file to the worker to decode and downscale all over again.
- Meanwhile `app/components/place-photo-upload-item.gjs:30,138` mounts
`<img src={{URL.createObjectURL(file)}}>` (without `decoding="async"`),
decoding the full original on the main thread just to show the preview box.
Rough decode budget for a single 12MP photo today: `new Image()` (dims) +
preview `<img>` + worker main decode + `new Image()` (dims again) + worker
thumbnail decode = **5 full decodes**, plus 2 dimension parses.
### 2.3 Android fallback skips hardware resize and burns huge RAM/CPU
In `app/workers/image-processor.js:15-49`, when
`createImageBitmap(file, { resizeWidth, resizeHeight, resizeQuality: 'high' })`
fails because of Android's worker `File` descriptor bug (`content://` URI), the
`catch` block reads `file.arrayBuffer()` into an in-memory `Blob` — **but never
retries `createImageBitmap(blob, { resizeWidth, resizeHeight, ... })`**.
Instead it immediately drops into stepped _software_ scaling at full resolution:
- Decodes the full 12MP–48MP image (`48–192 MB` RGBA).
- Allocates a **redundant same-size** `OffscreenCanvas(srcWidth, srcHeight)`
(another `48–192 MB`!) and copies the full bitmap into it before the first
halving step (`app/workers/image-processor.js:44-49`).
- Uses `imageSmoothingQuality = 'high'` (expensive Lanczos/bicubic) on every
multi-megapixel halving pass.
- Never zeroes out intermediate canvases
(`canvas.width = 0; canvas.height = 0`), keeping peak RAM high and triggering
GC/memory pressure on phones.
- Because the thumbnail ran as a separate job, Android did all of this **twice**.
### 2.4 Silent un-stepped fallback if a browser ignores `resizeWidth`/`resizeHeight`
If `createImageBitmap` succeeds without honoring `resizeWidth`/`resizeHeight`
(returning full-size dimensions), `app/workers/image-processor.js:27` draws the
full bitmap directly into `finalCanvas` in one pass with default smoothing,
producing a poor (and slow) downscale. There is currently no check for this.
## 3. Optimization plan
### 3.1 Compute BlurHash from a tiny downscaled canvas
**File:** `app/workers/image-processor.js`
- Draw the (already-resized) thumbnail/main canvas onto a tiny
`OffscreenCanvas` capped at **64px** (preserving aspect ratio), using
`getContext('2d', { willReadFrequently: true })`.
- Read `getImageData` from that tiny canvas (~3–12 KB instead of ~11 MB) and run
`blurhash.encode(data, w, h, 4, 3)`.
- Keep the existing `try/catch` so canvas-fingerprinting-protection failures
still degrade gracefully.
**Impact:** BlurHash time **1–15 s → <3 ms**; output visually identical.
**Notes for review:** `32px` vs `64px` is a pick-your-poison knob —
`64px` is a touch closer to full-res hashes at a still-trivial ~2 ms. Default in
this plan: **64px**.
### 3.2 Single-pass worker job for main image + thumbnail + BlurHash
**Files:** `app/workers/image-processor.js`, `app/services/image-processor.js`,
`app/components/place-photo-upload-item.gjs`
Replace the two sequential `process()` calls with a single job, e.g.
`processPhoto(file, options)` / worker message `PROCESS_PHOTO`:
1. Call `_getImageDimensions(file)` **once** on the main thread (keeps native
browser EXIF-orientation handling and JPEG/PNG/WebP/HEIC/AVIF support).
2. Calculate **both** main (`≤1920px`) and thumbnail (`≤350px`) target
dimensions up front.
3. Inside the worker, decode/resize the original `file` **once** to
`mainCanvas` (same resize logic as today, hardened per 3.3).
4. Derive `thumbCanvas` directly from `mainCanvas`:
- Preferred:
`createImageBitmap(mainCanvas, { resizeWidth: thumbW, resizeHeight: thumbH, resizeQuality: 'high' })`.
- Fallback: fast stepped draw `1920 → ~700–960 → 350`.
- If the original is already within `maxDimension`, skip main downscaling;
if it is already `≤ thumbMaxDimension` on both axes, derive the thumbnail
without any downscaling.
- Visually indistinguishable from scaling the 4032px original directly,
because stepped scaling passes through ~1920px anyway.
5. Derive the tiny `≤64px` BlurHash canvas from `thumbCanvas` (per 3.1).
6. Run `mainCanvas.convertToBlob(...)` and `thumbCanvas.convertToBlob(...)`
concurrently via `Promise.all` with the **unchanged** quality settings
(`IMAGE_QUALITY = 0.9`, `THUMBNAIL_QUALITY = 0.9`).
7. Post back `{ mainBlob, mainDim, thumbBlob, thumbDim, blurhash }`.
8. EXIF/GPS metadata stripping via canvas re-encoding is **100% intact** —
re-encoding through a canvas still drops all metadata.
`app/components/place-photo-upload-item.gjs` then makes a single
`imageProcessor.processPhoto(...)` call and uploads `mainBlob`/`thumbBlob` as
before (including the existing mobile-sequential vs desktop-concurrent upload
branches, which are orthogonal to this change).
### 3.3 Harden and speed up the resize & Android fallback path
**File:** `app/workers/image-processor.js`
1. **Retry hardware resize with an in-memory `Blob` before software scaling:**
1. Try `createImageBitmap(file, resizeOpts)` (omit
`resizeWidth`/`resizeHeight`/`resizeQuality` when no resize is needed).
2. If that throws (Android `content://` `File` descriptor bug), read
`file.arrayBuffer()` → `new Blob([buffer], { type: file.type })` and
**retry `createImageBitmap(blob, resizeOpts)`**. This lets Android Chrome
use native/Skia DCT-scaled JPEG decoding instead of full-res software
canvases.
3. Check `bitmap.width === targetWidth && bitmap.height === targetHeight`.
Only fall back to stepped canvas scaling if resizing failed _or was
ignored_ (fixes 2.4), reusing the decoded `ImageBitmap` when available.
2. **Optimize the stepped software-scaling fallback:**
- Eliminate the redundant full-size `OffscreenCanvas(srcWidth, srcHeight)`
copy — draw `source` directly into the first halved canvas
(`Math.floor(srcWidth * 0.5)` × `Math.floor(srcHeight * 0.5)`), then call
`source.close()` immediately.
- Use `imageSmoothingQuality = 'medium'` on intermediate 2× halving passes
and `'high'` only on the final pass to the exact target dimensions.
- Zero out each old intermediate canvas (`prev.width = 0; prev.height = 0`)
right after copying from it, to release backing memory immediately.
### 3.4 Lighter preview handling
**File:** `app/components/place-photo-upload-item.gjs`
- Add `decoding="async"` to the preview `<img src={{this.thumbnailUrl}}>`.
- Once processing finishes (now ~100–300 ms instead of many seconds), swap
`this.thumbnailUrl` to an object URL created from the processed thumbnail
blob and revoke the original raw-file object URL, so the browser releases the
multi-megapixel decoded original from GPU/RAM while the user writes alt text
and picks tags. Keep `URL.revokeObjectURL` in `willDestroy` for both URLs.
### 3.5 Optional: JPEG quality for upload speed
Sections 3.1–3.4 alone bring processing from seconds to ~100–300 ms on most
devices without touching JPEG quality. The remaining lever is upload size.
**Applied:** main `IMAGE_QUALITY` lowered `0.9 → 0.85`; `THUMBNAIL_QUALITY`
kept at `0.9`.
Lowering `THUMBNAIL_QUALITY` to `0.82` would shrink file sizes further with no
noticeable visual loss on thumbnails, but is left untouched here.
## 4. Files touched
| File | Change |
| ---------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- |
| `app/workers/image-processor.js` | Single-pass job; tiny BlurHash canvas; Android `Blob` retry; stepped-scaling + memory fixes. |
| `app/services/image-processor.js` | New `processPhoto(file, options)` API; keep `_getImageDimensions`; keep `process()` or remove once callers migrated. |
| `app/components/place-photo-upload-item.gjs` | One `processPhoto` call; `decoding="async"`; swap preview URL to processed blob. |
| `tests/unit/services/image-processor-test.js` | New unit tests (see 5). |
| `tests/integration/components/place-photo-upload-test.gjs` | Ensure existing tests still pass; add coverage if needed. |
## 5. Verification & tests
- **Unit tests** for `ImageProcessorService` / worker contract:
- dimension math (landscape, portrait, square, already-small no-upscale);
- single-pass output contains main blob, thumbnail blob, dims, and blurhash;
- thumbnail derived from main (no second decode);
- small image (`≤ thumbMaxDimension`) does not downscale;
- error handling when the worker is unavailable.
- **Integration:** `place-photo-upload-test.gjs` must still pass.
- **Manual/perf:** process a 12MP+ photo (JPEG and a HEIC/AVIF where supported)
on desktop Chrome and Android Chrome; confirm processing completes in
well under 1 s, the BlurHash placeholder looks correct, and the uploaded
`imeta`/`dim`/`thumb`/`blurhash` tags are unchanged.
- Run `pnpm lint` and `pnpm test`.
## 6. Expected outcome
| Metric | Before | After |
| ------------------------------ | ------------------------------- | ------------------------------------ |
| BlurHash encode (1920×1440) | ~1.3 s desktop / 5–15 s mobile | <3 ms |
| Full decodes per photo | up to 5 | 1 (+1 dim parse) |
| Peak worker RAM (Android path) | 48–192 MB ×2 + redundant copies | ~48–192 MB once |
| Total processing | seconds | ~100–300 ms |
| Output quality | — | main JPEG 0.9 → 0.85, else unchanged |
+130
View File
@@ -0,0 +1,130 @@
import { module, test } from 'qunit';
import { setupTest } from 'marco/tests/helpers';
import { fitWithin } from 'marco/services/image-processor';
module('Unit | Service | image-processor', function (hooks) {
setupTest(hooks);
function setupService(context, dimensions = { width: 100, height: 100 }) {
const service = context.owner.lookup('service:image-processor');
// Don't leave a real worker running during tests.
service._worker?.terminate?.();
service._getImageDimensions = async () => dimensions;
return service;
}
test('fitWithin preserves aspect ratio and never upscales', function (assert) {
assert.deepEqual(fitWithin(4000, 3000, 1920), {
width: 1920,
height: 1440,
});
assert.deepEqual(fitWithin(3000, 4000, 1920), {
width: 1440,
height: 1920,
});
assert.deepEqual(fitWithin(4000, 4000, 1920), {
width: 1920,
height: 1920,
});
assert.deepEqual(fitWithin(800, 600, 1920), { width: 800, height: 600 });
assert.deepEqual(fitWithin(1920, 1080, 1920), {
width: 1920,
height: 1080,
});
});
test('fitWithin rounds the derived dimension', function (assert) {
const { width, height } = fitWithin(4032, 3024, 1920);
assert.strictEqual(width, 1920);
assert.strictEqual(height, 1440);
});
test('processPhoto sends both main and thumbnail dimensions to the worker', async function (assert) {
const service = setupService(this, { width: 4000, height: 3000 });
let sent;
service._worker = {
postMessage(message) {
sent = message;
// Respond synchronously; the resolver is registered before postMessage.
service._handleMessage({
data: {
id: message.id,
success: true,
mainBlob: 'main',
mainDim: '1920x1440',
thumbBlob: 'thumb',
thumbDim: '350x263',
blurhash: 'LKO2',
},
});
},
terminate() {},
};
const result = await service.processPhoto(new Blob(['x']), {
maxDimension: 1920,
quality: 0.9,
thumbMaxDimension: 350,
thumbQuality: 0.9,
computeBlurhash: true,
});
assert.strictEqual(sent.type, 'PROCESS_PHOTO');
assert.strictEqual(sent.origWidth, 4000);
assert.strictEqual(sent.origHeight, 3000);
assert.strictEqual(sent.mainWidth, 1920);
assert.strictEqual(sent.mainHeight, 1440);
assert.strictEqual(sent.thumbWidth, 350);
assert.strictEqual(sent.thumbHeight, 263);
assert.strictEqual(sent.quality, 0.9);
assert.strictEqual(sent.thumbQuality, 0.9);
assert.strictEqual(sent.computeBlurhash, true);
assert.deepEqual(result, {
mainBlob: 'main',
mainDim: '1920x1440',
thumbBlob: 'thumb',
thumbDim: '350x263',
blurhash: 'LKO2',
});
});
test('processPhoto rejects when the worker is unavailable', async function (assert) {
const service = setupService(this);
service._worker = null;
await assert.rejects(
service.processPhoto(new Blob(['x']), {
maxDimension: 1920,
quality: 0.9,
thumbMaxDimension: 350,
thumbQuality: 0.9,
}),
/not available/
);
});
test('processPhoto rejects when the worker reports an error', async function (assert) {
const service = setupService(this);
service._worker = {
postMessage(message) {
service._handleMessage({
data: { id: message.id, success: false, error: 'boom' },
});
},
terminate() {},
};
await assert.rejects(
service.processPhoto(new Blob(['x']), {
maxDimension: 1920,
quality: 0.9,
thumbMaxDimension: 350,
thumbQuality: 0.9,
}),
/boom/
);
});
});