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

imageCompression.ts

332 lines12.4 KB

1/**
2 * Downscale + re-encode for image attachments that are too big for where
3 * they're headed. Two consumers share the same pipeline:
4 *
5 * - The prompt stash persists images as base64 in localStorage (~5MB origin
6 * quota), so `compressImageForStash` targets a per-image character budget.
7 * - The composer accepts pasted/dropped images larger than the provider's
8 * `PROVIDER_SEND_TURN_MAX_IMAGE_BYTES` wire cap and shrinks them to fit
9 * via `compressImageToByteLimit` instead of rejecting the paste.
10 *
11 * Images already within budget pass through untouched.
12 */
13​
14/**
15 * Longest edge kept when an image has to be re-encoded. Sized so a typical
16 * retina screenshot (3024px wide) stays legible rather than being halved.
17 */
18const MAX_DIMENSION = 2048;
19/** Base64 budget for a single stashed image (~975KB of binary). */
20export const MAX_STASH_IMAGE_DATA_URL_CHARS = 1_300_000;
21/**
22 * Ceiling on the *source* file handed to the re-encoder. File size is a
23 * proxy for pixel count, and decoding hundreds of megapixels into an
24 * ImageBitmap can OOM the tab — beyond this we refuse rather than risk it.
25 */
26export const MAX_COMPRESSIBLE_SOURCE_BYTES = 50 * 1024 * 1024;
27/**
28 * Quality ladder tried in order until the encoded image fits the budget.
29 * The floor stays high enough to avoid visible blocking on UI screenshots;
30 * if even that overflows we drop resolution instead of quality.
31 */
32const QUALITY_STEPS = [0.92, 0.85, 0.78, 0.68] as const;
33/** Extra downscale passes applied when even the lowest quality overflows. */
34const FALLBACK_SCALE_STEPS = [0.75, 0.55] as const;
35​
36export interface CompressedStashImage {
37 dataUrl: string;
38 mimeType: string;
39 sizeBytes: number;
40 /** True when the payload was re-encoded rather than stored verbatim. */
41 recompressed: boolean;
43​
44/**
45 * Why an image could not be compressed. Callers report these differently:
46 * "too large" is a budget outcome, "unreadable" is a decode failure.
47 */
48export type ImageCompressionFailureReason = "too-large" | "unreadable";
49​
50export type CompressStashImageResult =
51 | { ok: true; image: CompressedStashImage }
52 | { ok: false; reason: ImageCompressionFailureReason };
53​
54export type CompressImageFileResult =
55 | { ok: true; file: File; recompressed: boolean }
56 | { ok: false; reason: ImageCompressionFailureReason };
57​
58/** Chunked so a large image can't blow the argument limit of `fromCharCode`. */
59const BASE64_CHUNK_SIZE = 0x8000;
60​
61function bytesToBase64(bytes: Uint8Array): string {
62 let binary = "";
63 for (let offset = 0; offset < bytes.length; offset += BASE64_CHUNK_SIZE) {
64 binary += String.fromCharCode(...bytes.subarray(offset, offset + BASE64_CHUNK_SIZE));
65 }
66 return btoa(binary);
68​
69/**
70 * Blob → base64 data URL. Uses `arrayBuffer()` rather than `FileReader` so
71 * the module works anywhere `Blob` does (including non-DOM test runners).
72 */
73async function blobToDataUrl(blob: File | Blob, mimeTypeOverride?: string): Promise<string> {
74 const buffer = await blob.arrayBuffer();
75 const mimeType = mimeTypeOverride || blob.type || "application/octet-stream";
76 return `data:${mimeType};base64,${bytesToBase64(new Uint8Array(buffer))}`;
78​
79/** Approximate decoded byte count for a base64 data URL. */
80function dataUrlByteLength(dataUrl: string): number {
81 const commaIndex = dataUrl.indexOf(",");
82 const payload = commaIndex === -1 ? dataUrl : dataUrl.slice(commaIndex + 1);
83 const padding = payload.endsWith("==") ? 2 : payload.endsWith("=") ? 1 : 0;
84 return Math.max(0, Math.floor((payload.length * 3) / 4) - padding);
86​
87/** Base64 payload of a data URL decoded back into a `File`. */
88function dataUrlToFile(dataUrl: string, name: string, mimeType: string): File {
89 const payload = dataUrl.slice(dataUrl.indexOf(",") + 1);
90 const binary = atob(payload);
91 const bytes = new Uint8Array(binary.length);
92 for (let index = 0; index < binary.length; index += 1) {
93 bytes[index] = binary.charCodeAt(index);
94 }
95 return new File([bytes], name, { type: mimeType });
97​
98/**
99 * Re-encoding changes the container, so a name like `shot.png` would lie
100 * about its contents. Swap the extension to match the encoded mime type.
101 */
102function fileNameForMimeType(name: string, mimeType: string): string {
103 const extension = mimeType === "image/webp" ? ".webp" : ".jpg";
104 const dotIndex = name.lastIndexOf(".");
105 const base = dotIndex > 0 ? name.slice(0, dotIndex) : name;
106 return `${base}${extension}`;
108​
109function canRecompress(): boolean {
110 return (
111 typeof createImageBitmap === "function" &&
112 (typeof OffscreenCanvas === "function" || typeof document !== "undefined")
113 );
115​
116interface Canvas2D {
117 canvas: OffscreenCanvas | HTMLCanvasElement;
118 context: OffscreenCanvasRenderingContext2D | CanvasRenderingContext2D;
120​
121function createCanvas(width: number, height: number): Canvas2D | null {
122 if (typeof OffscreenCanvas === "function") {
123 const canvas = new OffscreenCanvas(width, height);
124 const context = canvas.getContext("2d");
125 if (!context) return null;
126 return { canvas, context };
127 }
128 if (typeof document === "undefined") return null;
129 const canvas = document.createElement("canvas");
130 canvas.width = width;
131 canvas.height = height;
132 const context = canvas.getContext("2d");
133 if (!context) return null;
134 return { canvas, context };
136​
137/**
138 * WebP is preferred: at matched visual quality it lands roughly 25-35%
139 * smaller than JPEG, so the same budget buys more resolution and detail —
140 * and it keeps alpha, so screenshots with transparency survive intact.
141 * Browsers that can't encode it silently fall back to JPEG.
142 */
143async function encodeCanvas(
144 canvas: OffscreenCanvas | HTMLCanvasElement,
145 quality: number,
146 mimeType: string,
147 budgetChars: number,
148): Promise<{ dataUrl: string | null; mimeType: string } | null> {
149 if (typeof HTMLCanvasElement !== "undefined" && canvas instanceof HTMLCanvasElement) {
150 const dataUrl = canvas.toDataURL(mimeType, quality);
151 // toDataURL silently returns a PNG when the requested type is unsupported.
152 if (!dataUrl.startsWith(`data:${mimeType}`)) return null;
153 return { dataUrl: dataUrl.length <= budgetChars ? dataUrl : null, mimeType };
154 }
155 const blob = await (canvas as OffscreenCanvas).convertToBlob({ type: mimeType, quality });
156 if (blob.type && blob.type !== mimeType) return null;
157 const dataUrlLength = `data:${mimeType};base64,`.length + 4 * Math.ceil(blob.size / 3);
158 if (dataUrlLength > budgetChars) return { dataUrl: null, mimeType };
159 return { dataUrl: await blobToDataUrl(blob, mimeType), mimeType };
161​
162/**
163 * Draws `bitmap` scaled to fit `maxDimension` and encodes it, stepping
164 * quality down until the data URL fits `budgetChars`.
165 */
166async function encodeWithinBudget(
167 bitmap: ImageBitmap,
168 maxDimension: number,
169 budgetChars: number,
170): Promise<{ dataUrl: string; mimeType: string } | null> {
171 const scale = Math.min(1, maxDimension / Math.max(bitmap.width, bitmap.height));
172 const width = Math.max(1, Math.round(bitmap.width * scale));
173 const height = Math.max(1, Math.round(bitmap.height * scale));
174 const target = createCanvas(width, height);
175 if (!target) return null;
176​
177 // Probe WebP once; JPEG (no alpha) needs a white matte, so the fill has to
178 // happen before drawing and depends on which codec we end up using.
179 const probe = await encodeCanvas(target.canvas, QUALITY_STEPS[0], "image/webp", 0);
180 const mimeType = probe ? "image/webp" : "image/jpeg";
181​
182 if (mimeType === "image/jpeg") {
183 target.context.fillStyle = "#ffffff";
184 target.context.fillRect(0, 0, width, height);
185 }
186 target.context.drawImage(bitmap, 0, 0, width, height);
187​
188 for (const quality of QUALITY_STEPS) {
189 const encoded = await encodeCanvas(target.canvas, quality, mimeType, budgetChars);
190 if (!encoded) break;
191 if (encoded.dataUrl !== null) {
192 return { dataUrl: encoded.dataUrl, mimeType: encoded.mimeType };
193 }
194 }
195 return null;
197​
198type ReencodeResult =
199 | { ok: true; dataUrl: string; mimeType: string }
200 | { ok: false; reason: ImageCompressionFailureReason };
201​
202/**
203 * Shared re-encode loop: decodes `file`, then walks the quality ladder and
204 * fallback downscale passes until an encoding fits `budgetChars`.
205 */
206async function reencodeWithinBudget(file: File, budgetChars: number): Promise<ReencodeResult> {
207 if (!canRecompress()) {
208 return { ok: false, reason: "too-large" };
209 }
210​
211 let bitmap: ImageBitmap;
212 try {
213 bitmap = await createImageBitmap(file);
214 } catch {
215 return { ok: false, reason: "unreadable" };
216 }
217​
218 try {
219 // Each pass shrinks relative to the *previous target*, capped by
220 // MAX_DIMENSION. Scaling a fixed ceiling instead would be a no-op for
221 // images already smaller than that ceiling — the fallback passes would
222 // all resolve to the source size and never actually reduce resolution.
223 const baseDimension = Math.min(MAX_DIMENSION, Math.max(bitmap.width, bitmap.height));
224 // Tracks whether the *last* attempt threw, so a run of encoder failures
225 // is reported as unreadable while a run of merely-too-big results is
226 // reported as too-large.
227 let encodeFailed = false;
228 for (const dimensionScale of [1, ...FALLBACK_SCALE_STEPS]) {
229 const targetDimension = Math.max(1, Math.round(baseDimension * dimensionScale));
230 let encoded: { dataUrl: string; mimeType: string } | null;
231 try {
232 encoded = await encodeWithinBudget(bitmap, targetDimension, budgetChars);
233 } catch {
234 // Canvas allocation, drawing, or the codec itself can throw — often
235 // precisely *because* the target is too big (OOM on a large bitmap).
236 // Keep trying the smaller fallback scales rather than giving up: a
237 // reduced pass may well succeed. The exception must never escape,
238 // though, since callers finalize state after this returns and a
239 // throw would strand it (e.g. a stash entry stuck "still saving").
240 encodeFailed = true;
241 continue;
242 }
243 encodeFailed = false;
244 if (encoded && encoded.dataUrl.length <= budgetChars) {
245 return { ok: true, dataUrl: encoded.dataUrl, mimeType: encoded.mimeType };
246 }
247 }
248 return { ok: false, reason: encodeFailed ? "unreadable" : "too-large" };
249 } finally {
250 bitmap.close();
251 }
253​
254/**
255 * Produces the payload to persist for a stashed image.
256 *
257 * Small images are stored verbatim (preserving PNG transparency and exact
258 * pixels). Anything over budget is downscaled and re-encoded; if it still
259 * doesn't fit after the fallback passes, reports a failure so the caller
260 * can record it as dropped.
261 */
262export async function compressImageForStash(
263 file: File,
264 budgetChars: number = MAX_STASH_IMAGE_DATA_URL_CHARS,
265): Promise<CompressStashImageResult> {
266 let originalDataUrl: string;
267 try {
268 originalDataUrl = await blobToDataUrl(file);
269 } catch {
270 return { ok: false, reason: "unreadable" };
271 }
272 if (originalDataUrl.length <= budgetChars) {
273 return {
274 ok: true,
275 image: {
276 dataUrl: originalDataUrl,
277 mimeType: file.type,
278 sizeBytes: file.size,
279 recompressed: false,
280 },
281 };
282 }
283 const reencoded = await reencodeWithinBudget(file, budgetChars);
284 if (!reencoded.ok) {
285 return reencoded;
286 }
287 return {
288 ok: true,
289 image: {
290 dataUrl: reencoded.dataUrl,
291 mimeType: reencoded.mimeType,
292 sizeBytes: dataUrlByteLength(reencoded.dataUrl),
293 recompressed: true,
294 },
295 };
297​
298/**
299 * Shrinks `file` until its binary size fits `maxBytes`, returning a new
300 * `File` (WebP or JPEG). Files already within the limit pass through
301 * untouched, preserving their exact bytes and format. Sources above
302 * `MAX_COMPRESSIBLE_SOURCE_BYTES` are refused outright — decoding them is
303 * the risk, so no amount of output budget makes them safe.
304 */
305export async function compressImageToByteLimit(
306 file: File,
307 maxBytes: number,
308): Promise<CompressImageFileResult> {
309 if (file.size <= maxBytes) {
310 return { ok: true, file, recompressed: false };
311 }
312 if (file.size > MAX_COMPRESSIBLE_SOURCE_BYTES) {
313 return { ok: false, reason: "too-large" };
314 }
315 // The re-encode loop budgets in data-URL characters. Base64 turns 3 bytes
316 // into 4 chars; flooring keeps the budget a hair conservative instead of
317 // admitting an encoding right at the byte cap.
318 const budgetChars = Math.floor(maxBytes / 3) * 4;
319 const reencoded = await reencodeWithinBudget(file, budgetChars);
320 if (!reencoded.ok) {
321 return reencoded;
322 }
323 return {
324 ok: true,
325 file: dataUrlToFile(
326 reencoded.dataUrl,
327 fileNameForMimeType(file.name || "image", reencoded.mimeType),
328 reencoded.mimeType,
329 ),
330 recompressed: true,
331 };