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

imageCanvas.ts

280 lines9.6 KB

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;
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;
78​
79function iccProfileBytesAreDisplayP3(profile: Uint8Array): boolean {
80 return iccProfileIsDisplayP3(
81 new DataView(profile.buffer, profile.byteOffset, profile.byteLength),
82 0,
83 profile.byteLength,
84 );
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;
104​
105const JPEG_ICC_SIGNATURE = "ICC_PROFILE\0";
106​
107function jpegIsDisplayP3(bytes: Uint8Array, view: DataView): boolean {
108 const segments: Uint8Array[] = [];
109 let count = 0;
110 let found = 0;
111 for (let offset = 2; offset + 2 <= bytes.length && bytes[offset] === 0xff;) {
112 const marker = bytes[offset + 1]!;
113 if (marker === 0xff) {
114 offset += 1;
115 continue;
116 }
117 if (marker === 0xda || marker === 0xd9) break;
118 if (marker === 0x01 || (marker >= 0xd0 && marker <= 0xd7)) {
119 offset += 2;
120 continue;
121 }
122 if (offset + 4 > bytes.length) break;
123 const length = view.getUint16(offset + 2);
124 const end = offset + 2 + length;
125 if (length < 2 || end > bytes.length) break;
126 const signature = String.fromCharCode(...bytes.subarray(offset + 4, offset + 16));
127 if (marker === 0xe2 && end > offset + 18 && signature === JPEG_ICC_SIGNATURE) {
128 // ICC.1 Annex B.4 allows chunks in any order; place each by its 1-based sequence number.
129 const sequence = bytes[offset + 16]!;
130 const total = bytes[offset + 17]!;
131 if (
132 sequence >= 1 &&
133 sequence <= total &&
134 (count === 0 || total === count) &&
135 !segments[sequence - 1]
136 ) {
137 count = total;
138 segments[sequence - 1] = bytes.subarray(offset + 18, end);
139 found += 1;
140 if (found === count) break;
141 }
142 }
143 offset = end;
144 }
145 if (count === 0 || found < count) return false;
146 const profile = new Uint8Array(segments.reduce((total, segment) => total + segment.length, 0));
147 let offset = 0;
148 for (const segment of segments) {
149 profile.set(segment, offset);
150 offset += segment.length;
151 }
152 return iccProfileBytesAreDisplayP3(profile);
154​
155function webpIsDisplayP3(bytes: Uint8Array, view: DataView): boolean {
156 if (view.getUint32(8) !== 0x57454250) return false;
157 for (let offset = 12; offset + 8 <= bytes.length;) {
158 const type = view.getUint32(offset);
159 const length = view.getUint32(offset + 4, true);
160 const data = offset + 8;
161 if (data + length > bytes.length) return false;
162 if (type === 0x49434350) return iccProfileIsDisplayP3(view, data, data + length);
163 offset = data + length + (length % 2);
164 }
165 return false;
167​
168/** Re-encode on a canvas in the source's own color space, so it keeps its gamut and profile. */
169export async function readImageColorSpace(file: Blob): Promise<PredefinedColorSpace> {
170 const bytes = new Uint8Array(await file.slice(0, MAX_IMAGE_METADATA_BYTES).arrayBuffer());
171 if (bytes.length < 16) return "srgb";
172 const view = new DataView(bytes.buffer);
173 const signature = view.getUint32(0);
174 let displayP3 = false;
175 if (signature === 0x89504e47) displayP3 = await pngIsDisplayP3(bytes, view);
176 else if (signature >>> 16 === 0xffd8) displayP3 = jpegIsDisplayP3(bytes, view);
177 else if (signature === 0x52494646) displayP3 = webpIsDisplayP3(bytes, view);
178 return displayP3 ? "display-p3" : "srgb";
180​
181export interface Canvas2D {
182 canvas: OffscreenCanvas | HTMLCanvasElement;
183 context: OffscreenCanvasRenderingContext2D | CanvasRenderingContext2D;
185​
186export function createCanvas(
187 width: number,
188 height: number,
189 colorSpace: PredefinedColorSpace,
190): Canvas2D | null {
191 if (typeof OffscreenCanvas === "function") {
192 const canvas = new OffscreenCanvas(width, height);
193 const context = canvas.getContext("2d", { colorSpace });
194 if (!context) return null;
195 return { canvas, context };
196 }
197 if (typeof document === "undefined") return null;
198 const canvas = document.createElement("canvas");
199 canvas.width = width;
200 canvas.height = height;
201 const context = canvas.getContext("2d", { colorSpace });
202 if (!context) return null;
203 return { canvas, context };
205​
206export const encodeCanvasOnThisThread: EncodeCanvas = async (
207 canvas,
208 _colorSpace,
209 quality,
210 mimeType,
211) => {
212 let blob: Blob | null;
213 if (typeof HTMLCanvasElement !== "undefined" && canvas instanceof HTMLCanvasElement) {
214 blob = await new Promise<Blob | null>((resolve) => canvas.toBlob(resolve, mimeType, quality));
215 } else {
216 blob = await (canvas as OffscreenCanvas).convertToBlob({ type: mimeType, quality });
217 }
218 return blob?.type === mimeType ? blob : null;
219};
220​
221/** `null` when the image already fits, or the browser cannot draw or encode it. */
222export async function fitImageToMaxEdge(
223 file: Blob,
224 mimeType: string,
225 quality: number,
226 encode: EncodeCanvas,
227): Promise<{ blob: Blob; imageSize: ImageSize } | null> {
228 const header = readImageDimensions(
229 new Uint8Array(await file.slice(0, IMAGE_DIMENSIONS_HEADER_BYTES).arrayBuffer()),
230 );
231 if (!header || !fitImageAttachmentSize(header)) return null;
232 const bitmap = await createImageBitmap(file, { imageOrientation: "from-image" });
233 try {
234 const imageSize = fitImageAttachmentSize(bitmap);
235 if (!imageSize) return null;
236 const colorSpace = await readImageColorSpace(file);
237 const target = createCanvas(imageSize.width, imageSize.height, colorSpace);
238 if (!target) return null;
239 target.context.imageSmoothingQuality = "high";
240 target.context.drawImage(bitmap, 0, 0, imageSize.width, imageSize.height);
241 const blob = await encode(target.canvas, colorSpace, quality, mimeType);
242 return blob ? { blob, imageSize } : null;
243 } finally {
244 bitmap.close();
245 }
247​
248export async function renderThumbnailFromBitmap(
249 bitmap: ImageBitmap,
250 colorSpace: PredefinedColorSpace,
251 encode: EncodeCanvas,
252): Promise<Blob | null> {
253 const side = Math.min(bitmap.width, bitmap.height);
254 if (side <= 0) return null;
255 const dimension = Math.min(256, side);
256 const surface = createCanvas(dimension, dimension, colorSpace);
257 if (!surface) return null;
258 surface.context.drawImage(
259 bitmap,
260 (bitmap.width - side) / 2,
261 (bitmap.height - side) / 2,
262 side,
263 side,
264 0,
265 0,
266 dimension,
267 dimension,
268 );
269 return encode(surface.canvas, colorSpace, 1, "image/png");
271​
272export async function renderThumbnail(file: Blob, encode: EncodeCanvas): Promise<Blob | null> {
273 const colorSpace = await readImageColorSpace(file);
274 const bitmap = await createImageBitmap(file);
275 try {
276 return await renderThumbnailFromBitmap(bitmap, colorSpace, encode);
277 } finally {
278 bitmap.close();
279 }