@jimp/wasm-jpeg2000 0.0.0-stage → 2.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/OPENJPEG-LICENSE +39 -0
- package/README.md +115 -2
- package/dist/browser/codestream.d.ts +29 -0
- package/dist/browser/codestream.d.ts.map +1 -0
- package/dist/browser/codestream.js +129 -0
- package/dist/browser/codestream.js.map +1 -0
- package/dist/browser/index.d.ts +71 -0
- package/dist/browser/index.d.ts.map +1 -0
- package/dist/browser/index.js +216 -0
- package/dist/browser/index.js.map +1 -0
- package/dist/browser/load-wasm-browser.d.mts.map +1 -0
- package/dist/browser/load-wasm-browser.mjs.map +1 -0
- package/dist/browser/load-wasm.d.ts +6 -0
- package/dist/browser/load-wasm.js +17 -0
- package/dist/browser/openjpegwasm.wasm +0 -0
- package/dist/browser/package.json +3 -0
- package/dist/esm/codestream.d.ts +29 -0
- package/dist/esm/codestream.d.ts.map +1 -0
- package/dist/esm/codestream.js +129 -0
- package/dist/esm/codestream.js.map +1 -0
- package/dist/esm/index.d.ts +71 -0
- package/dist/esm/index.d.ts.map +1 -0
- package/dist/esm/index.js +216 -0
- package/dist/esm/index.js.map +1 -0
- package/dist/esm/load-wasm.d.ts +3 -0
- package/dist/esm/load-wasm.d.ts.map +1 -0
- package/dist/esm/load-wasm.js +9 -0
- package/dist/esm/load-wasm.js.map +1 -0
- package/dist/esm/package.json +3 -0
- package/package.json +76 -4
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAChC,OAAO,YAEN,MAAM,sCAAsC,CAAC;AAE9C,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,EAEL,oBAAoB,EACpB,QAAQ,GACT,MAAM,iBAAiB,CAAC;AACzB,OAAO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,MAAM,EAAE,CAAC,IAAI,EAAE,OAAO,GAA0B,EAAE,EAAE,EAAE,CACpD,MAAM,CAAC,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,KAAK,CAAC;KACP,CAAC;AAClC,CAAC;AAED,kEAAkE;AAClE,MAAM,UAAU,GAAG,CAAC,EAAE,IAAI,EAAE,GAA0B,EAAE;IACtD,OAAO;QACL,IAAI,EAAE,WAAW;QACjB,QAAQ,EAAE,KAAK;QACf,MAAM,EAAE,CAAC,MAAM,EAAE,OAAO,GAA6B,EAAE,EAAE,EAAE,CACzD,MAAM,CAAC,MAAM,EAAE,OAAO,EAAE,IAAI,EAAE,KAAK,CAAC;QACtC,MAAM,EAAE,CAAC,IAAI,EAAE,OAAO,GAA0B,EAAE,EAAE,EAAE,CACpD,MAAM,CAAC,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,KAAK,CAAC;KACP,CAAC;AAClC,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,GAAG,CAAC,EAAE,IAAI,EAAE,GAA0B,EAAE;IACtD,OAAO;QACL,IAAI,EAAE,WAAW;QACjB,QAAQ,EAAE,KAAK;QACf,MAAM,EAAE,KAAK,IAAI,EAAE;YACjB,MAAM,IAAI,KAAK,CACb,+FAA+F,CAChG,CAAC;QACJ,CAAC;QACD,MAAM,EAAE,CAAC,IAAI,EAAE,OAAO,GAA0B,EAAE,EAAE,EAAE,CACpD,MAAM,CAAC,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,KAAK,CAAC;KACP,CAAC;AAClC,CAAC","sourcesContent":["import { Buffer } from \"buffer\";\nimport OpenJPEGWASM, {\n OpenJpegModule,\n} from \"@cornerstonejs/codec-openjpeg/wasmjs\";\nimport { Bitmap, Format } from \"@jimp/types\";\nimport { z } from \"zod\";\n\nimport {\n CodestreamHeader,\n readCodestreamHeader,\n writeJp2,\n} from \"./codestream.js\";\nimport { loadWasm } from \"./load-wasm.js\";\n\nconst Jpeg2000OptionsSchema = z\n .object({\n /**\n * How many times smaller than the uncompressed RGB pixels the file\n * should be, e.g. 20 for 20:1. 1 is lossless: it uses the reversible\n * wavelet and keeps every pixel exactly. Above 1, the irreversible\n * wavelet is used and quality drops as the ratio rises.\n * @default 1\n */\n compressionRatio: z.number().optional().default(1),\n /**\n * Wavelet decomposition levels. Each level is a resolution, half the\n * size of the one above, that decoders can `reduce` to without decoding\n * the full image. Limited to what the image's size allows.\n * @default 5\n */\n decompositions: z.number().optional().default(5),\n })\n .strict();\n\ntype Jpeg2000Options = z.infer<typeof Jpeg2000OptionsSchema>;\n\nexport interface DecodeJpeg2000Options {\n /**\n * Decode at a lower resolution. Each step halves the width and height\n * (rounding up), down to the image's smallest resolution. It's much faster\n * and uses less memory than decoding a huge image in full and resizing it.\n * @default 0\n */\n reduce?: number;\n /**\n * Decode only the first quality layers of an image encoded with several,\n * for a quick lower quality preview. 0 decodes all of them.\n * @default 0\n */\n layers?: number;\n /**\n * Largest image, in megapixels, that will be decoded, after `reduce`.\n * Larger images are rejected before any pixel memory is allocated.\n * @default 100\n */\n maxResolutionInMP?: number;\n}\n\nexport interface Jpeg2000Wasm {\n /** The compiled `@cornerstonejs/codec-openjpeg/wasm` */\n codec?: WebAssembly.Module;\n}\n\nexport interface Jpeg2000FormatOptions {\n /**\n * A precompiled wasm module for runtimes or bundlers where the plugin\n * can't load the codec's wasm itself.\n * The codec is initialized once, by the first instance that encodes or\n * decodes, so pass the same module to every instance.\n */\n wasm?: Jpeg2000Wasm;\n}\n\nlet codecReady: Promise<OpenJpegModule> | undefined;\n/** What OpenJPEG printed during the current encode or decode */\nlet messages: string[] = [];\n\nfunction initCodecOnce(module?: WebAssembly.Module) {\n codecReady ??= Promise.resolve(module ?? loadWasm()).then(\n (wasm) =>\n new Promise<OpenJpegModule>((resolve, reject) => {\n OpenJPEGWASM({\n // OpenJPEG logs its errors, warnings and progress\n print: (message) => messages.push(message),\n printErr: (message) => messages.push(message),\n instantiateWasm(imports, receiveInstance) {\n WebAssembly.instantiate(wasm, imports).then(\n (instance) => receiveInstance(instance, wasm),\n reject,\n );\n return {};\n },\n }).then(resolve, reject);\n }),\n );\n return codecReady;\n}\n\n/** The errors OpenJPEG printed, to explain why it failed */\nfunction withErrors(message: string) {\n const errors = messages\n .filter((line) => line.startsWith(\"[ERROR]\"))\n .map((line) => line.slice(\"[ERROR]\".length).trim());\n\n return new Error(\n errors.length ? `${message}: ${errors.join(\". \")}` : message,\n );\n}\n\n/** Rejects layouts the codec can't decode, or decodes to the wrong pixels */\nfunction validate({ components }: CodestreamHeader) {\n const [first, cb, cr] = components;\n\n if (\n !first ||\n components.some(\n ({ precision, signed }) =>\n precision !== first.precision || signed !== first.signed,\n )\n ) {\n throw new Error(\n \"Unsupported JPEG 2000 image: every component must have the same bit depth\",\n );\n }\n\n if (first.precision > 16) {\n throw new Error(\n `Unsupported JPEG 2000 bit depth ${first.precision}: up to 16 bits per sample can be decoded`,\n );\n }\n\n // The codec clamps them to 0-255, losing the negative half\n if (components.length === 1 && first.signed && first.precision <= 8) {\n throw new Error(\n \"Unsupported JPEG 2000 image: signed grayscale samples of 8 bits or fewer\",\n );\n }\n\n const subsampled = components.some(({ dx, dy }) => dx !== 1 || dy !== 1);\n // The codec converts YCbCr with 4:2:0 or 4:2:2 chroma to RGB\n const subsampledChroma =\n components.length === 3 &&\n first.dx === 1 &&\n first.dy === 1 &&\n cb!.dx === 2 &&\n cr!.dx === 2 &&\n cb!.dy === cr!.dy &&\n cb!.dy <= 2;\n\n if (subsampled && !subsampledChroma) {\n throw new Error(\n \"Unsupported JPEG 2000 subsampling: only the chroma of YCbCr 4:2:0 and 4:2:2 images can be subsampled\",\n );\n }\n}\n\n/** Converts the codec's interleaved gray or RGB samples to 8-bit RGBA */\nfunction toRgba(\n samples: Uint8Array,\n pixels: number,\n components: number,\n bitsPerSample: number,\n signed: boolean,\n) {\n // Copy the samples out of wasm memory, which also aligns 16-bit ones\n const copy = samples.slice();\n const values =\n bitsPerSample > 8\n ? signed\n ? new Int16Array(copy.buffer)\n : new Uint16Array(copy.buffer)\n : signed\n ? new Int8Array(copy.buffer)\n : copy;\n const offset = signed ? 2 ** (bitsPerSample - 1) : 0;\n const scale = 255 / (2 ** bitsPerSample - 1);\n // Rounds and clamps to 0-255\n const rgba = new Uint8ClampedArray(pixels * 4);\n\n for (let i = 0; i < pixels; i++) {\n for (let c = 0; c < 3; c++) {\n const value = values[i * components + (components === 1 ? 0 : c)]!;\n rgba[i * 4 + c] = (value + offset) * scale;\n }\n\n rgba[i * 4 + 3] = 255;\n }\n\n return Buffer.from(rgba.buffer);\n}\n\nasync function decode(\n data: Buffer,\n { reduce = 0, layers = 0, maxResolutionInMP = 100 }: DecodeJpeg2000Options,\n wasm?: WebAssembly.Module,\n): Promise<Bitmap> {\n const header = readCodestreamHeader(data);\n\n if (!header) {\n throw new Error(\n \"Invalid JPEG 2000 image: the codestream's main header can't be read\",\n );\n }\n\n validate(header);\n\n const level = Math.min(\n Math.max(0, Math.floor(reduce)),\n header.decompositions,\n );\n const width = Math.ceil(header.width / 2 ** level);\n const height = Math.ceil(header.height / 2 ** level);\n\n if (width * height > maxResolutionInMP * 1_000_000) {\n throw new Error(\n `JPEG 2000 dimensions ${width}x${height} exceed the maximum resolution of ${maxResolutionInMP} megapixels. Use the reduce option to decode it at a lower resolution.`,\n );\n }\n\n const codec = await initCodecOnce(wasm);\n const decoder = new codec.J2KDecoder();\n\n messages = [];\n\n try {\n try {\n decoder.getEncodedBuffer(data.length).set(data);\n decoder.decodeSubResolution(level, Math.max(0, Math.floor(layers)));\n } catch {\n // C++ exceptions reach JS as pointers, without their message\n const count = header.components.length;\n\n throw count === 1 || count === 3\n ? withErrors(\"Failed to decode the JPEG 2000 image\")\n : new Error(\n `Unsupported JPEG 2000 image with ${count} components: only grayscale and RGB images can be decoded, without alpha`,\n );\n }\n\n const frame = decoder.getFrameInfo();\n // Without an exception, OpenJPEG's own failures leave the frame empty\n if (!frame.width) {\n throw withErrors(\"Failed to decode the JPEG 2000 image\");\n }\n\n const size = decoder.calculateSizeAtDecompositionLevel(level);\n\n return {\n data: toRgba(\n decoder.getDecodedBuffer(),\n size.width * size.height,\n frame.componentCount,\n frame.bitsPerSample,\n frame.isSigned,\n ),\n width: size.width,\n height: size.height,\n };\n } finally {\n decoder.delete();\n }\n}\n\n/** Encodes the bitmap's RGB, without alpha, as a codestream */\nasync function encode(\n { width, height, data }: Bitmap,\n options: Partial<Jpeg2000Options>,\n wasm?: WebAssembly.Module,\n) {\n const { compressionRatio, decompositions } =\n Jpeg2000OptionsSchema.parse(options);\n const codec = await initCodecOnce(wasm);\n const encoder = new codec.J2KEncoder();\n\n messages = [];\n\n try {\n const pixels = encoder.getDecodedBuffer({\n width,\n height,\n bitsPerSample: 8,\n componentCount: 3,\n isSigned: false,\n });\n\n for (let i = 0; i < width * height; i++) {\n pixels[i * 3] = data[i * 4]!;\n pixels[i * 3 + 1] = data[i * 4 + 1]!;\n pixels[i * 3 + 2] = data[i * 4 + 2]!;\n }\n\n // The smallest resolution needs at least a pixel in each direction\n encoder.setDecompositions(\n Math.min(\n Math.max(0, Math.round(decompositions)),\n Math.floor(Math.log2(Math.min(width, height))),\n ),\n );\n\n if (compressionRatio > 1) {\n encoder.setQuality(false, 1);\n encoder.setCompressionRatio(0, compressionRatio);\n }\n\n try {\n encoder.encode();\n } catch {\n throw withErrors(\"Failed to encode the JPEG 2000 image\");\n }\n\n // Copied out of wasm memory\n return Buffer.from(encoder.getEncodedBuffer());\n } finally {\n encoder.delete();\n }\n}\n\n/**\n * JP2 files, the usual JPEG 2000 container (.jp2).\n * Images are written as 8-bit sRGB without alpha.\n */\nexport default function jpeg2000({ wasm }: Jpeg2000FormatOptions = {}) {\n return {\n mime: \"image/jp2\",\n hasAlpha: false,\n encode: async (bitmap, options: Partial<Jpeg2000Options> = {}) =>\n writeJp2(\n await encode(bitmap, options, wasm?.codec),\n bitmap.width,\n bitmap.height,\n ),\n decode: (data, options: DecodeJpeg2000Options = {}) =>\n decode(data, options, wasm?.codec),\n } satisfies Format<\"image/jp2\">;\n}\n\n/** Raw JPEG 2000 codestreams, without a container (.j2c, .j2k) */\nexport function j2c({ wasm }: Jpeg2000FormatOptions = {}) {\n return {\n mime: \"image/j2c\",\n hasAlpha: false,\n encode: (bitmap, options: Partial<Jpeg2000Options> = {}) =>\n encode(bitmap, options, wasm?.codec),\n decode: (data, options: DecodeJpeg2000Options = {}) =>\n decode(data, options, wasm?.codec),\n } satisfies Format<\"image/j2c\">;\n}\n\n/**\n * JPX files (.jpx, .jpf), the extended JPEG 2000 container. Only decoding is\n * supported, of the codestreams that only use JPEG 2000 part 1 features.\n */\nexport function jpx({ wasm }: Jpeg2000FormatOptions = {}) {\n return {\n mime: \"image/jpx\",\n hasAlpha: false,\n encode: async () => {\n throw new Error(\n \"Writing JPX isn't supported. Write a JP2 (image/jp2) instead, which JPX readers can read too.\",\n );\n },\n decode: (data, options: DecodeJpeg2000Options = {}) =>\n decode(data, options, wasm?.codec),\n } satisfies Format<\"image/jpx\">;\n}\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"load-wasm-browser.d.mts","sourceRoot":"","sources":["../../src/load-wasm-browser.mts"],"names":[],"mappings":"AAGA;;;GAGG;AACH,wBAAsB,QAAQ,gCAa7B"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"load-wasm-browser.mjs","sourceRoot":"","sources":["../../src/load-wasm-browser.mts"],"names":[],"mappings":"AAAA,2CAA2C;AAC3C,MAAM,UAAU,GAAG,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;AAE5C;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,QAAQ;IAC5B,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,qBAAqB,EAAE,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC;IAC5D,MAAM,QAAQ,GAAG,MAAM,KAAK,CAAC,GAAG,CAAC,CAAC;IAClC,MAAM,IAAI,GAAG,IAAI,UAAU,CAAC,MAAM,QAAQ,CAAC,WAAW,EAAE,CAAC,CAAC;IAE1D,qDAAqD;IACrD,IAAI,CAAC,QAAQ,CAAC,EAAE,IAAI,UAAU,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,CAAC,EAAE,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,IAAI,CAAC,EAAE,CAAC;QACnE,MAAM,IAAI,KAAK,CACb,kDAAkD,GAAG,kLAAkL,CACxO,CAAC;IACJ,CAAC;IAED,OAAO,WAAW,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;AACnC,CAAC","sourcesContent":["/** The first bytes of every wasm module */\nconst WASM_MAGIC = [0x00, 0x61, 0x73, 0x6d];\n\n/**\n * The build copies the codec's wasm next to this file. Bundlers like Vite,\n * webpack 5 and Rollup emit it as an asset from the `new URL`.\n */\nexport async function loadWasm() {\n const url = new URL(\"./openjpegwasm.wasm\", import.meta.url);\n const response = await fetch(url);\n const wasm = new Uint8Array(await response.arrayBuffer());\n\n // A dev server can answer with its HTML page instead\n if (!response.ok || WASM_MAGIC.some((byte, i) => wasm[i] !== byte)) {\n throw new Error(\n `Failed to load the JPEG 2000 codec's wasm from ${url}. If your bundler moves @jimp/wasm-jpeg2000 away from it, like Vite 7's dependency pre-bundling, see the package's README, or pass the compiled module as the wasm.codec option.`,\n );\n }\n\n return WebAssembly.compile(wasm);\n}\n"]}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/** The first bytes of every wasm module */
|
|
2
|
+
const WASM_MAGIC = [0x00, 0x61, 0x73, 0x6d];
|
|
3
|
+
/**
|
|
4
|
+
* The build copies the codec's wasm next to this file. Bundlers like Vite,
|
|
5
|
+
* webpack 5 and Rollup emit it as an asset from the `new URL`.
|
|
6
|
+
*/
|
|
7
|
+
export async function loadWasm() {
|
|
8
|
+
const url = new URL("./openjpegwasm.wasm", import.meta.url);
|
|
9
|
+
const response = await fetch(url);
|
|
10
|
+
const wasm = new Uint8Array(await response.arrayBuffer());
|
|
11
|
+
// A dev server can answer with its HTML page instead
|
|
12
|
+
if (!response.ok || WASM_MAGIC.some((byte, i) => wasm[i] !== byte)) {
|
|
13
|
+
throw new Error(`Failed to load the JPEG 2000 codec's wasm from ${url}. If your bundler moves @jimp/wasm-jpeg2000 away from it, like Vite 7's dependency pre-bundling, see the package's README, or pass the compiled module as the wasm.codec option.`);
|
|
14
|
+
}
|
|
15
|
+
return WebAssembly.compile(wasm);
|
|
16
|
+
}
|
|
17
|
+
//# sourceMappingURL=load-wasm-browser.mjs.map
|
|
Binary file
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { Buffer } from "buffer";
|
|
2
|
+
export interface Component {
|
|
3
|
+
/** Bits per sample */
|
|
4
|
+
precision: number;
|
|
5
|
+
signed: boolean;
|
|
6
|
+
/** Horizontal subsampling */
|
|
7
|
+
dx: number;
|
|
8
|
+
/** Vertical subsampling */
|
|
9
|
+
dy: number;
|
|
10
|
+
}
|
|
11
|
+
export interface CodestreamHeader {
|
|
12
|
+
width: number;
|
|
13
|
+
height: number;
|
|
14
|
+
components: Component[];
|
|
15
|
+
/** Wavelet decomposition levels, the most a decoder can reduce by */
|
|
16
|
+
decompositions: number;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Reads the image size, components and decomposition levels from the main
|
|
20
|
+
* header of the codestream. Returns undefined if it can't be read.
|
|
21
|
+
*/
|
|
22
|
+
export declare function readCodestreamHeader(data: Buffer): CodestreamHeader | undefined;
|
|
23
|
+
/**
|
|
24
|
+
* Wraps an 8-bit RGB codestream in the boxes of a JP2 file: the signature,
|
|
25
|
+
* file type, JP2 header (image header and sRGB colour specification) and
|
|
26
|
+
* codestream boxes.
|
|
27
|
+
*/
|
|
28
|
+
export declare function writeJp2(codestream: Buffer, width: number, height: number): Buffer<ArrayBuffer>;
|
|
29
|
+
//# sourceMappingURL=codestream.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"codestream.d.ts","sourceRoot":"","sources":["../../src/codestream.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAgBhC,MAAM,WAAW,SAAS;IACxB,sBAAsB;IACtB,SAAS,EAAE,MAAM,CAAC;IAClB,MAAM,EAAE,OAAO,CAAC;IAChB,6BAA6B;IAC7B,EAAE,EAAE,MAAM,CAAC;IACX,2BAA2B;IAC3B,EAAE,EAAE,MAAM,CAAC;CACZ;AAED,MAAM,WAAW,gBAAgB;IAC/B,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;IACf,UAAU,EAAE,SAAS,EAAE,CAAC;IACxB,qEAAqE;IACrE,cAAc,EAAE,MAAM,CAAC;CACxB;AAyCD;;;GAGG;AACH,wBAAgB,oBAAoB,CAClC,IAAI,EAAE,MAAM,GACX,gBAAgB,GAAG,SAAS,CA0D9B;AAYD;;;;GAIG;AACH,wBAAgB,QAAQ,CAAC,UAAU,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,uBAwBzE"}
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import { Buffer } from "buffer";
|
|
2
|
+
/** The signature box JP2 and JPX files start with */
|
|
3
|
+
const JP2_SIGNATURE = Buffer.from([
|
|
4
|
+
0x00, 0x00, 0x00, 0x0c, 0x6a, 0x50, 0x20, 0x20, 0x0d, 0x0a, 0x87, 0x0a,
|
|
5
|
+
]);
|
|
6
|
+
/** Codestream markers */
|
|
7
|
+
const SOC = 0xff4f;
|
|
8
|
+
const SIZ = 0xff51;
|
|
9
|
+
const COD = 0xff52;
|
|
10
|
+
const SOT = 0xff90;
|
|
11
|
+
/** Enumerated colour spaces of the JP2 colour specification box */
|
|
12
|
+
const SRGB = 16;
|
|
13
|
+
/** Finds the codestream of a JP2 or JPX file, or a raw codestream */
|
|
14
|
+
function findCodestream(data) {
|
|
15
|
+
if (data.readUInt16BE(0) === SOC) {
|
|
16
|
+
return data;
|
|
17
|
+
}
|
|
18
|
+
if (!data.subarray(0, 12).equals(JP2_SIGNATURE)) {
|
|
19
|
+
return undefined;
|
|
20
|
+
}
|
|
21
|
+
let offset = 0;
|
|
22
|
+
while (offset + 8 <= data.length) {
|
|
23
|
+
let length = data.readUInt32BE(offset);
|
|
24
|
+
let headerLength = 8;
|
|
25
|
+
if (length === 1 && offset + 16 <= data.length) {
|
|
26
|
+
// A 64-bit length follows the type
|
|
27
|
+
length = Number(data.readBigUInt64BE(offset + 8));
|
|
28
|
+
headerLength = 16;
|
|
29
|
+
}
|
|
30
|
+
else if (length === 0) {
|
|
31
|
+
// The last box can run to the end of the file
|
|
32
|
+
length = data.length - offset;
|
|
33
|
+
}
|
|
34
|
+
if (length < headerLength) {
|
|
35
|
+
return undefined;
|
|
36
|
+
}
|
|
37
|
+
if (data.toString("latin1", offset + 4, offset + 8) === "jp2c") {
|
|
38
|
+
return data.subarray(offset + headerLength, offset + length);
|
|
39
|
+
}
|
|
40
|
+
offset += length;
|
|
41
|
+
}
|
|
42
|
+
return undefined;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Reads the image size, components and decomposition levels from the main
|
|
46
|
+
* header of the codestream. Returns undefined if it can't be read.
|
|
47
|
+
*/
|
|
48
|
+
export function readCodestreamHeader(data) {
|
|
49
|
+
try {
|
|
50
|
+
const codestream = findCodestream(data);
|
|
51
|
+
if (!codestream) {
|
|
52
|
+
return undefined;
|
|
53
|
+
}
|
|
54
|
+
let header = {};
|
|
55
|
+
// Skip SOC. Each marker segment is the marker, then its length including
|
|
56
|
+
// the length's 2 bytes.
|
|
57
|
+
let offset = 2;
|
|
58
|
+
while (offset + 4 <= codestream.length) {
|
|
59
|
+
const marker = codestream.readUInt16BE(offset);
|
|
60
|
+
if (marker === SOT) {
|
|
61
|
+
break;
|
|
62
|
+
}
|
|
63
|
+
if (marker === SIZ) {
|
|
64
|
+
const width = codestream.readUInt32BE(offset + 6) -
|
|
65
|
+
codestream.readUInt32BE(offset + 14);
|
|
66
|
+
const height = codestream.readUInt32BE(offset + 10) -
|
|
67
|
+
codestream.readUInt32BE(offset + 18);
|
|
68
|
+
const count = codestream.readUInt16BE(offset + 38);
|
|
69
|
+
const components = [];
|
|
70
|
+
for (let i = 0; i < count; i++) {
|
|
71
|
+
const ssiz = codestream[offset + 40 + i * 3];
|
|
72
|
+
components.push({
|
|
73
|
+
precision: (ssiz & 0x7f) + 1,
|
|
74
|
+
signed: (ssiz & 0x80) !== 0,
|
|
75
|
+
dx: codestream[offset + 41 + i * 3],
|
|
76
|
+
dy: codestream[offset + 42 + i * 3],
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
header = { ...header, width, height, components };
|
|
80
|
+
}
|
|
81
|
+
else if (marker === COD) {
|
|
82
|
+
// After Scod, the progression order, layer count and MCT
|
|
83
|
+
header.decompositions = codestream[offset + 9];
|
|
84
|
+
}
|
|
85
|
+
offset += 2 + codestream.readUInt16BE(offset + 2);
|
|
86
|
+
}
|
|
87
|
+
const { width, height, components, decompositions } = header;
|
|
88
|
+
return width && height && components && decompositions !== undefined
|
|
89
|
+
? { width, height, components, decompositions }
|
|
90
|
+
: undefined;
|
|
91
|
+
}
|
|
92
|
+
catch {
|
|
93
|
+
return undefined;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
function box(type, ...contents) {
|
|
97
|
+
const data = Buffer.concat(contents);
|
|
98
|
+
const header = Buffer.alloc(8);
|
|
99
|
+
header.writeUInt32BE(data.length + 8, 0);
|
|
100
|
+
header.write(type, 4, "latin1");
|
|
101
|
+
return Buffer.concat([header, data]);
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Wraps an 8-bit RGB codestream in the boxes of a JP2 file: the signature,
|
|
105
|
+
* file type, JP2 header (image header and sRGB colour specification) and
|
|
106
|
+
* codestream boxes.
|
|
107
|
+
*/
|
|
108
|
+
export function writeJp2(codestream, width, height) {
|
|
109
|
+
const brand = Buffer.from("jp2 \0\0\0\0jp2 ", "latin1");
|
|
110
|
+
const ihdr = Buffer.alloc(14);
|
|
111
|
+
ihdr.writeUInt32BE(height, 0);
|
|
112
|
+
ihdr.writeUInt32BE(width, 4);
|
|
113
|
+
ihdr.writeUInt16BE(3, 8);
|
|
114
|
+
// 8 bits per component, stored minus one
|
|
115
|
+
ihdr[10] = 7;
|
|
116
|
+
// Compressed with JPEG 2000
|
|
117
|
+
ihdr[11] = 7;
|
|
118
|
+
const colr = Buffer.alloc(7);
|
|
119
|
+
// Enumerated colour space
|
|
120
|
+
colr[0] = 1;
|
|
121
|
+
colr.writeUInt32BE(SRGB, 3);
|
|
122
|
+
return Buffer.concat([
|
|
123
|
+
JP2_SIGNATURE,
|
|
124
|
+
box("ftyp", brand),
|
|
125
|
+
box("jp2h", box("ihdr", ihdr), box("colr", colr)),
|
|
126
|
+
box("jp2c", codestream),
|
|
127
|
+
]);
|
|
128
|
+
}
|
|
129
|
+
//# sourceMappingURL=codestream.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"codestream.js","sourceRoot":"","sources":["../../src/codestream.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAEhC,qDAAqD;AACrD,MAAM,aAAa,GAAG,MAAM,CAAC,IAAI,CAAC;IAChC,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI;CACvE,CAAC,CAAC;AAEH,yBAAyB;AACzB,MAAM,GAAG,GAAG,MAAM,CAAC;AACnB,MAAM,GAAG,GAAG,MAAM,CAAC;AACnB,MAAM,GAAG,GAAG,MAAM,CAAC;AACnB,MAAM,GAAG,GAAG,MAAM,CAAC;AAEnB,mEAAmE;AACnE,MAAM,IAAI,GAAG,EAAE,CAAC;AAoBhB,qEAAqE;AACrE,SAAS,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x0a,\n]);\n\n/** Codestream markers */\nconst SOC = 0xff4f;\nconst SIZ = 0xff51;\nconst COD = 0xff52;\nconst SOT = 0xff90;\n\n/** Enumerated colour spaces of the JP2 colour specification box */\nconst SRGB = 16;\n\nexport interface Component {\n /** Bits per sample */\n precision: number;\n signed: boolean;\n /** Horizontal subsampling */\n dx: number;\n /** Vertical subsampling */\n dy: number;\n}\n\nexport interface CodestreamHeader {\n width: number;\n height: number;\n components: Component[];\n /** Wavelet decomposition levels, the most a decoder can reduce by */\n decompositions: number;\n}\n\n/** Finds the codestream of a JP2 or JPX file, or a raw codestream */\nfunction findCodestream(data: Buffer) {\n if (data.readUInt16BE(0) === SOC) {\n return data;\n }\n\n if (!data.subarray(0, 12).equals(JP2_SIGNATURE)) {\n return undefined;\n }\n\n let offset = 0;\n\n while (offset + 8 <= data.length) {\n let length = data.readUInt32BE(offset);\n let headerLength = 8;\n\n if (length === 1 && offset + 16 <= data.length) {\n // A 64-bit length follows the type\n length = Number(data.readBigUInt64BE(offset + 8));\n headerLength = 16;\n } else if (length === 0) {\n // The last box can run to the end of the file\n length = data.length - offset;\n }\n\n if (length < headerLength) {\n return undefined;\n }\n\n if (data.toString(\"latin1\", offset + 4, offset + 8) === \"jp2c\") {\n return data.subarray(offset + headerLength, offset + length);\n }\n\n offset += length;\n }\n\n return undefined;\n}\n\n/**\n * Reads the image size, components and decomposition levels from the main\n * header of the codestream. Returns undefined if it can't be read.\n */\nexport function readCodestreamHeader(\n data: Buffer,\n): CodestreamHeader | undefined {\n try {\n const codestream = findCodestream(data);\n\n if (!codestream) {\n return undefined;\n }\n\n let header: Partial<CodestreamHeader> = {};\n // Skip SOC. Each marker segment is the marker, then its length including\n // the length's 2 bytes.\n let offset = 2;\n\n while (offset + 4 <= codestream.length) {\n const marker = codestream.readUInt16BE(offset);\n\n if (marker === SOT) {\n break;\n }\n\n if (marker === SIZ) {\n const width =\n codestream.readUInt32BE(offset + 6) -\n codestream.readUInt32BE(offset + 14);\n const height =\n codestream.readUInt32BE(offset + 10) -\n codestream.readUInt32BE(offset + 18);\n const count = codestream.readUInt16BE(offset + 38);\n const components: Component[] = [];\n\n for (let i = 0; i < count; i++) {\n const ssiz = codestream[offset + 40 + i * 3]!;\n\n components.push({\n precision: (ssiz & 0x7f) + 1,\n signed: (ssiz & 0x80) !== 0,\n dx: codestream[offset + 41 + i * 3]!,\n dy: codestream[offset + 42 + i * 3]!,\n });\n }\n\n header = { ...header, width, height, components };\n } else if (marker === COD) {\n // After Scod, the progression order, layer count and MCT\n header.decompositions = codestream[offset + 9];\n }\n\n offset += 2 + codestream.readUInt16BE(offset + 2);\n }\n\n const { width, height, components, decompositions } = header;\n\n return width && height && components && decompositions !== undefined\n ? { width, height, components, decompositions }\n : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction box(type: string, ...contents: Buffer[]) {\n const data = Buffer.concat(contents);\n const header = Buffer.alloc(8);\n\n header.writeUInt32BE(data.length + 8, 0);\n header.write(type, 4, \"latin1\");\n\n return Buffer.concat([header, data]);\n}\n\n/**\n * Wraps an 8-bit RGB codestream in the boxes of a JP2 file: the signature,\n * file type, JP2 header (image header and sRGB colour specification) and\n * codestream boxes.\n */\nexport function writeJp2(codestream: Buffer, width: number, height: number) {\n const brand = Buffer.from(\"jp2 \\0\\0\\0\\0jp2 \", \"latin1\");\n const ihdr = Buffer.alloc(14);\n\n ihdr.writeUInt32BE(height, 0);\n ihdr.writeUInt32BE(width, 4);\n ihdr.writeUInt16BE(3, 8);\n // 8 bits per component, stored minus one\n ihdr[10] = 7;\n // Compressed with JPEG 2000\n ihdr[11] = 7;\n\n const colr = Buffer.alloc(7);\n\n // Enumerated colour space\n colr[0] = 1;\n colr.writeUInt32BE(SRGB, 3);\n\n return Buffer.concat([\n JP2_SIGNATURE,\n box(\"ftyp\", brand),\n box(\"jp2h\", box(\"ihdr\", ihdr), box(\"colr\", colr)),\n box(\"jp2c\", codestream),\n ]);\n}\n"]}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { Buffer } from "buffer";
|
|
2
|
+
import { Bitmap } from "@jimp/types";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
declare const Jpeg2000OptionsSchema: z.ZodObject<{
|
|
5
|
+
compressionRatio: z.ZodDefault<z.ZodOptional<z.ZodNumber>>;
|
|
6
|
+
decompositions: z.ZodDefault<z.ZodOptional<z.ZodNumber>>;
|
|
7
|
+
}, z.core.$strict>;
|
|
8
|
+
type Jpeg2000Options = z.infer<typeof Jpeg2000OptionsSchema>;
|
|
9
|
+
export interface DecodeJpeg2000Options {
|
|
10
|
+
/**
|
|
11
|
+
* Decode at a lower resolution. Each step halves the width and height
|
|
12
|
+
* (rounding up), down to the image's smallest resolution. It's much faster
|
|
13
|
+
* and uses less memory than decoding a huge image in full and resizing it.
|
|
14
|
+
* @default 0
|
|
15
|
+
*/
|
|
16
|
+
reduce?: number;
|
|
17
|
+
/**
|
|
18
|
+
* Decode only the first quality layers of an image encoded with several,
|
|
19
|
+
* for a quick lower quality preview. 0 decodes all of them.
|
|
20
|
+
* @default 0
|
|
21
|
+
*/
|
|
22
|
+
layers?: number;
|
|
23
|
+
/**
|
|
24
|
+
* Largest image, in megapixels, that will be decoded, after `reduce`.
|
|
25
|
+
* Larger images are rejected before any pixel memory is allocated.
|
|
26
|
+
* @default 100
|
|
27
|
+
*/
|
|
28
|
+
maxResolutionInMP?: number;
|
|
29
|
+
}
|
|
30
|
+
export interface Jpeg2000Wasm {
|
|
31
|
+
/** The compiled `@cornerstonejs/codec-openjpeg/wasm` */
|
|
32
|
+
codec?: WebAssembly.Module;
|
|
33
|
+
}
|
|
34
|
+
export interface Jpeg2000FormatOptions {
|
|
35
|
+
/**
|
|
36
|
+
* A precompiled wasm module for runtimes or bundlers where the plugin
|
|
37
|
+
* can't load the codec's wasm itself.
|
|
38
|
+
* The codec is initialized once, by the first instance that encodes or
|
|
39
|
+
* decodes, so pass the same module to every instance.
|
|
40
|
+
*/
|
|
41
|
+
wasm?: Jpeg2000Wasm;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* JP2 files, the usual JPEG 2000 container (.jp2).
|
|
45
|
+
* Images are written as 8-bit sRGB without alpha.
|
|
46
|
+
*/
|
|
47
|
+
export default function jpeg2000({ wasm }?: Jpeg2000FormatOptions): {
|
|
48
|
+
mime: "image/jp2";
|
|
49
|
+
hasAlpha: false;
|
|
50
|
+
encode: (bitmap: Bitmap, options?: Partial<Jpeg2000Options>) => Promise<Buffer<ArrayBuffer>>;
|
|
51
|
+
decode: (data: Buffer<ArrayBufferLike>, options?: DecodeJpeg2000Options) => Promise<Bitmap>;
|
|
52
|
+
};
|
|
53
|
+
/** Raw JPEG 2000 codestreams, without a container (.j2c, .j2k) */
|
|
54
|
+
export declare function j2c({ wasm }?: Jpeg2000FormatOptions): {
|
|
55
|
+
mime: "image/j2c";
|
|
56
|
+
hasAlpha: false;
|
|
57
|
+
encode: (bitmap: Bitmap, options?: Partial<Jpeg2000Options>) => Promise<Buffer<ArrayBuffer>>;
|
|
58
|
+
decode: (data: Buffer<ArrayBufferLike>, options?: DecodeJpeg2000Options) => Promise<Bitmap>;
|
|
59
|
+
};
|
|
60
|
+
/**
|
|
61
|
+
* JPX files (.jpx, .jpf), the extended JPEG 2000 container. Only decoding is
|
|
62
|
+
* supported, of the codestreams that only use JPEG 2000 part 1 features.
|
|
63
|
+
*/
|
|
64
|
+
export declare function jpx({ wasm }?: Jpeg2000FormatOptions): {
|
|
65
|
+
mime: "image/jpx";
|
|
66
|
+
hasAlpha: false;
|
|
67
|
+
encode: () => Promise<never>;
|
|
68
|
+
decode: (data: Buffer<ArrayBufferLike>, options?: DecodeJpeg2000Options) => Promise<Bitmap>;
|
|
69
|
+
};
|
|
70
|
+
export {};
|
|
71
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAIhC,OAAO,EAAE,MAAM,EAAU,MAAM,aAAa,CAAC;AAC7C,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AASxB,QAAA,MAAM,qBAAqB;;;kBAkBhB,CAAC;AAEZ,KAAK,eAAe,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,qBAAqB,CAAC,CAAC;AAE7D,MAAM,WAAW,qBAAqB;IACpC;;;;;OAKG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB;;;;OAIG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB;;;;OAIG;IACH,iBAAiB,CAAC,EAAE,MAAM,CAAC;CAC5B;AAED,MAAM,WAAW,YAAY;IAC3B,wDAAwD;IACxD,KAAK,CAAC,EAAE,WAAW,CAAC,MAAM,CAAC;CAC5B;AAED,MAAM,WAAW,qBAAqB;IACpC;;;;;OAKG;IACH,IAAI,CAAC,EAAE,YAAY,CAAC;CACrB;AAsPD;;;GAGG;AACH,MAAM,CAAC,OAAO,UAAU,QAAQ,CAAC,EAAE,IAAI,EAAE,GAAE,qBAA0B;;;uCAIjC,OAAO,CAAC,eAAe,CAAC;sDAMhC,qBAAqB;EAGhD;AAED,kEAAkE;AAClE,wBAAgB,GAAG,CAAC,EAAE,IAAI,EAAE,GAAE,qBAA0B;;;uCAI1B,OAAO,CAAC,eAAe,CAAC;sDAE1B,qBAAqB;EAGhD;AAED;;;GAGG;AACH,wBAAgB,GAAG,CAAC,EAAE,IAAI,EAAE,GAAE,qBAA0B;;;;sDAS5B,qBAAqB;EAGhD"}
|
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
import { Buffer } from "buffer";
|
|
2
|
+
import OpenJPEGWASM from "@cornerstonejs/codec-openjpeg/wasmjs";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
import { readCodestreamHeader, writeJp2, } from "./codestream.js";
|
|
5
|
+
import { loadWasm } from "./load-wasm.js";
|
|
6
|
+
const Jpeg2000OptionsSchema = z
|
|
7
|
+
.object({
|
|
8
|
+
/**
|
|
9
|
+
* How many times smaller than the uncompressed RGB pixels the file
|
|
10
|
+
* should be, e.g. 20 for 20:1. 1 is lossless: it uses the reversible
|
|
11
|
+
* wavelet and keeps every pixel exactly. Above 1, the irreversible
|
|
12
|
+
* wavelet is used and quality drops as the ratio rises.
|
|
13
|
+
* @default 1
|
|
14
|
+
*/
|
|
15
|
+
compressionRatio: z.number().optional().default(1),
|
|
16
|
+
/**
|
|
17
|
+
* Wavelet decomposition levels. Each level is a resolution, half the
|
|
18
|
+
* size of the one above, that decoders can `reduce` to without decoding
|
|
19
|
+
* the full image. Limited to what the image's size allows.
|
|
20
|
+
* @default 5
|
|
21
|
+
*/
|
|
22
|
+
decompositions: z.number().optional().default(5),
|
|
23
|
+
})
|
|
24
|
+
.strict();
|
|
25
|
+
let codecReady;
|
|
26
|
+
/** What OpenJPEG printed during the current encode or decode */
|
|
27
|
+
let messages = [];
|
|
28
|
+
function initCodecOnce(module) {
|
|
29
|
+
codecReady ??= Promise.resolve(module ?? loadWasm()).then((wasm) => new Promise((resolve, reject) => {
|
|
30
|
+
OpenJPEGWASM({
|
|
31
|
+
// OpenJPEG logs its errors, warnings and progress
|
|
32
|
+
print: (message) => messages.push(message),
|
|
33
|
+
printErr: (message) => messages.push(message),
|
|
34
|
+
instantiateWasm(imports, receiveInstance) {
|
|
35
|
+
WebAssembly.instantiate(wasm, imports).then((instance) => receiveInstance(instance, wasm), reject);
|
|
36
|
+
return {};
|
|
37
|
+
},
|
|
38
|
+
}).then(resolve, reject);
|
|
39
|
+
}));
|
|
40
|
+
return codecReady;
|
|
41
|
+
}
|
|
42
|
+
/** The errors OpenJPEG printed, to explain why it failed */
|
|
43
|
+
function withErrors(message) {
|
|
44
|
+
const errors = messages
|
|
45
|
+
.filter((line) => line.startsWith("[ERROR]"))
|
|
46
|
+
.map((line) => line.slice("[ERROR]".length).trim());
|
|
47
|
+
return new Error(errors.length ? `${message}: ${errors.join(". ")}` : message);
|
|
48
|
+
}
|
|
49
|
+
/** Rejects layouts the codec can't decode, or decodes to the wrong pixels */
|
|
50
|
+
function validate({ components }) {
|
|
51
|
+
const [first, cb, cr] = components;
|
|
52
|
+
if (!first ||
|
|
53
|
+
components.some(({ precision, signed }) => precision !== first.precision || signed !== first.signed)) {
|
|
54
|
+
throw new Error("Unsupported JPEG 2000 image: every component must have the same bit depth");
|
|
55
|
+
}
|
|
56
|
+
if (first.precision > 16) {
|
|
57
|
+
throw new Error(`Unsupported JPEG 2000 bit depth ${first.precision}: up to 16 bits per sample can be decoded`);
|
|
58
|
+
}
|
|
59
|
+
// The codec clamps them to 0-255, losing the negative half
|
|
60
|
+
if (components.length === 1 && first.signed && first.precision <= 8) {
|
|
61
|
+
throw new Error("Unsupported JPEG 2000 image: signed grayscale samples of 8 bits or fewer");
|
|
62
|
+
}
|
|
63
|
+
const subsampled = components.some(({ dx, dy }) => dx !== 1 || dy !== 1);
|
|
64
|
+
// The codec converts YCbCr with 4:2:0 or 4:2:2 chroma to RGB
|
|
65
|
+
const subsampledChroma = components.length === 3 &&
|
|
66
|
+
first.dx === 1 &&
|
|
67
|
+
first.dy === 1 &&
|
|
68
|
+
cb.dx === 2 &&
|
|
69
|
+
cr.dx === 2 &&
|
|
70
|
+
cb.dy === cr.dy &&
|
|
71
|
+
cb.dy <= 2;
|
|
72
|
+
if (subsampled && !subsampledChroma) {
|
|
73
|
+
throw new Error("Unsupported JPEG 2000 subsampling: only the chroma of YCbCr 4:2:0 and 4:2:2 images can be subsampled");
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
/** Converts the codec's interleaved gray or RGB samples to 8-bit RGBA */
|
|
77
|
+
function toRgba(samples, pixels, components, bitsPerSample, signed) {
|
|
78
|
+
// Copy the samples out of wasm memory, which also aligns 16-bit ones
|
|
79
|
+
const copy = samples.slice();
|
|
80
|
+
const values = bitsPerSample > 8
|
|
81
|
+
? signed
|
|
82
|
+
? new Int16Array(copy.buffer)
|
|
83
|
+
: new Uint16Array(copy.buffer)
|
|
84
|
+
: signed
|
|
85
|
+
? new Int8Array(copy.buffer)
|
|
86
|
+
: copy;
|
|
87
|
+
const offset = signed ? 2 ** (bitsPerSample - 1) : 0;
|
|
88
|
+
const scale = 255 / (2 ** bitsPerSample - 1);
|
|
89
|
+
// Rounds and clamps to 0-255
|
|
90
|
+
const rgba = new Uint8ClampedArray(pixels * 4);
|
|
91
|
+
for (let i = 0; i < pixels; i++) {
|
|
92
|
+
for (let c = 0; c < 3; c++) {
|
|
93
|
+
const value = values[i * components + (components === 1 ? 0 : c)];
|
|
94
|
+
rgba[i * 4 + c] = (value + offset) * scale;
|
|
95
|
+
}
|
|
96
|
+
rgba[i * 4 + 3] = 255;
|
|
97
|
+
}
|
|
98
|
+
return Buffer.from(rgba.buffer);
|
|
99
|
+
}
|
|
100
|
+
async function decode(data, { reduce = 0, layers = 0, maxResolutionInMP = 100 }, wasm) {
|
|
101
|
+
const header = readCodestreamHeader(data);
|
|
102
|
+
if (!header) {
|
|
103
|
+
throw new Error("Invalid JPEG 2000 image: the codestream's main header can't be read");
|
|
104
|
+
}
|
|
105
|
+
validate(header);
|
|
106
|
+
const level = Math.min(Math.max(0, Math.floor(reduce)), header.decompositions);
|
|
107
|
+
const width = Math.ceil(header.width / 2 ** level);
|
|
108
|
+
const height = Math.ceil(header.height / 2 ** level);
|
|
109
|
+
if (width * height > maxResolutionInMP * 1_000_000) {
|
|
110
|
+
throw new Error(`JPEG 2000 dimensions ${width}x${height} exceed the maximum resolution of ${maxResolutionInMP} megapixels. Use the reduce option to decode it at a lower resolution.`);
|
|
111
|
+
}
|
|
112
|
+
const codec = await initCodecOnce(wasm);
|
|
113
|
+
const decoder = new codec.J2KDecoder();
|
|
114
|
+
messages = [];
|
|
115
|
+
try {
|
|
116
|
+
try {
|
|
117
|
+
decoder.getEncodedBuffer(data.length).set(data);
|
|
118
|
+
decoder.decodeSubResolution(level, Math.max(0, Math.floor(layers)));
|
|
119
|
+
}
|
|
120
|
+
catch {
|
|
121
|
+
// C++ exceptions reach JS as pointers, without their message
|
|
122
|
+
const count = header.components.length;
|
|
123
|
+
throw count === 1 || count === 3
|
|
124
|
+
? withErrors("Failed to decode the JPEG 2000 image")
|
|
125
|
+
: new Error(`Unsupported JPEG 2000 image with ${count} components: only grayscale and RGB images can be decoded, without alpha`);
|
|
126
|
+
}
|
|
127
|
+
const frame = decoder.getFrameInfo();
|
|
128
|
+
// Without an exception, OpenJPEG's own failures leave the frame empty
|
|
129
|
+
if (!frame.width) {
|
|
130
|
+
throw withErrors("Failed to decode the JPEG 2000 image");
|
|
131
|
+
}
|
|
132
|
+
const size = decoder.calculateSizeAtDecompositionLevel(level);
|
|
133
|
+
return {
|
|
134
|
+
data: toRgba(decoder.getDecodedBuffer(), size.width * size.height, frame.componentCount, frame.bitsPerSample, frame.isSigned),
|
|
135
|
+
width: size.width,
|
|
136
|
+
height: size.height,
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
finally {
|
|
140
|
+
decoder.delete();
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
/** Encodes the bitmap's RGB, without alpha, as a codestream */
|
|
144
|
+
async function encode({ width, height, data }, options, wasm) {
|
|
145
|
+
const { compressionRatio, decompositions } = Jpeg2000OptionsSchema.parse(options);
|
|
146
|
+
const codec = await initCodecOnce(wasm);
|
|
147
|
+
const encoder = new codec.J2KEncoder();
|
|
148
|
+
messages = [];
|
|
149
|
+
try {
|
|
150
|
+
const pixels = encoder.getDecodedBuffer({
|
|
151
|
+
width,
|
|
152
|
+
height,
|
|
153
|
+
bitsPerSample: 8,
|
|
154
|
+
componentCount: 3,
|
|
155
|
+
isSigned: false,
|
|
156
|
+
});
|
|
157
|
+
for (let i = 0; i < width * height; i++) {
|
|
158
|
+
pixels[i * 3] = data[i * 4];
|
|
159
|
+
pixels[i * 3 + 1] = data[i * 4 + 1];
|
|
160
|
+
pixels[i * 3 + 2] = data[i * 4 + 2];
|
|
161
|
+
}
|
|
162
|
+
// The smallest resolution needs at least a pixel in each direction
|
|
163
|
+
encoder.setDecompositions(Math.min(Math.max(0, Math.round(decompositions)), Math.floor(Math.log2(Math.min(width, height)))));
|
|
164
|
+
if (compressionRatio > 1) {
|
|
165
|
+
encoder.setQuality(false, 1);
|
|
166
|
+
encoder.setCompressionRatio(0, compressionRatio);
|
|
167
|
+
}
|
|
168
|
+
try {
|
|
169
|
+
encoder.encode();
|
|
170
|
+
}
|
|
171
|
+
catch {
|
|
172
|
+
throw withErrors("Failed to encode the JPEG 2000 image");
|
|
173
|
+
}
|
|
174
|
+
// Copied out of wasm memory
|
|
175
|
+
return Buffer.from(encoder.getEncodedBuffer());
|
|
176
|
+
}
|
|
177
|
+
finally {
|
|
178
|
+
encoder.delete();
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
/**
|
|
182
|
+
* JP2 files, the usual JPEG 2000 container (.jp2).
|
|
183
|
+
* Images are written as 8-bit sRGB without alpha.
|
|
184
|
+
*/
|
|
185
|
+
export default function jpeg2000({ wasm } = {}) {
|
|
186
|
+
return {
|
|
187
|
+
mime: "image/jp2",
|
|
188
|
+
hasAlpha: false,
|
|
189
|
+
encode: async (bitmap, options = {}) => writeJp2(await encode(bitmap, options, wasm?.codec), bitmap.width, bitmap.height),
|
|
190
|
+
decode: (data, options = {}) => decode(data, options, wasm?.codec),
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
/** Raw JPEG 2000 codestreams, without a container (.j2c, .j2k) */
|
|
194
|
+
export function j2c({ wasm } = {}) {
|
|
195
|
+
return {
|
|
196
|
+
mime: "image/j2c",
|
|
197
|
+
hasAlpha: false,
|
|
198
|
+
encode: (bitmap, options = {}) => encode(bitmap, options, wasm?.codec),
|
|
199
|
+
decode: (data, options = {}) => decode(data, options, wasm?.codec),
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
/**
|
|
203
|
+
* JPX files (.jpx, .jpf), the extended JPEG 2000 container. Only decoding is
|
|
204
|
+
* supported, of the codestreams that only use JPEG 2000 part 1 features.
|
|
205
|
+
*/
|
|
206
|
+
export function jpx({ wasm } = {}) {
|
|
207
|
+
return {
|
|
208
|
+
mime: "image/jpx",
|
|
209
|
+
hasAlpha: false,
|
|
210
|
+
encode: async () => {
|
|
211
|
+
throw new Error("Writing JPX isn't supported. Write a JP2 (image/jp2) instead, which JPX readers can read too.");
|
|
212
|
+
},
|
|
213
|
+
decode: (data, options = {}) => decode(data, options, wasm?.codec),
|
|
214
|
+
};
|
|
215
|
+
}
|
|
216
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAChC,OAAO,YAEN,MAAM,sCAAsC,CAAC;AAE9C,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,EAEL,oBAAoB,EACpB,QAAQ,GACT,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AAE1C,MAAM,qBAAqB,GAAG,CAAC;KAC5B,MAAM,CAAC;IACN;;;;;;OAMG;IACH,gBAAgB,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE,CAAC,OAAO,CAAC,CAAC,CAAC;IAClD;;;;;OAKG;IACH,cAAc,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE,CAAC,OAAO,CAAC,CAAC,CAAC;CACjD,CAAC;KACD,MAAM,EAAE,CAAC;AAyCZ,IAAI,UAA+C,CAAC;AACpD,gEAAgE;AAChE,IAAI,QAAQ,GAAa,EAAE,CAAC;AAE5B,SAAS,aAAa,CAAC,MAA2B;IAChD,UAAU,KAAK,OAAO,CAAC,OAAO,CAAC,MAAM,IAAI,QAAQ,EAAE,CAAC,CAAC,IAAI,CACv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CAAC;KACP,CAAC;AAClC,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,GAAG,CAAC,EAAE,IAAI,EAAE,GAA0B,EAAE;IACtD,OAAO;QACL,IAAI,EAAE,WAAW;QACjB,QAAQ,EAAE,KAAK;QACf,MAAM,EAAE,KAAK,IAAI,EAAE;YACjB,MAAM,IAAI,KAAK,CACb,+FAA+F,CAChG,CAAC;QACJ,CAAC;QACD,MAAM,EAAE,CAAC,IAAI,EAAE,OAAO,GAA0B,EAAE,EAAE,EAAE,CACpD,MAAM,CAAC,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,KAAK,CAAC;KACP,CAAC;AAClC,CAAC","sourcesContent":["import { Buffer } from \"buffer\";\nimport OpenJPEGWASM, {\n OpenJpegModule,\n} from \"@cornerstonejs/codec-openjpeg/wasmjs\";\nimport { Bitmap, Format } from \"@jimp/types\";\nimport { z } from \"zod\";\n\nimport {\n CodestreamHeader,\n readCodestreamHeader,\n writeJp2,\n} from \"./codestream.js\";\nimport { loadWasm } from \"./load-wasm.js\";\n\nconst Jpeg2000OptionsSchema = z\n .object({\n /**\n * How many times smaller than the uncompressed RGB pixels the file\n * should be, e.g. 20 for 20:1. 1 is lossless: it uses the reversible\n * wavelet and keeps every pixel exactly. Above 1, the irreversible\n * wavelet is used and quality drops as the ratio rises.\n * @default 1\n */\n compressionRatio: z.number().optional().default(1),\n /**\n * Wavelet decomposition levels. Each level is a resolution, half the\n * size of the one above, that decoders can `reduce` to without decoding\n * the full image. Limited to what the image's size allows.\n * @default 5\n */\n decompositions: z.number().optional().default(5),\n })\n .strict();\n\ntype Jpeg2000Options = z.infer<typeof Jpeg2000OptionsSchema>;\n\nexport interface DecodeJpeg2000Options {\n /**\n * Decode at a lower resolution. Each step halves the width and height\n * (rounding up), down to the image's smallest resolution. It's much faster\n * and uses less memory than decoding a huge image in full and resizing it.\n * @default 0\n */\n reduce?: number;\n /**\n * Decode only the first quality layers of an image encoded with several,\n * for a quick lower quality preview. 0 decodes all of them.\n * @default 0\n */\n layers?: number;\n /**\n * Largest image, in megapixels, that will be decoded, after `reduce`.\n * Larger images are rejected before any pixel memory is allocated.\n * @default 100\n */\n maxResolutionInMP?: number;\n}\n\nexport interface Jpeg2000Wasm {\n /** The compiled `@cornerstonejs/codec-openjpeg/wasm` */\n codec?: WebAssembly.Module;\n}\n\nexport interface Jpeg2000FormatOptions {\n /**\n * A precompiled wasm module for runtimes or bundlers where the plugin\n * can't load the codec's wasm itself.\n * The codec is initialized once, by the first instance that encodes or\n * decodes, so pass the same module to every instance.\n */\n wasm?: Jpeg2000Wasm;\n}\n\nlet codecReady: Promise<OpenJpegModule> | undefined;\n/** What OpenJPEG printed during the current encode or decode */\nlet messages: string[] = [];\n\nfunction initCodecOnce(module?: WebAssembly.Module) {\n codecReady ??= Promise.resolve(module ?? loadWasm()).then(\n (wasm) =>\n new Promise<OpenJpegModule>((resolve, reject) => {\n OpenJPEGWASM({\n // OpenJPEG logs its errors, warnings and progress\n print: (message) => messages.push(message),\n printErr: (message) => messages.push(message),\n instantiateWasm(imports, receiveInstance) {\n WebAssembly.instantiate(wasm, imports).then(\n (instance) => receiveInstance(instance, wasm),\n reject,\n );\n return {};\n },\n }).then(resolve, reject);\n }),\n );\n return codecReady;\n}\n\n/** The errors OpenJPEG printed, to explain why it failed */\nfunction withErrors(message: string) {\n const errors = messages\n .filter((line) => line.startsWith(\"[ERROR]\"))\n .map((line) => line.slice(\"[ERROR]\".length).trim());\n\n return new Error(\n errors.length ? `${message}: ${errors.join(\". \")}` : message,\n );\n}\n\n/** Rejects layouts the codec can't decode, or decodes to the wrong pixels */\nfunction validate({ components }: CodestreamHeader) {\n const [first, cb, cr] = components;\n\n if (\n !first ||\n components.some(\n ({ precision, signed }) =>\n precision !== first.precision || signed !== first.signed,\n )\n ) {\n throw new Error(\n \"Unsupported JPEG 2000 image: every component must have the same bit depth\",\n );\n }\n\n if (first.precision > 16) {\n throw new Error(\n `Unsupported JPEG 2000 bit depth ${first.precision}: up to 16 bits per sample can be decoded`,\n );\n }\n\n // The codec clamps them to 0-255, losing the negative half\n if (components.length === 1 && first.signed && first.precision <= 8) {\n throw new Error(\n \"Unsupported JPEG 2000 image: signed grayscale samples of 8 bits or fewer\",\n );\n }\n\n const subsampled = components.some(({ dx, dy }) => dx !== 1 || dy !== 1);\n // The codec converts YCbCr with 4:2:0 or 4:2:2 chroma to RGB\n const subsampledChroma =\n components.length === 3 &&\n first.dx === 1 &&\n first.dy === 1 &&\n cb!.dx === 2 &&\n cr!.dx === 2 &&\n cb!.dy === cr!.dy &&\n cb!.dy <= 2;\n\n if (subsampled && !subsampledChroma) {\n throw new Error(\n \"Unsupported JPEG 2000 subsampling: only the chroma of YCbCr 4:2:0 and 4:2:2 images can be subsampled\",\n );\n }\n}\n\n/** Converts the codec's interleaved gray or RGB samples to 8-bit RGBA */\nfunction toRgba(\n samples: Uint8Array,\n pixels: number,\n components: number,\n bitsPerSample: number,\n signed: boolean,\n) {\n // Copy the samples out of wasm memory, which also aligns 16-bit ones\n const copy = samples.slice();\n const values =\n bitsPerSample > 8\n ? signed\n ? new Int16Array(copy.buffer)\n : new Uint16Array(copy.buffer)\n : signed\n ? new Int8Array(copy.buffer)\n : copy;\n const offset = signed ? 2 ** (bitsPerSample - 1) : 0;\n const scale = 255 / (2 ** bitsPerSample - 1);\n // Rounds and clamps to 0-255\n const rgba = new Uint8ClampedArray(pixels * 4);\n\n for (let i = 0; i < pixels; i++) {\n for (let c = 0; c < 3; c++) {\n const value = values[i * components + (components === 1 ? 0 : c)]!;\n rgba[i * 4 + c] = (value + offset) * scale;\n }\n\n rgba[i * 4 + 3] = 255;\n }\n\n return Buffer.from(rgba.buffer);\n}\n\nasync function decode(\n data: Buffer,\n { reduce = 0, layers = 0, maxResolutionInMP = 100 }: DecodeJpeg2000Options,\n wasm?: WebAssembly.Module,\n): Promise<Bitmap> {\n const header = readCodestreamHeader(data);\n\n if (!header) {\n throw new Error(\n \"Invalid JPEG 2000 image: the codestream's main header can't be read\",\n );\n }\n\n validate(header);\n\n const level = Math.min(\n Math.max(0, Math.floor(reduce)),\n header.decompositions,\n );\n const width = Math.ceil(header.width / 2 ** level);\n const height = Math.ceil(header.height / 2 ** level);\n\n if (width * height > maxResolutionInMP * 1_000_000) {\n throw new Error(\n `JPEG 2000 dimensions ${width}x${height} exceed the maximum resolution of ${maxResolutionInMP} megapixels. Use the reduce option to decode it at a lower resolution.`,\n );\n }\n\n const codec = await initCodecOnce(wasm);\n const decoder = new codec.J2KDecoder();\n\n messages = [];\n\n try {\n try {\n decoder.getEncodedBuffer(data.length).set(data);\n decoder.decodeSubResolution(level, Math.max(0, Math.floor(layers)));\n } catch {\n // C++ exceptions reach JS as pointers, without their message\n const count = header.components.length;\n\n throw count === 1 || count === 3\n ? withErrors(\"Failed to decode the JPEG 2000 image\")\n : new Error(\n `Unsupported JPEG 2000 image with ${count} components: only grayscale and RGB images can be decoded, without alpha`,\n );\n }\n\n const frame = decoder.getFrameInfo();\n // Without an exception, OpenJPEG's own failures leave the frame empty\n if (!frame.width) {\n throw withErrors(\"Failed to decode the JPEG 2000 image\");\n }\n\n const size = decoder.calculateSizeAtDecompositionLevel(level);\n\n return {\n data: toRgba(\n decoder.getDecodedBuffer(),\n size.width * size.height,\n frame.componentCount,\n frame.bitsPerSample,\n frame.isSigned,\n ),\n width: size.width,\n height: size.height,\n };\n } finally {\n decoder.delete();\n }\n}\n\n/** Encodes the bitmap's RGB, without alpha, as a codestream */\nasync function encode(\n { width, height, data }: Bitmap,\n options: Partial<Jpeg2000Options>,\n wasm?: WebAssembly.Module,\n) {\n const { compressionRatio, decompositions } =\n Jpeg2000OptionsSchema.parse(options);\n const codec = await initCodecOnce(wasm);\n const encoder = new codec.J2KEncoder();\n\n messages = [];\n\n try {\n const pixels = encoder.getDecodedBuffer({\n width,\n height,\n bitsPerSample: 8,\n componentCount: 3,\n isSigned: false,\n });\n\n for (let i = 0; i < width * height; i++) {\n pixels[i * 3] = data[i * 4]!;\n pixels[i * 3 + 1] = data[i * 4 + 1]!;\n pixels[i * 3 + 2] = data[i * 4 + 2]!;\n }\n\n // The smallest resolution needs at least a pixel in each direction\n encoder.setDecompositions(\n Math.min(\n Math.max(0, Math.round(decompositions)),\n Math.floor(Math.log2(Math.min(width, height))),\n ),\n );\n\n if (compressionRatio > 1) {\n encoder.setQuality(false, 1);\n encoder.setCompressionRatio(0, compressionRatio);\n }\n\n try {\n encoder.encode();\n } catch {\n throw withErrors(\"Failed to encode the JPEG 2000 image\");\n }\n\n // Copied out of wasm memory\n return Buffer.from(encoder.getEncodedBuffer());\n } finally {\n encoder.delete();\n }\n}\n\n/**\n * JP2 files, the usual JPEG 2000 container (.jp2).\n * Images are written as 8-bit sRGB without alpha.\n */\nexport default function jpeg2000({ wasm }: Jpeg2000FormatOptions = {}) {\n return {\n mime: \"image/jp2\",\n hasAlpha: false,\n encode: async (bitmap, options: Partial<Jpeg2000Options> = {}) =>\n writeJp2(\n await encode(bitmap, options, wasm?.codec),\n bitmap.width,\n bitmap.height,\n ),\n decode: (data, options: DecodeJpeg2000Options = {}) =>\n decode(data, options, wasm?.codec),\n } satisfies Format<\"image/jp2\">;\n}\n\n/** Raw JPEG 2000 codestreams, without a container (.j2c, .j2k) */\nexport function j2c({ wasm }: Jpeg2000FormatOptions = {}) {\n return {\n mime: \"image/j2c\",\n hasAlpha: false,\n encode: (bitmap, options: Partial<Jpeg2000Options> = {}) =>\n encode(bitmap, options, wasm?.codec),\n decode: (data, options: DecodeJpeg2000Options = {}) =>\n decode(data, options, wasm?.codec),\n } satisfies Format<\"image/j2c\">;\n}\n\n/**\n * JPX files (.jpx, .jpf), the extended JPEG 2000 container. Only decoding is\n * supported, of the codestreams that only use JPEG 2000 part 1 features.\n */\nexport function jpx({ wasm }: Jpeg2000FormatOptions = {}) {\n return {\n mime: \"image/jpx\",\n hasAlpha: false,\n encode: async () => {\n throw new Error(\n \"Writing JPX isn't supported. Write a JP2 (image/jp2) instead, which JPX readers can read too.\",\n );\n },\n decode: (data, options: DecodeJpeg2000Options = {}) =>\n decode(data, options, wasm?.codec),\n } satisfies Format<\"image/jpx\">;\n}\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"load-wasm.d.ts","sourceRoot":"","sources":["../../src/load-wasm.ts"],"names":[],"mappings":"AAKA,oDAAoD;AACpD,wBAAsB,QAAQ,gCAK7B"}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { readFile } from "node:fs/promises";
|
|
2
|
+
import { createRequire } from "node:module";
|
|
3
|
+
const require = createRequire(import.meta.url);
|
|
4
|
+
/** Reads and compiles the codec's wasm from disk */
|
|
5
|
+
export async function loadWasm() {
|
|
6
|
+
const wasm = await readFile(require.resolve("@cornerstonejs/codec-openjpeg/wasm"));
|
|
7
|
+
return WebAssembly.compile(new Uint8Array(wasm));
|
|
8
|
+
}
|
|
9
|
+
//# sourceMappingURL=load-wasm.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"load-wasm.js","sourceRoot":"","sources":["../../src/load-wasm.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAE5C,MAAM,OAAO,GAAG,aAAa,CAAC,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC;AAE/C,oDAAoD;AACpD,MAAM,CAAC,KAAK,UAAU,QAAQ;IAC5B,MAAM,IAAI,GAAG,MAAM,QAAQ,CACzB,OAAO,CAAC,OAAO,CAAC,oCAAoC,CAAC,CACtD,CAAC;IACF,OAAO,WAAW,CAAC,OAAO,CAAC,IAAI,UAAU,CAAC,IAAI,CAAC,CAAC,CAAC;AACnD,CAAC","sourcesContent":["import { readFile } from \"node:fs/promises\";\nimport { createRequire } from \"node:module\";\n\nconst require = createRequire(import.meta.url);\n\n/** Reads and compiles the codec's wasm from disk */\nexport async function loadWasm() {\n const wasm = await readFile(\n require.resolve(\"@cornerstonejs/codec-openjpeg/wasm\"),\n );\n return WebAssembly.compile(new Uint8Array(wasm));\n}\n"]}
|