Open History to see the last commit
1import { fitImageAttachmentSize } from "@t3tools/client-runtime/image-attachment-size";
2import {
3 IMAGE_DIMENSIONS_HEADER_BYTES,
4 readImageDimensions,
5} from "@t3tools/shared/imageDimensions";
6
7// Canvas work shared by the main thread and imageCompression.worker.ts, so it imports no UI code.
8
9export const MAX_IMAGE_METADATA_BYTES = 1024 * 1024;
10
11export type ImageSize = { width: number; height: number };
12
13export type EncodeCanvas = (
14 canvas: OffscreenCanvas | HTMLCanvasElement,
15 colorSpace: PredefinedColorSpace,
16 quality: number,
17 mimeType: string,
18) => Promise<Blob | null>;
19
20// D50-adapted Display P3 primaries, as an ICC profile's rXYZ, gXYZ and bXYZ tags carry them.
21const DISPLAY_P3_ICC_PRIMARIES = [
22 [0x7258595a, 0.5151, 0.2412, -0.0011],
23 [0x6758595a, 0.292, 0.6922, 0.0419],
24 [0x6258595a, 0.1571, 0.0666, 0.7841],
25] as const;
26
27export function iccProfileIsDisplayP3(view: DataView, start: number, end: number): boolean {
28 if (start + 132 > end) return false;
29 const tagCount = Math.min(view.getUint32(start + 128), Math.floor((end - start - 132) / 12));
30 let matched = 0;
31 for (let index = 0; index < tagCount; index += 1) {
32 const entry = start + 132 + index * 12;
33 const primary = DISPLAY_P3_ICC_PRIMARIES.find(
34 ([signature]) => signature === view.getUint32(entry),
35 );
36 if (!primary) continue;
37 const tag = start + view.getUint32(entry + 4);
38 if (tag < start || tag + 20 > end || view.getUint32(tag) !== 0x58595a20) return false;
39 for (let axis = 0; axis < 3; axis += 1) {
40 if (Math.abs(view.getInt32(tag + 8 + axis * 4) / 65536 - primary[axis + 1]!) > 0.005) {
41 return false;
42 }
43 }
44 matched += 1;
45 }
46 return matched === DISPLAY_P3_ICC_PRIMARIES.length;
47}
48
49async function inflateIccProfile(deflated: Uint8Array<ArrayBuffer>): Promise<Uint8Array | null> {
50 const reader = new Blob([deflated])
51 .stream()
52 .pipeThrough(new DecompressionStream("deflate"))
53 .getReader();
54 const chunks: Uint8Array[] = [];
55 let length = 0;
56 try {
57 for (;;) {
58 const { done, value } = await reader.read();
59 if (done) break;
60 length += value.length;
61 // A real profile is a few KiB; refuse to inflate a compression bomb.
62 if (length > MAX_IMAGE_METADATA_BYTES) return null;
63 chunks.push(value);
64 }
65 } catch {
66 return null;
67 } finally {
68 void reader.cancel().catch(() => undefined);
69 }
70 const profile = new Uint8Array(length);
71 let offset = 0;
72 for (const chunk of chunks) {
73 profile.set(chunk, offset);
74 offset += chunk.length;
75 }
76 return profile;
77}
78
79function iccProfileBytesAreDisplayP3(profile: Uint8Array): boolean {
80 return iccProfileIsDisplayP3(
81 new DataView(profile.buffer, profile.byteOffset, profile.byteLength),
82 0,
83 profile.byteLength,
84 );
85}
86
87async function pngIsDisplayP3(bytes: Uint8Array<ArrayBuffer>, view: DataView): Promise<boolean> {
88 for (let offset = 8; offset + 8 <= bytes.length;) {
89 const length = view.getUint32(offset);
90 const type = view.getUint32(offset + 4);
91 const data = offset + 8;
92 if (type === 0x49444154 || data + length > bytes.length) return false;
93 if (type === 0x63494350) return length >= 1 && bytes[data] === 12;
94 if (type === 0x69434350) {
95 const nameEnd = bytes.subarray(data, data + Math.min(length, 80)).indexOf(0);
96 if (nameEnd < 0) return false;
97 const profile = await inflateIccProfile(bytes.slice(data + nameEnd + 2, data + length));
98 return profile !== null && iccProfileBytesAreDisplayP3(profile);
99 }
100 offset = data + length + 4;
101 }
102 return false;
103}
104
105const JPEG_ICC_SIGNATURE = "ICC_PROFILE\0";
106
107function jpegIsDisplayP3(bytes: Uint8Array, view: DataView): boolean {
108 const segments: Uint8Array[] = [];
109 for (let offset = 2; offset + 4 <= bytes.length && bytes[offset] === 0xff;) {
110 const marker = bytes[offset + 1]!;
111 if (marker === 0xda || marker === 0xd9) break;
112 const length = view.getUint16(offset + 2);
113 const end = offset + 2 + length;
114 if (length < 2 || end > bytes.length) break;
115 const signature = String.fromCharCode(...bytes.subarray(offset + 4, offset + 16));
116 if (marker === 0xe2 && signature === JPEG_ICC_SIGNATURE) {
117 segments.push(bytes.subarray(offset + 18, end));
118 }
119 offset = end;
120 }
121 if (segments.length === 0) return false;
122 const profile = new Uint8Array(segments.reduce((total, segment) => total + segment.length, 0));
123 let offset = 0;
124 for (const segment of segments) {
125 profile.set(segment, offset);
126 offset += segment.length;
127 }
128 return iccProfileBytesAreDisplayP3(profile);
129}
130
131function webpIsDisplayP3(bytes: Uint8Array, view: DataView): boolean {
132 if (view.getUint32(8) !== 0x57454250) return false;
133 for (let offset = 12; offset + 8 <= bytes.length;) {
134 const type = view.getUint32(offset);
135 const length = view.getUint32(offset + 4, true);
136 const data = offset + 8;
137 if (data + length > bytes.length) return false;
138 if (type === 0x49434350) return iccProfileIsDisplayP3(view, data, data + length);
139 offset = data + length + (length % 2);
140 }
141 return false;
142}
143
144/** Re-encode on a canvas in the source's own color space, so it keeps its gamut and profile. */
145export async function readImageColorSpace(file: Blob): Promise<PredefinedColorSpace> {
146 const bytes = new Uint8Array(await file.slice(0, MAX_IMAGE_METADATA_BYTES).arrayBuffer());
147 if (bytes.length < 16) return "srgb";
148 const view = new DataView(bytes.buffer);
149 const signature = view.getUint32(0);
150 let displayP3 = false;
151 if (signature === 0x89504e47) displayP3 = await pngIsDisplayP3(bytes, view);
152 else if (signature >>> 16 === 0xffd8) displayP3 = jpegIsDisplayP3(bytes, view);
153 else if (signature === 0x52494646) displayP3 = webpIsDisplayP3(bytes, view);
154 return displayP3 ? "display-p3" : "srgb";
155}
156
157export interface Canvas2D {
158 canvas: OffscreenCanvas | HTMLCanvasElement;
159 context: OffscreenCanvasRenderingContext2D | CanvasRenderingContext2D;
160}
161
162export function createCanvas(
163 width: number,
164 height: number,
165 colorSpace: PredefinedColorSpace,
166): Canvas2D | null {
167 if (typeof OffscreenCanvas === "function") {
168 const canvas = new OffscreenCanvas(width, height);
169 const context = canvas.getContext("2d", { colorSpace });
170 if (!context) return null;
171 return { canvas, context };
172 }
173 if (typeof document === "undefined") return null;
174 const canvas = document.createElement("canvas");
175 canvas.width = width;
176 canvas.height = height;
177 const context = canvas.getContext("2d", { colorSpace });
178 if (!context) return null;
179 return { canvas, context };
180}
181
182export const encodeCanvasOnThisThread: EncodeCanvas = async (
183 canvas,
184 _colorSpace,
185 quality,
186 mimeType,
187) => {
188 let blob: Blob | null;
189 if (typeof HTMLCanvasElement !== "undefined" && canvas instanceof HTMLCanvasElement) {
190 blob = await new Promise<Blob | null>((resolve) => canvas.toBlob(resolve, mimeType, quality));
191 } else {
192 blob = await (canvas as OffscreenCanvas).convertToBlob({ type: mimeType, quality });
193 }
194 return blob?.type === mimeType ? blob : null;
195};
196
197/** `null` when the image already fits, or the browser cannot draw or encode it. */
198export async function fitImageToMaxEdge(
199 file: Blob,
200 mimeType: string,
201 quality: number,
202 encode: EncodeCanvas,
203): Promise<{ blob: Blob; imageSize: ImageSize } | null> {
204 const header = readImageDimensions(
205 new Uint8Array(await file.slice(0, IMAGE_DIMENSIONS_HEADER_BYTES).arrayBuffer()),
206 );
207 if (!header || !fitImageAttachmentSize(header)) return null;
208 const bitmap = await createImageBitmap(file, { imageOrientation: "from-image" });
209 try {
210 const imageSize = fitImageAttachmentSize(bitmap);
211 if (!imageSize) return null;
212 const colorSpace = await readImageColorSpace(file);
213 const target = createCanvas(imageSize.width, imageSize.height, colorSpace);
214 if (!target) return null;
215 target.context.imageSmoothingQuality = "high";
216 target.context.drawImage(bitmap, 0, 0, imageSize.width, imageSize.height);
217 const blob = await encode(target.canvas, colorSpace, quality, mimeType);
218 return blob ? { blob, imageSize } : null;
219 } finally {
220 bitmap.close();
221 }
222}
223
224export async function renderThumbnailFromBitmap(
225 bitmap: ImageBitmap,
226 colorSpace: PredefinedColorSpace,
227 encode: EncodeCanvas,
228): Promise<Blob | null> {
229 const side = Math.min(bitmap.width, bitmap.height);
230 if (side <= 0) return null;
231 const dimension = Math.min(256, side);
232 const surface = createCanvas(dimension, dimension, colorSpace);
233 if (!surface) return null;
234 surface.context.drawImage(
235 bitmap,
236 (bitmap.width - side) / 2,
237 (bitmap.height - side) / 2,
238 side,
239 side,
240 0,
241 0,
242 dimension,
243 dimension,
244 );
245 return encode(surface.canvas, colorSpace, 1, "image/png");
246}
247
248export async function renderThumbnail(file: Blob, encode: EncodeCanvas): Promise<Blob | null> {
249 const colorSpace = await readImageColorSpace(file);
250 const bitmap = await createImageBitmap(file);
251 try {
252 return await renderThumbnailFromBitmap(bitmap, colorSpace, encode);
253 } finally {
254 bitmap.close();
255 }
256}