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

+7 -2
View File
@@ -1,12 +1,17 @@
import { fetchURL, removePrefix, createURL } from "./utils";
import { baseURL } from "@/utils/constants";
export async function fetch(url: string, password: string = "") {
export async function fetch(
url: string,
password: string = "",
options: { signal?: AbortSignal; token?: string } = {}
) {
url = removePrefix(url);
const res = await fetchURL(
`/api/public/share${url}`,
`/api/public/share${url}${options.token ? `?token=${encodeURIComponent(options.token)}` : ""}`,
{
signal: options.signal,
headers: { "X-SHARE-PASSWORD": encodeURIComponent(password) },
},
false
+119 -5
View File
@@ -7,7 +7,21 @@
>
<div class="document-tools">
<strong>DICOM</strong>
<template v-if="ready">
<button
v-if="series.length && !volume && !volumeLoading"
class="button button--flat"
@click="openVolume"
>
{{ t("documents.open3d") }} ({{ series.length }})
</button>
<button
v-if="volume || volumeLoading"
class="button button--flat"
@click="closeVolume"
>
{{ t("documents.back2d") }}
</button>
<template v-if="ready && !volume && !volumeLoading">
<label
>{{ t("documents.frame") }}
<input
@@ -29,9 +43,19 @@
</button>
</template>
</div>
<p v-if="volumeError" role="alert" class="document-error">
{{ volumeError }}
</p>
<p v-if="volumeLoading" role="status">
{{ t("documents.loading3d", { count: loaded, total: series.length }) }}
<button class="button button--flat" @click="closeVolume">
{{ t("buttons.cancel") }}
</button>
</p>
<DicomVolumeViewer v-if="volume" :volume="volume" @failed="volumeFailed" />
<p v-if="error" role="alert" class="document-error">{{ error }}</p>
<p v-else-if="!ready">{{ t("files.loading") }}</p>
<div class="document-stage">
<div v-show="!volume && !volumeLoading" class="document-stage">
<canvas
v-show="ready && !error"
ref="canvas"
@@ -41,12 +65,98 @@
</div>
</template>
<script setup lang="ts">
import { nextTick, onBeforeUnmount, ref, watch } from "vue";
import {
defineAsyncComponent,
nextTick,
onBeforeUnmount,
ref,
shallowRef,
watch,
} from "vue";
import { useI18n } from "vue-i18n";
import DicomWorker from "@/utils/dicom.worker?worker";
import { readDicomFile } from "@/utils/dicom-file";
const props = defineProps<{ source: string }>();
import { findDicomSeries } from "@/utils/dicom-context";
import { loadDicomVolume } from "@/utils/dicom-volume";
import type { DicomSource, DicomVolume } from "@/utils/dicom-series";
const DicomVolumeViewer = defineAsyncComponent({
loader: () => import("./DicomVolumeViewer.vue"),
onError: (_error, _retry, fail) => {
volumeFailed();
fail();
},
});
const props = defineProps<{ source: string; resource?: Resource }>();
const { t } = useI18n();
const series = shallowRef<DicomSource[]>([]),
volume = shallowRef<DicomVolume>();
const volumeLoading = ref(false),
volumeError = ref(""),
loaded = ref(0);
let seriesController: AbortController | undefined,
volumeController: AbortController | undefined;
function closeVolume() {
volumeController?.abort();
volumeController = undefined;
volume.value = undefined;
volumeLoading.value = false;
}
function volumeFailed() {
closeVolume();
volumeError.value = t("documents.volumeUnavailable");
}
async function openVolume() {
closeVolume();
volumeError.value = "";
const probe = document.createElement("canvas");
const gl = probe.getContext("webgl2");
if (!gl) {
volumeFailed();
return;
}
gl.getExtension("WEBGL_lose_context")?.loseContext();
const request = (volumeController = new AbortController());
volumeLoading.value = true;
loaded.value = 0;
try {
const result = await loadDicomVolume(
series.value,
request.signal,
(count) => {
loaded.value = count;
}
);
if (!request.signal.aborted) volume.value = result;
} catch (e) {
if (!request.signal.aborted)
volumeError.value = t(
e instanceof Error &&
["DICOM_VOLUME_LIMIT", "DICOM_TOO_LARGE"].includes(e.message)
? "documents.volumeLimit"
: "documents.volumeInvalid"
);
} finally {
if (volumeController === request) volumeLoading.value = false;
}
}
watch(
() => props.resource,
async (resource) => {
seriesController?.abort();
closeVolume();
volumeError.value = "";
series.value = [];
if (!resource) return;
const request = (seriesController = new AbortController());
try {
const found = await findDicomSeries(resource, request.signal);
if (!request.signal.aborted) series.value = found;
} catch {
/* A file-only share or denied parent must not reveal siblings. */
}
},
{ immediate: true }
);
const canvas = ref<HTMLCanvasElement>();
const ready = ref(false),
error = ref(""),
@@ -159,5 +269,9 @@ watch(
},
{ immediate: true }
);
onBeforeUnmount(stop);
onBeforeUnmount(() => {
stop();
closeVolume();
seriesController?.abort();
});
</script>
@@ -0,0 +1,335 @@
<template>
<div class="dicom-volume">
<div class="document-tools">
<button
v-for="view in views"
:key="view"
class="button button--flat"
:aria-pressed="mode === view"
@click="switchView(view)"
>
{{ view === "3d" ? "3D" : t(`documents.${view}`) }}
</button>
<template>
<label
>{{ t("documents.window") }}
<input v-model.number="width" type="number" min="1"
/></label>
<label
>{{ t("documents.level") }}
<input v-model.number="center" type="number"
/></label>
</template>
<template v-if="mode === '3d'">
<label
>{{ t("documents.opacity") }}
<input
v-model.number="opacity"
type="range"
min="0.05"
max="1"
step="0.05"
/></label>
</template>
<button class="button button--flat" @click="reset">
{{ t("documents.reset") }}
</button>
</div>
<p class="dicom-volume-hint">
{{ t(mode === "3d" ? "documents.volumeHint" : "documents.sliceHint") }}
</p>
<div
ref="element"
class="dicom-volume-stage"
@wheel.prevent="wheel"
@pointerdown="pointerDown"
@pointermove="pointerMove"
@pointerup="pointerUp"
@pointercancel="pointerUp"
@contextmenu.prevent
/>
</div>
</template>
<script setup lang="ts">
import { onMounted, onBeforeUnmount, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import * as core from "@cornerstonejs/core";
import type { DicomVolume } from "@/utils/dicom-series";
const props = defineProps<{ volume: DicomVolume }>();
const emit = defineEmits<{ failed: [] }>();
const { t } = useI18n();
const element = ref<HTMLDivElement>();
const views = ["3d", "axial", "sagittal", "coronal"] as const;
type Mode = (typeof views)[number];
const mode = ref<Mode>("3d"),
center = ref(props.volume.first.center),
width = ref(props.volume.first.width),
opacity = ref(0.3);
const id = `fs-dicom-${crypto.getRandomValues(new Uint32Array(2)).join("-")}`;
const viewportID = `${id}-viewport`;
let engine: InstanceType<typeof core.RenderingEngine> | undefined;
let observer: ResizeObserver | undefined,
disposed = false,
changing = false;
let drag: { id: number; x: number; y: number } | undefined;
let frame = 0;
const viewport = () => engine?.getViewport<core.BaseVolumeViewport>(viewportID);
function schedule() {
if (!frame)
frame = requestAnimationFrame(() => {
frame = 0;
engine?.render();
});
}
function applyWindow() {
if (
Number.isFinite(width.value) &&
width.value >= 1 &&
Number.isFinite(center.value)
) {
viewport()?.setProperties({
...(mode.value === "3d" && { colormap: volumeColormap() }),
voiRange: {
lower: center.value - width.value / 2,
upper: center.value + width.value / 2,
},
});
schedule();
}
}
function volumeColormap() {
return {
opacity: opacity.value,
opacityMapping: [
{ value: center.value - width.value / 2, opacity: 0 },
{ value: center.value + width.value / 2, opacity: 1 },
],
};
}
watch([center, width, opacity], applyWindow);
async function switchView(value: Mode) {
if (!engine || !element.value || disposed || changing) return;
changing = true;
try {
mode.value = value;
engine.setViewports([
{
viewportId: viewportID,
type:
value === "3d"
? core.Enums.ViewportType.VOLUME_3D
: core.Enums.ViewportType.ORTHOGRAPHIC,
element: element.value,
defaultOptions: {
background: [0, 0, 0],
orientation:
value === "sagittal"
? core.Enums.OrientationAxis.SAGITTAL
: value === "coronal"
? core.Enums.OrientationAxis.CORONAL
: core.Enums.OrientationAxis.AXIAL,
},
},
]);
await core.setVolumesForViewports(engine, [{ volumeId: id }], [viewportID]);
if (disposed) return;
viewport()?.resetCamera();
if (value === "3d")
viewport()?.setProperties({
colormap: volumeColormap(),
voiRange: {
lower: center.value - width.value / 2,
upper: center.value + width.value / 2,
},
sampleDistanceMultiplier: 2,
});
else applyWindow();
engine.render();
} catch {
if (!disposed) emit("failed");
} finally {
changing = false;
}
}
function reset() {
center.value = props.volume.first.center;
width.value = props.volume.first.width;
opacity.value = 0.3;
viewport()?.resetCamera();
schedule();
}
function wheel(event: WheelEvent) {
const view = viewport();
if (!view || changing) return;
if (mode.value !== "3d" && !event.ctrlKey)
view.scroll(event.deltaY > 0 ? 1 : -1);
else
view.setZoom(
Math.max(
0.1,
Math.min(20, view.getZoom() * (event.deltaY > 0 ? 0.9 : 1.1))
)
);
schedule();
}
function pointerDown(event: PointerEvent) {
if (event.button !== 0 || !viewport()) return;
drag = { id: event.pointerId, x: event.clientX, y: event.clientY };
element.value?.setPointerCapture(event.pointerId);
}
// Rodrigues rotation around the camera's axes keeps oblique patient geometry intact.
function rotate(
vector: number[],
axis: number[],
angle: number
): [number, number, number] {
const length = Math.hypot(...axis),
a = axis.map((v) => v / length),
c = Math.cos(angle),
s = Math.sin(angle);
const dot = vector.reduce((n, v, i) => n + v * a[i], 0);
const cross = [
a[1] * vector[2] - a[2] * vector[1],
a[2] * vector[0] - a[0] * vector[2],
a[0] * vector[1] - a[1] * vector[0],
];
return vector.map((v, i) => v * c + cross[i] * s + a[i] * dot * (1 - c)) as [
number,
number,
number,
];
}
function pointerMove(event: PointerEvent) {
const view = viewport();
if (!drag || drag.id !== event.pointerId || !view || changing) return;
const dx = event.clientX - drag.x,
dy = event.clientY - drag.y;
drag.x = event.clientX;
drag.y = event.clientY;
if (mode.value === "3d") {
const camera = view.getCamera(),
up = camera.viewUp!,
focus = camera.focalPoint!,
position = camera.position!;
let offset = position.map((v, i) => v - focus[i]);
offset = rotate(offset, up, -dx * 0.008);
const right = [
up[1] * offset[2] - up[2] * offset[1],
up[2] * offset[0] - up[0] * offset[2],
up[0] * offset[1] - up[1] * offset[0],
];
offset = rotate(offset, right, -dy * 0.008);
view.setCamera({
position: offset.map((v, i) => v + focus[i]) as [number, number, number],
viewUp: rotate(up, right, -dy * 0.008),
});
} else {
const pan = view.getPan();
view.setPan([pan[0] + dx, pan[1] + dy]);
}
schedule();
}
function pointerUp() {
drag = undefined;
}
onMounted(async () => {
try {
core.init({ rendering: { useGenericViewport: false }, debug: {} });
if (core.getShouldUseCPURendering()) throw new Error("WebGL2 unavailable");
const { first, scalarData, dimensions, spacing, origin, direction } =
props.volume;
core.volumeLoader.createLocalVolume(id, {
scalarData,
dimensions,
spacing,
origin,
direction,
metadata: {
BitsAllocated: 32,
BitsStored: 32,
HighBit: 31,
SamplesPerPixel: 1,
PixelRepresentation: 1,
PhotometricInterpretation: "MONOCHROME2",
Modality: first.modality,
FrameOfReferenceUID: first.reference,
SeriesInstanceUID: first.series,
Columns: first.cols,
Rows: first.rows,
ImageOrientationPatient: first.orientation,
PixelSpacing: first.spacing,
voiLut: [],
VOILUTFunction: "LINEAR",
},
});
engine = new core.RenderingEngine(id);
await switchView("3d");
if (disposed) return;
observer = new ResizeObserver(() => {
if (!disposed) {
engine?.resize(true, true);
}
});
observer.observe(element.value!);
} catch {
if (!disposed) emit("failed");
}
});
onBeforeUnmount(() => {
disposed = true;
observer?.disconnect();
cancelAnimationFrame(frame);
engine?.destroy();
engine = undefined;
const volume = core.cache.getVolume(id);
// Also remove slices if allocation failed before the volume entered the cache.
const images = Array.from(
{ length: props.volume.dimensions[2] },
(_, i) => `${id}_slice_${i}`
);
if (volume) {
volume.vtkOpenGLTexture.releaseGraphicsResources();
volume.vtkOpenGLTexture.delete();
core.cache.removeVolumeLoadObject(id);
volume.voxelManager?.clear();
}
for (const image of images)
if (core.cache.getImage(image))
core.cache.removeImageLoadObject(image, { force: true });
});
</script>
<style scoped>
.dicom-volume {
display: flex;
flex: 1;
flex-direction: column;
min-height: 0;
overflow: hidden;
}
.dicom-volume-stage {
flex: 1;
min-height: 240px;
position: relative;
width: 100%;
background: #000;
touch-action: none;
}
.dicom-volume-hint {
font-size: 12px;
margin: 8px 12px;
text-align: center;
}
button[aria-pressed="true"] {
background: var(--surfaceSecondary);
color: var(--primaryColor);
}
@media (max-width: 600px) {
.document-tools {
gap: 5px;
padding: 6px;
}
.document-tools input {
width: 65px;
}
}
</style>
@@ -1,6 +1,10 @@
<template>
<PdfViewer v-if="kind === 'pdf'" :source="source" />
<DicomViewer v-else-if="kind === 'dicom'" :source="source" />
<DicomViewer
v-else-if="kind === 'dicom'"
:source="source"
:resource="resource"
/>
<ZipPreview v-else-if="kind === 'zip'" :source="source" :size="size || 0" />
<div
v-else
@@ -87,6 +91,7 @@ const props = defineProps<{
name: string;
type?: string;
size?: number;
resource?: Resource;
}>();
const { t } = useI18n();
const kind = computed(() => previewKind(props.name, props.type));
+13 -1
View File
@@ -361,7 +361,19 @@
"zipEmpty": "Empty archive",
"zipVisibleLimit": "Showing the first 1000 rows. Collapse folders to see other entries.",
"zipLimit": "The file list exceeds safe preview limits.",
"zipUnavailable": "Unable to read the file list. A standard ZIP and server support for range requests are required."
"zipUnavailable": "Unable to read the file list. A standard ZIP and server support for range requests are required.",
"open3d": "Open as 3D",
"back2d": "Back to 2D",
"loading3d": "Loading series: {count} / {total}",
"volumeLimit": "This series exceeds the safe 3D preview limit (128 MiB of decoded voxels, 2048 files). Use 2D preview.",
"volumeInvalid": "Cannot build a volume: the slices must belong to one study and series, have matching geometry and uniform spacing. 2D preview remains available.",
"volumeUnavailable": "3D preview is unavailable on this device. WebGL2 with volume rendering support is required.",
"axial": "Axial",
"sagittal": "Sagittal",
"coronal": "Coronal",
"opacity": "Opacity",
"volumeHint": "Drag to rotate · Scroll to zoom",
"sliceHint": "Scroll to change slice · Drag to pan · Ctrl + scroll to zoom"
},
"fileInfo": {
"dicom": "DICOM metadata",
+13 -1
View File
@@ -358,7 +358,19 @@
"zipEmpty": "Архив пуст",
"zipVisibleLimit": "Показаны первые 1000 строк. Сверните папки, чтобы увидеть остальные.",
"zipLimit": "Список файлов превышает безопасные лимиты предпросмотра.",
"zipUnavailable": "Не удалось прочитать список файлов. Требуется обычный ZIP и поддержка частичного скачивания сервером."
"zipUnavailable": "Не удалось прочитать список файлов. Требуется обычный ZIP и поддержка частичного скачивания сервером.",
"open3d": "Открыть как 3D",
"back2d": "Вернуться к 2D",
"loading3d": "Загрузка серии: {count} / {total}",
"volumeLimit": "Серия превышает безопасный лимит 3D-просмотра (128 МиБ декодированных вокселей, 2048 файлов). Используйте 2D.",
"volumeInvalid": "Не удалось построить объём: нужны срезы одного исследования и серии, с одинаковой геометрией и равномерным шагом. Просмотр в 2D доступен.",
"volumeUnavailable": "3D-просмотр недоступен на этом устройстве. Нужна поддержка WebGL2 и объёмного рендеринга.",
"axial": "Аксиально",
"sagittal": "Сагиттально",
"coronal": "Коронально",
"opacity": "Непрозрачность",
"volumeHint": "Перетаскивание — вращение · Колесо — масштаб",
"sliceHint": "Колесо — смена среза · Перетаскивание — перемещение · Ctrl + колесо — масштаб"
},
"fileInfo": {
"dicom": "Метаданные DICOM",
@@ -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);
+1
View File
@@ -125,6 +125,7 @@
:name="req.name"
:type="req.type"
:size="req.size"
:resource="req"
/>
</div>
<div
+6 -2
View File
@@ -75,7 +75,11 @@
:class="{ 'document-preview': isDicom || isPdf || isGenericPreview }"
>
<PdfViewer v-if="isPdf" :source="previewUrl" />
<DicomViewer v-else-if="isDicom" :source="previewUrl" />
<DicomViewer
v-else-if="isDicom"
:source="previewUrl"
:resource="fileStore.req || undefined"
/>
<div v-else-if="isEpub" class="epub-reader">
<vue-reader
:location="location"
@@ -310,7 +314,7 @@ const previewUrl = computed(() => {
return "";
}
if (fileStore.req.type === "image" && !fullSize.value) {
if (fileStore.req.type === "image" && !isDicom.value && !fullSize.value) {
return api.getPreviewURL(fileStore.req, "big");
}