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/**
14 * Ceiling on the *source* file handed to the re-encoder. File size is a
15 * proxy for pixel count, and decoding hundreds of megapixels into an
16 * ImageBitmap can OOM the tab — beyond this we refuse rather than risk it.
17 */
18export const MAX_COMPRESSIBLE_SOURCE_BYTES = 50 * 1024 * 1024;
19const MAX_HEIC_DECODE_PIXELS = 64_000_000;
20const MAX_HEIC_METADATA_BYTES = 1024 * 1024;
21const QUALITY_STEPS = [0.92, 0.85, 0.78, 0.68] as const;
22const FALLBACK_SCALE_STEPS = [0.75, 0.55] as const;
23const HEIC_IMAGE_MIME_TYPE = /^image\/hei(?:c|f)$/i;
24const HEIC_IMAGE_EXTENSION = /\.(?:heic|heif)$/i;
25
26type ImageSize = { width: number; height: number };
27
28export interface CompressedStashImage {
29 imageSize?: ImageSize;
30 dataUrl: string;
31 mimeType: string;
32 sizeBytes: number;
33 recompressed: boolean;
34}
35
36export type ImageCompressionFailureReason = "too-large" | "unreadable";
37
38export type CompressStashImageResult =
39 | { ok: true; image: CompressedStashImage }
40 | { ok: false; reason: ImageCompressionFailureReason };
41
42export type CompressImageFileResult =
43 | { ok: true; file: File; recompressed: boolean; imageSize?: ImageSize }
44 | { ok: false; reason: ImageCompressionFailureReason };
45
46/** Finder and some browsers omit the MIME type when dragging HEIC photos. */
47export function isHeicImageFile(file: Pick<File, "name" | "type">): boolean {
48 if (HEIC_IMAGE_MIME_TYPE.test(file.type)) {
49 return true;
50 }
51 return (
52 (file.type === "" || file.type.toLowerCase() === "application/octet-stream") &&
53 HEIC_IMAGE_EXTENSION.test(file.name)
54 );
55}
56
57interface HeicMetadataBox {
58 payloadOffset: number;
59 endOffset: number;
60}
61
62function findHeicMetadataBox(
63 view: DataView,
64 startOffset: number,
65 endOffset: number,
66 type: number,
67): HeicMetadataBox | null {
68 let offset = startOffset;
69 while (offset + 8 <= endOffset) {
70 let size = view.getUint32(offset);
71 let headerSize = 8;
72 if (size === 1) {
73 if (offset + 16 > endOffset) return null;
74 const extendedSize = view.getBigUint64(offset + 8);
75 if (extendedSize > BigInt(Number.MAX_SAFE_INTEGER)) return null;
76 size = Number(extendedSize);
77 headerSize = 16;
78 } else if (size === 0) {
79 size = endOffset - offset;
80 }
81 if (size < headerSize || size > endOffset - offset) return null;
82
83 const nextOffset = offset + size;
84 if (view.getUint32(offset + 4) === type) {
85 return { payloadOffset: offset + headerSize, endOffset: nextOffset };
86 }
87 offset = nextOffset;
88 }
89 return null;
90}
91
92async function validateHeicImageDimensions(
93 file: File,
94): Promise<ImageCompressionFailureReason | null> {
95 const metadata = await file.slice(0, MAX_HEIC_METADATA_BYTES).arrayBuffer();
96 const view = new DataView(metadata);
97 const meta = findHeicMetadataBox(view, 0, view.byteLength, 0x6d657461);
98 if (!meta || meta.payloadOffset + 4 > meta.endOffset) return "unreadable";
99 const properties = findHeicMetadataBox(view, meta.payloadOffset + 4, meta.endOffset, 0x69707270);
100 if (!properties) return "unreadable";
101 const containers = findHeicMetadataBox(
102 view,
103 properties.payloadOffset,
104 properties.endOffset,
105 0x6970636f,
106 );
107 if (!containers) return "unreadable";
108
109 let offset = containers.payloadOffset;
110 let foundImageDimensions = false;
111 while (offset < containers.endOffset) {
112 const image = findHeicMetadataBox(view, offset, containers.endOffset, 0x69737065);
113 if (!image) break;
114 if (image.payloadOffset + 12 > image.endOffset) return "unreadable";
115 const width = view.getUint32(image.payloadOffset + 4);
116 const height = view.getUint32(image.payloadOffset + 8);
117 if (width === 0 || height === 0) return "unreadable";
118 if (width > MAX_HEIC_DECODE_PIXELS / height) return "too-large";
119 foundImageDimensions = true;
120 offset = image.endOffset;
121 }
122 return foundImageDimensions ? null : "unreadable";
123}
124
125export function readFileAsDataUrl(file: Blob): Promise<string> {
126 return new Promise((resolve, reject) => {
127 const reader = new FileReader();
128 reader.addEventListener("load", () => {
129 if (typeof reader.result === "string") {
130 resolve(reader.result);
131 return;
132 }
133 reject(new Error("Could not read image data."));
134 });
135 reader.addEventListener("error", () => {
136 reject(reader.error ?? new Error("Failed to read image."));
137 });
138 reader.readAsDataURL(file);
139 });
140}
141
142function dataUrlLength(blob: Blob): number {
143 return (
144 `data:${blob.type || "application/octet-stream"};base64,`.length + 4 * Math.ceil(blob.size / 3)
145 );
146}
147
148export function dataUrlToFile(dataUrl: string, name: string, mimeType: string): File {
149 const payload = dataUrl.slice(dataUrl.indexOf(",") + 1);
150 const binary = atob(payload);
151 const bytes = new Uint8Array(binary.length);
152 for (let index = 0; index < binary.length; index += 1) {
153 bytes[index] = binary.charCodeAt(index);
154 }
155 return new File([bytes], name, { type: mimeType });
156}
157
158function fileNameForMimeType(name: string, mimeType: string): string {
159 const extension = mimeType === "image/webp" ? ".webp" : ".jpg";
160 const dotIndex = name.lastIndexOf(".");
161 const base = dotIndex > 0 ? name.slice(0, dotIndex) : name;
162 return `${base}${extension}`;
163}
164
165function canRecompress(): boolean {
166 return (
167 typeof createImageBitmap === "function" &&
168 (typeof OffscreenCanvas === "function" || typeof document !== "undefined")
169 );
170}
171
172interface Canvas2D {
173 canvas: OffscreenCanvas | HTMLCanvasElement;
174 context: OffscreenCanvasRenderingContext2D | CanvasRenderingContext2D;
175}
176
177function createCanvas(width: number, height: number): Canvas2D | null {
178 if (typeof OffscreenCanvas === "function") {
179 const canvas = new OffscreenCanvas(width, height);
180 const context = canvas.getContext("2d");
181 if (!context) return null;
182 return { canvas, context };
183 }
184 if (typeof document === "undefined") return null;
185 const canvas = document.createElement("canvas");
186 canvas.width = width;
187 canvas.height = height;
188 const context = canvas.getContext("2d");
189 if (!context) return null;
190 return { canvas, context };
191}
192
193async function encodeCanvas(
194 canvas: OffscreenCanvas | HTMLCanvasElement,
195 quality: number,
196 mimeType: string,
197): Promise<Blob | null> {
198 let blob: Blob | null;
199 if (typeof HTMLCanvasElement !== "undefined" && canvas instanceof HTMLCanvasElement) {
200 blob = await new Promise<Blob | null>((resolve) => canvas.toBlob(resolve, mimeType, quality));
201 } else {
202 blob = await (canvas as OffscreenCanvas).convertToBlob({ type: mimeType, quality });
203 }
204 return blob?.type === mimeType ? blob : null;
205}
206
207const COMPOSER_THUMBNAIL_SIZES = {
208 square: { width: 256, height: 256 },
209 // The 208x112 snapshot tile at retina density and 2x app zoom.
210 snapshot: { width: 832, height: 448 },
211} as const;
212export type ComposerImageThumbnailMode = keyof typeof COMPOSER_THUMBNAIL_SIZES;
213const composerThumbnails = new WeakMap<
214 File,
215 Partial<Record<ComposerImageThumbnailMode, Promise<string | null>>>
216>();
217
218export function createComposerImageThumbnail(
219 file: File,
220 mode: ComposerImageThumbnailMode = "square",
221): Promise<string | null> {
222 const fileThumbnails = composerThumbnails.get(file);
223 const cached = fileThumbnails?.[mode];
224 if (cached) return cached;
225 const thumbnail = (async () => {
226 if (!canRecompress()) return null;
227 let bitmap: ImageBitmap | undefined;
228 try {
229 bitmap = await createImageBitmap(file);
230 if (bitmap.width <= 0 || bitmap.height <= 0) return null;
231 const side = Math.min(bitmap.width, bitmap.height);
232 const sourceWidth = mode === "square" ? side : bitmap.width;
233 const sourceHeight = mode === "square" ? side : bitmap.height;
234 const bounds = COMPOSER_THUMBNAIL_SIZES[mode];
235 const scale = Math.min(1, bounds.width / sourceWidth, bounds.height / sourceHeight);
236 const width = Math.max(1, Math.round(sourceWidth * scale));
237 const height = Math.max(1, Math.round(sourceHeight * scale));
238 const surface = createCanvas(width, height);
239 if (!surface) return null;
240 surface.context.drawImage(
241 bitmap,
242 (bitmap.width - sourceWidth) / 2,
243 (bitmap.height - sourceHeight) / 2,
244 sourceWidth,
245 sourceHeight,
246 0,
247 0,
248 width,
249 height,
250 );
251 const blob = await encodeCanvas(surface.canvas, 1, "image/png");
252 return blob ? await readFileAsDataUrl(blob) : null;
253 } catch {
254 return null;
255 } finally {
256 bitmap?.close();
257 }
258 })();
259 composerThumbnails.set(file, { ...fileThumbnails, [mode]: thumbnail });
260 return thumbnail;
261}
262
263async function encodeWithinBudget(
264 bitmap: ImageBitmap,
265 maxDimension: number,
266 budgetChars: number,
267 preferredMimeType?: "image/jpeg",
268): Promise<{ blob: Blob; mimeType: string; imageSize: ImageSize } | null> {
269 const scale = Math.min(1, maxDimension / Math.max(bitmap.width, bitmap.height));
270 const width = Math.max(1, Math.round(bitmap.width * scale));
271 const height = Math.max(1, Math.round(bitmap.height * scale));
272 const target = createCanvas(width, height);
273 if (!target) return null;
274
275 // Probe WebP once; JPEG (no alpha) needs a white matte, so the fill has to
276 // happen before drawing and depends on which codec we end up using.
277 const mimeType =
278 preferredMimeType ??
279 ((await encodeCanvas(target.canvas, QUALITY_STEPS[0], "image/webp"))
280 ? "image/webp"
281 : "image/jpeg");
282
283 if (mimeType === "image/jpeg") {
284 target.context.fillStyle = "#ffffff";
285 target.context.fillRect(0, 0, width, height);
286 }
287 target.context.drawImage(bitmap, 0, 0, width, height);
288
289 for (const quality of QUALITY_STEPS) {
290 const encoded = await encodeCanvas(target.canvas, quality, mimeType);
291 if (!encoded) break;
292 if (dataUrlLength(encoded) <= budgetChars) {
293 return { blob: encoded, mimeType, imageSize: { width, height } };
294 }
295 }
296 return null;
297}
298
299type ReencodeResult =
300 | { ok: true; blob: Blob; mimeType: string; imageSize: ImageSize }
301 | { ok: false; reason: ImageCompressionFailureReason };
302
303async function reencodeWithinBudget(
304 file: File,
305 budgetChars: number,
306 preferredMimeType?: "image/jpeg",
307): Promise<ReencodeResult> {
308 if (!canRecompress()) {
309 return { ok: false, reason: "too-large" };
310 }
311
312 let bitmap: ImageBitmap;
313 try {
314 bitmap = await createImageBitmap(file);
315 } catch {
316 return { ok: false, reason: "unreadable" };
317 }
318
319 try {
320 // Each pass shrinks relative to the *previous target*, capped by
321 // MAX_DIMENSION. Scaling a fixed ceiling instead would be a no-op for
322 // images already smaller than that ceiling — the fallback passes would
323 // all resolve to the source size and never actually reduce resolution.
324 const baseDimension = Math.min(MAX_DIMENSION, Math.max(bitmap.width, bitmap.height));
325 let encodeFailed = false;
326 for (const dimensionScale of [1, ...FALLBACK_SCALE_STEPS]) {
327 const targetDimension = Math.max(1, Math.round(baseDimension * dimensionScale));
328 let encoded: Awaited<ReturnType<typeof encodeWithinBudget>>;
329 try {
330 encoded = await encodeWithinBudget(bitmap, targetDimension, budgetChars, preferredMimeType);
331 } catch {
332 encodeFailed = true;
333 continue;
334 }
335 encodeFailed = false;
336 if (encoded) {
337 return {
338 ok: true,
339 blob: encoded.blob,
340 mimeType: encoded.mimeType,
341 imageSize: encoded.imageSize,
342 };
343 }
344 }
345 return { ok: false, reason: encodeFailed ? "unreadable" : "too-large" };
346 } finally {
347 bitmap.close();
348 }
349}
350
351export async function compressImageForStash(
352 file: File,
353 budgetChars: number = MAX_STASH_IMAGE_DATA_URL_CHARS,
354): Promise<CompressStashImageResult> {
355 try {
356 if (dataUrlLength(file) <= budgetChars) {
357 return {
358 ok: true,
359 image: {
360 dataUrl: await readFileAsDataUrl(file),
361 mimeType: file.type,
362 sizeBytes: file.size,
363 recompressed: false,
364 },
365 };
366 }
367 const reencoded = await reencodeWithinBudget(file, budgetChars);
368 if (!reencoded.ok) {
369 return reencoded;
370 }
371 return {
372 ok: true,
373 image: {
374 dataUrl: await readFileAsDataUrl(reencoded.blob),
375 mimeType: reencoded.mimeType,
376 sizeBytes: reencoded.blob.size,
377 recompressed: true,
378 imageSize: reencoded.imageSize,
379 },
380 };
381 } catch {
382 return { ok: false, reason: "unreadable" };
383 }
384}
385
386async function fitImageToMaxEdge(file: File): Promise<{ file: File; imageSize: ImageSize } | null> {
387 const mimeType = downscalableImageMimeType(file.type);
388 if (!mimeType || !canRecompress() || file.size > MAX_COMPRESSIBLE_SOURCE_BYTES) return null;
389 let bitmap: ImageBitmap | undefined;
390 try {
391 const header = readImageDimensions(
392 new Uint8Array(await file.slice(0, IMAGE_DIMENSIONS_HEADER_BYTES).arrayBuffer()),
393 );
394 if (!header || !fitImageAttachmentSize(header)) return null;
395 bitmap = await createImageBitmap(file, { imageOrientation: "from-image" });
396 const imageSize = fitImageAttachmentSize(bitmap);
397 if (!imageSize) return null;
398 const target = createCanvas(imageSize.width, imageSize.height);
399 if (!target) return null;
400 target.context.imageSmoothingQuality = "high";
401 target.context.drawImage(bitmap, 0, 0, imageSize.width, imageSize.height);
402 const blob = await encodeCanvas(target.canvas, QUALITY_STEPS[0], mimeType);
403 if (!blob) return null;
404 return {
405 file: new File([blob], file.name, { type: mimeType, lastModified: file.lastModified }),
406 imageSize,
407 };
408 } catch {
409 return null;
410 } finally {
411 bitmap?.close();
412 }
413}
414
415export async function compressImageToByteLimit(
416 file: File,
417 maxBytes: number,
418 options?: { preferredMimeType?: "image/jpeg"; sourceSizeBytes?: number },
419): Promise<CompressImageFileResult> {
420 const fitted = await fitImageToMaxEdge(file);
421 if (fitted && fitted.file.size <= maxBytes) {
422 return { ok: true, file: fitted.file, recompressed: true, imageSize: fitted.imageSize };
423 }
424 if (!fitted && file.size <= maxBytes) {
425 return { ok: true, file, recompressed: false };
426 }
427 if ((options?.sourceSizeBytes ?? file.size) > MAX_COMPRESSIBLE_SOURCE_BYTES) {
428 return { ok: false, reason: "too-large" };
429 }
430 const budgetChars = Math.floor(maxBytes / 3) * 4;
431 const reencoded = await reencodeWithinBudget(
432 fitted?.file ?? file,
433 budgetChars,
434 options?.preferredMimeType,
435 );
436 if (!reencoded.ok) {
437 return reencoded;
438 }
439 return {
440 ok: true,
441 file: new File(
442 [reencoded.blob],
443 fileNameForMimeType(file.name || "image", reencoded.mimeType),
444 { type: reencoded.mimeType },
445 ),
446 recompressed: true,
447 imageSize: reencoded.imageSize,
448 };
449}
450
451export async function prepareImageForAttachment(
452 file: File,
453 maxBytes: number,
454): Promise<CompressImageFileResult> {
455 if (!isHeicImageFile(file)) {
456 return compressImageToByteLimit(file, maxBytes);
457 }
458
459 if (file.size > MAX_COMPRESSIBLE_SOURCE_BYTES) {
460 return { ok: false, reason: "too-large" };
461 }
462
463 let converted: Blob;
464 try {
465 const dimensionError = await validateHeicImageDimensions(file);
466 if (dimensionError) {
467 return { ok: false, reason: dimensionError };
468 }
469 const { heicTo } = await import("heic-to/csp");
470 converted = await heicTo({ blob: file, type: "image/jpeg", quality: QUALITY_STEPS[0] });
471 } catch {
472 return { ok: false, reason: "unreadable" };
473 }
474
475 const jpeg = new File([converted], fileNameForMimeType(file.name || "image", "image/jpeg"), {
476 type: "image/jpeg",
477 lastModified: file.lastModified,
478 });
479 const result = await compressImageToByteLimit(jpeg, maxBytes, {
480 preferredMimeType: "image/jpeg",
481 sourceSizeBytes: file.size,
482 });
483
484 return result.ok ? { ...result, recompressed: true } : result;
485}