Open History to see the last commit
1import {
2 downscalableImageMimeType,
3 fitImageAttachmentSize,
4 IMAGE_ATTACHMENT_MAX_EDGE,
5} from "@t3tools/client-runtime/image-attachment-size";
6import {
7 IMAGE_DIMENSIONS_HEADER_BYTES,
8 readImageDimensions,
9} from "@t3tools/shared/imageDimensions";
10
11const MAX_DIMENSION = IMAGE_ATTACHMENT_MAX_EDGE;
12export const MAX_STASH_IMAGE_DATA_URL_CHARS = 1_300_000;
13/** Bound source decoding: enormous ImageBitmaps can OOM the tab before resizing. */
14export const MAX_COMPRESSIBLE_SOURCE_BYTES = 50 * 1024 * 1024;
15const MAX_HEIC_DECODE_PIXELS = 64_000_000;
16const MAX_HEIC_METADATA_BYTES = 1024 * 1024;
17const QUALITY_STEPS = [0.92, 0.85, 0.78, 0.68] as const;
18const FALLBACK_SCALE_STEPS = [0.75, 0.55] as const;
19const HEIC_IMAGE_MIME_TYPE = /^image\/hei(?:c|f)$/i;
20const HEIC_IMAGE_EXTENSION = /\.(?:heic|heif)$/i;
21
22type ImageSize = { width: number; height: number };
23
24export interface CompressedStashImage {
25 imageSize?: ImageSize;
26 dataUrl: string;
27 mimeType: string;
28 sizeBytes: number;
29 recompressed: boolean;
30}
31
32export type ImageCompressionFailureReason = "too-large" | "unreadable";
33
34export type CompressStashImageResult =
35 | { ok: true; image: CompressedStashImage }
36 | { ok: false; reason: ImageCompressionFailureReason };
37
38export type CompressImageFileResult =
39 | { ok: true; file: File; recompressed: boolean; imageSize?: ImageSize }
40 | { ok: false; reason: ImageCompressionFailureReason };
41
42/** Finder and some browsers omit the MIME type when dragging HEIC photos. */
43export function isHeicImageFile(file: Pick<File, "name" | "type">): boolean {
44 if (HEIC_IMAGE_MIME_TYPE.test(file.type)) {
45 return true;
46 }
47 return (
48 (file.type === "" || file.type.toLowerCase() === "application/octet-stream") &&
49 HEIC_IMAGE_EXTENSION.test(file.name)
50 );
51}
52
53interface HeicMetadataBox {
54 payloadOffset: number;
55 endOffset: number;
56}
57
58function findHeicMetadataBox(
59 view: DataView,
60 startOffset: number,
61 endOffset: number,
62 type: number,
63): HeicMetadataBox | null {
64 let offset = startOffset;
65 while (offset + 8 <= endOffset) {
66 let size = view.getUint32(offset);
67 let headerSize = 8;
68 if (size === 1) {
69 if (offset + 16 > endOffset) return null;
70 const extendedSize = view.getBigUint64(offset + 8);
71 if (extendedSize > BigInt(Number.MAX_SAFE_INTEGER)) return null;
72 size = Number(extendedSize);
73 headerSize = 16;
74 } else if (size === 0) {
75 size = endOffset - offset;
76 }
77 if (size < headerSize || size > endOffset - offset) return null;
78
79 const nextOffset = offset + size;
80 if (view.getUint32(offset + 4) === type) {
81 return { payloadOffset: offset + headerSize, endOffset: nextOffset };
82 }
83 offset = nextOffset;
84 }
85 return null;
86}
87
88async function validateHeicImageDimensions(
89 file: File,
90): Promise<ImageCompressionFailureReason | null> {
91 const metadata = await file.slice(0, MAX_HEIC_METADATA_BYTES).arrayBuffer();
92 const view = new DataView(metadata);
93 const meta = findHeicMetadataBox(view, 0, view.byteLength, 0x6d657461);
94 if (!meta || meta.payloadOffset + 4 > meta.endOffset) return "unreadable";
95 const properties = findHeicMetadataBox(view, meta.payloadOffset + 4, meta.endOffset, 0x69707270);
96 if (!properties) return "unreadable";
97 const containers = findHeicMetadataBox(
98 view,
99 properties.payloadOffset,
100 properties.endOffset,
101 0x6970636f,
102 );
103 if (!containers) return "unreadable";
104
105 let offset = containers.payloadOffset;
106 let foundImageDimensions = false;
107 while (offset < containers.endOffset) {
108 const image = findHeicMetadataBox(view, offset, containers.endOffset, 0x69737065);
109 if (!image) break;
110 if (image.payloadOffset + 12 > image.endOffset) return "unreadable";
111 const width = view.getUint32(image.payloadOffset + 4);
112 const height = view.getUint32(image.payloadOffset + 8);
113 if (width === 0 || height === 0) return "unreadable";
114 if (width > MAX_HEIC_DECODE_PIXELS / height) return "too-large";
115 foundImageDimensions = true;
116 offset = image.endOffset;
117 }
118 return foundImageDimensions ? null : "unreadable";
119}
120
121export function readFileAsDataUrl(file: Blob): Promise<string> {
122 return new Promise((resolve, reject) => {
123 const reader = new FileReader();
124 reader.addEventListener("load", () => {
125 if (typeof reader.result === "string") {
126 resolve(reader.result);
127 return;
128 }
129 reject(new Error("Could not read image data."));
130 });
131 reader.addEventListener("error", () => {
132 reject(reader.error ?? new Error("Failed to read image."));
133 });
134 reader.readAsDataURL(file);
135 });
136}
137
138function dataUrlLength(blob: Blob): number {
139 return (
140 `data:${blob.type || "application/octet-stream"};base64,`.length + 4 * Math.ceil(blob.size / 3)
141 );
142}
143
144export function dataUrlToFile(dataUrl: string, name: string, mimeType: string): File {
145 const payload = dataUrl.slice(dataUrl.indexOf(",") + 1);
146 const binary = atob(payload);
147 const bytes = new Uint8Array(binary.length);
148 for (let index = 0; index < binary.length; index += 1) {
149 bytes[index] = binary.charCodeAt(index);
150 }
151 return new File([bytes], name, { type: mimeType });
152}
153
154function fileNameForMimeType(name: string, mimeType: string): string {
155 const extension = mimeType === "image/webp" ? ".webp" : ".jpg";
156 const dotIndex = name.lastIndexOf(".");
157 const base = dotIndex > 0 ? name.slice(0, dotIndex) : name;
158 return `${base}${extension}`;
159}
160
161function canRecompress(): boolean {
162 return (
163 typeof createImageBitmap === "function" &&
164 (typeof OffscreenCanvas === "function" || typeof document !== "undefined")
165 );
166}
167
168interface Canvas2D {
169 canvas: OffscreenCanvas | HTMLCanvasElement;
170 context: OffscreenCanvasRenderingContext2D | CanvasRenderingContext2D;
171}
172
173function createCanvas(width: number, height: number): Canvas2D | null {
174 if (typeof OffscreenCanvas === "function") {
175 const canvas = new OffscreenCanvas(width, height);
176 const context = canvas.getContext("2d");
177 if (!context) return null;
178 return { canvas, context };
179 }
180 if (typeof document === "undefined") return null;
181 const canvas = document.createElement("canvas");
182 canvas.width = width;
183 canvas.height = height;
184 const context = canvas.getContext("2d");
185 if (!context) return null;
186 return { canvas, context };
187}
188
189async function encodeCanvas(
190 canvas: OffscreenCanvas | HTMLCanvasElement,
191 quality: number,
192 mimeType: string,
193): Promise<Blob | null> {
194 let blob: Blob | null;
195 if (typeof HTMLCanvasElement !== "undefined" && canvas instanceof HTMLCanvasElement) {
196 blob = await new Promise<Blob | null>((resolve) => canvas.toBlob(resolve, mimeType, quality));
197 } else {
198 blob = await (canvas as OffscreenCanvas).convertToBlob({ type: mimeType, quality });
199 }
200 return blob?.type === mimeType ? blob : null;
201}
202
203const composerThumbnails = new WeakMap<File, Promise<string | null>>();
204const settledComposerThumbnails = new WeakMap<File, string | null>();
205
206function cacheComposerImageThumbnail(
207 file: File,
208 thumbnail: Promise<string | null>,
209): Promise<string | null> {
210 composerThumbnails.set(file, thumbnail);
211 void thumbnail.then((src) => settledComposerThumbnails.set(file, src));
212 return thumbnail;
213}
214
215/** `undefined` until the thumbnail settles, so a tile can paint a known thumbnail immediately. */
216export function readComposerImageThumbnail(file: File): string | null | undefined {
217 return settledComposerThumbnails.get(file);
218}
219
220export function createComposerImageThumbnail(file: File): Promise<string | null> {
221 return (
222 composerThumbnails.get(file) ??
223 cacheComposerImageThumbnail(file, renderComposerImageThumbnail(file))
224 );
225}
226
227/**
228 * Pasted images are re-encoded after their placeholder already shows the source's thumbnail.
229 * Reusing it keeps the tile from flashing back to its fallback while the new file is decoded.
230 */
231export function inheritComposerImageThumbnail(source: File, target: File): void {
232 const sourceThumbnail = composerThumbnails.get(source);
233 if (source === target || !sourceThumbnail || composerThumbnails.has(target)) return;
234 const settled = settledComposerThumbnails.get(source);
235 if (settled) settledComposerThumbnails.set(target, settled);
236 cacheComposerImageThumbnail(
237 target,
238 sourceThumbnail.then((src) => src ?? renderComposerImageThumbnail(target)),
239 );
240}
241
242async function renderComposerImageThumbnail(file: File): Promise<string | null> {
243 if (isHeicImageFile(file)) return prepareHeicImage(file).thumbnail;
244 // Placeholders thumbnail the uncompressed source, which can be big enough to OOM the decode.
245 if (!canRecompress() || file.size > MAX_COMPRESSIBLE_SOURCE_BYTES) return null;
246 let bitmap: ImageBitmap | undefined;
247 try {
248 bitmap = await createImageBitmap(file);
249 return await renderComposerImageThumbnailFromBitmap(bitmap);
250 } catch {
251 return null;
252 } finally {
253 bitmap?.close();
254 }
255}
256
257async function renderComposerImageThumbnailFromBitmap(bitmap: ImageBitmap): Promise<string | null> {
258 try {
259 const side = Math.min(bitmap.width, bitmap.height);
260 if (side <= 0) return null;
261 const dimension = Math.min(256, side);
262 const surface = createCanvas(dimension, dimension);
263 if (!surface) return null;
264 surface.context.drawImage(
265 bitmap,
266 (bitmap.width - side) / 2,
267 (bitmap.height - side) / 2,
268 side,
269 side,
270 0,
271 0,
272 dimension,
273 dimension,
274 );
275 const blob = await encodeCanvas(surface.canvas, 1, "image/png");
276 return blob ? await readFileAsDataUrl(blob) : null;
277 } catch {
278 return null;
279 }
280}
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 the codec before drawing; JPEG needs a white matte because it has no alpha.
295 const mimeType =
296 preferredMimeType ??
297 ((await encodeCanvas(target.canvas, QUALITY_STEPS[0], "image/webp"))
298 ? "image/webp"
299 : "image/jpeg");
300
301 if (mimeType === "image/jpeg") {
302 target.context.fillStyle = "#ffffff";
303 target.context.fillRect(0, 0, width, height);
304 }
305 target.context.drawImage(bitmap, 0, 0, width, height);
306
307 for (const quality of QUALITY_STEPS) {
308 const encoded = await encodeCanvas(target.canvas, quality, mimeType);
309 if (!encoded) break;
310 if (dataUrlLength(encoded) <= budgetChars) {
311 return { blob: encoded, mimeType, imageSize: { width, height } };
312 }
313 }
314 return null;
315}
316
317type ReencodeResult =
318 | { ok: true; blob: Blob; mimeType: string; imageSize: ImageSize }
319 | { ok: false; reason: ImageCompressionFailureReason };
320
321async function reencodeWithinBudget(
322 file: File,
323 budgetChars: number,
324 preferredMimeType?: "image/jpeg",
325): Promise<ReencodeResult> {
326 if (!canRecompress()) {
327 return { ok: false, reason: "too-large" };
328 }
329
330 let bitmap: ImageBitmap;
331 try {
332 bitmap = await createImageBitmap(file);
333 } catch {
334 return { ok: false, reason: "unreadable" };
335 }
336
337 try {
338 // Shrink the previous target; using MAX_DIMENSION leaves smaller images unchanged.
339 const baseDimension = Math.min(MAX_DIMENSION, Math.max(bitmap.width, bitmap.height));
340 let encodeFailed = false;
341 for (const dimensionScale of [1, ...FALLBACK_SCALE_STEPS]) {
342 const targetDimension = Math.max(1, Math.round(baseDimension * dimensionScale));
343 let encoded: Awaited<ReturnType<typeof encodeWithinBudget>>;
344 try {
345 encoded = await encodeWithinBudget(bitmap, targetDimension, budgetChars, preferredMimeType);
346 } catch {
347 encodeFailed = true;
348 continue;
349 }
350 encodeFailed = false;
351 if (encoded) {
352 return {
353 ok: true,
354 blob: encoded.blob,
355 mimeType: encoded.mimeType,
356 imageSize: encoded.imageSize,
357 };
358 }
359 }
360 return { ok: false, reason: encodeFailed ? "unreadable" : "too-large" };
361 } finally {
362 bitmap.close();
363 }
364}
365
366export async function compressImageForStash(
367 file: File,
368 budgetChars: number = MAX_STASH_IMAGE_DATA_URL_CHARS,
369): Promise<CompressStashImageResult> {
370 try {
371 if (dataUrlLength(file) <= budgetChars) {
372 return {
373 ok: true,
374 image: {
375 dataUrl: await readFileAsDataUrl(file),
376 mimeType: file.type,
377 sizeBytes: file.size,
378 recompressed: false,
379 },
380 };
381 }
382 const reencoded = await reencodeWithinBudget(file, budgetChars);
383 if (!reencoded.ok) {
384 return reencoded;
385 }
386 return {
387 ok: true,
388 image: {
389 dataUrl: await readFileAsDataUrl(reencoded.blob),
390 mimeType: reencoded.mimeType,
391 sizeBytes: reencoded.blob.size,
392 recompressed: true,
393 imageSize: reencoded.imageSize,
394 },
395 };
396 } catch {
397 return { ok: false, reason: "unreadable" };
398 }
399}
400
401async function fitImageToMaxEdge(file: File): Promise<{ file: File; imageSize: ImageSize } | null> {
402 const mimeType = downscalableImageMimeType(file.type);
403 if (!mimeType || !canRecompress() || file.size > MAX_COMPRESSIBLE_SOURCE_BYTES) return null;
404 let bitmap: ImageBitmap | undefined;
405 try {
406 const header = readImageDimensions(
407 new Uint8Array(await file.slice(0, IMAGE_DIMENSIONS_HEADER_BYTES).arrayBuffer()),
408 );
409 if (!header || !fitImageAttachmentSize(header)) return null;
410 bitmap = await createImageBitmap(file, { imageOrientation: "from-image" });
411 const imageSize = fitImageAttachmentSize(bitmap);
412 if (!imageSize) return null;
413 const target = createCanvas(imageSize.width, imageSize.height);
414 if (!target) return null;
415 target.context.imageSmoothingQuality = "high";
416 target.context.drawImage(bitmap, 0, 0, imageSize.width, imageSize.height);
417 const blob = await encodeCanvas(target.canvas, QUALITY_STEPS[0], mimeType);
418 if (!blob) return null;
419 return {
420 file: new File([blob], file.name, { type: mimeType, lastModified: file.lastModified }),
421 imageSize,
422 };
423 } catch {
424 return null;
425 } finally {
426 bitmap?.close();
427 }
428}
429
430export async function compressImageToByteLimit(
431 file: File,
432 maxBytes: number,
433 options?: { preferredMimeType?: "image/jpeg"; sourceSizeBytes?: number },
434): Promise<CompressImageFileResult> {
435 const fitted = await fitImageToMaxEdge(file);
436 if (fitted && fitted.file.size <= maxBytes) {
437 return { ok: true, file: fitted.file, recompressed: true, imageSize: fitted.imageSize };
438 }
439 if (!fitted && file.size <= maxBytes) {
440 return { ok: true, file, recompressed: false };
441 }
442 if ((options?.sourceSizeBytes ?? file.size) > MAX_COMPRESSIBLE_SOURCE_BYTES) {
443 return { ok: false, reason: "too-large" };
444 }
445 const budgetChars = Math.floor(maxBytes / 3) * 4;
446 const reencoded = await reencodeWithinBudget(
447 fitted?.file ?? file,
448 budgetChars,
449 options?.preferredMimeType,
450 );
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
466const heicPreparations = new WeakMap<
467 File,
468 { image: Promise<CompressImageFileResult>; thumbnail: Promise<string | null> }
469>();
470// Preparing tiles share full-size decodes, so keep only one HEIC bitmap alive at a time.
471let heicPreparationQueue = Promise.resolve();
472
473function prepareHeicImage(file: File) {
474 const cached = heicPreparations.get(file);
475 if (cached) return cached;
476 let resolveThumbnail!: (src: string | null) => void;
477 const thumbnail = new Promise<string | null>((resolve) => {
478 resolveThumbnail = resolve;
479 });
480 const image = heicPreparationQueue
481 .then(() => convertHeicImage(file, resolveThumbnail))
482 .finally(() => resolveThumbnail(null));
483 heicPreparationQueue = image.then(
484 () => undefined,
485 () => undefined,
486 );
487 const preparation = { image, thumbnail };
488 heicPreparations.set(file, preparation);
489 return preparation;
490}
491
492async function convertHeicImage(
493 file: File,
494 onThumbnail: (src: string | null) => void,
495): Promise<CompressImageFileResult> {
496 if (file.size > MAX_COMPRESSIBLE_SOURCE_BYTES) {
497 return { ok: false, reason: "too-large" };
498 }
499
500 let bitmap: ImageBitmap | undefined;
501 try {
502 const dimensionError = await validateHeicImageDimensions(file);
503 if (dimensionError) {
504 return { ok: false, reason: dimensionError };
505 }
506 bitmap =
507 typeof createImageBitmap === "function"
508 ? await createImageBitmap(file).catch(() => undefined)
509 : undefined;
510 if (!bitmap) {
511 const { heicTo } = await import("heic-to/csp");
512 bitmap = await heicTo({ blob: file, type: "bitmap" });
513 }
514 const imageSize = fitImageAttachmentSize(bitmap) ?? {
515 width: bitmap.width,
516 height: bitmap.height,
517 };
518 const surface = createCanvas(imageSize.width, imageSize.height);
519 if (!surface) return { ok: false, reason: "unreadable" };
520 surface.context.drawImage(bitmap, 0, 0, imageSize.width, imageSize.height);
521 const [converted] = await Promise.all([
522 encodeCanvas(surface.canvas, QUALITY_STEPS[0], "image/jpeg"),
523 renderComposerImageThumbnailFromBitmap(bitmap).then(onThumbnail),
524 ]);
525 if (!converted) return { ok: false, reason: "unreadable" };
526 return {
527 ok: true,
528 file: new File([converted], fileNameForMimeType(file.name || "image", "image/jpeg"), {
529 type: "image/jpeg",
530 lastModified: file.lastModified,
531 }),
532 recompressed: true,
533 imageSize,
534 };
535 } catch {
536 return { ok: false, reason: "unreadable" };
537 } finally {
538 bitmap?.close();
539 }
540}
541
542export async function prepareImageForAttachment(
543 file: File,
544 maxBytes: number,
545): Promise<CompressImageFileResult> {
546 if (!isHeicImageFile(file)) return compressImageToByteLimit(file, maxBytes);
547 const prepared = await prepareHeicImage(file).image;
548 if (!prepared.ok || prepared.file.size <= maxBytes) return prepared;
549 const result = await compressImageToByteLimit(prepared.file, maxBytes, {
550 preferredMimeType: "image/jpeg",
551 sourceSizeBytes: file.size,
552 });
553
554 return result.ok ? { ...result, recompressed: true } : result;
555}