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

imageCompression.ts

756 lines25.7 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";
10import { msg } from "gt-react";
11​
12import { m } from "../i18n/messages";
13​
14const MAX_DIMENSION = IMAGE_ATTACHMENT_MAX_EDGE;
15export const MAX_STASH_IMAGE_DATA_URL_CHARS = 1_300_000;
16/** Bound source decoding: enormous ImageBitmaps can OOM the tab before resizing. */
17export const MAX_COMPRESSIBLE_SOURCE_BYTES = 50 * 1024 * 1024;
18const MAX_HEIC_DECODE_PIXELS = 64_000_000;
19const MAX_HEIC_METADATA_BYTES = 1024 * 1024;
20const QUALITY_STEPS = [0.92, 0.85, 0.78, 0.68] as const;
21const FALLBACK_SCALE_STEPS = [0.75, 0.55] as const;
22const HEIC_IMAGE_MIME_TYPE = /^image\/hei(?:c|f)$/i;
23const HEIC_IMAGE_EXTENSION = /\.(?:heic|heif)$/i;
24​
25type ImageSize = { width: number; height: number };
26​
27export interface CompressedStashImage {
28 imageSize?: ImageSize;
29 dataUrl: string;
30 mimeType: string;
31 sizeBytes: number;
32 recompressed: boolean;
34​
35export type ImageCompressionFailureReason = "too-large" | "unreadable";
36​
37export type CompressStashImageResult =
38 | { ok: true; image: CompressedStashImage }
39 | { ok: false; reason: ImageCompressionFailureReason };
40​
41export type CompressImageFileResult =
42 | { ok: true; file: File; recompressed: boolean; imageSize?: ImageSize }
43 | { ok: false; reason: ImageCompressionFailureReason };
44​
45/** Finder and some browsers omit the MIME type when dragging HEIC photos. */
46export function isHeicImageFile(file: Pick<File, "name" | "type">): boolean {
47 if (HEIC_IMAGE_MIME_TYPE.test(file.type)) {
48 return true;
49 }
50 return (
51 (file.type === "" || file.type.toLowerCase() === "application/octet-stream") &&
52 HEIC_IMAGE_EXTENSION.test(file.name)
53 );
55​
56interface HeicMetadataBox {
57 payloadOffset: number;
58 endOffset: number;
60​
61function findHeicMetadataBox(
62 view: DataView,
63 startOffset: number,
64 endOffset: number,
65 type: number,
66): HeicMetadataBox | null {
67 let offset = startOffset;
68 while (offset + 8 <= endOffset) {
69 let size = view.getUint32(offset);
70 let headerSize = 8;
71 if (size === 1) {
72 if (offset + 16 > endOffset) return null;
73 const extendedSize = view.getBigUint64(offset + 8);
74 if (extendedSize > BigInt(Number.MAX_SAFE_INTEGER)) return null;
75 size = Number(extendedSize);
76 headerSize = 16;
77 } else if (size === 0) {
78 size = endOffset - offset;
79 }
80 if (size < headerSize || size > endOffset - offset) return null;
81​
82 const nextOffset = offset + size;
83 if (view.getUint32(offset + 4) === type) {
84 return { payloadOffset: offset + headerSize, endOffset: nextOffset };
85 }
86 offset = nextOffset;
87 }
88 return null;
90​
91// D50-adapted Display P3 primaries, as an ICC profile's rXYZ, gXYZ and bXYZ tags carry them.
92const DISPLAY_P3_ICC_PRIMARIES = [
93 [0x7258595a, 0.5151, 0.2412, -0.0011],
94 [0x6758595a, 0.292, 0.6922, 0.0419],
95 [0x6258595a, 0.1571, 0.0666, 0.7841],
96] as const;
97​
98function iccProfileIsDisplayP3(view: DataView, start: number, end: number): boolean {
99 if (start + 132 > end) return false;
100 const tagCount = Math.min(view.getUint32(start + 128), Math.floor((end - start - 132) / 12));
101 let matched = 0;
102 for (let index = 0; index < tagCount; index += 1) {
103 const entry = start + 132 + index * 12;
104 const primary = DISPLAY_P3_ICC_PRIMARIES.find(
105 ([signature]) => signature === view.getUint32(entry),
106 );
107 if (!primary) continue;
108 const tag = start + view.getUint32(entry + 4);
109 if (tag < start || tag + 20 > end || view.getUint32(tag) !== 0x58595a20) return false;
110 for (let axis = 0; axis < 3; axis += 1) {
111 if (Math.abs(view.getInt32(tag + 8 + axis * 4) / 65536 - primary[axis + 1]!) > 0.005) {
112 return false;
113 }
114 }
115 matched += 1;
116 }
117 return matched === DISPLAY_P3_ICC_PRIMARIES.length;
119​
120/** `colr` is an nclx code point (12 is Display P3) or an embedded ICC profile. */
121function heicColorIsDisplayP3(view: DataView, box: HeicMetadataBox): boolean {
122 if (box.payloadOffset + 6 > box.endOffset) return false;
123 const colorType = view.getUint32(box.payloadOffset);
124 if (colorType === 0x6e636c78) return view.getUint16(box.payloadOffset + 4) === 12;
125 if (colorType === 0x70726f66 || colorType === 0x72494343) {
126 return iccProfileIsDisplayP3(view, box.payloadOffset + 4, box.endOffset);
127 }
128 return false;
130​
131type HeicMetadataResult =
132 | { ok: true; displayP3: boolean }
133 | { ok: false; reason: ImageCompressionFailureReason };
134​
135async function readHeicMetadata(file: File): Promise<HeicMetadataResult> {
136 const unreadable = { ok: false, reason: "unreadable" } as const;
137 const metadata = await file.slice(0, MAX_HEIC_METADATA_BYTES).arrayBuffer();
138 const view = new DataView(metadata);
139 const meta = findHeicMetadataBox(view, 0, view.byteLength, 0x6d657461);
140 if (!meta || meta.payloadOffset + 4 > meta.endOffset) return unreadable;
141 const properties = findHeicMetadataBox(view, meta.payloadOffset + 4, meta.endOffset, 0x69707270);
142 if (!properties) return unreadable;
143 const containers = findHeicMetadataBox(
144 view,
145 properties.payloadOffset,
146 properties.endOffset,
147 0x6970636f,
148 );
149 if (!containers) return unreadable;
150​
151 let offset = containers.payloadOffset;
152 let foundImageDimensions = false;
153 while (offset < containers.endOffset) {
154 const image = findHeicMetadataBox(view, offset, containers.endOffset, 0x69737065);
155 if (!image) break;
156 if (image.payloadOffset + 12 > image.endOffset) return unreadable;
157 const width = view.getUint32(image.payloadOffset + 4);
158 const height = view.getUint32(image.payloadOffset + 8);
159 if (width === 0 || height === 0) return unreadable;
160 if (width > MAX_HEIC_DECODE_PIXELS / height) return { ok: false, reason: "too-large" };
161 foundImageDimensions = true;
162 offset = image.endOffset;
163 }
164 if (!foundImageDimensions) return unreadable;
165​
166 let displayP3 = false;
167 offset = containers.payloadOffset;
168 while (!displayP3 && offset < containers.endOffset) {
169 const color = findHeicMetadataBox(view, offset, containers.endOffset, 0x636f6c72);
170 if (!color) break;
171 displayP3 = heicColorIsDisplayP3(view, color);
172 offset = color.endOffset;
173 }
174 return { ok: true, displayP3 };
176​
177async function inflateIccProfile(deflated: Uint8Array<ArrayBuffer>): Promise<Uint8Array | null> {
178 const reader = new Blob([deflated])
179 .stream()
180 .pipeThrough(new DecompressionStream("deflate"))
181 .getReader();
182 const chunks: Uint8Array[] = [];
183 let length = 0;
184 try {
185 for (;;) {
186 const { done, value } = await reader.read();
187 if (done) break;
188 length += value.length;
189 // A real profile is a few KiB; refuse to inflate a compression bomb.
190 if (length > MAX_HEIC_METADATA_BYTES) return null;
191 chunks.push(value);
192 }
193 } catch {
194 return null;
195 } finally {
196 void reader.cancel().catch(() => undefined);
197 }
198 const profile = new Uint8Array(length);
199 let offset = 0;
200 for (const chunk of chunks) {
201 profile.set(chunk, offset);
202 offset += chunk.length;
203 }
204 return profile;
206​
207function iccProfileBytesAreDisplayP3(profile: Uint8Array): boolean {
208 return iccProfileIsDisplayP3(
209 new DataView(profile.buffer, profile.byteOffset, profile.byteLength),
210 0,
211 profile.byteLength,
212 );
214​
215async function pngIsDisplayP3(bytes: Uint8Array<ArrayBuffer>, view: DataView): Promise<boolean> {
216 for (let offset = 8; offset + 8 <= bytes.length;) {
217 const length = view.getUint32(offset);
218 const type = view.getUint32(offset + 4);
219 const data = offset + 8;
220 if (type === 0x49444154 || data + length > bytes.length) return false;
221 if (type === 0x63494350) return length >= 1 && bytes[data] === 12;
222 if (type === 0x69434350) {
223 const nameEnd = bytes.subarray(data, data + Math.min(length, 80)).indexOf(0);
224 if (nameEnd < 0) return false;
225 const profile = await inflateIccProfile(bytes.slice(data + nameEnd + 2, data + length));
226 return profile !== null && iccProfileBytesAreDisplayP3(profile);
227 }
228 offset = data + length + 4;
229 }
230 return false;
232​
233const JPEG_ICC_SIGNATURE = "ICC_PROFILE\0";
234​
235function jpegIsDisplayP3(bytes: Uint8Array, view: DataView): boolean {
236 const segments: Uint8Array[] = [];
237 for (let offset = 2; offset + 4 <= bytes.length && bytes[offset] === 0xff;) {
238 const marker = bytes[offset + 1]!;
239 if (marker === 0xda || marker === 0xd9) break;
240 const length = view.getUint16(offset + 2);
241 const end = offset + 2 + length;
242 if (length < 2 || end > bytes.length) break;
243 const signature = String.fromCharCode(...bytes.subarray(offset + 4, offset + 16));
244 if (marker === 0xe2 && signature === JPEG_ICC_SIGNATURE) {
245 segments.push(bytes.subarray(offset + 18, end));
246 }
247 offset = end;
248 }
249 if (segments.length === 0) return false;
250 const profile = new Uint8Array(segments.reduce((total, segment) => total + segment.length, 0));
251 let offset = 0;
252 for (const segment of segments) {
253 profile.set(segment, offset);
254 offset += segment.length;
255 }
256 return iccProfileBytesAreDisplayP3(profile);
258​
259function webpIsDisplayP3(bytes: Uint8Array, view: DataView): boolean {
260 if (view.getUint32(8) !== 0x57454250) return false;
261 for (let offset = 12; offset + 8 <= bytes.length;) {
262 const type = view.getUint32(offset);
263 const length = view.getUint32(offset + 4, true);
264 const data = offset + 8;
265 if (data + length > bytes.length) return false;
266 if (type === 0x49434350) return iccProfileIsDisplayP3(view, data, data + length);
267 offset = data + length + (length % 2);
268 }
269 return false;
271​
272/** Re-encode on a canvas in the source's own color space, so it keeps its gamut and profile. */
273async function readImageColorSpace(file: Blob): Promise<PredefinedColorSpace> {
274 const bytes = new Uint8Array(await file.slice(0, MAX_HEIC_METADATA_BYTES).arrayBuffer());
275 if (bytes.length < 16) return "srgb";
276 const view = new DataView(bytes.buffer);
277 const signature = view.getUint32(0);
278 let displayP3 = false;
279 if (signature === 0x89504e47) displayP3 = await pngIsDisplayP3(bytes, view);
280 else if (signature >>> 16 === 0xffd8) displayP3 = jpegIsDisplayP3(bytes, view);
281 else if (signature === 0x52494646) displayP3 = webpIsDisplayP3(bytes, view);
282 return displayP3 ? "display-p3" : "srgb";
284​
285export function readFileAsDataUrl(file: Blob): Promise<string> {
286 return new Promise((resolve, reject) => {
287 const reader = new FileReader();
288 reader.addEventListener("load", () => {
289 if (typeof reader.result === "string") {
290 resolve(reader.result);
291 return;
292 }
293 reject(new Error(m(msg("Could not read image data."))));
294 });
295 reader.addEventListener("error", () => {
296 reject(reader.error ?? new Error(m(msg("Failed to read image."))));
297 });
298 reader.readAsDataURL(file);
299 });
301​
302function dataUrlLength(blob: Blob): number {
303 return (
304 `data:${blob.type || "application/octet-stream"};base64,`.length + 4 * Math.ceil(blob.size / 3)
305 );
307​
308export function dataUrlToFile(dataUrl: string, name: string, mimeType: string): File {
309 const payload = dataUrl.slice(dataUrl.indexOf(",") + 1);
310 const binary = atob(payload);
311 const bytes = new Uint8Array(binary.length);
312 for (let index = 0; index < binary.length; index += 1) {
313 bytes[index] = binary.charCodeAt(index);
314 }
315 return new File([bytes], name, { type: mimeType });
317​
318function fileNameForMimeType(name: string, mimeType: string): string {
319 const extension = mimeType === "image/webp" ? ".webp" : ".jpg";
320 const dotIndex = name.lastIndexOf(".");
321 const base = dotIndex > 0 ? name.slice(0, dotIndex) : name;
322 return `${base}${extension}`;
324​
325function canRecompress(): boolean {
326 return (
327 typeof createImageBitmap === "function" &&
328 (typeof OffscreenCanvas === "function" || typeof document !== "undefined")
329 );
331​
332interface Canvas2D {
333 canvas: OffscreenCanvas | HTMLCanvasElement;
334 context: OffscreenCanvasRenderingContext2D | CanvasRenderingContext2D;
336​
337function createCanvas(
338 width: number,
339 height: number,
340 colorSpace: PredefinedColorSpace,
341): Canvas2D | null {
342 if (typeof OffscreenCanvas === "function") {
343 const canvas = new OffscreenCanvas(width, height);
344 const context = canvas.getContext("2d", { colorSpace });
345 if (!context) return null;
346 return { canvas, context };
347 }
348 if (typeof document === "undefined") return null;
349 const canvas = document.createElement("canvas");
350 canvas.width = width;
351 canvas.height = height;
352 const context = canvas.getContext("2d", { colorSpace });
353 if (!context) return null;
354 return { canvas, context };
356​
357async function encodeCanvas(
358 canvas: OffscreenCanvas | HTMLCanvasElement,
359 quality: number,
360 mimeType: string,
361): Promise<Blob | null> {
362 let blob: Blob | null;
363 if (typeof HTMLCanvasElement !== "undefined" && canvas instanceof HTMLCanvasElement) {
364 blob = await new Promise<Blob | null>((resolve) => canvas.toBlob(resolve, mimeType, quality));
365 } else {
366 blob = await (canvas as OffscreenCanvas).convertToBlob({ type: mimeType, quality });
367 }
368 return blob?.type === mimeType ? blob : null;
370​
371const composerThumbnails = new WeakMap<File, Promise<string | null>>();
372const settledComposerThumbnails = new WeakMap<File, string | null>();
373​
374function cacheComposerImageThumbnail(
375 file: File,
376 thumbnail: Promise<string | null>,
377): Promise<string | null> {
378 composerThumbnails.set(file, thumbnail);
379 void thumbnail.then((src) => settledComposerThumbnails.set(file, src));
380 return thumbnail;
382​
383/** `undefined` until the thumbnail settles, so a tile can paint a known thumbnail immediately. */
384export function readComposerImageThumbnail(file: File): string | null | undefined {
385 return settledComposerThumbnails.get(file);
387​
388export function createComposerImageThumbnail(file: File): Promise<string | null> {
389 return (
390 composerThumbnails.get(file) ??
391 cacheComposerImageThumbnail(file, renderComposerImageThumbnail(file))
392 );
394​
395/**
396 * Pasted images are re-encoded after their placeholder already shows the source's thumbnail.
397 * Reusing it keeps the tile from flashing back to its fallback while the new file is decoded.
398 * Resolves once the target's thumbnail is readable, so a tile swapped to it paints at once even
399 * when compression finished before the source's thumbnail did.
400 */
401export async function inheritComposerImageThumbnail(source: File, target: File): Promise<void> {
402 const sourceThumbnail = composerThumbnails.get(source);
403 if (source === target || !sourceThumbnail || composerThumbnails.has(target)) return;
404 cacheComposerImageThumbnail(
405 target,
406 sourceThumbnail.then((src) => src ?? renderComposerImageThumbnail(target)),
407 );
408 const src = await sourceThumbnail;
409 if (src) settledComposerThumbnails.set(target, src);
411​
412async function renderComposerImageThumbnail(file: File): Promise<string | null> {
413 if (isHeicImageFile(file)) return prepareHeicImage(file).thumbnail;
414 // Placeholders thumbnail the uncompressed source, which can be big enough to OOM the decode.
415 if (!canRecompress() || file.size > MAX_COMPRESSIBLE_SOURCE_BYTES) return null;
416 let bitmap: ImageBitmap | undefined;
417 try {
418 const colorSpace = await readImageColorSpace(file);
419 bitmap = await createImageBitmap(file);
420 return await renderComposerImageThumbnailFromBitmap(bitmap, colorSpace);
421 } catch {
422 return null;
423 } finally {
424 bitmap?.close();
425 }
427​
428async function renderComposerImageThumbnailFromBitmap(
429 bitmap: ImageBitmap,
430 colorSpace: PredefinedColorSpace,
431): Promise<string | null> {
432 try {
433 const side = Math.min(bitmap.width, bitmap.height);
434 if (side <= 0) return null;
435 const dimension = Math.min(256, side);
436 const surface = createCanvas(dimension, dimension, colorSpace);
437 if (!surface) return null;
438 surface.context.drawImage(
439 bitmap,
440 (bitmap.width - side) / 2,
441 (bitmap.height - side) / 2,
442 side,
443 side,
444 0,
445 0,
446 dimension,
447 dimension,
448 );
449 const blob = await encodeCanvas(surface.canvas, 1, "image/png");
450 return blob ? await readFileAsDataUrl(blob) : null;
451 } catch {
452 return null;
453 }
455​
456async function encodeWithinBudget(
457 bitmap: ImageBitmap,
458 colorSpace: PredefinedColorSpace,
459 maxDimension: number,
460 budgetChars: number,
461 preferredMimeType?: "image/jpeg",
462): Promise<{ blob: Blob; mimeType: string; imageSize: ImageSize } | null> {
463 const scale = Math.min(1, maxDimension / Math.max(bitmap.width, bitmap.height));
464 const width = Math.max(1, Math.round(bitmap.width * scale));
465 const height = Math.max(1, Math.round(bitmap.height * scale));
466 const target = createCanvas(width, height, colorSpace);
467 if (!target) return null;
468​
469 // Probe the codec before drawing; JPEG needs a white matte because it has no alpha.
470 const mimeType =
471 preferredMimeType ??
472 ((await encodeCanvas(target.canvas, QUALITY_STEPS[0], "image/webp"))
473 ? "image/webp"
474 : "image/jpeg");
475​
476 if (mimeType === "image/jpeg") {
477 target.context.fillStyle = "#ffffff";
478 target.context.fillRect(0, 0, width, height);
479 }
480 target.context.drawImage(bitmap, 0, 0, width, height);
481​
482 for (const quality of QUALITY_STEPS) {
483 const encoded = await encodeCanvas(target.canvas, quality, mimeType);
484 if (!encoded) break;
485 if (dataUrlLength(encoded) <= budgetChars) {
486 return { blob: encoded, mimeType, imageSize: { width, height } };
487 }
488 }
489 return null;
491​
492type ReencodeResult =
493 | { ok: true; blob: Blob; mimeType: string; imageSize: ImageSize }
494 | { ok: false; reason: ImageCompressionFailureReason };
495​
496async function reencodeWithinBudget(
497 file: File,
498 budgetChars: number,
499 preferredMimeType?: "image/jpeg",
500): Promise<ReencodeResult> {
501 if (!canRecompress()) {
502 return { ok: false, reason: "too-large" };
503 }
504​
505 let bitmap: ImageBitmap;
506 let colorSpace: PredefinedColorSpace;
507 try {
508 colorSpace = await readImageColorSpace(file);
509 bitmap = await createImageBitmap(file);
510 } catch {
511 return { ok: false, reason: "unreadable" };
512 }
513​
514 try {
515 // Shrink the previous target; using MAX_DIMENSION leaves smaller images unchanged.
516 const baseDimension = Math.min(MAX_DIMENSION, Math.max(bitmap.width, bitmap.height));
517 let encodeFailed = false;
518 for (const dimensionScale of [1, ...FALLBACK_SCALE_STEPS]) {
519 const targetDimension = Math.max(1, Math.round(baseDimension * dimensionScale));
520 let encoded: Awaited<ReturnType<typeof encodeWithinBudget>>;
521 try {
522 encoded = await encodeWithinBudget(
523 bitmap,
524 colorSpace,
525 targetDimension,
526 budgetChars,
527 preferredMimeType,
528 );
529 } catch {
530 encodeFailed = true;
531 continue;
532 }
533 encodeFailed = false;
534 if (encoded) {
535 return {
536 ok: true,
537 blob: encoded.blob,
538 mimeType: encoded.mimeType,
539 imageSize: encoded.imageSize,
540 };
541 }
542 }
543 return { ok: false, reason: encodeFailed ? "unreadable" : "too-large" };
544 } finally {
545 bitmap.close();
546 }
548​
549export async function compressImageForStash(
550 file: File,
551 budgetChars: number = MAX_STASH_IMAGE_DATA_URL_CHARS,
552): Promise<CompressStashImageResult> {
553 try {
554 if (dataUrlLength(file) <= budgetChars) {
555 return {
556 ok: true,
557 image: {
558 dataUrl: await readFileAsDataUrl(file),
559 mimeType: file.type,
560 sizeBytes: file.size,
561 recompressed: false,
562 },
563 };
564 }
565 const reencoded = await reencodeWithinBudget(file, budgetChars);
566 if (!reencoded.ok) {
567 return reencoded;
568 }
569 return {
570 ok: true,
571 image: {
572 dataUrl: await readFileAsDataUrl(reencoded.blob),
573 mimeType: reencoded.mimeType,
574 sizeBytes: reencoded.blob.size,
575 recompressed: true,
576 imageSize: reencoded.imageSize,
577 },
578 };
579 } catch {
580 return { ok: false, reason: "unreadable" };
581 }
583​
584async function fitImageToMaxEdge(file: File): Promise<{ file: File; imageSize: ImageSize } | null> {
585 const mimeType = downscalableImageMimeType(file.type);
586 if (!mimeType || !canRecompress() || file.size > MAX_COMPRESSIBLE_SOURCE_BYTES) return null;
587 let bitmap: ImageBitmap | undefined;
588 try {
589 const header = readImageDimensions(
590 new Uint8Array(await file.slice(0, IMAGE_DIMENSIONS_HEADER_BYTES).arrayBuffer()),
591 );
592 if (!header || !fitImageAttachmentSize(header)) return null;
593 bitmap = await createImageBitmap(file, { imageOrientation: "from-image" });
594 const imageSize = fitImageAttachmentSize(bitmap);
595 if (!imageSize) return null;
596 const target = createCanvas(imageSize.width, imageSize.height, await readImageColorSpace(file));
597 if (!target) return null;
598 target.context.imageSmoothingQuality = "high";
599 target.context.drawImage(bitmap, 0, 0, imageSize.width, imageSize.height);
600 const blob = await encodeCanvas(target.canvas, QUALITY_STEPS[0], mimeType);
601 if (!blob) return null;
602 return {
603 file: new File([blob], file.name, { type: mimeType, lastModified: file.lastModified }),
604 imageSize,
605 };
606 } catch {
607 return null;
608 } finally {
609 bitmap?.close();
610 }
612​
613export async function compressImageToByteLimit(
614 file: File,
615 maxBytes: number,
616 options?: { preferredMimeType?: "image/jpeg"; sourceSizeBytes?: number },
617): Promise<CompressImageFileResult> {
618 const fitted = await fitImageToMaxEdge(file);
619 if (fitted && fitted.file.size <= maxBytes) {
620 return { ok: true, file: fitted.file, recompressed: true, imageSize: fitted.imageSize };
621 }
622 if (!fitted && file.size <= maxBytes) {
623 return { ok: true, file, recompressed: false };
624 }
625 if ((options?.sourceSizeBytes ?? file.size) > MAX_COMPRESSIBLE_SOURCE_BYTES) {
626 return { ok: false, reason: "too-large" };
627 }
628 const budgetChars = Math.floor(maxBytes / 3) * 4;
629 const reencoded = await reencodeWithinBudget(
630 fitted?.file ?? file,
631 budgetChars,
632 options?.preferredMimeType,
633 );
634 if (!reencoded.ok) {
635 return reencoded;
636 }
637 return {
638 ok: true,
639 file: new File(
640 [reencoded.blob],
641 fileNameForMimeType(file.name || "image", reencoded.mimeType),
642 { type: reencoded.mimeType },
643 ),
644 recompressed: true,
645 imageSize: reencoded.imageSize,
646 };
648​
649const heicPreparations = new WeakMap<
650 File,
651 { image: Promise<CompressImageFileResult>; thumbnail: Promise<string | null> }
652>();
653// Preparing tiles share full-size decodes, so keep only one HEIC bitmap alive at a time.
654let heicPreparationQueue = Promise.resolve();
655​
656function prepareHeicImage(file: File) {
657 const cached = heicPreparations.get(file);
658 if (cached) return cached;
659 let resolveThumbnail!: (src: string | null) => void;
660 const thumbnail = new Promise<string | null>((resolve) => {
661 resolveThumbnail = resolve;
662 });
663 const image = heicPreparationQueue
664 .then(() => convertHeicImage(file, resolveThumbnail))
665 .finally(() => resolveThumbnail(null));
666 heicPreparationQueue = image.then(
667 () => undefined,
668 () => undefined,
669 );
670 const preparation = { image, thumbnail };
671 heicPreparations.set(file, preparation);
672 return preparation;
674​
675async function readPixelsAsDisplayP3(
676 bitmap: ImageBitmap,
677 { width, height }: ImageSize,
678): Promise<ImageBitmap | undefined> {
679 const raw = createCanvas(width, height, "srgb");
680 if (!raw) return undefined;
681 raw.context.drawImage(bitmap, 0, 0, width, height);
682 const pixels = raw.context.getImageData(0, 0, width, height);
683 return createImageBitmap(new ImageData(pixels.data, width, height, { colorSpace: "display-p3" }));
685​
686async function convertHeicImage(
687 file: File,
688 onThumbnail: (src: string | null) => void,
689): Promise<CompressImageFileResult> {
690 if (file.size > MAX_COMPRESSIBLE_SOURCE_BYTES) {
691 return { ok: false, reason: "too-large" };
692 }
693​
694 let bitmap: ImageBitmap | undefined;
695 try {
696 const metadata = await readHeicMetadata(file);
697 if (!metadata.ok) return metadata;
698 bitmap =
699 typeof createImageBitmap === "function"
700 ? await createImageBitmap(file).catch(() => undefined)
701 : undefined;
702 const decodedNatively = bitmap !== undefined;
703 if (!bitmap) {
704 const { heicTo } = await import("heic-to/csp");
705 bitmap = await heicTo({ blob: file, type: "bitmap" });
706 }
707 const imageSize = fitImageAttachmentSize(bitmap) ?? {
708 width: bitmap.width,
709 height: bitmap.height,
710 };
711 // heic-to ignores the color profile and hands back the raw Display P3 values as sRGB.
712 if (!decodedNatively && metadata.displayP3) {
713 const source = bitmap;
714 bitmap = await readPixelsAsDisplayP3(source, imageSize);
715 source.close();
716 if (!bitmap) return { ok: false, reason: "unreadable" };
717 }
718 const colorSpace = metadata.displayP3 ? "display-p3" : "srgb";
719 const surface = createCanvas(imageSize.width, imageSize.height, colorSpace);
720 if (!surface) return { ok: false, reason: "unreadable" };
721 surface.context.drawImage(bitmap, 0, 0, imageSize.width, imageSize.height);
722 const [converted] = await Promise.all([
723 encodeCanvas(surface.canvas, QUALITY_STEPS[0], "image/jpeg"),
724 renderComposerImageThumbnailFromBitmap(bitmap, colorSpace).then(onThumbnail),
725 ]);
726 if (!converted) return { ok: false, reason: "unreadable" };
727 return {
728 ok: true,
729 file: new File([converted], fileNameForMimeType(file.name || "image", "image/jpeg"), {
730 type: "image/jpeg",
731 lastModified: file.lastModified,
732 }),
733 recompressed: true,
734 imageSize,
735 };
736 } catch {
737 return { ok: false, reason: "unreadable" };
738 } finally {
739 bitmap?.close();
740 }
742​
743export async function prepareImageForAttachment(
744 file: File,
745 maxBytes: number,
746): Promise<CompressImageFileResult> {
747 if (!isHeicImageFile(file)) return compressImageToByteLimit(file, maxBytes);
748 const prepared = await prepareHeicImage(file).image;
749 if (!prepared.ok || prepared.file.size <= maxBytes) return prepared;
750 const result = await compressImageToByteLimit(prepared.file, maxBytes, {
751 preferredMimeType: "image/jpeg",
752 sourceSizeBytes: file.size,
753 });
754​
755 return result.ok ? { ...result, recompressed: true } : result;