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