Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

imageCompression.ts

478 lines17.3 KB

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