diff --git a/package-lock.json b/package-lock.json index a827a3940..a0c1c82e9 100644 --- a/package-lock.json +++ b/package-lock.json @@ -10,6 +10,7 @@ "devDependencies": { "@commitlint/cli": "^21.0.0", "@commitlint/config-conventional": "^21.0.0", + "@cornerstonejs/codec-openjph": "2.4.11", "@eslint/js": "^9.39.1", "@fontsource/roboto": "^5.3.0", "@itk-wasm/dicom": "^7.6.4", @@ -1039,6 +1040,16 @@ "node": ">=10" } }, + "node_modules/@cornerstonejs/codec-openjph": { + "version": "2.4.11", + "resolved": "https://registry.npmjs.org/@cornerstonejs/codec-openjph/-/codec-openjph-2.4.11.tgz", + "integrity": "sha512-NzwCYevGSj2JOuP7BztxrOd5WnJ86gOGLv3sq36jZxxHUXoDo1YhzizHiYz+T7GQqkzbfaQcwSyxsRogzGFIPQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.14" + } + }, "node_modules/@cspotcode/source-map-support": { "version": "0.8.1", "resolved": "https://registry.npmjs.org/@cspotcode/source-map-support/-/source-map-support-0.8.1.tgz", diff --git a/package.json b/package.json index d6d5ad55b..4ea3b0b3f 100644 --- a/package.json +++ b/package.json @@ -35,6 +35,7 @@ "devDependencies": { "@commitlint/cli": "^21.0.0", "@commitlint/config-conventional": "^21.0.0", + "@cornerstonejs/codec-openjph": "2.4.11", "@eslint/js": "^9.39.1", "@fontsource/roboto": "^5.3.0", "@itk-wasm/dicom": "^7.6.4", diff --git a/src/dicom/README.md b/src/dicom/README.md index dc30f5ea7..4d76b9aaa 100644 --- a/src/dicom/README.md +++ b/src/dicom/README.md @@ -16,7 +16,7 @@ defines it. | `core/collections` | header facts, collection planning and the registry | | `core/volume` | allocation, pixel formats, validation and `loadVolume` | | `core/pixels` | decoders, the decoder table, frame index, encapsulated frames | -| `core/runtime` | the runtime, its request pool, metadata workers and GDCM decoder | +| `core/runtime` | the runtime, its request pool, metadata workers, GDCM and HTJ2K decoders | | `vtk` | the vtk.js image and slice thumbnails | `core` uses no Vue, Pinia, vtk.js or VolView application code. `vtk` shows a @@ -26,7 +26,7 @@ core `Volume` as a `vtkImageData`. `eslint.config.js` enforces both boundaries. - Instances, collection updates and volumes are plain values. Only the runtime from `createDicomRuntime` holds resources (request pool, metadata - workers, GDCM workers), and only it has `dispose()`. Importing a file starts + workers, GDCM and HTJ2K workers), and only it has `dispose()`. Importing a file starts no worker and touches no DOM. - Every asynchronous operation takes an `AbortSignal`; aborting it is the whole of cancellation. @@ -56,7 +56,10 @@ core `Volume` as a `vtkImageData`. `eslint.config.js` enforces both boundaries. in one request. - `nativeFrameDecoder` accepts only instances whose result is identical to GDCM's. The default table sends other instances whole to GDCM in a worker, - and fails JPIP, video and JPEG XL syntaxes as having no decoder. + HTJ2K instances whole to OpenJPH in a worker, and fails JPIP, video and + JPEG XL syntaxes as having no decoder. The HTJ2K decoder reads only the + Pixel Data value and finishes samples as native frames are, so it declines + what `nativeFrameDecoder` declines. ## Spacing diff --git a/src/dicom/core/pixels/__tests__/decoderTable.spec.ts b/src/dicom/core/pixels/__tests__/decoderTable.spec.ts index f108441d9..07cf34eda 100644 --- a/src/dicom/core/pixels/__tests__/decoderTable.spec.ts +++ b/src/dicom/core/pixels/__tests__/decoderTable.spec.ts @@ -11,7 +11,10 @@ import { pixelInstance } from './pixelFixture'; const gdcm = wholeInstanceDecoder('GDCM', () => { throw new Error('not decoded in these tests'); }); -const table = defaultDecoderTable(gdcm); +const htj2k = wholeInstanceDecoder('HTJ2K', () => { + throw new Error('not decoded in these tests'); +}); +const table = defaultDecoderTable({ gdcm, htj2k }); const declining = (name: string, reason: string): PixelDecoder => ({ name, @@ -57,9 +60,21 @@ describe('planDecode', () => { }); }); + it.each([ + '1.2.840.10008.1.2.4.201', + '1.2.840.10008.1.2.4.202', + '1.2.840.10008.1.2.4.203', + ])('hands HTJ2K syntax %s to the HTJ2K decoder', async (syntax) => { + const { instance } = await pixelInstance({ transferSyntaxUid: syntax }); + + expect(planDecode(table, instance, Uint16Array)).toMatchObject({ + decoder: htj2k, + }); + }); + it.each([ ['1.2.840.10008.1.2.4.102', 'MPEG-4 AVC/H.264 High Profile'], - ['1.2.840.10008.1.2.4.201', 'High-Throughput JPEG 2000 Lossless'], + ['1.2.840.10008.1.2.4.112', 'JPEG XL'], ])( 'names known transfer syntax %s that has no decoder', async (transferSyntaxUid, name) => { diff --git a/src/dicom/core/pixels/decoderTable.ts b/src/dicom/core/pixels/decoderTable.ts index ca3460249..f54a2b350 100644 --- a/src/dicom/core/pixels/decoderTable.ts +++ b/src/dicom/core/pixels/decoderTable.ts @@ -25,7 +25,7 @@ export const singleDecoderTable = (decoder: PixelDecoder): DecoderTable => ({ names: new Map(), }); -type Codec = 'native' | 'gdcm' | 'none'; +type Codec = 'native' | 'gdcm' | 'htj2k' | 'none'; // prettier-ignore const SYNTAXES: Array<[string, string, Codec]> = [ @@ -53,19 +53,32 @@ const SYNTAXES: Array<[string, string, Codec]> = [ ['1.2.840.10008.1.2.4.106', 'MPEG-4 AVC/H.264 Stereo High Profile', 'none'], ['1.2.840.10008.1.2.4.107', 'HEVC/H.265 Main Profile', 'none'], ['1.2.840.10008.1.2.4.108', 'HEVC/H.265 Main 10 Profile', 'none'], - ['1.2.840.10008.1.2.4.201', 'High-Throughput JPEG 2000 Lossless', 'none'], - ['1.2.840.10008.1.2.4.202', 'High-Throughput JPEG 2000 with RPCL Lossless', 'none'], - ['1.2.840.10008.1.2.4.203', 'High-Throughput JPEG 2000', 'none'], + ['1.2.840.10008.1.2.4.201', 'High-Throughput JPEG 2000 Lossless', 'htj2k'], + ['1.2.840.10008.1.2.4.202', 'High-Throughput JPEG 2000 with RPCL Lossless', 'htj2k'], + ['1.2.840.10008.1.2.4.203', 'High-Throughput JPEG 2000', 'htj2k'], ['1.2.840.10008.1.2.4.110', 'JPEG XL Lossless', 'none'], ['1.2.840.10008.1.2.4.111', 'JPEG XL JPEG Recompression', 'none'], ['1.2.840.10008.1.2.4.112', 'JPEG XL', 'none'], ]; -/** Native frames for uncompressed syntaxes, then GDCM for every syntax it may know. */ -export function defaultDecoderTable(gdcm: PixelDecoder): DecoderTable { +/** The runtime's worker-backed decoders, which a table is built around. */ +export type RuntimeDecoders = Readonly<{ + gdcm: PixelDecoder; + htj2k: PixelDecoder; +}>; + +/** + * Native frames for uncompressed syntaxes, then GDCM for every syntax it may + * know. HTJ2K, which GDCM lacks, goes to OpenJPH. + */ +export function defaultDecoderTable({ + gdcm, + htj2k, +}: RuntimeDecoders): DecoderTable { const candidates = { native: [nativeFrameDecoder, gdcm], gdcm: [gdcm], + htj2k: [htj2k], none: [], }; return { diff --git a/src/dicom/core/pixels/htj2k.worker.ts b/src/dicom/core/pixels/htj2k.worker.ts new file mode 100644 index 000000000..07a30d164 --- /dev/null +++ b/src/dicom/core/pixels/htj2k.worker.ts @@ -0,0 +1,21 @@ +import * as Comlink from 'comlink'; +import createOpenJph, { + type OpenJphModule, +} from '@cornerstonejs/codec-openjph'; +import openJphWasmUrl from '@cornerstonejs/codec-openjph/wasm?url'; +import { decodeHtj2kFrames } from './htj2kFrames'; + +let openJph: Promise | undefined; +const loadOpenJph = () => + (openJph ??= createOpenJph({ locateFile: () => openJphWasmUrl })); + +const api = { + async decode(value: Uint8Array, frameCount: number) { + const frames = decodeHtj2kFrames(await loadOpenJph(), value, frameCount); + return Comlink.transfer(frames, [frames.bytes.buffer]); + }, +}; + +export type Htj2kWorker = typeof api; + +Comlink.expose(api); diff --git a/src/dicom/core/pixels/htj2kFrames.ts b/src/dicom/core/pixels/htj2kFrames.ts new file mode 100644 index 000000000..f52b32be3 --- /dev/null +++ b/src/dicom/core/pixels/htj2kFrames.ts @@ -0,0 +1,61 @@ +import type { FrameInfo, OpenJphModule } from '@cornerstonejs/codec-openjph'; +import { splitEncapsulatedFrames } from './encapsulatedFrames'; + +/** Every frame's samples back to back, interleaved by component, little endian. */ +export type DecodedFrames = Readonly<{ + bytes: Uint8Array; + columns: number; + rows: number; + components: number; + bytesPerSample: number; +}>; + +const shapeOf = (info: FrameInfo) => ({ + columns: info.width, + rows: info.height, + components: info.componentCount, + bytesPerSample: info.bitsPerSample > 8 ? 2 : 1, +}); + +function decodeFrame(codec: OpenJphModule, frame: Uint8Array, index: number) { + const decoder = new codec.HTJ2KDecoder(); + try { + decoder.getEncodedBuffer(frame.length).set(frame); + decoder.decode(); + return { + shape: shapeOf(decoder.getFrameInfo()), + samples: decoder.getDecodedBuffer().slice(), + }; + } catch (error) { + throw new Error(`HTJ2K frame ${index + 1} did not decode`, { + cause: error, + }); + } finally { + decoder.delete(); + } +} + +/** Decodes the frames of an encapsulated Pixel Data value. */ +export function decodeHtj2kFrames( + codec: OpenJphModule, + value: Uint8Array, + frameCount: number +): DecodedFrames { + const frames = splitEncapsulatedFrames(value, frameCount).map( + (frame, index) => decodeFrame(codec, frame, index) + ); + const [{ shape }] = frames; + const mismatch = frames.findIndex( + (frame) => JSON.stringify(frame.shape) !== JSON.stringify(shape) + ); + if (mismatch >= 0) + throw new Error( + `HTJ2K frame ${mismatch + 1} differs in size or depth from frame 1` + ); + const frameLength = frames[0].samples.length; + const bytes = new Uint8Array(frameLength * frames.length); + frames.forEach(({ samples }, index) => + bytes.set(samples, index * frameLength) + ); + return { bytes, ...shape }; +} diff --git a/src/dicom/core/pixels/openjph.d.ts b/src/dicom/core/pixels/openjph.d.ts new file mode 100644 index 000000000..2dab79f95 --- /dev/null +++ b/src/dicom/core/pixels/openjph.d.ts @@ -0,0 +1,37 @@ +declare module '@cornerstonejs/codec-openjph' { + export type FrameInfo = { + width: number; + height: number; + bitsPerSample: number; + componentCount: number; + isSigned: boolean; + isUsingColorTransform: boolean; + }; + + /** An Embind object: it lives on the WASM heap until `delete`. */ + export type HTJ2KDecoder = { + getEncodedBuffer(length: number): Uint8Array; + decode(): void; + getFrameInfo(): FrameInfo; + /** A view of the WASM heap, valid until the next call. */ + getDecodedBuffer(): Uint8Array; + delete(): void; + }; + + export type HTJ2KEncoder = { + getDecodedBuffer(frameInfo: FrameInfo): Uint8Array; + encode(): void; + getEncodedBuffer(): Uint8Array; + delete(): void; + }; + + export type OpenJphModule = { + HTJ2KDecoder: new () => HTJ2KDecoder; + HTJ2KEncoder: new () => HTJ2KEncoder; + }; + + const createOpenJph: (options?: { + locateFile?: (path: string) => string; + }) => Promise; + export default createOpenJph; +} diff --git a/src/dicom/core/runtime/createDicomRuntime.ts b/src/dicom/core/runtime/createDicomRuntime.ts index affc36a05..6fdb4ea19 100644 --- a/src/dicom/core/runtime/createDicomRuntime.ts +++ b/src/dicom/core/runtime/createDicomRuntime.ts @@ -3,22 +3,26 @@ import { readInstance } from '../instance/readInstance'; import { RequestPool } from './requestPool'; import { abortError, linkedController, untilAborted } from '../utils'; import { createMetadataReader } from './metadataReader'; -import { defaultDecoderTable, type DecoderTable } from '../pixels/decoderTable'; -import type { PixelDecoder } from '../pixels/pixelDecoder'; +import { + defaultDecoderTable, + type DecoderTable, + type RuntimeDecoders, +} from '../pixels/decoderTable'; import { createGdcmDecoder, type CreateGdcmLane, type DicomAssets, } from './gdcmDecoder'; +import { createHtj2kDecoder, type CreateHtj2kLane } from './htj2kDecoder'; export type DicomRuntimeOptions = { fetch?: typeof fetch; assets?: DicomAssets; - /** Builds the decoder table around the runtime's GDCM decoder. */ - decoders?: (gdcm: PixelDecoder) => DecoderTable; + /** Builds the decoder table around the runtime's worker-backed decoders. */ + decoders?: (decoders: RuntimeDecoders) => DecoderTable; /** - * GDCM workers, and the decodes one volume runs at once. Each worker - * carries its own WASM heap. + * Workers per worker-backed decoder, and the decodes one volume runs at + * once. Each worker carries its own WASM heap and starts on first use. */ decodeConcurrency?: number; }; @@ -35,13 +39,14 @@ export const defaultDecodeConcurrency = ( ); /** - * Owns the request pool, the metadata workers and the GDCM workers. Nothing + * Owns the request pool and the metadata, GDCM and HTJ2K workers. Nothing * else in the loading API needs disposal: aborting a signal stops one * operation, and `dispose` stops them all and settles what is pending. */ export function createDicomRuntime( options: DicomRuntimeOptions = {}, - createGdcmLane?: CreateGdcmLane + createGdcmLane?: CreateGdcmLane, + createHtj2kLane?: CreateHtj2kLane ) { const decodeConcurrency = options.decodeConcurrency ?? @@ -56,6 +61,7 @@ export function createDicomRuntime( decodeConcurrency, createGdcmLane ); + const htj2k = createHtj2kDecoder(decodeConcurrency, createHtj2kLane); const read = async (source: ByteSource, signal: AbortSignal) => { const { controller, release } = linkedController(signal, lifetime.signal); @@ -76,6 +82,7 @@ export function createDicomRuntime( requests.dispose(reason); metadata.dispose(reason); gdcm.dispose(reason); + htj2k.dispose(reason); }; return { @@ -84,7 +91,10 @@ export function createDicomRuntime( /** Aborts when the runtime is disposed. */ signal: lifetime.signal, decodeConcurrency, - decoders: (options.decoders ?? defaultDecoderTable)(gdcm.decoder), + decoders: (options.decoders ?? defaultDecoderTable)({ + gdcm: gdcm.decoder, + htj2k: htj2k.decoder, + }), /** Requests awaiting headers at once; also how far reads run ahead of decoding. */ readConcurrency: requests.poolSize, readInstance: read, diff --git a/src/dicom/core/runtime/gdcmDecoder.ts b/src/dicom/core/runtime/gdcmDecoder.ts index 58d3429a6..804817dbe 100644 --- a/src/dicom/core/runtime/gdcmDecoder.ts +++ b/src/dicom/core/runtime/gdcmDecoder.ts @@ -1,6 +1,6 @@ import type { Image, runPipeline, TypedArray } from 'itk-wasm'; import { hasUniformModalityRescale } from '../metadata/modalityRescale'; -import { linkedController, untilAborted } from '../utils'; +import { createLanePool, type Lane } from './lanePool'; import { asPart10 } from './part10Bytes'; import { wholeInstanceDecoder, @@ -68,7 +68,8 @@ function createGdcmLane(assets: DicomAssets) { ownedWorker.addEventListener('messageerror', onMessageError); return ownedWorker; }; - const run = async (name: string, data: Uint8Array) => { + const run = async (data: Uint8Array) => { + const name = 'instance.dcm'; const failed = new Promise((_, rejectFailure) => { rejectActive = rejectFailure; }); @@ -102,42 +103,9 @@ function createGdcmLane(assets: DicomAssets) { return { run, reset }; } -export type GdcmLane = ReturnType; +export type GdcmLane = Lane; export type CreateGdcmLane = (assets: DicomAssets) => GdcmLane; -/** Numbered slots handed out first come, first served. */ -function createSlots(count: number) { - const free = Array.from({ length: count }, (_, index) => count - 1 - index); - const waiters: Array<(index: number) => void> = []; - const acquire = (signal: AbortSignal) => - new Promise((resolve, reject) => { - if (signal.aborted) { - reject(signal.reason); - return; - } - if (free.length > 0) { - resolve(free.pop()!); - return; - } - const onAbort = () => { - waiters.splice(waiters.indexOf(waiter), 1); - reject(signal.reason); - }; - const waiter = (index: number) => { - signal.removeEventListener('abort', onAbort); - resolve(index); - }; - waiters.push(waiter); - signal.addEventListener('abort', onAbort, { once: true }); - }); - const release = (index: number) => { - const next = waiters.shift(); - if (next) next(index); - else free.push(index); - }; - return { acquire, release }; -} - /** * Decodes whole instances on at most `count` GDCM workers at once, queueing * the rest. `dispose` settles running and queued decodes. @@ -147,48 +115,15 @@ export function createGdcmDecoder( count: number, createLane: CreateGdcmLane = createGdcmLane ) { - const lifetime = new AbortController(); - const slots = createSlots(count); - const lanes = assets - ? Array.from({ length: count }, () => createLane(assets)) - : []; + const pool = createLanePool( + assets ? Array.from({ length: count }, () => createLane(assets)) : [] + ); - const decodeOn = async ( - index: number, - bytes: Uint8Array, - signal: AbortSignal - ) => { + const whole = wholeInstanceDecoder('GDCM', async (unit, signal) => { signal.throwIfAborted(); - const lane = lanes[index]; - if (!lane) + if (!assets) throw new Error('GDCM decoding needs createDicomRuntime({ assets })'); - // GDCM cannot be interrupted, so an abort terminates the worker. - const stop = () => lane.reset(signal.reason); - signal.addEventListener('abort', stop, { once: true }); - try { - return await lane.run('instance.dcm', bytes); - } finally { - signal.removeEventListener('abort', stop); - } - }; - - const whole = wholeInstanceDecoder('GDCM', async (unit, signal) => { - const bytes = asPart10(unit.instance, unit.bytes); - const { controller, release } = linkedController(signal, lifetime.signal); - const linked = controller.signal; - const pooled = async () => { - const index = await slots.acquire(linked); - try { - return await decodeOn(index, bytes, linked); - } finally { - slots.release(index); - } - }; - try { - return await untilAborted(pooled(), linked); - } finally { - release(); - } + return pool.run(asPart10(unit.instance, unit.bytes), signal); }); // GDCM applies one transform to an instance, so its frames must agree. @@ -200,10 +135,5 @@ export function createGdcmDecoder( : { declined: 'Frames with differing modality rescale' }, }; - const dispose = (reason: unknown) => { - lifetime.abort(reason); - lanes.forEach((lane) => lane.reset(reason)); - }; - - return { decoder, dispose }; + return { decoder, dispose: pool.dispose }; } diff --git a/src/dicom/core/runtime/htj2kDecoder.ts b/src/dicom/core/runtime/htj2kDecoder.ts new file mode 100644 index 000000000..154f7e020 --- /dev/null +++ b/src/dicom/core/runtime/htj2kDecoder.ts @@ -0,0 +1,171 @@ +import * as Comlink from 'comlink'; +import type { Instance } from '../instance/readInstance'; +import type { DecodedFrames } from '../pixels/htj2kFrames'; +import type { Htj2kWorker } from '../pixels/htj2k.worker'; +import { + decodeNativeFrame, + nativeCapability, + type NativePixelFormat, +} from '../pixels/nativeFrame'; +import { + frameCount, + type DecodedPixels, + type PixelDecoder, +} from '../pixels/pixelDecoder'; +import type { VolumeBufferConstructor } from '../volume/pixelFormat'; +import { createLanePool, type Lane } from './lanePool'; + +type Htj2kJob = Readonly<{ value: Uint8Array; frameCount: number }>; +export type Htj2kLane = Lane; +export type CreateHtj2kLane = () => Htj2kLane; + +const createHtj2kWorker = () => + new Worker(new URL('../pixels/htj2k.worker.ts', import.meta.url), { + type: 'module', + }); + +/** + * One HTJ2K worker, created on first use. A worker error rejects the running + * decode and drops the worker, so the next decode starts a fresh one. + */ +function createHtj2kLane(): Htj2kLane { + let worker: { worker: Worker; remote: Comlink.Remote } | null = + null; + let rejectActive: ((reason: unknown) => void) | undefined; + const reset = (reason: unknown) => { + if (worker) { + worker.remote[Comlink.releaseProxy](); + worker.worker.terminate(); + worker = null; + } + rejectActive?.(reason); + }; + const start = () => { + const created = createHtj2kWorker(); + created.addEventListener('error', () => + reset(new Error('HTJ2K decoder worker failed')) + ); + created.addEventListener('messageerror', () => + reset(new Error('HTJ2K decoder worker message failed')) + ); + worker = { worker: created, remote: Comlink.wrap(created) }; + return worker; + }; + const run = async ({ value, frameCount: frames }: Htj2kJob) => { + const failed = new Promise((_, reject) => { + rejectActive = reject; + }); + try { + const { remote } = worker ?? start(); + return await Promise.race([ + remote.decode(Comlink.transfer(value, [value.buffer]), frames), + failed, + ]); + } finally { + rejectActive = undefined; + } + }; + return { run, reset }; +} + +type Htj2kCapability = + | Readonly<{ format: NativePixelFormat; valueOffset: number }> + | Readonly<{ declined: string }>; + +// OpenJPH undoes a colour transform itself, so its samples are those stored. +function htj2kCapability(instance: Instance): Htj2kCapability { + const { pixelData } = instance; + if (!pixelData) return { declined: 'The header locates no Pixel Data' }; + if (pixelData.length !== null) + return { declined: 'Pixel Data is not encapsulated' }; + const capability = nativeCapability(instance, true); + if (capability.kind === 'declined') return { declined: capability.reason }; + const { format } = capability; + if (format.bitsAllocated > 16) + return { declined: `Bits Allocated ${format.bitsAllocated}` }; + return { + format: { ...format, planar: false }, + valueOffset: pixelData.valueOffset, + }; +} + +function checkShape(decoded: DecodedFrames, format: NativePixelFormat) { + const decodedShape = `${decoded.columns}x${decoded.rows}, ${decoded.components} samples of ${decoded.bytesPerSample * 8} bits`; + const declared = `${format.columns}x${format.rows}, ${format.samplesPerPixel} samples of ${format.bitsAllocated} bits`; + if (decodedShape !== declared) + throw new Error( + `HTJ2K frames decode to ${decodedShape}; the header declares ${declared}` + ); +} + +/** Interleaved samples of every frame, finished as native frames are. */ +function toPixels( + decoded: DecodedFrames, + format: NativePixelFormat, + frames: number, + Target: VolumeBufferConstructor +): DecodedPixels { + checkShape(decoded, format); + const { columns, rows, samplesPerPixel: components } = format; + const count = columns * rows * components; + const frameLength = count * decoded.bytesPerSample; + const data = new Target(count * frames); + const ranges = Array.from({ length: frames }, (_, frame) => { + const { samples, range } = decodeNativeFrame( + decoded.bytes.subarray(frame * frameLength), + format, + Target + ); + data.set(samples, frame * count); + return range; + }); + const range = Array.from({ length: components }, (_, component) => { + const each = ranges.map((frameRange) => frameRange[component]); + return [ + Math.min(...each.map(([low]) => low)), + Math.max(...each.map(([, high]) => high)), + ] as const; + }); + return { data, size: [columns, rows, frames], components, range }; +} + +// The worker takes ownership of what it is sent. +const ownedBytes = (bytes: Uint8Array) => + bytes.byteOffset === 0 && bytes.byteLength === bytes.buffer.byteLength + ? bytes + : bytes.slice(); + +/** + * Decodes HTJ2K instances whole on at most `count` workers at once, from a + * read of their Pixel Data. `dispose` settles running and queued decodes. + */ +export function createHtj2kDecoder( + count: number, + createLane: CreateHtj2kLane = createHtj2kLane +) { + const pool = createLanePool(Array.from({ length: count }, createLane)); + + const decoder: PixelDecoder = { + name: 'HTJ2K', + plan: (instance, Target) => { + const capability = htj2kCapability(instance); + if ('declined' in capability) return capability; + const { format, valueOffset } = capability; + const frames = frameCount(instance.dataset); + return [ + { + firstFrame: 0, + frames, + range: { start: valueOffset }, + decode: async (bytes, signal) => { + const job = { value: ownedBytes(bytes), frameCount: frames }; + const decoded = await pool.run(job, signal); + return toPixels(decoded, format, frames, Target); + }, + }, + ]; + }, + }; + + return { decoder, dispose: pool.dispose }; +} diff --git a/src/dicom/core/runtime/lanePool.ts b/src/dicom/core/runtime/lanePool.ts new file mode 100644 index 000000000..e7ef35ef4 --- /dev/null +++ b/src/dicom/core/runtime/lanePool.ts @@ -0,0 +1,89 @@ +import { linkedController, untilAborted } from '../utils'; + +/** A worker that runs one job at a time; `reset` stops it and rejects that job. */ +export type Lane = Readonly<{ + run: (job: Job) => Promise; + reset: (reason: unknown) => void; +}>; + +/** Numbered slots handed out first come, first served. */ +function createSlots(count: number) { + const free = Array.from({ length: count }, (_, index) => count - 1 - index); + const waiters: Array<(index: number) => void> = []; + const acquire = (signal: AbortSignal) => + new Promise((resolve, reject) => { + if (signal.aborted) { + reject(signal.reason); + return; + } + if (free.length > 0) { + resolve(free.pop()!); + return; + } + const onAbort = () => { + waiters.splice(waiters.indexOf(waiter), 1); + reject(signal.reason); + }; + const waiter = (index: number) => { + signal.removeEventListener('abort', onAbort); + resolve(index); + }; + waiters.push(waiter); + signal.addEventListener('abort', onAbort, { once: true }); + }); + const release = (index: number) => { + const next = waiters.shift(); + if (next) next(index); + else free.push(index); + }; + return { acquire, release }; +} + +/** + * Runs jobs on at most `lanes.length` lanes at once, queueing the rest. A + * running job cannot be interrupted, so aborting it resets its lane. + * `dispose` settles running and queued jobs. + */ +export function createLanePool( + lanes: ReadonlyArray> +) { + const lifetime = new AbortController(); + const slots = createSlots(lanes.length); + + const runOn = async (index: number, job: Job, signal: AbortSignal) => { + signal.throwIfAborted(); + const lane = lanes[index]; + const stop = () => lane.reset(signal.reason); + signal.addEventListener('abort', stop, { once: true }); + try { + return await lane.run(job); + } finally { + signal.removeEventListener('abort', stop); + } + }; + + const run = async (job: Job, signal: AbortSignal) => { + const { controller, release } = linkedController(signal, lifetime.signal); + const linked = controller.signal; + const pooled = async () => { + const index = await slots.acquire(linked); + try { + return await runOn(index, job, linked); + } finally { + slots.release(index); + } + }; + try { + return await untilAborted(pooled(), linked); + } finally { + release(); + } + }; + + const dispose = (reason: unknown) => { + lifetime.abort(reason); + lanes.forEach((lane) => lane.reset(reason)); + }; + + return { run, dispose }; +} diff --git a/src/dicom/core/volume/__tests__/loadFrames.spec.ts b/src/dicom/core/volume/__tests__/loadFrames.spec.ts index 9169c83de..5dd9d069b 100644 --- a/src/dicom/core/volume/__tests__/loadFrames.spec.ts +++ b/src/dicom/core/volume/__tests__/loadFrames.spec.ts @@ -116,13 +116,13 @@ const frameUnit = (valueOffset: number, frame: number): DecodeUnit => { /** A runtime whose table tries `decoder` first for transfer syntax `codec`. */ const runtimeFor = (codec: string, decoder: PixelDecoder) => { const runtime = createDicomRuntime({ - decoders: (gdcm) => { - const table = defaultDecoderTable(gdcm); + decoders: (decoders) => { + const table = defaultDecoderTable(decoders); return { ...table, byTransferSyntax: new Map([ ...table.byTransferSyntax, - [codec, [decoder, gdcm]], + [codec, [decoder, decoders.gdcm]], ]), }; }, diff --git a/src/dicom/core/volume/__tests__/loadVolume.spec.ts b/src/dicom/core/volume/__tests__/loadVolume.spec.ts index c777106d7..65e3ad6c7 100644 --- a/src/dicom/core/volume/__tests__/loadVolume.spec.ts +++ b/src/dicom/core/volume/__tests__/loadVolume.spec.ts @@ -424,7 +424,7 @@ describe('loadVolume', () => { const runtime = createDicomRuntime( { assets: { pipelineWorkerUrl: '/unused', imageIOUrl: '/unused' }, - decoders: singleDecoderTable, + decoders: ({ gdcm }) => singleDecoderTable(gdcm), decodeConcurrency: 1, }, hangingLane diff --git a/tests/dicomVolumeCorpus.json b/tests/dicomVolumeCorpus.json index c3a87a3f6..926036ef4 100644 --- a/tests/dicomVolumeCorpus.json +++ b/tests/dicomVolumeCorpus.json @@ -1544,6 +1544,108 @@ "spacing": [1.0, 1.0] } }, + { + "id": "pydicom-data-HTJ2KLossless_08_RGB", + "name": "dicom-corpus-pydicom-data-HTJ2KLossless_08_RGB.dcm", + "url": "https://github.com/pydicom/pydicom-data/raw/9bde4d24b2d4a666fa8c4e93c8bccb2a775ea536/data_store/data/HTJ2KLossless_08_RGB.dcm", + "sha256": "38f8e8adf46b928a12f1905df1405bc8a32c10286733c47562c75be84ceae00e", + "bytes": 393228, + "license": "MIT", + "attribution": "pydicom-data contributors; file provenance in the pydicom-data README", + "sourcePage": "https://github.com/pydicom/pydicom-data", + "quirk": "HTJ2K Lossless RGB secondary capture, reversible colour transform, no geometry", + "facts": { + "sopClassUID": "1.2.840.10008.5.1.4.1.1.7", + "modality": "", + "transferSyntaxUID": "1.2.840.10008.1.2.4.201", + "filePreamble": true, + "pixels": true, + "photometricInterpretation": "RGB", + "frames": { + "numberOfFrames": 1, + "frameIncrementPointer": [], + "numberOfSlices": null, + "numberOfTimeSlots": null, + "temporalDimension": false + }, + "frameAxis": "space", + "geometryTags": { + "frameOfReference": false, + "imagePosition": null, + "imageOrientation": null, + "pixelSpacing": null, + "sliceSpacing": [], + "ultrasoundRegions": 0, + "ophthalmicFrameLocation": false + }, + "volume": { + "dimensions": [640, 480, 1], + "pixels": { + "kind": "hash", + "value": "9580c6ea228c756b842724bbdaa8f3b32de1535c10b28074b6d5b1daf4de1248" + } + }, + "reference": "manual", + "referenceNote": "highdicom: RuntimeError: Image does not exist within a frame-of-reference coordinate system." + }, + "module": { + "outcome": "volume", + "fallbackGeometry": true, + "spacing": [1.0, 1.0] + } + }, + { + "id": "pydicom-data-HTJ2K_08_RGB", + "name": "dicom-corpus-pydicom-data-HTJ2K_08_RGB.dcm", + "url": "https://github.com/pydicom/pydicom-data/raw/9bde4d24b2d4a666fa8c4e93c8bccb2a775ea536/data_store/data/HTJ2K_08_RGB.dcm", + "sha256": "9a7ae1960f18315c4d58876c2a8333a704e89ca3697edd5b69f600773220eb90", + "bytes": 235614, + "license": "MIT", + "attribution": "pydicom-data contributors; file provenance in the pydicom-data README", + "sourcePage": "https://github.com/pydicom/pydicom-data", + "quirk": "HTJ2K lossy RGB secondary capture, irreversible colour transform, no geometry", + "facts": { + "sopClassUID": "1.2.840.10008.5.1.4.1.1.7", + "modality": "", + "transferSyntaxUID": "1.2.840.10008.1.2.4.203", + "filePreamble": true, + "pixels": true, + "photometricInterpretation": "RGB", + "frames": { + "numberOfFrames": 1, + "frameIncrementPointer": [], + "numberOfSlices": null, + "numberOfTimeSlots": null, + "temporalDimension": false + }, + "frameAxis": "space", + "geometryTags": { + "frameOfReference": false, + "imagePosition": null, + "imageOrientation": null, + "pixelSpacing": null, + "sliceSpacing": [], + "ultrasoundRegions": 0, + "ophthalmicFrameLocation": false + }, + "volume": { + "dimensions": [640, 480, 1], + "pixels": { + "kind": "stats", + "min": [64.0, 10.0, 0.0], + "max": [255.0, 255.0, 248.0], + "mean": [166.2931, 132.6156, 82.4031] + } + }, + "reference": "manual", + "referenceNote": "highdicom: RuntimeError: Image does not exist within a frame-of-reference coordinate system." + }, + "module": { + "outcome": "volume", + "fallbackGeometry": true, + "spacing": [1.0, 1.0] + } + }, { "id": "generated-oct-positioned", "name": "dicom-corpus-generated-oct-positioned.dcm", @@ -2172,6 +2274,55 @@ "fallbackGeometry": true, "spacing": [1.0, 1.0] } + }, + { + "id": "generated-htj2k-signed-frames", + "name": "dicom-corpus-generated-htj2k-signed-frames.dcm", + "generator": "htj2k-signed-frames", + "license": "generated", + "attribution": "tests/fixtures/dicom-pages/htj2kCorpus.ts", + "sourcePage": null, + "quirk": "HTJ2K Lossless, three signed 12 bit frames in 16 bit words, no geometry", + "facts": { + "sopClassUID": "1.2.840.10008.5.1.4.1.1.7.3", + "modality": "OT", + "transferSyntaxUID": "1.2.840.10008.1.2.4.201", + "filePreamble": true, + "pixels": true, + "photometricInterpretation": "MONOCHROME2", + "frames": { + "numberOfFrames": 3, + "frameIncrementPointer": [], + "numberOfSlices": null, + "numberOfTimeSlots": null, + "temporalDimension": false + }, + "frameAxis": "space", + "geometryTags": { + "frameOfReference": false, + "imagePosition": null, + "imageOrientation": null, + "pixelSpacing": null, + "sliceSpacing": [], + "ultrasoundRegions": 0, + "ophthalmicFrameLocation": false + }, + "volume": { + "dimensions": [64, 48, 3], + "range": [-2048.0, 2047.0], + "pixels": { + "kind": "hash", + "value": "d0ed23ce456e27fdbd53596a250f69f22ec1e444d01d32d2f57ae19e69a65b80" + } + }, + "reference": "manual", + "referenceNote": "highdicom: RuntimeError: Image does not exist within a frame-of-reference coordinate system." + }, + "module": { + "outcome": "volume", + "fallbackGeometry": true, + "spacing": [1.0, 1.0] + } } ] } diff --git a/tests/fixtures/dicom-pages/generatedCorpus.ts b/tests/fixtures/dicom-pages/generatedCorpus.ts index 9c1700e28..83d8d5918 100644 --- a/tests/fixtures/dicom-pages/generatedCorpus.ts +++ b/tests/fixtures/dicom-pages/generatedCorpus.ts @@ -1,6 +1,7 @@ import reference from '../oct/reference.json'; import { createSyntheticOCT, element, syntheticScalars } from '../oct/dicom'; import { part10File } from '../../specs/syntheticDicom'; +import { htj2kSignedFrames } from './htj2kCorpus'; const [width, depth, frames] = reference.size; const [sx] = reference.spacing; @@ -54,7 +55,10 @@ function encapsulatedPdf() { } /** Corpus files built in memory, keyed by the manifest's `generator`. */ -export const GENERATED_CORPUS: Record Uint8Array> = { +export const GENERATED_CORPUS: Record< + string, + () => Uint8Array | Promise +> = { 'oct-positioned': () => createSyntheticOCT(), 'oct-slice-thickness-only': () => createSyntheticOCT({ @@ -86,6 +90,7 @@ export const GENERATED_CORPUS: Record Uint8Array> = { scalars: bScans(1), }), 'encapsulated-pdf': encapsulatedPdf, + 'htj2k-signed-frames': htj2kSignedFrames, }; export const generatedName = (generator: string) => diff --git a/tests/fixtures/dicom-pages/htj2kCorpus.ts b/tests/fixtures/dicom-pages/htj2kCorpus.ts new file mode 100644 index 000000000..6710fac95 --- /dev/null +++ b/tests/fixtures/dicom-pages/htj2kCorpus.ts @@ -0,0 +1,77 @@ +import createOpenJph from '@cornerstonejs/codec-openjph'; +import { element } from '../oct/dicom'; +import { + combine, + elementHeader, + encapsulatedPixelData, + part10File, + rawElement, +} from '../../specs/syntheticDicom'; + +const HTJ2K_LOSSLESS = '1.2.840.10008.1.2.4.201'; +const MULTIFRAME_WORD_SC = '1.2.840.10008.5.1.4.1.1.7.3'; +const [columns, rows, frames] = [64, 48, 3]; +const bitsStored = 12; + +const us = (tag: string, value: number) => + rawElement( + parseInt(tag.slice(0, 4), 16), + parseInt(tag.slice(4), 16), + 'US', + new Uint8Array(Uint16Array.of(value).buffer) + ); + +/** Signed 12 bit samples spanning the whole stored range, distinct per frame. */ +const frameSamples = (frame: number) => + Int16Array.from({ length: columns * rows }, (_, index) => { + const x = index % columns; + const y = Math.floor(index / columns); + return ((x * 61 + y * 17 + frame * 997) % 4096) - 2048; + }); + +async function encodeFrames() { + const openJph = await createOpenJph(); + return Array.from({ length: frames }, (_, frame) => { + const encoder = new openJph.HTJ2KEncoder(); + try { + encoder + .getDecodedBuffer({ + width: columns, + height: rows, + bitsPerSample: bitsStored, + componentCount: 1, + isSigned: true, + isUsingColorTransform: false, + }) + .set(new Uint8Array(frameSamples(frame).buffer)); + encoder.encode(); + return [encoder.getEncodedBuffer().slice()]; + } finally { + encoder.delete(); + } + }); +} + +/** Three signed 12 bit frames, losslessly HTJ2K encoded, with no geometry. */ +export async function htj2kSignedFrames() { + const sopInstance = '1.2.826.0.1.3680043.10.999.3.3'; + const dataset = combine( + element('00080016', 'UI', MULTIFRAME_WORD_SC), + element('00080018', 'UI', sopInstance), + element('00080060', 'CS', 'OT'), + element('0020000d', 'UI', '1.2.826.0.1.3680043.10.999.3.1'), + element('0020000e', 'UI', '1.2.826.0.1.3680043.10.999.3.2'), + us('00280002', 1), + element('00280004', 'CS', 'MONOCHROME2'), + element('00280008', 'IS', String(frames)), + us('00280010', rows), + us('00280011', columns), + us('00280100', 16), + us('00280101', bitsStored), + us('00280102', bitsStored - 1), + us('00280103', 1), + elementHeader(0x7fe0, 0x0010, 'OB', 0xffffffff), + encapsulatedPixelData({ frames: await encodeFrames() }) + ); + return part10File(MULTIFRAME_WORD_SC, sopInstance, HTJ2K_LOSSLESS, dataset); +} diff --git a/tests/fixtures/dicom-pages/shared.ts b/tests/fixtures/dicom-pages/shared.ts index 9821b15b2..b23e6d75f 100644 --- a/tests/fixtures/dicom-pages/shared.ts +++ b/tests/fixtures/dicom-pages/shared.ts @@ -6,6 +6,7 @@ import { fromBlob, fromUrl } from '@/src/dicom/core/source/byteSource'; import { planDecode, singleDecoderTable, + type RuntimeDecoders, } from '@/src/dicom/core/pixels/decoderTable'; import type { Instance } from '@/src/dicom/core/instance/readInstance'; @@ -30,7 +31,9 @@ export const runtime = createRuntime(); export const never = new AbortController().signal; /** Runtime options that send every instance whole to GDCM. */ -export const gdcmOnly = { decoders: singleDecoderTable }; +export const gdcmOnly = { + decoders: ({ gdcm }: RuntimeDecoders) => singleDecoderTable(gdcm), +}; /** The first unit `decoding`'s table plans for an instance. */ export function firstUnit( diff --git a/tests/fixtures/dicom-pages/writeGeneratedCorpus.ts b/tests/fixtures/dicom-pages/writeGeneratedCorpus.ts index 343a914f4..118472004 100644 --- a/tests/fixtures/dicom-pages/writeGeneratedCorpus.ts +++ b/tests/fixtures/dicom-pages/writeGeneratedCorpus.ts @@ -10,6 +10,6 @@ import { GENERATED_CORPUS, generatedName } from './generatedCorpus'; mkdirSync(DATASET_CACHE, { recursive: true }); for (const [generator, build] of Object.entries(GENERATED_CORPUS)) { const path = join(DATASET_CACHE, generatedName(generator)); - writeFileSync(path, build()); + writeFileSync(path, await build()); console.log(path); } diff --git a/tests/specs/dicom-corpus-app.e2e.ts b/tests/specs/dicom-corpus-app.e2e.ts index 23b2d246b..a97ed11ee 100644 --- a/tests/specs/dicom-corpus-app.e2e.ts +++ b/tests/specs/dicom-corpus-app.e2e.ts @@ -3,7 +3,23 @@ import volumeCorpus from '../dicomVolumeCorpus.json'; import { DATASET_CACHE } from '../downloadDatasets'; import { volViewPage } from '../pageobjects/volview.page'; import { waitForRenderedSlice } from './dicomRenderedSlice'; -import { dropFiles } from './utils'; +import { captureViewPixels, dropFiles } from './utils'; + +// Undecoded slices render black; chroma can only come from the image. +const colorFraction = async (fileName: string) => { + const [view] = await captureViewPixels( + '[data-testid~="vtk-two-view"]', + 80, + fileName + ); + const { data } = view; + let colored = 0; + for (let index = 0; index < data.length; index += 4) { + const channels = [data[index], data[index + 1], data[index + 2]]; + if (Math.max(...channels) - Math.min(...channels) > 32) colored++; + } + return colored / (data.length / 4); +}; const corpusFile = (id: string) => { const entry = volumeCorpus.datasets.find((dataset) => dataset.id === id); @@ -22,6 +38,19 @@ describe('Corpus files in the application', () => { expect(await volViewPage.getNotificationsCount()).toBe(0); }); + it('renders an HTJ2K image', async () => { + const name = corpusFile('pydicom-data-HTJ2KLossless_08_RGB'); + await volViewPage.open(`?urls=[tmp/${name}]`); + await volViewPage.waitForVolumeCardSliceCounts([1]); + await volViewPage.waitForViewsLoaded(); + await $('header').moveTo(); + await browser.waitUntil( + async () => (await colorFraction(`${name}.png`)) > 0.5, + { timeoutMsg: 'Expected the decoded colour image in the slice view' } + ); + expect(await volViewPage.getNotificationsCount()).toBe(0); + }); + it('loads the images of a drop that also holds a structured report', async () => { const report = corpusFile('pydicom-test-SR'); const image = corpusFile('pydicom-CT_small'); diff --git a/tests/specs/dicom-volume-corpus.e2e.ts b/tests/specs/dicom-volume-corpus.e2e.ts index 92d92f55c..e13937d21 100644 --- a/tests/specs/dicom-volume-corpus.e2e.ts +++ b/tests/specs/dicom-volume-corpus.e2e.ts @@ -143,7 +143,11 @@ describe('Public DICOM volume corpus', () => { let fixture: Awaited>; before(async () => { const files = Object.fromEntries( - [...corpus, ...available].map((entry) => [entry.name, bytesOf(entry)]) + await Promise.all( + [...corpus, ...available].map( + async (entry) => [entry.name, await bytesOf(entry)] as const + ) + ) ); fixture = await startDicomPages({ kinds: ['corpus'], diff --git a/tests/specs/syntheticDicom.ts b/tests/specs/syntheticDicom.ts index 25c99f5ef..87aaa4375 100644 --- a/tests/specs/syntheticDicom.ts +++ b/tests/specs/syntheticDicom.ts @@ -51,7 +51,7 @@ export const LONG_FORM_VRS = new Set( 'OB OD OF OL OV OW SQ SV UC UN UR UT'.split(' ') ); -const elementHeader = ( +export const elementHeader = ( group: number, element: number, vr: string,