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.
14 KiB
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, theimage-processorservice, and theimage-processorworker). 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-59requestscomputeBlurhash = trueon the 1920px main image (up to ~2.76 MP for 4:3, e.g.1920×1440).app/workers/image-processor.js:90-98callsfinalCtx.getImageData(0, 0, targetWidth, targetHeight)— an ~11 MB GPU→CPU readback — and passes all ~2.76M pixels toblurhash.encode(..., 4, 3).- Inside
blurhash@2.0.5,encodeloops over every pixel 12 times (4×3components ≈ 33.2M iterations), callingMath.cos~66M times andMath.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×3encodes only 12 low-frequency DCT color components — it is designed to be encoded from a small image. Marco decodes it at32×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-69callsimageProcessor.process(file, ...)twice sequentially on the raw originalfile: once for the 1920px main image, then again from scratch for the 350px thumbnail.- Each call runs
_getImageDimensions(file)vianew 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,138mounts<img src={{URL.createObjectURL(file)}}>(withoutdecoding="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 MBRGBA). - Allocates a redundant same-size
OffscreenCanvas(srcWidth, srcHeight)(another48–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
OffscreenCanvascapped at 64px (preserving aspect ratio), usinggetContext('2d', { willReadFrequently: true }). - Read
getImageDatafrom that tiny canvas (~3–12 KB instead of ~11 MB) and runblurhash.encode(data, w, h, 4, 3). - Keep the existing
try/catchso 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:
- Call
_getImageDimensions(file)once on the main thread (keeps native browser EXIF-orientation handling and JPEG/PNG/WebP/HEIC/AVIF support). - Calculate both main (
≤1920px) and thumbnail (≤350px) target dimensions up front. - Inside the worker, decode/resize the original
fileonce tomainCanvas(same resize logic as today, hardened per 3.3). - Derive
thumbCanvasdirectly frommainCanvas:- 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≤ thumbMaxDimensionon both axes, derive the thumbnail without any downscaling. - Visually indistinguishable from scaling the 4032px original directly, because stepped scaling passes through ~1920px anyway.
- Preferred:
- Derive the tiny
≤64pxBlurHash canvas fromthumbCanvas(per 3.1). - Run
mainCanvas.convertToBlob(...)andthumbCanvas.convertToBlob(...)concurrently viaPromise.allwith the unchanged quality settings (IMAGE_QUALITY = 0.9,THUMBNAIL_QUALITY = 0.9). - Post back
{ mainBlob, mainDim, thumbBlob, thumbDim, blurhash }. - 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
- Retry hardware resize with an in-memory
Blobbefore software scaling:- Try
createImageBitmap(file, resizeOpts)(omitresizeWidth/resizeHeight/resizeQualitywhen no resize is needed). - If that throws (Android
content://Filedescriptor bug), readfile.arrayBuffer()→new Blob([buffer], { type: file.type })and retrycreateImageBitmap(blob, resizeOpts). This lets Android Chrome use native/Skia DCT-scaled JPEG decoding instead of full-res software canvases. - 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 decodedImageBitmapwhen available.
- Try
- Optimize the stepped software-scaling fallback:
- Eliminate the redundant full-size
OffscreenCanvas(srcWidth, srcHeight)copy — drawsourcedirectly into the first halved canvas (Math.floor(srcWidth * 0.5)×Math.floor(srcHeight * 0.5)), then callsource.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.
- Eliminate the redundant full-size
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.thumbnailUrlto 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. KeepURL.revokeObjectURLinwillDestroyfor 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.gjsmust 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/blurhashtags are unchanged. - Run
pnpm lintandpnpm 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 |