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

imageCompression.ts

499 lines16.3 KB

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;
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 );
56​
57interface HeicMetadataBox {
58 payloadOffset: number;
59 endOffset: number;
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;
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";
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 });
141​
142function dataUrlLength(blob: Blob): number {
143 return (
144 `data:${blob.type || "application/octet-stream"};base64,`.length + 4 * Math.ceil(blob.size / 3)
145 );
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 });
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}`;
164​
165function canRecompress(): boolean {
166 return (
167 typeof createImageBitmap === "function" &&
168 (typeof OffscreenCanvas === "function" || typeof document !== "undefined")
169 );
171​
172interface Canvas2D {
173 canvas: OffscreenCanvas | HTMLCanvasElement;
174 context: OffscreenCanvasRenderingContext2D | CanvasRenderingContext2D;
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 };
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;
206​
207const composerThumbnails = new WeakMap<File, Promise<string | null>>();
208const settledComposerThumbnails = new WeakMap<File, string | null>();
209​
210function cacheComposerImageThumbnail(
211 file: File,
212 thumbnail: Promise<string | null>,
213): Promise<string | null> {
214 composerThumbnails.set(file, thumbnail);
215 void thumbnail.then((src) => settledComposerThumbnails.set(file, src));
216 return thumbnail;
218​
219/** `undefined` until the thumbnail settles, so a tile can paint a known thumbnail immediately. */
220export function readComposerImageThumbnail(file: File): string | null | undefined {
221 return settledComposerThumbnails.get(file);
223​
224export function createComposerImageThumbnail(file: File): Promise<string | null> {
225 return (
226 composerThumbnails.get(file) ??
227 cacheComposerImageThumbnail(file, renderComposerImageThumbnail(file))
228 );
230​
231/**
232 * Pasted images are re-encoded after their placeholder already shows the source's thumbnail.
233 * Reusing it keeps the tile from flashing back to its fallback while the new file is decoded.
234 */
235export function inheritComposerImageThumbnail(source: File, target: File): void {
236 const sourceThumbnail = composerThumbnails.get(source);
237 if (source === target || !sourceThumbnail || composerThumbnails.has(target)) return;
238 const settled = settledComposerThumbnails.get(source);
239 if (settled) settledComposerThumbnails.set(target, settled);
240 cacheComposerImageThumbnail(
241 target,
242 sourceThumbnail.then((src) => src ?? renderComposerImageThumbnail(target)),
243 );
245​
246async function renderComposerImageThumbnail(file: File): Promise<string | null> {
247 // Placeholders thumbnail the uncompressed source, which can be big enough to OOM the decode.
248 if (!canRecompress() || file.size > MAX_COMPRESSIBLE_SOURCE_BYTES) return null;
249 let bitmap: ImageBitmap | undefined;
250 try {
251 bitmap = await createImageBitmap(file);
252 const side = Math.min(bitmap.width, bitmap.height);
253 if (side <= 0) return null;
254 const dimension = Math.min(256, side);
255 const surface = createCanvas(dimension, dimension);
256 if (!surface) return null;
257 surface.context.drawImage(
258 bitmap,
259 (bitmap.width - side) / 2,
260 (bitmap.height - side) / 2,
261 side,
262 side,
263 0,
264 0,
265 dimension,
266 dimension,
267 );
268 const blob = await encodeCanvas(surface.canvas, 1, "image/png");
269 return blob ? await readFileAsDataUrl(blob) : null;
270 } catch {
271 return null;
272 } finally {
273 bitmap?.close();
274 }
276​
277async function encodeWithinBudget(
278 bitmap: ImageBitmap,
279 maxDimension: number,
280 budgetChars: number,
281 preferredMimeType?: "image/jpeg",
282): Promise<{ blob: Blob; mimeType: string; imageSize: ImageSize } | null> {
283 const scale = Math.min(1, maxDimension / Math.max(bitmap.width, bitmap.height));
284 const width = Math.max(1, Math.round(bitmap.width * scale));
285 const height = Math.max(1, Math.round(bitmap.height * scale));
286 const target = createCanvas(width, height);
287 if (!target) return null;
288​
289 // Probe WebP once; JPEG (no alpha) needs a white matte, so the fill has to
290 // happen before drawing and depends on which codec we end up using.
291 const mimeType =
292 preferredMimeType ??
293 ((await encodeCanvas(target.canvas, QUALITY_STEPS[0], "image/webp"))
294 ? "image/webp"
295 : "image/jpeg");
296​
297 if (mimeType === "image/jpeg") {
298 target.context.fillStyle = "#ffffff";
299 target.context.fillRect(0, 0, width, height);
300 }
301 target.context.drawImage(bitmap, 0, 0, width, height);
302​
303 for (const quality of QUALITY_STEPS) {
304 const encoded = await encodeCanvas(target.canvas, quality, mimeType);
305 if (!encoded) break;
306 if (dataUrlLength(encoded) <= budgetChars) {
307 return { blob: encoded, mimeType, imageSize: { width, height } };
308 }
309 }
310 return null;
312​
313type ReencodeResult =
314 | { ok: true; blob: Blob; mimeType: string; imageSize: ImageSize }
315 | { ok: false; reason: ImageCompressionFailureReason };
316​
317async function reencodeWithinBudget(
318 file: File,
319 budgetChars: number,
320 preferredMimeType?: "image/jpeg",
321): Promise<ReencodeResult> {
322 if (!canRecompress()) {
323 return { ok: false, reason: "too-large" };
324 }
325​
326 let bitmap: ImageBitmap;
327 try {
328 bitmap = await createImageBitmap(file);
329 } catch {
330 return { ok: false, reason: "unreadable" };
331 }
332​
333 try {
334 // Each pass shrinks relative to the *previous target*, capped by
335 // MAX_DIMENSION. Scaling a fixed ceiling instead would be a no-op for
336 // images already smaller than that ceiling — the fallback passes would
337 // all resolve to the source size and never actually reduce resolution.
338 const baseDimension = Math.min(MAX_DIMENSION, Math.max(bitmap.width, bitmap.height));
339 let encodeFailed = false;
340 for (const dimensionScale of [1, ...FALLBACK_SCALE_STEPS]) {
341 const targetDimension = Math.max(1, Math.round(baseDimension * dimensionScale));
342 let encoded: Awaited<ReturnType<typeof encodeWithinBudget>>;
343 try {
344 encoded = await encodeWithinBudget(bitmap, targetDimension, budgetChars, preferredMimeType);
345 } catch {
346 encodeFailed = true;
347 continue;
348 }
349 encodeFailed = false;
350 if (encoded) {
351 return {
352 ok: true,
353 blob: encoded.blob,
354 mimeType: encoded.mimeType,
355 imageSize: encoded.imageSize,
356 };
357 }
358 }
359 return { ok: false, reason: encodeFailed ? "unreadable" : "too-large" };
360 } finally {
361 bitmap.close();
362 }
364​
365export async function compressImageForStash(
366 file: File,
367 budgetChars: number = MAX_STASH_IMAGE_DATA_URL_CHARS,
368): Promise<CompressStashImageResult> {
369 try {
370 if (dataUrlLength(file) <= budgetChars) {
371 return {
372 ok: true,
373 image: {
374 dataUrl: await readFileAsDataUrl(file),
375 mimeType: file.type,
376 sizeBytes: file.size,
377 recompressed: false,
378 },
379 };
380 }
381 const reencoded = await reencodeWithinBudget(file, budgetChars);
382 if (!reencoded.ok) {
383 return reencoded;
384 }
385 return {
386 ok: true,
387 image: {
388 dataUrl: await readFileAsDataUrl(reencoded.blob),
389 mimeType: reencoded.mimeType,
390 sizeBytes: reencoded.blob.size,
391 recompressed: true,
392 imageSize: reencoded.imageSize,
393 },
394 };
395 } catch {
396 return { ok: false, reason: "unreadable" };
397 }
399​
400async function fitImageToMaxEdge(file: File): Promise<{ file: File; imageSize: ImageSize } | null> {
401 const mimeType = downscalableImageMimeType(file.type);
402 if (!mimeType || !canRecompress() || file.size > MAX_COMPRESSIBLE_SOURCE_BYTES) return null;
403 let bitmap: ImageBitmap | undefined;
404 try {
405 const header = readImageDimensions(
406 new Uint8Array(await file.slice(0, IMAGE_DIMENSIONS_HEADER_BYTES).arrayBuffer()),
407 );
408 if (!header || !fitImageAttachmentSize(header)) return null;
409 bitmap = await createImageBitmap(file, { imageOrientation: "from-image" });
410 const imageSize = fitImageAttachmentSize(bitmap);
411 if (!imageSize) return null;
412 const target = createCanvas(imageSize.width, imageSize.height);
413 if (!target) return null;
414 target.context.imageSmoothingQuality = "high";
415 target.context.drawImage(bitmap, 0, 0, imageSize.width, imageSize.height);
416 const blob = await encodeCanvas(target.canvas, QUALITY_STEPS[0], mimeType);
417 if (!blob) return null;
418 return {
419 file: new File([blob], file.name, { type: mimeType, lastModified: file.lastModified }),
420 imageSize,
421 };
422 } catch {
423 return null;
424 } finally {
425 bitmap?.close();
426 }
428​
429export async function compressImageToByteLimit(
430 file: File,
431 maxBytes: number,
432 options?: { preferredMimeType?: "image/jpeg"; sourceSizeBytes?: number },
433): Promise<CompressImageFileResult> {
434 const fitted = await fitImageToMaxEdge(file);
435 if (fitted && fitted.file.size <= maxBytes) {
436 return { ok: true, file: fitted.file, recompressed: true, imageSize: fitted.imageSize };
437 }
438 if (!fitted && file.size <= maxBytes) {
439 return { ok: true, file, recompressed: false };
440 }
441 if ((options?.sourceSizeBytes ?? file.size) > MAX_COMPRESSIBLE_SOURCE_BYTES) {
442 return { ok: false, reason: "too-large" };
443 }
444 const budgetChars = Math.floor(maxBytes / 3) * 4;
445 const reencoded = await reencodeWithinBudget(
446 fitted?.file ?? file,
447 budgetChars,
448 options?.preferredMimeType,
449 );
450 if (!reencoded.ok) {
451 return reencoded;
452 }
453 return {
454 ok: true,
455 file: new File(
456 [reencoded.blob],
457 fileNameForMimeType(file.name || "image", reencoded.mimeType),
458 { type: reencoded.mimeType },
459 ),
460 recompressed: true,
461 imageSize: reencoded.imageSize,
462 };
464​
465export async function prepareImageForAttachment(
466 file: File,
467 maxBytes: number,
468): Promise<CompressImageFileResult> {
469 if (!isHeicImageFile(file)) {
470 return compressImageToByteLimit(file, maxBytes);
471 }
472​
473 if (file.size > MAX_COMPRESSIBLE_SOURCE_BYTES) {
474 return { ok: false, reason: "too-large" };
475 }
476​
477 let converted: Blob;
478 try {
479 const dimensionError = await validateHeicImageDimensions(file);
480 if (dimensionError) {
481 return { ok: false, reason: dimensionError };
482 }
483 const { heicTo } = await import("heic-to/csp");
484 converted = await heicTo({ blob: file, type: "image/jpeg", quality: QUALITY_STEPS[0] });
485 } catch {
486 return { ok: false, reason: "unreadable" };
487 }
488​
489 const jpeg = new File([converted], fileNameForMimeType(file.name || "image", "image/jpeg"), {
490 type: "image/jpeg",
491 lastModified: file.lastModified,
492 });
493 const result = await compressImageToByteLimit(jpeg, maxBytes, {
494 preferredMimeType: "image/jpeg",
495 sourceSizeBytes: file.size,
496 });
497​
498 return result.ok ? { ...result, recompressed: true } : result;