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

imageCompression.browser.test.ts

178 lines7.5 KB

1import { describe, expect, it, vi } from "vite-plus/test";
2​
3import heicUrl from "../../test/fixtures/images/photo.heic?url";
4import {
5 compressImageForStash,
6 createComposerImageThumbnail,
7 dataUrlToFile,
8 prepareImageForAttachment,
9 readFileAsDataUrl,
10} from "./imageCompression";
11​
12async function makeImage(
13 colorSpace: PredefinedColorSpace,
14 fill: string,
15 type: string,
16): Promise<File> {
17 const canvas = new OffscreenCanvas(2400, 1600);
18 const context = canvas.getContext("2d", { colorSpace });
19 if (!context) throw new Error("no 2d context");
20 context.fillStyle = fill;
21 context.fillRect(0, 0, 2400, 1600);
22 const blob = await canvas.convertToBlob({ type, quality: 0.95 });
23 return new File([blob], `shot.${type.slice(6)}`, { type });
25​
26/** `raw` ignores any embedded profile, as a reader without color management would. */
27async function readPixel(file: Blob, raw = false): Promise<number[]> {
28 const bitmap = await createImageBitmap(file, { colorSpaceConversion: raw ? "none" : "default" });
29 const colorSpace = raw ? "srgb" : "display-p3";
30 const canvas = new OffscreenCanvas(1, 1);
31 const context = canvas.getContext("2d", { colorSpace });
32 if (!context) throw new Error("no 2d context");
33 context.drawImage(bitmap, 0, 0, 1, 1);
34 bitmap.close();
35 return Array.from(context.getImageData(0, 0, 1, 1, { colorSpace }).data.slice(0, 3));
37​
38async function expectSameColors(actual: Blob, expected: Blob) {
39 expectNear(await readPixel(actual), await readPixel(expected));
40 expectNear(await readPixel(actual, true), await readPixel(expected, true));
42​
43function expectNear(actual: number[], expected: number[]) {
44 expected.forEach((channel, index) =>
45 expect(Math.abs(actual[index]! - channel)).toBeLessThanOrEqual(2),
46 );
48​
49async function readChromiumDisplayP3Profile(): Promise<Uint8Array> {
50 const canvas = new OffscreenCanvas(1, 1);
51 canvas.getContext("2d", { colorSpace: "display-p3" });
52 const png = new Uint8Array(
53 await (await canvas.convertToBlob({ type: "image/png" })).arrayBuffer(),
54 );
55 const view = new DataView(png.buffer);
56 for (let offset = 8; offset < png.length; offset += 12 + view.getUint32(offset)) {
57 if (new TextDecoder().decode(png.subarray(offset + 4, offset + 8)) !== "iCCP") continue;
58 const chunk = png.subarray(offset + 8, offset + 8 + view.getUint32(offset));
59 const deflated = chunk.subarray(chunk.indexOf(0) + 2);
60 const inflate = new Blob([deflated]).stream().pipeThrough(new DecompressionStream("deflate"));
61 return new Uint8Array(await new Response(inflate).arrayBuffer());
62 }
63 throw new Error("no iCCP chunk");
65​
66// The fixture's only `colr` is nclx; swap it for an embedded ICC profile and fix up sizes and offsets.
67function replaceHeicColorWithProfile(heic: Uint8Array, profile: Uint8Array) {
68 const view = new DataView(heic.buffer);
69 const colr = heic.findIndex((_, index) => view.getUint32(index) === 0x636f6c72) - 4;
70 const colrSize = view.getUint32(colr);
71 const box = new Uint8Array(12 + profile.length);
72 new DataView(box.buffer).setUint32(0, box.length);
73 box.set(new TextEncoder().encode("colrprof"), 4);
74 box.set(profile, 12);
75 const delta = box.length - colrSize;
76 const out = new Uint8Array(heic.length + delta);
77 out.set(heic.subarray(0, colr));
78 out.set(box, colr);
79 out.set(heic.subarray(colr + colrSize), colr + box.length);
80 const outView = new DataView(out.buffer);
81 const find = (type: string) =>
82 out.findIndex((_, index) => new TextDecoder().decode(out.subarray(index, index + 4)) === type) -
83 4;
84 for (const type of ["meta", "iprp", "ipco"]) {
85 const offset = find(type);
86 outView.setUint32(offset, outView.getUint32(offset) + delta);
87 }
88 // iloc v0 with 4-byte offsets and lengths, no base offset: one extent per item.
89 const iloc = find("iloc");
90 for (let item = 0; item < outView.getUint16(iloc + 14); item += 1) {
91 const extentOffset = iloc + 16 + item * 14 + 6;
92 outView.setUint32(extentOffset, outView.getUint32(extentOffset) + delta);
93 }
94 return out;
96​
97describe("prepareImageForAttachment encoding", () => {
98 // Main-thread canvas encodes are idle tasks and Blob reads wait behind busy frames.
99 it("decodes, resizes and encodes off the main thread", async () => {
100 const source = await makeImage("srgb", "#ff0000", "image/png");
101 const convertToBlob = vi.spyOn(OffscreenCanvas.prototype, "convertToBlob");
102 const decode = vi.spyOn(window, "createImageBitmap");
103 try {
104 const [result, thumbnail] = await Promise.all([
105 prepareImageForAttachment(source, 20 * 1024 * 1024),
106 createComposerImageThumbnail(source),
107 ]);
108 if (!result.ok) throw new Error(result.reason);
109 expect(result.imageSize).toEqual({ width: 2000, height: 1333 });
110 expect(thumbnail).toMatch(/^data:image\/png;base64,/);
111 expect(convertToBlob).not.toHaveBeenCalled();
112 expect(decode).not.toHaveBeenCalled();
113 } finally {
114 convertToBlob.mockRestore();
115 decode.mockRestore();
116 }
117 });
118});
119​
120describe("prepareImageForAttachment color", () => {
121 // P3 green lies outside sRGB, so an sRGB canvas clips it; a P3 canvas would turn sRGB red's
122 // stored (255,0,0) into P3 values.
123 it.each([
124 ["Display P3 PNG", "display-p3", "color(display-p3 0 1 0)", "image/png"],
125 ["Display P3 JPEG", "display-p3", "color(display-p3 0 1 0)", "image/jpeg"],
126 ["sRGB PNG", "srgb", "#ff0000", "image/png"],
127 ["sRGB JPEG", "srgb", "#ff0000", "image/jpeg"],
128 ] as const)("keeps a downscaled %s in its own color space", async (_, space, fill, type) => {
129 const source = await makeImage(space, fill, type);
130​
131 const result = await prepareImageForAttachment(source, 20 * 1024 * 1024);
132 if (!result.ok) throw new Error(result.reason);
133 expect(result.recompressed).toBe(true);
134 expect(result.imageSize).toEqual({ width: 2000, height: 1333 });
135 await expectSameColors(result.file, source);
136 });
137​
138 it("keeps Display P3 colors when the stash re-encodes a WebP", async () => {
139 const source = await makeImage("display-p3", "color(display-p3 0 1 0)", "image/webp");
140 const result = await compressImageForStash(
141 source,
142 (await readFileAsDataUrl(source)).length - 1,
143 );
144 if (!result.ok) throw new Error(result.reason);
145 expect(result.image.recompressed).toBe(true);
146 const stored = dataUrlToFile(result.image.dataUrl, "stash", result.image.mimeType);
147 await expectSameColors(stored, source);
148 });
149​
150 it("keeps Display P3 colors when it converts a P3-tagged HEIC that the browser cannot decode", async () => {
151 const fixture = new Uint8Array(await (await fetch(heicUrl)).arrayBuffer());
152 const fixtureResult = await prepareImageForAttachment(
153 new File([fixture], "photo.heic", { type: "image/heic" }),
154 20 * 1024 * 1024,
155 );
156 if (!fixtureResult.ok) throw new Error(fixtureResult.reason);
157 // The fixture declares unspecified primaries, so it decodes as sRGB.
158 const decoded = await readPixel(fixtureResult.file, true);
159​
160 const nclx = fixture.slice();
161 const nclxOffset = nclx.findIndex(
162 (_, index) => new DataView(nclx.buffer).getUint32(index) === 0x6e636c78,
163 );
164 new DataView(nclx.buffer).setUint16(nclxOffset + 4, 12);
165 const tagged = [
166 nclx,
167 replaceHeicColorWithProfile(fixture, await readChromiumDisplayP3Profile()),
168 ];
169 for (const heic of tagged) {
170 const result = await prepareImageForAttachment(
171 new File([heic], "photo.heic", { type: "image/heic" }),
172 20 * 1024 * 1024,
173 );
174 if (!result.ok) throw new Error(result.reason);
175 expectNear(await readPixel(result.file), decoded);
176 }
177 });
178});