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
41export interface CompressedStashImage {
42 dataUrl: string;
43 mimeType: string;
44 sizeBytes: number;
45 /** True when the payload was re-encoded rather than stored verbatim. */
46 recompressed: boolean;
47}
48
49/**
50 * Why an image could not be compressed. Callers report these differently:
51 * "too large" is a budget outcome, "unreadable" is a decode failure.
52 */
53export type ImageCompressionFailureReason = "too-large" | "unreadable";
54
55export type CompressStashImageResult =
56 | { ok: true; image: CompressedStashImage }
57 | { ok: false; reason: ImageCompressionFailureReason };
58
59export type CompressImageFileResult =
60 | { ok: true; file: File; recompressed: boolean }
61 | { ok: false; reason: ImageCompressionFailureReason };
62
63/** Finder and some browsers omit the MIME type when dragging HEIC photos. */
64export function isHeicImageFile(file: Pick<File, "name" | "type">): boolean {
65 if (HEIC_IMAGE_MIME_TYPE.test(file.type)) {
66 return true;
67 }
68 return (
69 (file.type === "" || file.type.toLowerCase() === "application/octet-stream") &&
70 HEIC_IMAGE_EXTENSION.test(file.name)
71 );
72}
73
74interface HeicMetadataBox {
75 payloadOffset: number;
76 endOffset: number;
77}
78
79function findHeicMetadataBox(
80 view: DataView,
81 startOffset: number,
82 endOffset: number,
83 type: number,
84): HeicMetadataBox | null {
85 let offset = startOffset;
86 while (offset + 8 <= endOffset) {
87 let size = view.getUint32(offset);
88 let headerSize = 8;
89 if (size === 1) {
90 if (offset + 16 > endOffset) return null;
91 const extendedSize = view.getBigUint64(offset + 8);
92 if (extendedSize > BigInt(Number.MAX_SAFE_INTEGER)) return null;
93 size = Number(extendedSize);
94 headerSize = 16;
95 } else if (size === 0) {
96 size = endOffset - offset;
97 }
98 if (size < headerSize || size > endOffset - offset) return null;
99
100 const nextOffset = offset + size;
101 if (view.getUint32(offset + 4) === type) {
102 return { payloadOffset: offset + headerSize, endOffset: nextOffset };
103 }
104 offset = nextOffset;
105 }
106 return null;
107}
108
109/** Read HEIC image dimensions before the decoder allocates full RGBA buffers. */
110async function validateHeicImageDimensions(
111 file: File,
112): Promise<ImageCompressionFailureReason | null> {
113 const metadata = await file.slice(0, MAX_HEIC_METADATA_BYTES).arrayBuffer();
114 const view = new DataView(metadata);
115 const meta = findHeicMetadataBox(view, 0, view.byteLength, 0x6d657461);
116 if (!meta || meta.payloadOffset + 4 > meta.endOffset) return "unreadable";
117 const properties = findHeicMetadataBox(view, meta.payloadOffset + 4, meta.endOffset, 0x69707270);
118 if (!properties) return "unreadable";
119 const containers = findHeicMetadataBox(
120 view,
121 properties.payloadOffset,
122 properties.endOffset,
123 0x6970636f,
124 );
125 if (!containers) return "unreadable";
126
127 let offset = containers.payloadOffset;
128 let foundImageDimensions = false;
129 while (offset < containers.endOffset) {
130 const image = findHeicMetadataBox(view, offset, containers.endOffset, 0x69737065);
131 if (!image) break;
132 if (image.payloadOffset + 12 > image.endOffset) return "unreadable";
133 const width = view.getUint32(image.payloadOffset + 4);
134 const height = view.getUint32(image.payloadOffset + 8);
135 if (width === 0 || height === 0) return "unreadable";
136 if (width > MAX_HEIC_DECODE_PIXELS / height) return "too-large";
137 foundImageDimensions = true;
138 offset = image.endOffset;
139 }
140 return foundImageDimensions ? null : "unreadable";
141}
142
143/** Chunked so a large image can't blow the argument limit of `fromCharCode`. */
144const BASE64_CHUNK_SIZE = 0x8000;
145
146function bytesToBase64(bytes: Uint8Array): string {
147 let binary = "";
148 for (let offset = 0; offset < bytes.length; offset += BASE64_CHUNK_SIZE) {
149 binary += String.fromCharCode(...bytes.subarray(offset, offset + BASE64_CHUNK_SIZE));
150 }
151 return btoa(binary);
152}
153
154/**
155 * Blob → base64 data URL. Uses `arrayBuffer()` rather than `FileReader` so
156 * the module works anywhere `Blob` does (including non-DOM test runners).
157 */
158async function blobToDataUrl(blob: File | Blob, mimeTypeOverride?: string): Promise<string> {
159 const buffer = await blob.arrayBuffer();
160 const mimeType = mimeTypeOverride || blob.type || "application/octet-stream";
161 return `data:${mimeType};base64,${bytesToBase64(new Uint8Array(buffer))}`;
162}
163
164/** Approximate decoded byte count for a base64 data URL. */
165function dataUrlByteLength(dataUrl: string): number {
166 const commaIndex = dataUrl.indexOf(",");
167 const payload = commaIndex === -1 ? dataUrl : dataUrl.slice(commaIndex + 1);
168 const padding = payload.endsWith("==") ? 2 : payload.endsWith("=") ? 1 : 0;
169 return Math.max(0, Math.floor((payload.length * 3) / 4) - padding);
170}
171
172/** Base64 payload of a data URL decoded back into a `File`. */
173function dataUrlToFile(dataUrl: string, name: string, mimeType: string): File {
174 const payload = dataUrl.slice(dataUrl.indexOf(",") + 1);
175 const binary = atob(payload);
176 const bytes = new Uint8Array(binary.length);
177 for (let index = 0; index < binary.length; index += 1) {
178 bytes[index] = binary.charCodeAt(index);
179 }
180 return new File([bytes], name, { type: mimeType });
181}
182
183/**
184 * Re-encoding changes the container, so a name like `shot.png` would lie
185 * about its contents. Swap the extension to match the encoded mime type.
186 */
187function fileNameForMimeType(name: string, mimeType: string): string {
188 const extension = mimeType === "image/webp" ? ".webp" : ".jpg";
189 const dotIndex = name.lastIndexOf(".");
190 const base = dotIndex > 0 ? name.slice(0, dotIndex) : name;
191 return `${base}${extension}`;
192}
193
194function canRecompress(): boolean {
195 return (
196 typeof createImageBitmap === "function" &&
197 (typeof OffscreenCanvas === "function" || typeof document !== "undefined")
198 );
199}
200
201interface Canvas2D {
202 canvas: OffscreenCanvas | HTMLCanvasElement;
203 context: OffscreenCanvasRenderingContext2D | CanvasRenderingContext2D;
204}
205
206function createCanvas(width: number, height: number): Canvas2D | null {
207 if (typeof OffscreenCanvas === "function") {
208 const canvas = new OffscreenCanvas(width, height);
209 const context = canvas.getContext("2d");
210 if (!context) return null;
211 return { canvas, context };
212 }
213 if (typeof document === "undefined") return null;
214 const canvas = document.createElement("canvas");
215 canvas.width = width;
216 canvas.height = height;
217 const context = canvas.getContext("2d");
218 if (!context) return null;
219 return { canvas, context };
220}
221
222/**
223 * WebP is preferred: at matched visual quality it lands roughly 25-35%
224 * smaller than JPEG, so the same budget buys more resolution and detail —
225 * and it keeps alpha, so screenshots with transparency survive intact.
226 * Browsers that can't encode it silently fall back to JPEG.
227 */
228async function encodeCanvas(
229 canvas: OffscreenCanvas | HTMLCanvasElement,
230 quality: number,
231 mimeType: string,
232 budgetChars: number,
233): Promise<{ dataUrl: string | null; mimeType: string } | null> {
234 if (typeof HTMLCanvasElement !== "undefined" && canvas instanceof HTMLCanvasElement) {
235 const dataUrl = canvas.toDataURL(mimeType, quality);
236 // toDataURL silently returns a PNG when the requested type is unsupported.
237 if (!dataUrl.startsWith(`data:${mimeType}`)) return null;
238 return { dataUrl: dataUrl.length <= budgetChars ? dataUrl : null, mimeType };
239 }
240 const blob = await (canvas as OffscreenCanvas).convertToBlob({ type: mimeType, quality });
241 if (blob.type && blob.type !== mimeType) return null;
242 const dataUrlLength = `data:${mimeType};base64,`.length + 4 * Math.ceil(blob.size / 3);
243 if (dataUrlLength > budgetChars) return { dataUrl: null, mimeType };
244 return { dataUrl: await blobToDataUrl(blob, mimeType), mimeType };
245}
246
247/**
248 * Draws `bitmap` scaled to fit `maxDimension` and encodes it, stepping
249 * quality down until the data URL fits `budgetChars`.
250 */
251async function encodeWithinBudget(
252 bitmap: ImageBitmap,
253 maxDimension: number,
254 budgetChars: number,
255 preferredMimeType?: "image/jpeg",
256): Promise<{ dataUrl: string; mimeType: string } | null> {
257 const scale = Math.min(1, maxDimension / Math.max(bitmap.width, bitmap.height));
258 const width = Math.max(1, Math.round(bitmap.width * scale));
259 const height = Math.max(1, Math.round(bitmap.height * scale));
260 const target = createCanvas(width, height);
261 if (!target) return null;
262
263 // Probe WebP once; JPEG (no alpha) needs a white matte, so the fill has to
264 // happen before drawing and depends on which codec we end up using.
265 const mimeType =
266 preferredMimeType ??
267 ((await encodeCanvas(target.canvas, QUALITY_STEPS[0], "image/webp", 0))
268 ? "image/webp"
269 : "image/jpeg");
270
271 if (mimeType === "image/jpeg") {
272 target.context.fillStyle = "#ffffff";
273 target.context.fillRect(0, 0, width, height);
274 }
275 target.context.drawImage(bitmap, 0, 0, width, height);
276
277 for (const quality of QUALITY_STEPS) {
278 const encoded = await encodeCanvas(target.canvas, quality, mimeType, budgetChars);
279 if (!encoded) break;
280 if (encoded.dataUrl !== null) {
281 return { dataUrl: encoded.dataUrl, mimeType: encoded.mimeType };
282 }
283 }
284 return null;
285}
286
287type ReencodeResult =
288 | { ok: true; dataUrl: string; mimeType: string }
289 | { ok: false; reason: ImageCompressionFailureReason };
290
291/**
292 * Shared re-encode loop: decodes `file`, then walks the quality ladder and
293 * fallback downscale passes until an encoding fits `budgetChars`.
294 */
295async function reencodeWithinBudget(
296 file: File,
297 budgetChars: number,
298 preferredMimeType?: "image/jpeg",
299): Promise<ReencodeResult> {
300 if (!canRecompress()) {
301 return { ok: false, reason: "too-large" };
302 }
303
304 let bitmap: ImageBitmap;
305 try {
306 bitmap = await createImageBitmap(file);
307 } catch {
308 return { ok: false, reason: "unreadable" };
309 }
310
311 try {
312 // Each pass shrinks relative to the *previous target*, capped by
313 // MAX_DIMENSION. Scaling a fixed ceiling instead would be a no-op for
314 // images already smaller than that ceiling — the fallback passes would
315 // all resolve to the source size and never actually reduce resolution.
316 const baseDimension = Math.min(MAX_DIMENSION, Math.max(bitmap.width, bitmap.height));
317 // Tracks whether the *last* attempt threw, so a run of encoder failures
318 // is reported as unreadable while a run of merely-too-big results is
319 // reported as too-large.
320 let encodeFailed = false;
321 for (const dimensionScale of [1, ...FALLBACK_SCALE_STEPS]) {
322 const targetDimension = Math.max(1, Math.round(baseDimension * dimensionScale));
323 let encoded: { dataUrl: string; mimeType: string } | null;
324 try {
325 encoded = await encodeWithinBudget(bitmap, targetDimension, budgetChars, preferredMimeType);
326 } catch {
327 // Canvas allocation, drawing, or the codec itself can throw — often
328 // precisely *because* the target is too big (OOM on a large bitmap).
329 // Keep trying the smaller fallback scales rather than giving up: a
330 // reduced pass may well succeed. The exception must never escape,
331 // though, since callers finalize state after this returns and a
332 // throw would strand it (e.g. a stash entry stuck "still saving").
333 encodeFailed = true;
334 continue;
335 }
336 encodeFailed = false;
337 if (encoded && encoded.dataUrl.length <= budgetChars) {
338 return { ok: true, dataUrl: encoded.dataUrl, mimeType: encoded.mimeType };
339 }
340 }
341 return { ok: false, reason: encodeFailed ? "unreadable" : "too-large" };
342 } finally {
343 bitmap.close();
344 }
345}
346
347/**
348 * Produces the payload to persist for a stashed image.
349 *
350 * Small images are stored verbatim (preserving PNG transparency and exact
351 * pixels). Anything over budget is downscaled and re-encoded; if it still
352 * doesn't fit after the fallback passes, reports a failure so the caller
353 * can record it as dropped.
354 */
355export async function compressImageForStash(
356 file: File,
357 budgetChars: number = MAX_STASH_IMAGE_DATA_URL_CHARS,
358): Promise<CompressStashImageResult> {
359 let originalDataUrl: string;
360 try {
361 originalDataUrl = await blobToDataUrl(file);
362 } catch {
363 return { ok: false, reason: "unreadable" };
364 }
365 if (originalDataUrl.length <= budgetChars) {
366 return {
367 ok: true,
368 image: {
369 dataUrl: originalDataUrl,
370 mimeType: file.type,
371 sizeBytes: file.size,
372 recompressed: false,
373 },
374 };
375 }
376 const reencoded = await reencodeWithinBudget(file, budgetChars);
377 if (!reencoded.ok) {
378 return reencoded;
379 }
380 return {
381 ok: true,
382 image: {
383 dataUrl: reencoded.dataUrl,
384 mimeType: reencoded.mimeType,
385 sizeBytes: dataUrlByteLength(reencoded.dataUrl),
386 recompressed: true,
387 },
388 };
389}
390
391/**
392 * Shrinks `file` until its binary size fits `maxBytes`, returning a new
393 * `File` (WebP or JPEG). Files already within the limit pass through
394 * untouched, preserving their exact bytes and format. Sources above
395 * `MAX_COMPRESSIBLE_SOURCE_BYTES` are refused outright — decoding them is
396 * the risk, so no amount of output budget makes them safe. An internally
397 * converted image can provide its original source size when the intermediate
398 * format expands beyond that ceiling.
399 */
400export async function compressImageToByteLimit(
401 file: File,
402 maxBytes: number,
403 options?: { preferredMimeType?: "image/jpeg"; sourceSizeBytes?: number },
404): Promise<CompressImageFileResult> {
405 if (file.size <= maxBytes) {
406 return { ok: true, file, recompressed: false };
407 }
408 if ((options?.sourceSizeBytes ?? file.size) > MAX_COMPRESSIBLE_SOURCE_BYTES) {
409 return { ok: false, reason: "too-large" };
410 }
411 // The re-encode loop budgets in data-URL characters. Base64 turns 3 bytes
412 // into 4 chars; flooring keeps the budget a hair conservative instead of
413 // admitting an encoding right at the byte cap.
414 const budgetChars = Math.floor(maxBytes / 3) * 4;
415 const reencoded = await reencodeWithinBudget(file, budgetChars, options?.preferredMimeType);
416 if (!reencoded.ok) {
417 return reencoded;
418 }
419 return {
420 ok: true,
421 file: dataUrlToFile(
422 reencoded.dataUrl,
423 fileNameForMimeType(file.name || "image", reencoded.mimeType),
424 reencoded.mimeType,
425 ),
426 recompressed: true,
427 };
428}
429
430/**
431 * Converts HEIC/HEIF photos to provider-compatible JPEG before applying the
432 * attachment size limit. The decoder is loaded only when such a photo arrives.
433 */
434export async function prepareImageForAttachment(
435 file: File,
436 maxBytes: number,
437): Promise<CompressImageFileResult> {
438 if (!isHeicImageFile(file)) {
439 return compressImageToByteLimit(file, maxBytes);
440 }
441
442 if (file.size > MAX_COMPRESSIBLE_SOURCE_BYTES) {
443 return { ok: false, reason: "too-large" };
444 }
445
446 let converted: Blob;
447 try {
448 const dimensionError = await validateHeicImageDimensions(file);
449 if (dimensionError) {
450 return { ok: false, reason: dimensionError };
451 }
452 const { heicTo } = await import("heic-to/csp");
453 converted = await heicTo({ blob: file, type: "image/jpeg", quality: QUALITY_STEPS[0] });
454 } catch {
455 return { ok: false, reason: "unreadable" };
456 }
457
458 const jpeg = new File([converted], fileNameForMimeType(file.name || "image", "image/jpeg"), {
459 type: "image/jpeg",
460 lastModified: file.lastModified,
461 });
462 const result = await compressImageToByteLimit(jpeg, maxBytes, {
463 preferredMimeType: "image/jpeg",
464 sourceSizeBytes: file.size,
465 });
466
467 return result.ok ? { ...result, recompressed: true } : result;
468}