Open History to see the last commit
1/**
2 * Downscale + re-encode for image attachments that are too big for where
3 * they're headed. Two consumers share the same pipeline:
4 *
5 * - The prompt stash persists images as base64 in localStorage (~5MB origin
6 * quota), so `compressImageForStash` targets a per-image character budget.
7 * - The composer accepts pasted/dropped images larger than the provider's
8 * `PROVIDER_SEND_TURN_MAX_IMAGE_BYTES` wire cap and shrinks them to fit
9 * via `compressImageToByteLimit` instead of rejecting the paste.
10 *
11 * Supported images already within budget pass through untouched. HEIC/HEIF
12 * photos are decoded to JPEG first because providers cannot consume them.
13 */
14
15/**
16 * Longest edge kept when an image has to be re-encoded. Sized so a typical
17 * retina screenshot (3024px wide) stays legible rather than being halved.
18 */
19const MAX_DIMENSION = 2048;
20/** Base64 budget for a single stashed image (~975KB of binary). */
21export const MAX_STASH_IMAGE_DATA_URL_CHARS = 1_300_000;
22/**
23 * Ceiling on the *source* file handed to the re-encoder. File size is a
24 * proxy for pixel count, and decoding hundreds of megapixels into an
25 * ImageBitmap can OOM the tab — beyond this we refuse rather than risk it.
26 */
27export const MAX_COMPRESSIBLE_SOURCE_BYTES = 50 * 1024 * 1024;
28const MAX_HEIC_DECODE_PIXELS = 64_000_000;
29const MAX_HEIC_METADATA_BYTES = 1024 * 1024;
30/**
31 * Quality ladder tried in order until the encoded image fits the budget.
32 * The floor stays high enough to avoid visible blocking on UI screenshots;
33 * if even that overflows we drop resolution instead of quality.
34 */
35const QUALITY_STEPS = [0.92, 0.85, 0.78, 0.68] as const;
36/** Extra downscale passes applied when even the lowest quality overflows. */
37const FALLBACK_SCALE_STEPS = [0.75, 0.55] as const;
38const HEIC_IMAGE_MIME_TYPE = /^image\/hei(?:c|f)$/i;
39const HEIC_IMAGE_EXTENSION = /\.(?:heic|heif)$/i;
40
41type ImageSize = { width: number; height: number };
42
43export interface CompressedStashImage {
44 imageSize?: ImageSize;
45 dataUrl: string;
46 mimeType: string;
47 sizeBytes: number;
48 /** True when the payload was re-encoded rather than stored verbatim. */
49 recompressed: boolean;
50}
51
52/**
53 * Why an image could not be compressed. Callers report these differently:
54 * "too large" is a budget outcome, "unreadable" is a decode failure.
55 */
56export type ImageCompressionFailureReason = "too-large" | "unreadable";
57
58export type CompressStashImageResult =
59 | { ok: true; image: CompressedStashImage }
60 | { ok: false; reason: ImageCompressionFailureReason };
61
62export type CompressImageFileResult =
63 | { ok: true; file: File; recompressed: boolean; imageSize?: ImageSize }
64 | { ok: false; reason: ImageCompressionFailureReason };
65
66/** Finder and some browsers omit the MIME type when dragging HEIC photos. */
67export function isHeicImageFile(file: Pick<File, "name" | "type">): boolean {
68 if (HEIC_IMAGE_MIME_TYPE.test(file.type)) {
69 return true;
70 }
71 return (
72 (file.type === "" || file.type.toLowerCase() === "application/octet-stream") &&
73 HEIC_IMAGE_EXTENSION.test(file.name)
74 );
75}
76
77interface HeicMetadataBox {
78 payloadOffset: number;
79 endOffset: number;
80}
81
82function findHeicMetadataBox(
83 view: DataView,
84 startOffset: number,
85 endOffset: number,
86 type: number,
87): HeicMetadataBox | null {
88 let offset = startOffset;
89 while (offset + 8 <= endOffset) {
90 let size = view.getUint32(offset);
91 let headerSize = 8;
92 if (size === 1) {
93 if (offset + 16 > endOffset) return null;
94 const extendedSize = view.getBigUint64(offset + 8);
95 if (extendedSize > BigInt(Number.MAX_SAFE_INTEGER)) return null;
96 size = Number(extendedSize);
97 headerSize = 16;
98 } else if (size === 0) {
99 size = endOffset - offset;
100 }
101 if (size < headerSize || size > endOffset - offset) return null;
102
103 const nextOffset = offset + size;
104 if (view.getUint32(offset + 4) === type) {
105 return { payloadOffset: offset + headerSize, endOffset: nextOffset };
106 }
107 offset = nextOffset;
108 }
109 return null;
110}
111
112/** Read HEIC image dimensions before the decoder allocates full RGBA buffers. */
113async function validateHeicImageDimensions(
114 file: File,
115): Promise<ImageCompressionFailureReason | null> {
116 const metadata = await file.slice(0, MAX_HEIC_METADATA_BYTES).arrayBuffer();
117 const view = new DataView(metadata);
118 const meta = findHeicMetadataBox(view, 0, view.byteLength, 0x6d657461);
119 if (!meta || meta.payloadOffset + 4 > meta.endOffset) return "unreadable";
120 const properties = findHeicMetadataBox(view, meta.payloadOffset + 4, meta.endOffset, 0x69707270);
121 if (!properties) return "unreadable";
122 const containers = findHeicMetadataBox(
123 view,
124 properties.payloadOffset,
125 properties.endOffset,
126 0x6970636f,
127 );
128 if (!containers) return "unreadable";
129
130 let offset = containers.payloadOffset;
131 let foundImageDimensions = false;
132 while (offset < containers.endOffset) {
133 const image = findHeicMetadataBox(view, offset, containers.endOffset, 0x69737065);
134 if (!image) break;
135 if (image.payloadOffset + 12 > image.endOffset) return "unreadable";
136 const width = view.getUint32(image.payloadOffset + 4);
137 const height = view.getUint32(image.payloadOffset + 8);
138 if (width === 0 || height === 0) return "unreadable";
139 if (width > MAX_HEIC_DECODE_PIXELS / height) return "too-large";
140 foundImageDimensions = true;
141 offset = image.endOffset;
142 }
143 return foundImageDimensions ? null : "unreadable";
144}
145
146export function readFileAsDataUrl(file: Blob): Promise<string> {
147 return new Promise((resolve, reject) => {
148 const reader = new FileReader();
149 reader.addEventListener("load", () => {
150 if (typeof reader.result === "string") {
151 resolve(reader.result);
152 return;
153 }
154 reject(new Error("Could not read image data."));
155 });
156 reader.addEventListener("error", () => {
157 reject(reader.error ?? new Error("Failed to read image."));
158 });
159 reader.readAsDataURL(file);
160 });
161}
162
163function dataUrlLength(blob: Blob): number {
164 return (
165 `data:${blob.type || "application/octet-stream"};base64,`.length + 4 * Math.ceil(blob.size / 3)
166 );
167}
168
169/** Base64 payload of a data URL decoded back into a `File`. */
170export function dataUrlToFile(dataUrl: string, name: string, mimeType: string): File {
171 const payload = dataUrl.slice(dataUrl.indexOf(",") + 1);
172 const binary = atob(payload);
173 const bytes = new Uint8Array(binary.length);
174 for (let index = 0; index < binary.length; index += 1) {
175 bytes[index] = binary.charCodeAt(index);
176 }
177 return new File([bytes], name, { type: mimeType });
178}
179
180/**
181 * Re-encoding changes the container, so a name like `shot.png` would lie
182 * about its contents. Swap the extension to match the encoded mime type.
183 */
184function fileNameForMimeType(name: string, mimeType: string): string {
185 const extension = mimeType === "image/webp" ? ".webp" : ".jpg";
186 const dotIndex = name.lastIndexOf(".");
187 const base = dotIndex > 0 ? name.slice(0, dotIndex) : name;
188 return `${base}${extension}`;
189}
190
191function canRecompress(): boolean {
192 return (
193 typeof createImageBitmap === "function" &&
194 (typeof OffscreenCanvas === "function" || typeof document !== "undefined")
195 );
196}
197
198interface Canvas2D {
199 canvas: OffscreenCanvas | HTMLCanvasElement;
200 context: OffscreenCanvasRenderingContext2D | CanvasRenderingContext2D;
201}
202
203function createCanvas(width: number, height: number): Canvas2D | null {
204 if (typeof OffscreenCanvas === "function") {
205 const canvas = new OffscreenCanvas(width, height);
206 const context = canvas.getContext("2d");
207 if (!context) return null;
208 return { canvas, context };
209 }
210 if (typeof document === "undefined") return null;
211 const canvas = document.createElement("canvas");
212 canvas.width = width;
213 canvas.height = height;
214 const context = canvas.getContext("2d");
215 if (!context) return null;
216 return { canvas, context };
217}
218
219/**
220 * WebP is preferred: at matched visual quality it lands roughly 25-35%
221 * smaller than JPEG, so the same budget buys more resolution and detail —
222 * and it keeps alpha, so screenshots with transparency survive intact.
223 * Browsers that can't encode it silently fall back to JPEG.
224 */
225async function encodeCanvas(
226 canvas: OffscreenCanvas | HTMLCanvasElement,
227 quality: number,
228 mimeType: string,
229): Promise<Blob | null> {
230 let blob: Blob | null;
231 if (typeof HTMLCanvasElement !== "undefined" && canvas instanceof HTMLCanvasElement) {
232 blob = await new Promise<Blob | null>((resolve) => canvas.toBlob(resolve, mimeType, quality));
233 } else {
234 blob = await (canvas as OffscreenCanvas).convertToBlob({ type: mimeType, quality });
235 }
236 return blob?.type === mimeType ? blob : null;
237}
238
239const composerThumbnails = new WeakMap<File, Promise<string | null>>();
240
241/** Cache a centered square crop for the composer's object-cover image tiles. */
242export function createComposerImageThumbnail(file: File): Promise<string | null> {
243 const cached = composerThumbnails.get(file);
244 if (cached) return cached;
245 const thumbnail = (async () => {
246 if (!canRecompress()) return null;
247 let bitmap: ImageBitmap | undefined;
248 try {
249 bitmap = await createImageBitmap(file);
250 const side = Math.min(bitmap.width, bitmap.height);
251 if (side <= 0) return null;
252 const dimension = Math.min(256, side);
253 const surface = createCanvas(dimension, dimension);
254 if (!surface) return null;
255 surface.context.drawImage(
256 bitmap,
257 (bitmap.width - side) / 2,
258 (bitmap.height - side) / 2,
259 side,
260 side,
261 0,
262 0,
263 dimension,
264 dimension,
265 );
266 const blob = await encodeCanvas(surface.canvas, 1, "image/png");
267 return blob ? await readFileAsDataUrl(blob) : null;
268 } catch {
269 return null;
270 } finally {
271 bitmap?.close();
272 }
273 })();
274 composerThumbnails.set(file, thumbnail);
275 return thumbnail;
276}
277
278/**
279 * Draws `bitmap` scaled to fit `maxDimension` and encodes it, stepping
280 * quality down until the data URL fits `budgetChars`.
281 */
282async function encodeWithinBudget(
283 bitmap: ImageBitmap,
284 maxDimension: number,
285 budgetChars: number,
286 preferredMimeType?: "image/jpeg",
287): Promise<{ blob: Blob; mimeType: string; imageSize: ImageSize } | null> {
288 const scale = Math.min(1, maxDimension / Math.max(bitmap.width, bitmap.height));
289 const width = Math.max(1, Math.round(bitmap.width * scale));
290 const height = Math.max(1, Math.round(bitmap.height * scale));
291 const target = createCanvas(width, height);
292 if (!target) return null;
293
294 // Probe WebP once; JPEG (no alpha) needs a white matte, so the fill has to
295 // happen before drawing and depends on which codec we end up using.
296 const mimeType =
297 preferredMimeType ??
298 ((await encodeCanvas(target.canvas, QUALITY_STEPS[0], "image/webp"))
299 ? "image/webp"
300 : "image/jpeg");
301
302 if (mimeType === "image/jpeg") {
303 target.context.fillStyle = "#ffffff";
304 target.context.fillRect(0, 0, width, height);
305 }
306 target.context.drawImage(bitmap, 0, 0, width, height);
307
308 for (const quality of QUALITY_STEPS) {
309 const encoded = await encodeCanvas(target.canvas, quality, mimeType);
310 if (!encoded) break;
311 if (dataUrlLength(encoded) <= budgetChars) {
312 return { blob: encoded, mimeType, imageSize: { width, height } };
313 }
314 }
315 return null;
316}
317
318type ReencodeResult =
319 | { ok: true; blob: Blob; mimeType: string; imageSize: ImageSize }
320 | { ok: false; reason: ImageCompressionFailureReason };
321
322/**
323 * Shared re-encode loop: decodes `file`, then walks the quality ladder and
324 * fallback downscale passes until an encoding fits `budgetChars`.
325 */
326async function reencodeWithinBudget(
327 file: File,
328 budgetChars: number,
329 preferredMimeType?: "image/jpeg",
330): Promise<ReencodeResult> {
331 if (!canRecompress()) {
332 return { ok: false, reason: "too-large" };
333 }
334
335 let bitmap: ImageBitmap;
336 try {
337 bitmap = await createImageBitmap(file);
338 } catch {
339 return { ok: false, reason: "unreadable" };
340 }
341
342 try {
343 // Each pass shrinks relative to the *previous target*, capped by
344 // MAX_DIMENSION. Scaling a fixed ceiling instead would be a no-op for
345 // images already smaller than that ceiling — the fallback passes would
346 // all resolve to the source size and never actually reduce resolution.
347 const baseDimension = Math.min(MAX_DIMENSION, Math.max(bitmap.width, bitmap.height));
348 // Tracks whether the *last* attempt threw, so a run of encoder failures
349 // is reported as unreadable while a run of merely-too-big results is
350 // reported as too-large.
351 let encodeFailed = false;
352 for (const dimensionScale of [1, ...FALLBACK_SCALE_STEPS]) {
353 const targetDimension = Math.max(1, Math.round(baseDimension * dimensionScale));
354 let encoded: Awaited<ReturnType<typeof encodeWithinBudget>>;
355 try {
356 encoded = await encodeWithinBudget(bitmap, targetDimension, budgetChars, preferredMimeType);
357 } catch {
358 // Canvas allocation, drawing, or the codec itself can throw — often
359 // precisely *because* the target is too big (OOM on a large bitmap).
360 // Keep trying the smaller fallback scales rather than giving up: a
361 // reduced pass may well succeed. The exception must never escape,
362 // though, since callers finalize state after this returns and a
363 // throw would strand it (e.g. a stash entry stuck "still saving").
364 encodeFailed = true;
365 continue;
366 }
367 encodeFailed = false;
368 if (encoded) {
369 return {
370 ok: true,
371 blob: encoded.blob,
372 mimeType: encoded.mimeType,
373 imageSize: encoded.imageSize,
374 };
375 }
376 }
377 return { ok: false, reason: encodeFailed ? "unreadable" : "too-large" };
378 } finally {
379 bitmap.close();
380 }
381}
382
383/**
384 * Produces the payload to persist for a stashed image.
385 *
386 * Small images are stored verbatim (preserving PNG transparency and exact
387 * pixels). Anything over budget is downscaled and re-encoded; if it still
388 * doesn't fit after the fallback passes, reports a failure so the caller
389 * can record it as dropped.
390 */
391export async function compressImageForStash(
392 file: File,
393 budgetChars: number = MAX_STASH_IMAGE_DATA_URL_CHARS,
394): Promise<CompressStashImageResult> {
395 try {
396 if (dataUrlLength(file) <= budgetChars) {
397 return {
398 ok: true,
399 image: {
400 dataUrl: await readFileAsDataUrl(file),
401 mimeType: file.type,
402 sizeBytes: file.size,
403 recompressed: false,
404 },
405 };
406 }
407 const reencoded = await reencodeWithinBudget(file, budgetChars);
408 if (!reencoded.ok) {
409 return reencoded;
410 }
411 return {
412 ok: true,
413 image: {
414 dataUrl: await readFileAsDataUrl(reencoded.blob),
415 mimeType: reencoded.mimeType,
416 sizeBytes: reencoded.blob.size,
417 recompressed: true,
418 imageSize: reencoded.imageSize,
419 },
420 };
421 } catch {
422 return { ok: false, reason: "unreadable" };
423 }
424}
425
426/**
427 * Shrinks `file` until its binary size fits `maxBytes`, returning a new
428 * `File` (WebP or JPEG). Files already within the limit pass through
429 * untouched, preserving their exact bytes and format. Sources above
430 * `MAX_COMPRESSIBLE_SOURCE_BYTES` are refused outright — decoding them is
431 * the risk, so no amount of output budget makes them safe. An internally
432 * converted image can provide its original source size when the intermediate
433 * format expands beyond that ceiling.
434 */
435export async function compressImageToByteLimit(
436 file: File,
437 maxBytes: number,
438 options?: { preferredMimeType?: "image/jpeg"; sourceSizeBytes?: number },
439): Promise<CompressImageFileResult> {
440 if (file.size <= maxBytes) {
441 return { ok: true, file, recompressed: false };
442 }
443 if ((options?.sourceSizeBytes ?? file.size) > MAX_COMPRESSIBLE_SOURCE_BYTES) {
444 return { ok: false, reason: "too-large" };
445 }
446 // The re-encode loop budgets in data-URL characters. Base64 turns 3 bytes
447 // into 4 chars; flooring keeps the budget a hair conservative instead of
448 // admitting an encoding right at the byte cap.
449 const budgetChars = Math.floor(maxBytes / 3) * 4;
450 const reencoded = await reencodeWithinBudget(file, budgetChars, options?.preferredMimeType);
451 if (!reencoded.ok) {
452 return reencoded;
453 }
454 return {
455 ok: true,
456 file: new File(
457 [reencoded.blob],
458 fileNameForMimeType(file.name || "image", reencoded.mimeType),
459 { type: reencoded.mimeType },
460 ),
461 recompressed: true,
462 imageSize: reencoded.imageSize,
463 };
464}
465
466/**
467 * Converts HEIC/HEIF photos to provider-compatible JPEG before applying the
468 * attachment size limit. The decoder is loaded only when such a photo arrives.
469 */
470export async function prepareImageForAttachment(
471 file: File,
472 maxBytes: number,
473): Promise<CompressImageFileResult> {
474 if (!isHeicImageFile(file)) {
475 return compressImageToByteLimit(file, maxBytes);
476 }
477
478 if (file.size > MAX_COMPRESSIBLE_SOURCE_BYTES) {
479 return { ok: false, reason: "too-large" };
480 }
481
482 let converted: Blob;
483 try {
484 const dimensionError = await validateHeicImageDimensions(file);
485 if (dimensionError) {
486 return { ok: false, reason: dimensionError };
487 }
488 const { heicTo } = await import("heic-to/csp");
489 converted = await heicTo({ blob: file, type: "image/jpeg", quality: QUALITY_STEPS[0] });
490 } catch {
491 return { ok: false, reason: "unreadable" };
492 }
493
494 const jpeg = new File([converted], fileNameForMimeType(file.name || "image", "image/jpeg"), {
495 type: "image/jpeg",
496 lastModified: file.lastModified,
497 });
498 const result = await compressImageToByteLimit(jpeg, maxBytes, {
499 preferredMimeType: "image/jpeg",
500 sourceSizeBytes: file.size,
501 });
502
503 return result.ok ? { ...result, recompressed: true } : result;
504}