Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
9 changes: 6 additions & 3 deletions src/dicom/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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.
Expand Down Expand Up @@ -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

Expand Down
19 changes: 17 additions & 2 deletions src/dicom/core/pixels/__tests__/decoderTable.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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) => {
Expand Down
25 changes: 19 additions & 6 deletions src/dicom/core/pixels/decoderTable.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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]> = [
Expand Down Expand Up @@ -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 {
Expand Down
21 changes: 21 additions & 0 deletions src/dicom/core/pixels/htj2k.worker.ts
Original file line number Diff line number Diff line change
@@ -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<OpenJphModule> | 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);
61 changes: 61 additions & 0 deletions src/dicom/core/pixels/htj2kFrames.ts
Original file line number Diff line number Diff line change
@@ -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 };
}
37 changes: 37 additions & 0 deletions src/dicom/core/pixels/openjph.d.ts
Original file line number Diff line number Diff line change
@@ -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<OpenJphModule>;
export default createOpenJph;
}
28 changes: 19 additions & 9 deletions src/dicom/core/runtime/createDicomRuntime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
};
Expand All @@ -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 ??
Expand All @@ -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);
Expand All @@ -76,6 +82,7 @@ export function createDicomRuntime(
requests.dispose(reason);
metadata.dispose(reason);
gdcm.dispose(reason);
htj2k.dispose(reason);
};

return {
Expand All @@ -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,
Expand Down
Loading
Loading