#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere
TypeScript dockerhacktoberfestjavapdfpdf-converterpdf-editorpdf-manipulationpdf-mergerpdf-ocrpdf-toolspdf-web-appspdfmergerself-hosted
perf(thumbnails): zero-copy view for contiguous wasm bitmap rows (#8134)
briosea7b5d349335
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/PdfTextEditor.tsx b/frontend/editor/src/core/tools/pdfTextEditor/PdfTextEditor.tsxindex 73b04cd7fa..7d2a33dfdf 100644--- a/frontend/editor/src/core/tools/pdfTextEditor/PdfTextEditor.tsx+++ b/frontend/editor/src/core/tools/pdfTextEditor/PdfTextEditor.tsx@@ -40,7 +40,7 @@ import { PageStage } from "@app/tools/pdfTextEditor/components/PageStage";import { InsertImageCommand } from "@app/tools/pdfTextEditor/commands/InsertImageCommand";import { InsertTextCommand } from "@app/tools/pdfTextEditor/commands/InsertTextCommand";import { DisplayTransform } from "@app/tools/pdfTextEditor/model/DisplayTransform";-import { jpegExifOrientation } from "@app/tools/pdfTextEditor/util/jpegOrientation";+import { jpegExifOrientation } from "@app/utils/jpegOrientation";import { MergeRunsCommand } from "@app/tools/pdfTextEditor/commands/MergeRunsCommand";import { UngroupParagraphCommand } from "@app/tools/pdfTextEditor/commands/UngroupParagraphCommand";import { exportToBlob } from "@app/tools/pdfTextEditor/util/exportPdf";diff --git a/frontend/editor/src/core/tools/pdfTextEditor/util/jpegOrientation.ts b/frontend/editor/src/core/utils/jpegOrientation.tssimilarity index 100%rename from frontend/editor/src/core/tools/pdfTextEditor/util/jpegOrientation.tsrename to frontend/editor/src/core/utils/jpegOrientation.tsdiff --git a/frontend/editor/src/core/utils/pdfiumPageRender.ts b/frontend/editor/src/core/utils/pdfiumPageRender.tsindex bbe222fa1b..536a98da2f 100644--- a/frontend/editor/src/core/utils/pdfiumPageRender.ts+++ b/frontend/editor/src/core/utils/pdfiumPageRender.ts@@ -11,6 +11,22 @@ import {type ExtendedPdfiumRuntime,} from "@app/services/pdfiumService";+/** Row-by-row copy for padded strides, where rows are not contiguous. */+function copyRows(+ heap: Uint8Array,+ bufferPtr: number,+ stride: number,+ w: number,+ h: number,+): Uint8ClampedArray<ArrayBuffer> {+ const pixels = new Uint8ClampedArray(w * h * 4);+ for (let y = 0; y < h; y++) {+ const srcRow = bufferPtr + y * stride;+ pixels.set(heap.subarray(srcRow, srcRow + w * 4), y * w * 4);+ }+ return pixels;+}+/** FPDF_ANNOT (0x01) | FPDF_LCD_TEXT (0x10). */const PDFIUM_RENDER_FLAGS = 0x01 | 0x10;@@ -76,14 +92,18 @@ export async function renderPdfiumPageDataUrl(const bufferPtr = m.FPDFBitmap_GetBuffer(bitmapPtr);const stride = m.FPDFBitmap_GetStride(bitmapPtr);const heap = (m.pdfium as typeof m.pdfium & ExtendedPdfiumRuntime).HEAPU8;- const pixels = new Uint8ClampedArray(w * h * 4);-// @embedpdf/pdfium WASM stores pixels in RGBA byte order (not BGRA),- // so copy rows directly without channel swapping.- for (let y = 0; y < h; y++) {- const srcRow = bufferPtr + y * stride;- pixels.set(heap.subarray(srcRow, srcRow + w * 4), y * w * 4);- }+ // so rows copy directly without channel swapping. The view below is+ // safe: putImageData runs synchronously with no wasm call between, so+ // no memory.grow can detach it (unlike retained ImageData elsewhere).+ const pixels =+ stride === w * 4+ ? new Uint8ClampedArray(+ heap.buffer as ArrayBuffer,+ bufferPtr,+ w * h * 4,+ )+ : copyRows(heap, bufferPtr, stride, w, h);const canvas = document.createElement("canvas");canvas.width = w;diff --git a/frontend/editor/src/core/utils/thumbnailUtils.test.ts b/frontend/editor/src/core/utils/thumbnailUtils.test.tsindex 18278154b9..694b557a7f 100644--- a/frontend/editor/src/core/utils/thumbnailUtils.test.ts+++ b/frontend/editor/src/core/utils/thumbnailUtils.test.ts@@ -1,4 +1,4 @@-import { describe, it, expect } from "vitest";+import { describe, it, expect, vi, afterEach } from "vitest";import { containsEncryptMarker } from "@app/utils/thumbnailUtils";import {PdfiumOpenError,@@ -80,3 +80,250 @@ describe("encrypted-PDF identification contract", () => {);});});++/**+ * Image thumbnails decode at tooltip size (shrink-on-load) instead of+ * full-res-then-downscale. jsdom has no createImageBitmap, so the fast path+ * is exercised with a stub; the fallback path uses the real FileReader.+ */+describe("generateThumbnailForFile — images", () => {+ const pngBytes = new Uint8Array([+ 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a,+ ]);++ /** A PNG header carrying IHDR dimensions, as the size probe reads them. */+ function pngHeader(width: number, height: number): Uint8Array<ArrayBuffer> {+ const bytes = new Uint8Array(24);+ bytes.set(pngBytes, 0);+ const view = new DataView(bytes.buffer);+ view.setUint32(8, 13);+ bytes.set([0x49, 0x48, 0x44, 0x52], 12);+ view.setUint32(16, width);+ view.setUint32(20, height);+ return bytes;+ }++ /** jsdom's Blob polyfill returns fixed bytes, so serve the header directly. */+ function fileWithHeader(+ header: Uint8Array<ArrayBuffer>,+ name = "photo.png",+ type = "image/png",+ ): File {+ const file = new File([header], name, { type });+ vi.spyOn(file, "slice").mockImplementation(+ (start?: number, end?: number) => {+ const part = header.slice(start ?? 0, end ?? header.length);+ return { arrayBuffer: async () => part.buffer } as unknown as Blob;+ },+ );+ return file;+ }++ /** Minimal JPEG: optional EXIF orientation, optional padding before the SOF. */+ function buildJpeg(+ width: number,+ height: number,+ options: { orientation?: number; padding?: number } = {},+ ): Uint8Array<ArrayBuffer> {+ const parts: number[] = [0xff, 0xd8];+ const pushSegment = (marker: number, payload: number[]) => {+ const length = payload.length + 2;+ parts.push(0xff, marker, (length >> 8) & 0xff, length & 0xff, ...payload);+ };+ if (options.orientation) {+ pushSegment(0xe1, [+ 0x45,+ 0x78,+ 0x69,+ 0x66,+ 0x00,+ 0x00, // "Exif\0\0"+ 0x49,+ 0x49,+ 0x2a,+ 0x00,+ 0x08,+ 0x00,+ 0x00,+ 0x00, // TIFF header, IFD at 8+ 0x01,+ 0x00, // one entry+ 0x12,+ 0x01,+ 0x03,+ 0x00,+ 0x01,+ 0x00,+ 0x00,+ 0x00, // orientation tag+ options.orientation,+ 0x00,+ 0x00,+ 0x00,+ 0x00,+ 0x00,+ 0x00,+ 0x00, // no next IFD+ ]);+ }+ let padding = options.padding ?? 0;+ while (padding > 0) {+ const chunk = Math.min(padding, 0xffff - 2);+ pushSegment(0xfe, new Array<number>(chunk).fill(0));+ padding -= chunk;+ }+ parts.push(+ 0xff,+ 0xc0,+ 0x00,+ 0x0b,+ 0x08,+ (height >> 8) & 0xff,+ height & 0xff,+ (width >> 8) & 0xff,+ width & 0xff,+ 0x01,+ 0x01,+ 0x11,+ 0xff,+ 0xda,+ );+ return new Uint8Array(parts);+ }++ function stubBitmapPipeline() {+ const closed: string[] = [];+ const draws: Array<[number, number]> = [];+ const bitmap = {+ width: 320,+ height: 240,+ close: () => void closed.push("closed"),+ };+ const calls: Array<Record<string, unknown>> = [];+ (globalThis as Record<string, unknown>).createImageBitmap = async (+ _blob: Blob,+ options?: ImageBitmapOptions,+ ) => {+ calls.push({ ...(options as object) });+ return bitmap;+ };+ const realCreateElement = document.createElement.bind(document);+ type CreateElement = (tagName: string, ...rest: unknown[]) => HTMLElement;+ vi.spyOn(document, "createElement").mockImplementation(((+ tagName: string,+ ...rest: unknown[]+ ) => {+ if (tagName !== "canvas") {+ return (realCreateElement as CreateElement)(tagName, ...rest);+ }+ return {+ width: 0,+ height: 0,+ getContext: () => ({+ fillStyle: "",+ fillRect: () => {},+ drawImage: (img: unknown, x: number, y: number) => {+ draws.push([x, y]);+ expect(img).toBe(bitmap);+ },+ }),+ toDataURL: (type?: string) => {+ expect(type).toBe("image/jpeg");+ return "data:image/jpeg;base64,stub";+ },+ };+ }) as typeof document.createElement);+ return { bitmap, closed, draws, calls };+ }++ afterEach(() => {+ vi.restoreAllMocks();+ delete (globalThis as Record<string, unknown>).createImageBitmap;+ });++ it("skips the decode when the header gives no dimensions", async () => {+ const { generateThumbnailForFile } =+ await import("@app/utils/thumbnailUtils");+ const { closed, draws, calls } = stubBitmapPipeline();+ const file = new File([pngBytes], "photo.png", { type: "image/png" });+ const thumb = await generateThumbnailForFile(file);+ // A width-only resize would let an extreme aspect ratio ask for an+ // arbitrarily tall bitmap, so this falls back to the data URL instead.+ expect(calls).toEqual([]);+ expect(draws).toEqual([]);+ expect(closed).toEqual([]);+ expect(thumb.startsWith("data:image/png")).toBe(true);+ });++ it("passes both dimensions when the header gives the source size", async () => {+ const { generateThumbnailForFile } =+ await import("@app/utils/thumbnailUtils");+ const { closed, calls } = stubBitmapPipeline();+ const file = fileWithHeader(pngHeader(400, 300));+ const thumb = await generateThumbnailForFile(file);+ expect(thumb).toBe("data:image/jpeg;base64,stub");+ expect(calls[0]).toEqual({+ resizeWidth: 320,+ resizeHeight: 240,+ resizeQuality: "high",+ imageOrientation: "from-image",+ });+ expect(closed).toEqual(["closed"]);+ });++ it("bounds the resize request for extreme-aspect images", async () => {+ const { generateThumbnailForFile } =+ await import("@app/utils/thumbnailUtils");+ const { calls } = stubBitmapPipeline();+ const file = fileWithHeader(pngHeader(1, 100000));+ await generateThumbnailForFile(file);+ expect(calls[0].resizeWidth).toBe(1);+ expect(calls[0].resizeHeight).toBe(320);+ });++ it("reads JPEG dimensions from the start-of-frame marker", async () => {+ const { generateThumbnailForFile } =+ await import("@app/utils/thumbnailUtils");+ const { calls } = stubBitmapPipeline();+ const file = fileWithHeader(buildJpeg(600, 300), "photo.jpg", "image/jpeg");+ await generateThumbnailForFile(file);+ expect(calls[0].resizeWidth).toBe(320);+ expect(calls[0].resizeHeight).toBe(160);+ });++ it("swaps axes for EXIF orientations that rotate the image", async () => {+ const { generateThumbnailForFile } =+ await import("@app/utils/thumbnailUtils");+ const { calls } = stubBitmapPipeline();+ const file = fileWithHeader(+ buildJpeg(600, 300, { orientation: 6 }),+ "photo.jpg",+ "image/jpeg",+ );+ await generateThumbnailForFile(file);+ expect(calls[0].resizeWidth).toBe(160);+ expect(calls[0].resizeHeight).toBe(320);+ });++ it("finds a JPEG start-of-frame behind a large metadata segment", async () => {+ const { generateThumbnailForFile } =+ await import("@app/utils/thumbnailUtils");+ const { calls } = stubBitmapPipeline();+ const file = fileWithHeader(+ buildJpeg(400, 300, { padding: 300 * 1024 }),+ "photo.jpg",+ "image/jpeg",+ );+ await generateThumbnailForFile(file);+ expect(calls[0].resizeWidth).toBe(320);+ expect(calls[0].resizeHeight).toBe(240);+ });++ it("falls back to the data URL when decode-at-size is unavailable", async () => {+ const { generateThumbnailForFile } =+ await import("@app/utils/thumbnailUtils");+ const file = new File([pngBytes], "photo.png", { type: "image/png" });+ const thumb = await generateThumbnailForFile(file);+ expect(thumb.startsWith("data:image/png;base64,")).toBe(true);+ });+});diff --git a/frontend/editor/src/core/utils/thumbnailUtils.ts b/frontend/editor/src/core/utils/thumbnailUtils.tsindex 003a0dfc89..de6d56d97b 100644--- a/frontend/editor/src/core/utils/thumbnailUtils.ts+++ b/frontend/editor/src/core/utils/thumbnailUtils.ts@@ -9,6 +9,7 @@ import {renderPdfiumPageDataUrl,readPdfiumPageMetadata,} from "@app/utils/pdfiumPageRender";+import { jpegExifOrientation } from "@app/utils/jpegOrientation";import { getDocumentBytes } from "@app/services/documentBytesCache";export interface ThumbnailWithMetadata {@@ -45,6 +46,17 @@ export const LARGE_PDF_PARSE_LIMIT = 100 * 1024 * 1024;* prefix is often enough to render a thumbnail without reading the file. */const LINEARIZED_PREFIX_BYTES = 2 * 1024 * 1024;+/** Longest side of an image thumbnail, in pixels (aspect preserved); the+ * hover preview renders at 150 CSS px, so this covers 2x displays. */+const IMAGE_THUMBNAIL_MAX_SIZE = 320;++/** Bytes read from the head of an image to locate its intrinsic size. */+const IMAGE_HEADER_PROBE_BYTES = 256 * 1024;++/** Extra bytes read when a JPEG's start-of-frame marker sits behind a large+ * metadata segment; the first probe covers the common case. */+const IMAGE_HEADER_PROBE_LIMIT = 4 * 1024 * 1024;+/** Window at each end of the file searched for an /Encrypt entry. */const ENCRYPT_PROBE_BYTES = 64 * 1024;@@ -251,6 +263,219 @@ async function generatePDFThumbnail(return result.thumbnail;}+/**+ * Read intrinsic pixel dimensions from an image header without decoding it.+ * Returns null for formats the probe does not recognise, so the caller keeps+ * the width-only resize request instead of failing.+ */+async function readImageDimensions(+ file: File,+): Promise<{ width: number; height: number } | null> {+ let bytes: Uint8Array;+ try {+ bytes = new Uint8Array(+ await file.slice(0, IMAGE_HEADER_PROBE_BYTES).arrayBuffer(),+ );+ } catch {+ return null;+ }+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);++ // PNG: IHDR is the first chunk; big-endian width/height at offsets 16/20.+ if (+ bytes.length >= 24 &&+ bytes[0] === 0x89 &&+ bytes[1] === 0x50 &&+ bytes[2] === 0x4e &&+ bytes[3] === 0x47+ ) {+ return { width: view.getUint32(16), height: view.getUint32(20) };+ }++ // GIF: logical screen descriptor; little-endian width/height at offsets 6/8.+ if (+ bytes.length >= 10 &&+ bytes[0] === 0x47 &&+ bytes[1] === 0x49 &&+ bytes[2] === 0x46+ ) {+ return { width: view.getUint16(6, true), height: view.getUint16(8, true) };+ }++ // BMP: BITMAPINFOHEADER; signed little-endian at 18/22, negative = top-down.+ if (bytes.length >= 26 && bytes[0] === 0x42 && bytes[1] === 0x4d) {+ return {+ width: Math.abs(view.getInt32(18, true)),+ height: Math.abs(view.getInt32(22, true)),+ };+ }++ // WebP: RIFF container, the chunk id at offset 12 identifies the encoding.+ if (+ bytes.length >= 30 &&+ bytes[0] === 0x52 &&+ bytes[1] === 0x49 &&+ bytes[2] === 0x46 &&+ bytes[3] === 0x46 &&+ bytes[8] === 0x57 &&+ bytes[9] === 0x45 &&+ bytes[10] === 0x42 &&+ bytes[11] === 0x50+ ) {+ const chunk = String.fromCharCode(+ bytes[12],+ bytes[13],+ bytes[14],+ bytes[15],+ );+ if (chunk === "VP8X") {+ return {+ width: 1 + (bytes[24] | (bytes[25] << 8) | (bytes[26] << 16)),+ height: 1 + (bytes[27] | (bytes[28] << 8) | (bytes[29] << 16)),+ };+ }+ if (chunk === "VP8 ") {+ return {+ width: view.getUint16(26, true) & 0x3fff,+ height: view.getUint16(28, true) & 0x3fff,+ };+ }+ if (chunk === "VP8L") {+ const bits = view.getUint32(21, true);+ return {+ width: (bits & 0x3fff) + 1,+ height: ((bits >> 14) & 0x3fff) + 1,+ };+ }+ return null;+ }++ // JPEG: walk the segment list until a start-of-frame marker carries the size.+ // A large EXIF/ICC segment can push that marker past the first probe, so the+ // window doubles until it is found or the cap is reached.+ if (bytes.length >= 4 && bytes[0] === 0xff && bytes[1] === 0xd8) {+ const limit = Math.min(file.size, IMAGE_HEADER_PROBE_LIMIT);+ for (let end = bytes.length; ; end = Math.min(end * 2, limit)) {+ const window =+ end === bytes.length+ ? bytes+ : new Uint8Array(await file.slice(0, end).arrayBuffer());+ const dimensions = readJpegDimensions(+ window,+ new DataView(window.buffer, window.byteOffset, window.byteLength),+ );+ if (dimensions) {+ // EXIF orientations 5-8 rotate the image, so the bitmap+ // createImageBitmap produces has the header's axes swapped.+ const orientation = jpegExifOrientation(window);+ return orientation >= 5 && orientation <= 8+ ? { width: dimensions.height, height: dimensions.width }+ : dimensions;+ }+ if (end >= limit) return null;+ }+ }++ return null;+}++/** Walk JPEG segments to the start-of-frame marker that carries the size. */+function readJpegDimensions(+ bytes: Uint8Array,+ view: DataView,+): { width: number; height: number } | null {+ let offset = 2;+ while (offset + 9 <= bytes.length) {+ if (bytes[offset] !== 0xff) return null;+ const marker = bytes[offset + 1];+ if (marker === 0xff) {+ offset += 1;+ continue;+ }+ // Standalone markers have no length field.+ if (marker === 0x01 || (marker >= 0xd0 && marker <= 0xd8)) {+ offset += 2;+ continue;+ }+ if (marker === 0xd9) return null;+ const length = view.getUint16(offset + 2);+ if (length < 2) return null;+ const isStartOfFrame =+ marker >= 0xc0 &&+ marker <= 0xcf &&+ marker !== 0xc4 &&+ marker !== 0xc8 &&+ marker !== 0xcc;+ if (isStartOfFrame) {+ return {+ height: view.getUint16(offset + 5),+ width: view.getUint16(offset + 7),+ };+ }+ offset += 2 + length;+ }+ return null;+}++/** Resize a known source into a thumbnail-sized box, longest side first. */+function thumbnailResizeOptions(source: { width: number; height: number }): {+ resizeWidth: number;+ resizeHeight: number;+} {+ const scale =+ IMAGE_THUMBNAIL_MAX_SIZE / Math.max(source.width, source.height);+ return {+ resizeWidth: Math.max(1, Math.round(source.width * scale)),+ resizeHeight: Math.max(1, Math.round(source.height * scale)),+ };+}++function paintThumbnail(+ ctx: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D,+ bitmap: ImageBitmap,+): void {+ ctx.fillStyle = "#ffffff";+ ctx.fillRect(0, 0, bitmap.width, bitmap.height);+ ctx.drawImage(bitmap, 0, 0);+}++function blobToDataUrl(blob: Blob): Promise<string> {+ return new Promise((resolve, reject) => {+ const reader = new FileReader();+ reader.onload = () => resolve(reader.result as string);+ reader.onerror = () => reject(reader.error);+ reader.readAsDataURL(blob);+ });+}++/** JPEG-encode a bitmap. OffscreenCanvas keeps the encode off the main thread+ * where the engine supports it; jsdom and older WebKit fall back to a DOM+ * canvas. */+async function encodeThumbnailJpeg(bitmap: ImageBitmap): Promise<string> {+ if (typeof OffscreenCanvas === "function") {+ const canvas = new OffscreenCanvas(bitmap.width, bitmap.height);+ const ctx = canvas.getContext("2d");+ if (!ctx) throw new Error("2d context unavailable");+ paintThumbnail(ctx, bitmap);+ // JPEG on purpose: the data URL is the thumbnail contract every consumer+ // and the DOM fallback below share, so the engine must not pick another+ // format here.+ const blob = await canvas.convertToBlob({+ type: "image/jpeg",+ quality: 0.8,+ });+ return blobToDataUrl(blob);+ }++ const canvas = document.createElement("canvas");+ canvas.width = bitmap.width;+ canvas.height = bitmap.height;+ const ctx = canvas.getContext("2d");+ if (!ctx) throw new Error("2d context unavailable");+ paintThumbnail(ctx, bitmap);+ return canvas.toDataURL("image/jpeg", 0.8);+}+/*** Generate thumbnail for any file type - always returns a thumbnail (placeholder if needed)*/@@ -260,14 +485,36 @@ export async function generateThumbnailForFile(file: File): Promise<string> {return "";}- // Handle image files - convert to data URL for persistence+ // Handle image files - decode once at tooltip size instead of full-res.+ // A phone photo decodes to ~48 MB RGBA plus an ~11 MB data URL string that+ // then lives in IndexedDB; the 320px JPEG below is ~30 KB and identical in+ // the 150px hover preview. Anything createImageBitmap cannot handle (SVG+ // without intrinsic size, exotic codecs) falls back to the data URL.if (file.type.startsWith("image/")) {- return new Promise((resolve, reject) => {- const reader = new FileReader();- reader.onload = () => resolve(reader.result as string);- reader.onerror = () => reject(reader.error);- reader.readAsDataURL(file);- });+ try {+ const source = await readImageDimensions(file);+ // Without a header ratio a width-only request would let an extreme+ // portrait ask for a 320 x tens-of-millions bitmap, so unknown sizes take+ // the data URL path below instead of decoding.+ if (!source) throw new Error("image dimensions unavailable");+ const bitmap = await createImageBitmap(file, {+ ...thumbnailResizeOptions(source),+ resizeQuality: "high",+ imageOrientation: "from-image",+ });+ try {+ return await encodeThumbnailJpeg(bitmap);+ } finally {+ bitmap.close();+ }+ } catch {+ return new Promise((resolve, reject) => {+ const reader = new FileReader();+ reader.onload = () => resolve(reader.result as string);+ reader.onerror = () => reject(reader.error);+ reader.readAsDataURL(file);+ });+ }}// Handle PDF files