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

imageDecode.worker.ts

226 lines9.9 KB

1import { PreviewError, previewFailure } from "./previewFailure";
2​
3const MAX_PIXELS = 32_000_000;
4​
5function validateTiffMetadata(bytes: ArrayBuffer) {
6 const view = new DataView(bytes);
7 if (bytes.byteLength < 8) throw new PreviewError({ code: "tiff-metadata-invalid" });
8 const order = view.getUint16(0);
9 const littleEndian = order === 0x4949;
10 if (![0x4949, 0x4d4d].includes(order) || view.getUint16(2, littleEndian) !== 42)
11 throw new PreviewError({ code: "tiff-metadata-invalid" });
12 const visited = new Set<number>();
13 let entries = 0;
14 let allocation = 0;
15 const inspect = (offset: number, depth: number) => {
16 if (depth > 8 || visited.has(offset) || offset < 8 || offset + 2 > bytes.byteLength)
17 throw new PreviewError({ code: "tiff-metadata-invalid" });
18 visited.add(offset);
19 const count = view.getUint16(offset, littleEndian);
20 entries += count;
21 if (entries > 2048 || offset + 2 + count * 12 + 4 > bytes.byteLength)
22 throw new PreviewError({ code: "tiff-metadata-truncated" });
23 for (let index = 0; index < count; index++) {
24 const entry = offset + 2 + index * 12;
25 const tag = view.getUint16(entry, littleEndian);
26 const type = view.getUint16(entry + 2, littleEndian);
27 const values = view.getUint32(entry + 4, littleEndian);
28 const width = [0, 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8, 4][type];
29 if (!width) throw new PreviewError({ code: "tiff-metadata-type" });
30 const length = values * width;
31 const start = length > 4 ? view.getUint32(entry + 8, littleEndian) : entry + 8;
32 // The decoder retains a separate array or string for every tag, including aliases.
33 allocation += values * Math.max(16, width);
34 if (start + length > bytes.byteLength || allocation > 8 * 1024 * 1024)
35 throw new PreviewError({ code: "tiff-metadata-truncated" });
36 if (tag === 0x8769 || tag === 0x8825) {
37 if ((type !== 4 && type !== 13) || values !== 1)
38 throw new PreviewError({ code: "tiff-metadata-pointer" });
39 inspect(view.getUint32(entry + 8, littleEndian), depth + 1);
40 }
41 }
42 };
43 inspect(view.getUint32(4, littleEndian), 0);
45​
46function dimensions(width: number, height: number) {
47 if (!(width > 0 && height > 0) || width > 16384 || height > 16384 || width > MAX_PIXELS / height)
48 throw new PreviewError({ code: "image-too-large" });
50​
51function validateHeif(bytes: ArrayBuffer) {
52 const view = new DataView(bytes);
53 let found = false;
54 let count = 0;
55 const boxes = (start: number, end: number, depth: number) => {
56 if (depth > 4) return;
57 let offset = start;
58 while (offset + 8 <= end) {
59 if (++count > 2048) throw new PreviewError({ code: "image-metadata-too-large" });
60 let size = view.getUint32(offset);
61 let header = 8;
62 if (size === 1) {
63 if (offset + 16 > end) throw new PreviewError({ code: "heif-metadata-invalid" });
64 const large = view.getBigUint64(offset + 8);
65 if (large > BigInt(bytes.byteLength))
66 throw new PreviewError({ code: "heif-metadata-invalid" });
67 size = Number(large);
68 header = 16;
69 } else if (size === 0) size = end - offset;
70 if (size < header || offset + size > end)
71 throw new PreviewError({ code: "heif-metadata-invalid" });
72 const type = view.getUint32(offset + 4);
73 if (type === 0x69737065) {
74 if (size < header + 12) throw new PreviewError({ code: "heif-dimensions-invalid" });
75 dimensions(view.getUint32(offset + header + 4), view.getUint32(offset + header + 8));
76 found = true;
77 } else if (type === 0x6d657461 || type === 0x69707270 || type === 0x6970636f)
78 boxes(offset + header + (type === 0x6d657461 ? 4 : 0), offset + size, depth + 1);
79 offset += size;
80 }
81 };
82 boxes(0, bytes.byteLength, 0);
83 if (!found) throw new PreviewError({ code: "heif-no-dimensions" });
85​
86// Count LZW output without building strings before the decoder allocates its strip buffer.
87function validateLzw(bytes: Uint8Array, limit: number) {
88 const lengths = new Uint16Array(4096).fill(1, 0, 256);
89 let bits = 9;
90 let bit = 0;
91 let next = 258;
92 let previous = 0;
93 let total = 0;
94 while (bit + bits <= bytes.length * 8) {
95 let code = 0;
96 for (let index = 0; index < bits; index++, bit++)
97 code = (code << 1) | ((bytes[bit >> 3]! >> (7 - (bit & 7))) & 1);
98 if (code === 257) return;
99 if (code === 256) {
100 bits = 9;
101 next = 258;
102 previous = 0;
103 continue;
104 }
105 const length = code < next ? lengths[code]! : code === next && previous ? previous + 1 : 0;
106 if (!length || (total += length) > limit)
107 throw new PreviewError({ code: "tiff-strip-invalid-or-oversized" });
108 if (previous) {
109 if (next >= 4096) throw new PreviewError({ code: "tiff-lzw-invalid" });
110 lengths[next++] = previous + 1;
111 if (next === (1 << bits) - 1 && bits < 12) bits++;
112 }
113 previous = length;
114 }
115 throw new PreviewError({ code: "tiff-strip-truncated" });
117​
118async function validateTiffStrips(bytes: ArrayBuffer, image: import("tiff").TiffIfd) {
119 const offsets = image.tiled ? image.tileOffsets : image.stripOffsets;
120 const counts = image.tiled ? image.tileByteCounts : image.stripByteCounts;
121 const width = image.tiled ? image.tileWidth! : image.width;
122 const height = image.tiled ? image.tileHeight! : Math.min(image.rowsPerStrip, image.height);
123 dimensions(width, height);
124 const limit = width * height * image.components * (image.bitsPerSample / 8);
125 if (!offsets?.length || offsets.length > 2048 || counts?.length !== offsets.length)
126 throw new PreviewError({ code: "tiff-strip-layout" });
127 let expanded = 0;
128 for (let index = 0; index < offsets.length; index++) {
129 const offset = offsets[index]!;
130 const size = counts[index]!;
131 if (offset < 0 || size < 1 || offset + size > bytes.byteLength)
132 throw new PreviewError({ code: "tiff-strip-invalid" });
133 const strip = new Uint8Array(bytes, offset, size);
134 if (image.compression === 5) validateLzw(strip, limit);
135 else if (image.compression === 8 || image.compression === 32946) {
136 const reader = new Blob([strip])
137 .stream()
138 .pipeThrough(new DecompressionStream("deflate"))
139 .getReader();
140 let length = 0;
141 try {
142 while (true) {
143 const { value, done } = await reader.read();
144 if (done) break;
145 if ((length += value.length) > limit)
146 throw new PreviewError({ code: "tiff-strip-oversized" });
147 }
148 } finally {
149 await reader.cancel();
150 }
151 } else if (image.compression !== 1) throw new PreviewError({ code: "tiff-compression" });
152 // Bound repeated strips and padding as well as the visible image dimensions.
153 expanded += limit;
154 if (expanded > 256 * 1024 * 1024) throw new PreviewError({ code: "tiff-data-too-large" });
155 }
157​
158async function decode(bytes: ArrayBuffer, heif: boolean) {
159 if (bytes.byteLength > 50 * 1024 * 1024) throw new PreviewError({ code: "file-too-large" });
160 if (heif) {
161 validateHeif(bytes);
162 // Desktop CSP forbids the JavaScript evaluation used by heic-to/next.
163 const { heicTo } = await import("heic-to/csp");
164 const bitmap = await heicTo({ blob: new Blob([bytes]), type: "bitmap" });
165 try {
166 const canvas = new OffscreenCanvas(bitmap.width, bitmap.height);
167 const context = canvas.getContext("2d");
168 if (!context) throw new PreviewError({ code: "image-decoding-unavailable" });
169 context.drawImage(bitmap, 0, 0);
170 return await canvas.convertToBlob({ type: "image/png" });
171 } finally {
172 bitmap.close();
173 }
174 }
175 const { decode: decodeTiff } = await import("tiff");
176 validateTiffMetadata(bytes);
177 const metadata = decodeTiff(bytes, { ignoreImageData: true, pages: [0] })[0];
178 if (!metadata) throw new PreviewError({ code: "tiff-no-image" });
179 dimensions(metadata.width, metadata.height);
180 if (metadata.orientation && metadata.orientation !== 1)
181 throw new PreviewError({ code: "tiff-orientation" });
182 if (
183 (metadata.tiled && metadata.components > 1) ||
184 ![1, 2, 3, 4].includes(metadata.components) ||
185 ![8, 16].includes(metadata.bitsPerSample) ||
186 ![0, 1, 2, 3].includes(metadata.type)
187 )
188 throw new PreviewError({ code: "tiff-color-format" });
189 await validateTiffStrips(bytes, metadata);
190 const image = decodeTiff(bytes, { pages: [0] })[0]!;
191 const rgba = new Uint8ClampedArray(image.width * image.height * 4);
192 const scale = image.bitsPerSample === 16 ? 257 : 1;
193 const palette = image.palette;
194 const alpha = image.alpha;
195 // The tiff decoder inverts every WhiteIsZero sample, alpha included.
196 const invertAlpha = alpha && image.type === 0;
197 for (let pixel = 0; pixel < image.width * image.height; pixel++) {
198 const index = pixel * image.components;
199 if (palette) {
200 const color = palette[image.data[index]!] ?? [0, 0, 0];
201 for (let channel = 0; channel < 3; channel++)
202 rgba[pixel * 4 + channel] = color[channel]! / 257;
203 } else if (image.type === 2) {
204 for (let channel = 0; channel < 3; channel++)
205 rgba[pixel * 4 + channel] = image.data[index + channel]! / scale;
206 } else {
207 const gray = image.data[index]! / scale;
208 rgba.fill(gray, pixel * 4, pixel * 4 + 3);
209 }
210 const value = alpha ? image.data[index + image.components - 1]! / scale : 255;
211 rgba[pixel * 4 + 3] = invertAlpha ? 255 - value : value;
212 }
213 const canvas = new OffscreenCanvas(image.width, image.height);
214 const context = canvas.getContext("2d");
215 if (!context) throw new PreviewError({ code: "image-decoding-unavailable" });
216 context.putImageData(new ImageData(rgba, image.width, image.height), 0, 0);
217 return await canvas.convertToBlob({ type: "image/png" });
219​
220self.addEventListener("message", (event: MessageEvent<{ bytes: ArrayBuffer; heif: boolean }>) => {
221 void decode(event.data.bytes, event.data.heif).then(
222 (blob) => self.postMessage({ blob }, { transfer: [] }),
223 (cause: unknown) =>
224 self.postMessage({ failure: previewFailure(cause, "image-decode-failed") }, { transfer: [] }),
225 );
226});