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