Files
marco/doc/dev/photo-upload-performance.md
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

14 KiB
Raw Permalink Blame History

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