Add scoped DICOM series previews with 3D volume and MPR views

This commit is contained in:
SantaSpeen committed 2026-10-22 21:06:46 +03:00
1 parent 7371c29111
commit 6d8faa7d03
23 files changed
+1479 -20

No files matched your search

@@ -0,0 +1,65 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import * as files from "@/api/files";
import * as pub from "@/api/pub";
import { findDicomSeries } from "../dicom-context";
vi.mock("@/api/files", () => ({
fetch: vi.fn(),
getDownloadURL: (item: ResourceItem) => `/api/raw${item.path}`,
}));
vi.mock("@/api/pub", () => ({
fetch: vi.fn(),
getDownloadURL: (item: Resource) =>
`/api/public/dl/${item.hash}${item.path}?token=${item.token}`,
}));
const listing = {
isDir: true,
items: [1, 2].map((i) => ({
name: `scan_${i}.dcm`,
path: `/scan_${i}.dcm`,
size: 400,
})),
} as Resource;
beforeEach(() => vi.clearAllMocks());
describe("DICOM scope", () => {
it("loads authenticated siblings from the same folder", async () => {
vi.mocked(files.fetch).mockResolvedValue(listing);
const signal = new AbortController().signal;
const series = await findDicomSeries(
{ name: "scan_1.dcm", path: "/CT/scan_1.dcm" } as Resource,
signal
);
expect(files.fetch).toHaveBeenCalledWith("/files/CT/", signal);
expect(pub.fetch).not.toHaveBeenCalled();
expect(series).toHaveLength(2);
});
it("keeps protected public series inside their share and retains the token", async () => {
vi.mocked(pub.fetch).mockResolvedValue(listing);
const signal = new AbortController().signal;
const series = await findDicomSeries(
{
name: "scan_1.dcm",
path: "/scan_1.dcm",
hash: "public",
token: "secret",
} as Resource,
signal
);
expect(pub.fetch).toHaveBeenCalledWith("/s/public/", "", {
signal,
token: "secret",
});
expect(files.fetch).not.toHaveBeenCalled();
expect(series[0].source).toBe(
"/api/public/dl/public/scan_1.dcm?token=secret"
);
});
it("never looks for siblings of a single-file public share", async () => {
const series = await findDicomSeries(
{ name: "scan_1.dcm", path: "/", hash: "file" } as Resource,
new AbortController().signal
);
expect(series).toEqual([]);
expect(files.fetch).not.toHaveBeenCalled();
expect(pub.fetch).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,133 @@
import { describe, expect, it, vi } from "vitest";
import {
assembleVolume,
dicomSeries,
MAX_VOLUME_BYTES,
type DicomSlice,
} from "../dicom-series";
import { fixture } from "./fixtures/dicom";
const entry = (name: string, isDir = false) => ({
name,
source: `/${name}`,
size: 100,
isDir,
});
const slice = (z: number): DicomSlice => ({
study: "study",
series: "series",
reference: "frame",
instance: `sop-${z}`,
modality: "CT",
rows: 2,
cols: 2,
orientation: [1, 0, 0, 0, 1, 0],
position: [0, 0, z],
spacing: [0.5, 0.75],
pixels: new Float32Array([z, -1000, 0, 2000]),
center: 0,
width: 4000,
});
describe("DICOM series", () => {
it("offers a single numbered series, sorted numerically, without reading files", () => {
expect(
dicomSeries("scan_10.dcm", [
entry("scan_10.dcm"),
entry("scan_2.dcm"),
entry("subdir", true),
]).map((s) => s.name)
).toEqual(["scan_2.dcm", "scan_10.dcm"]);
});
it("does not offer mixed folders, duplicate indices, unrelated or solitary files", () => {
for (const names of [
["scan_1.dcm"],
["scan_1.dcm", "notes.txt"],
["scan_1.dcm", "other_2.dcm"],
["scan_1.dcm", "scan_01.dcm"],
["scan_1.dcm", "scan_999999999999999999.dcm"],
]) {
expect(
dicomSeries(
"scan_1.dcm",
names.map((n) => entry(n))
)
).toEqual([]);
}
expect(
dicomSeries("missing_1.dcm", [entry("scan_1.dcm"), entry("scan_2.dcm")])
).toEqual([]);
});
it("orders by patient coordinates, preserves physical spacing and CT values", () => {
const volume = assembleVolume([slice(2), slice(0), slice(1)]);
expect(volume.dimensions).toEqual([2, 2, 3]);
expect(volume.spacing).toEqual([0.75, 0.5, 1]);
expect(volume.origin).toEqual([0, 0, 0]);
expect(Array.from(volume.scalarData)).toEqual([
0, -1000, 0, 2000, 1, -1000, 0, 2000, 2, -1000, 0, 2000,
]);
});
it("rejects mixed studies/series, duplicates, gaps, tilt and invalid spacing", () => {
for (const change of [
{ study: "another" },
{ series: "another" },
{ reference: "another" },
{ instance: "sop-0" },
{ position: [0, 0, 0] },
{ position: [1, 0, 1] },
{ spacing: [0, 1] },
{ orientation: [1, 0, 0, 1, 0, 0] },
{ position: [0, 0, NaN] },
]) {
expect(() =>
assembleVolume([slice(0), { ...slice(1), ...change }, slice(2)])
).toThrow("DICOM_GEOMETRY");
}
expect(() => assembleVolume([slice(0), slice(1), slice(3)])).toThrow(
"DICOM_GEOMETRY"
);
});
it("rejects excessive allocations before allocating a volume", () => {
expect(MAX_VOLUME_BYTES).toBe(128 * 1024 * 1024);
expect(() =>
assembleVolume([
{ ...slice(0), rows: 4096, cols: 4096 },
{ ...slice(1), rows: 4096, cols: 4096 },
{ ...slice(2), rows: 4096, cols: 4096 },
])
).toThrow("DICOM_VOLUME_LIMIT");
});
it("decodes real DICOM slices and validates their geometry", async () => {
const replies: { slice?: DicomSlice; error?: string }[] = [];
const scope = {
postMessage: (data: (typeof replies)[number]) => replies.push(data),
onmessage: null as unknown as (event: { data: object }) => void,
};
vi.stubGlobal("self", scope);
vi.resetModules();
try {
await import("../dicom.worker");
for (const z of [2, 0, 1])
scope.onmessage({
data: {
id: z,
mode: "volumeSlice",
buffer: fixture(16, { slice: z }),
},
});
expect(replies.map((r) => r.error)).toEqual([
undefined,
undefined,
undefined,
]);
const volume = assembleVolume(replies.map((r) => r.slice!));
expect(volume.spacing).toEqual([0.75, 0.5, 1]);
expect(volume.scalarData[0]).toBe(-2048);
scope.onmessage({
data: { id: 4, mode: "volumeSlice", buffer: fixture() },
});
expect(replies.at(-1)?.error).toBe("DICOM_GEOMETRY");
} finally {
vi.unstubAllGlobals();
}
});
});
+17 -2
View File
@@ -1,6 +1,11 @@
export function fixture(
bits = 16,
options: { charset?: string; patientBytes?: number[] } = {}
options: {
charset?: string;
patientBytes?: number[];
slice?: number;
series?: string;
} = {}
) {
const data: number[] = [...new Uint8Array(128), 68, 73, 67, 77];
const add = (group: number, element: number, vr: string, bytes: number[]) => {
@@ -23,13 +28,23 @@ export function fixture(
if (options.charset) add(8, 5, "CS", text(options.charset));
add(8, 0x20, "DA", text("20261022"));
add(8, 0x60, "CS", text("CT"));
if (options.slice != null)
add(8, 0x18, "UI", text(`1.2.3.${options.slice + 1}`));
add(0x10, 0x10, "PN", options.patientBytes || text("Example^Patient"));
add(0x10, 0x20, "LO", text("TEST-123"));
if (options.slice != null) {
add(0x20, 0x0d, "UI", text("1.2.3"));
add(0x20, 0x0e, "UI", text(options.series || "1.2.3.4"));
add(0x20, 0x32, "DS", text(`0\\0\\${options.slice}`));
add(0x20, 0x37, "DS", text("1\\0\\0\\0\\1\\0"));
add(0x20, 0x52, "UI", text("1.2.3.5"));
}
add(0x28, 2, "US", [1, 0]);
add(0x28, 4, "CS", text("MONOCHROME2"));
add(0x28, 8, "IS", text("2"));
add(0x28, 8, "IS", text(options.slice == null ? "2" : "1"));
add(0x28, 0x10, "US", [2, 0]);
add(0x28, 0x11, "US", [2, 0]);
if (options.slice != null) add(0x28, 0x30, "DS", text("0.5\\0.75"));
add(0x28, 0x100, "US", [bits, 0]);
add(0x28, 0x101, "US", [12, 0]);
add(0x28, 0x102, "US", [11, 0]);
+42
View File
@@ -0,0 +1,42 @@
import * as files from "@/api/files";
import * as pub from "@/api/pub";
import { encodePath } from "./url";
import { dicomSeries } from "./dicom-series";
export async function findDicomSeries(resource: Resource, signal: AbortSignal) {
if (
!/^.+_\d+\.dcm$/i.test(resource.name) ||
!resource.path ||
resource.path === "/"
)
return [];
const parent =
resource.path.slice(0, resource.path.lastIndexOf("/") + 1) || "/";
const listing = resource.hash
? await pub.fetch(
`/s/${encodeURIComponent(resource.hash)}${encodePath(parent)}`,
"",
{ signal, token: resource.token }
)
: await files.fetch(`/files${encodePath(parent)}`, signal);
if (!listing.isDir) return [];
return dicomSeries(
resource.name,
listing.items.map((item) => ({
name: item.name,
size: item.size,
isDir: item.isDir,
source: resource.hash
? pub.getDownloadURL(
{
...listing,
path: item.path,
hash: resource.hash,
token: resource.token,
},
true
)
: files.getDownloadURL(item, true),
}))
);
}
+3 -1
View File
@@ -2,8 +2,10 @@ export async function readDicomFile(source: string, signal: AbortSignal) {
const response = await fetch(source, { credentials: "same-origin", signal });
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const limit = 64 * 1024 * 1024;
if (Number(response.headers.get("Content-Length")) > limit)
if (Number(response.headers.get("Content-Length")) > limit) {
await response.body?.cancel();
throw new Error("DICOM_TOO_LARGE");
}
const reader = response.body?.getReader();
if (!reader) throw new Error("Empty response");
const chunks: Uint8Array[] = [];
+155
View File
@@ -0,0 +1,155 @@
export interface DicomSource {
name: string;
source: string;
size: number;
isDir?: boolean;
}
export const MAX_VOLUME_BYTES = 128 * 1024 * 1024;
export const MAX_SERIES_FILES = 2048;
// Names only trigger the offer. Patient-space geometry is checked after consent.
export function dicomSeries(
name: string,
entries: DicomSource[]
): DicomSource[] {
const match = /^(.*)_(\d+)\.dcm$/i.exec(name);
const files = entries.filter((entry) => !entry.isDir);
if (!match || files.length < 2 || files.length > MAX_SERIES_FILES) return [];
const numbered = files.map((entry) => ({
entry,
match: /^(.*)_(\d+)\.dcm$/i.exec(entry.name),
}));
if (
!files.some((entry) => entry.name === name) ||
numbered.some(({ match: part }) => !part || part[1] !== match[1])
)
return [];
const indices = numbered.map(({ match: part }) => Number(part![2]));
if (
!indices.every(Number.isSafeInteger) ||
new Set(indices).size !== files.length
)
return [];
return numbered
.sort((a, b) => Number(a.match![2]) - Number(b.match![2]))
.map(({ entry }) => entry);
}
export interface DicomSlice {
study: string;
series: string;
reference: string;
instance: string;
modality: string;
rows: number;
cols: number;
orientation: number[];
position: number[];
spacing: number[];
pixels: Float32Array;
center: number;
width: number;
}
const dot = (a: number[], b: number[]) =>
a.reduce((n, v, i) => n + v * b[i], 0);
const close = (a: number[], b: number[], tolerance = 1e-4) =>
a.length === b.length && a.every((v, i) => Math.abs(v - b[i]) <= tolerance);
export function checkSlice(slice: DicomSlice, first = slice) {
if (
!slice.study ||
!slice.series ||
!slice.reference ||
!slice.instance ||
!Number.isFinite(slice.center) ||
!Number.isFinite(slice.width) ||
slice.width < 1 ||
slice.study !== first.study ||
slice.series !== first.series ||
slice.reference !== first.reference ||
slice.rows !== first.rows ||
slice.cols !== first.cols ||
![slice.rows, slice.cols].every(
(v) => Number.isSafeInteger(v) && v > 0 && v <= 4096
) ||
slice.pixels.length !== slice.rows * slice.cols ||
slice.orientation.length !== 6 ||
slice.position.length !== 3 ||
slice.spacing.length !== 2 ||
![...slice.orientation, ...slice.position, ...slice.spacing].every(
Number.isFinite
) ||
slice.spacing.some((v) => v <= 0) ||
!close(slice.orientation, first.orientation) ||
!close(slice.spacing, first.spacing) ||
Math.abs(dot(slice.orientation.slice(0, 3), slice.orientation.slice(3))) >
1e-4 ||
Math.abs(
dot(slice.orientation.slice(0, 3), slice.orientation.slice(0, 3)) - 1
) > 1e-4 ||
Math.abs(dot(slice.orientation.slice(3), slice.orientation.slice(3)) - 1) >
1e-4
)
throw new Error("DICOM_GEOMETRY");
}
export function assembleVolume(slices: DicomSlice[]) {
if (slices.length < 2 || slices.length > MAX_SERIES_FILES)
throw new Error("DICOM_GEOMETRY");
const first = slices[0];
const size = first.rows * first.cols * slices.length;
if (!Number.isSafeInteger(size) || size * 4 > MAX_VOLUME_BYTES)
throw new Error("DICOM_VOLUME_LIMIT");
slices.forEach((slice) => checkSlice(slice, first));
if (new Set(slices.map((s) => s.instance)).size !== slices.length)
throw new Error("DICOM_GEOMETRY");
const x = first.orientation.slice(0, 3),
y = first.orientation.slice(3);
const z = [
x[1] * y[2] - x[2] * y[1],
x[2] * y[0] - x[0] * y[2],
x[0] * y[1] - x[1] * y[0],
];
const ordered = [...slices].sort(
(a, b) => dot(a.position, z) - dot(b.position, z)
);
const origin = ordered[0].position;
const step =
(dot(ordered.at(-1)!.position, z) - dot(origin, z)) / (ordered.length - 1);
if (step < 0.001 || step > 100) throw new Error("DICOM_GEOMETRY");
ordered.forEach((slice, i) => {
// Reject missing/duplicate slices, gantry tilt and shifted acquisitions.
const expected = origin.map((v, j) => v + z[j] * step * i);
if (!close(slice.position, expected, Math.max(0.01, step * 0.01)))
throw new Error("DICOM_GEOMETRY");
});
const scalarData = new Float32Array(size);
ordered.forEach((slice, i) =>
scalarData.set(slice.pixels, i * first.cols * first.rows)
);
return {
scalarData,
dimensions: [first.cols, first.rows, slices.length] as [
number,
number,
number,
],
spacing: [first.spacing[1], first.spacing[0], step] as [
number,
number,
number,
],
origin: [...origin] as [number, number, number],
direction: [...x, ...y, ...z] as [
number,
number,
number,
number,
number,
number,
number,
number,
number,
],
first,
};
}
export type DicomVolume = ReturnType<typeof assembleVolume>;
+74
View File
@@ -0,0 +1,74 @@
import DicomWorker from "./dicom.worker?worker";
import { readDicomFile } from "./dicom-file";
import {
assembleVolume,
checkSlice,
MAX_VOLUME_BYTES,
MAX_SERIES_FILES,
type DicomSlice,
type DicomSource,
} from "./dicom-series";
export async function loadDicomVolume(
sources: DicomSource[],
signal: AbortSignal,
progress: (loaded: number) => void
) {
if (sources.length < 2 || sources.length > MAX_SERIES_FILES)
throw new Error("DICOM_VOLUME_LIMIT");
if (
sources.some((s) => s.size > 64 * 1024 * 1024) ||
sources.reduce((n, s) => n + s.size, 0) > 512 * 1024 * 1024
)
throw new Error("DICOM_VOLUME_LIMIT");
const worker = new DicomWorker();
const slices: DicomSlice[] = [];
let bytes = 0;
try {
for (const source of sources) {
if (signal.aborted) throw new DOMException("Aborted", "AbortError");
const buffer = await readDicomFile(source.source, signal);
if (signal.aborted) throw new DOMException("Aborted", "AbortError");
bytes += buffer.byteLength;
if (bytes > 512 * 1024 * 1024) throw new Error("DICOM_VOLUME_LIMIT");
const slice = await new Promise<DicomSlice>((resolve, reject) => {
const cleanup = () => {
clearTimeout(timeout);
signal.removeEventListener("abort", abort);
worker.onmessage = null;
worker.onerror = null;
};
const fail = (error: unknown) => {
cleanup();
reject(error);
};
const abort = () => fail(new DOMException("Aborted", "AbortError"));
const timeout = setTimeout(
() => fail(new Error("DICOM_DECODE_TIMEOUT")),
30000
);
signal.addEventListener("abort", abort, { once: true });
worker.onerror = () => fail(new Error("DICOM_DECODE"));
worker.onmessage = ({ data }) => {
if (data.error) fail(new Error(data.error));
else {
cleanup();
resolve(data.slice);
}
};
worker.postMessage({ id: slices.length, buffer, mode: "volumeSlice" }, [
buffer,
]);
});
checkSlice(slice, slices[0] || slice);
if (slice.pixels.byteLength * sources.length > MAX_VOLUME_BYTES)
throw new Error("DICOM_VOLUME_LIMIT");
slices.push(slice);
progress(slices.length);
}
if (signal.aborted) throw new DOMException("Aborted", "AbortError");
return assembleVolume(slices);
} finally {
worker.terminate();
}
}
+44
View File
@@ -111,6 +111,50 @@ self.onmessage = (event: MessageEvent) => {
defaultCenter =
image.getWindowWidth() > 0 ? image.getWindowCenter() : (min + max) / 2;
}
if (mode === "volumeSlice") {
if (
frames !== 1 ||
samples !== 1 ||
!Number.isFinite(slope) ||
!Number.isFinite(intercept)
)
throw new Error("DICOM_GEOMETRY");
const tag = (group: number, element: number) => {
const value = Object.values(image.tags).find(
(t) => t.group === group && t.element === element
)?.value;
return Array.isArray(value) ? value : value == null ? [] : [value];
};
const uid = (element: number) =>
String(tag(0x20, element)[0] || "").trim();
const pixels = new Float32Array(cols * rows);
for (let i = 0; i < pixels.length; i++) {
pixels[i] = pixel(i);
if (!Number.isFinite(pixels[i])) throw new Error("DICOM_GEOMETRY");
}
self.postMessage(
{
id,
slice: {
study: uid(0x0d),
series: uid(0x0e),
reference: uid(0x52),
instance: String(tag(8, 0x18)[0] || "").trim(),
modality: String(tag(8, 0x60)[0] || ""),
position: tag(0x20, 0x32).map(Number),
orientation: tag(0x20, 0x37).map(Number),
spacing: tag(0x28, 0x30).map(Number),
rows,
cols,
pixels,
center: defaultCenter,
width: defaultWidth,
},
},
{ transfer: [pixels.buffer] }
);
return;
}
if (!raw || !Number.isInteger(frame) || frame < 0 || frame >= frames)
throw new Error("Invalid DICOM frame");
const rgba = new Uint8ClampedArray(cols * rows * 4);