Skip to content

refactor(dicom): unify loading and extract core and vtk modules - #1046

Open
PaulHax wants to merge 12 commits into
mainfrom
dicom-loading
Open

PaulHax wants to merge 12 commits into
mainfrom
dicom-loading

Conversation

@PaulHax

@PaulHax PaulHax commented Nov 24, 2026 •

Copy link
Copy Markdown
Collaborator

Replaces #994, now opened from a branch in this repository. It also includes #1047 (SliceThickness slice spacing), #1053 (HTJ2K decoding), decoders for every transfer syntax VolView loads, which take DICOM pixel decoding off GDCM and itk-wasm, MONOCHROME1 display handling and a DICOM test corpus.

DICOM files and URLs share one metadata-first pipeline that loads volumes frame by frame. Collections are planned the same way for batch and incremental imports, splitting incompatible acquisitions and pixel geometries while keeping stable identities, reconstruction details and session provenance.

The loader lives in src/dicom, split into core and vtk. Lint keeps core free of application, Vue, Pinia, vtk.js and itk-wasm imports and vtk free of application state and itk-wasm. src/dicom/README.md describes the layout and invariants.

  • Core reads instances from byte sources (files, blobs, URLs with Range requests) using an AbortSignal, plans collections with a pure registry reducer, and allocates and fills a Volume buffer it owns. A runtime owns the request pool, metadata workers and the codec decoders, and dispose() stops everything it started. Core imports no Vue, Pinia, vtk.js, itk-wasm or application code.
  • vtk wraps the volume buffer in vtkImageData without copying and widens the scalar range as slices arrive.
  • VolView keeps its stores and UI. Each registry update says whether its collection is unchanged, so a volume that still stands is not reallocated. An import plans and commits synchronously, so a series that fails changes nothing, and other series in the same import still land.

Loading order and decoding:

  • The slice in view loads first, then the rest coarse to fine. Scrolling re-prioritizes what is still queued. Slices that finish within 30 ms of each other are announced to the views together, since each announcement costs them a texture update.
  • Every unit of pixels loads one way. A pixel decoder plans, from the header alone, the units it would read and decode, and a decoder table gives each transfer syntax its decoder. Uncompressed pixel data is planned as one ranged read per frame, including multiframe files.
  • Each compressed transfer syntax has its own decoder. The instance is read as its Pixel Data value and its frames are decoded on a shared pool of codec workers that start on first use, each loading a codec's WASM the first time a frame needs it. The samples are then finished by the same code as uncompressed frames, which masks to Bits Stored, extends the sign and applies the modality rescale. JPEG 2000 and HTJ2K keep a codestream precision above Bits Stored, as GDCM did.
    • RLE Lossless: decoded in rleFrame.ts, no dependency.
    • JPEG-LS: CharLS (@cornerstonejs/codec-charls, MIT).
    • JPEG 2000: OpenJPEG (@cornerstonejs/codec-openjpeg, MIT).
    • HTJ2K, which VolView could not decode before: OpenJPH (@cornerstonejs/codec-openjph, MIT).
    • JPEG Baseline and Extended: libjpeg-turbo, in an 8 bit build (@cornerstonejs/codec-libjpeg-turbo-8bit, ISC) and a 12 bit build (@cornerstonejs/codec-libjpeg-turbo-12bit, ISC). The worker picks the build from the sample precision the stream declares.
    • JPEG Lossless: @cornerstonejs/jpeg-lossless-decoder-js (MIT), plain JavaScript.
    • Deflated Explicit VR Little Endian: inflated with the inflater the header parser already uses, then decoded as uncompressed frames. This runs on the calling thread.
  • The module no longer uses GDCM or itk-wasm. The same decoders now take what went to GDCM before: PALETTE COLOR with plain or segmented tables, YBR_FULL and YBR_FULL_422 color, samples of 1 and 12 bits allocated, big endian 8 and 32 bit samples, and files that were declined for carrying overlay planes, a Modality LUT Sequence or an ICC profile. VolView still uses itk-wasm outside this module, for other image formats, DICOM SEG, resampling and fill between slices.
  • A decoder is chosen from the header alone, so a file its codec accepts but cannot decode fails. A transfer syntax the table does not list fails as having no decoder; GDCM used to be tried for those.
  • Where GDCM and other libraries differ, the decoders follow what pydicom, DCMTK, fo-dicom and highdicom do:
    • Samples are masked to Bits Stored at every width. GDCM left 8 bit samples whole.
    • A Modality LUT Sequence is applied to grayscale in place of the rescale, except for X-Ray Angiographic and Radiofluoroscopic images, whose stored values are the ones to display. GDCM did not apply it.
    • High Bit is not consulted, as in GDCM, pydicom and Cornerstone.
  • The four WASM codecs are between 145 and 300 KB each before compression and are fetched only when a file needs them. The 12 bit JPEG build is a single JavaScript file of about 550 KB that carries its WASM, and it too is fetched only for a stream that needs it. For that, workers are now built as ES modules (worker.format in vite.config.ts), which applies to every worker in the app.
  • A frame of a local file is one Blob read. When a server ignores Range, the remaining frames of that file are read in one request instead of one full download per frame.
  • Volumes use Float32 buffers where integer or fractional rescale allows. vtk.js renders Float32 without converting the whole volume on each 3D render, which Int32 and Float64 buffers required. Values for fractional rescale (for example PET and DSC) can differ from Float64 by Float32 rounding, and a few test expectations change by that rounding only.

Cine:

  • Whether a multiframe ultrasound instance plays as a clip is decided from its header, so no pixel bytes are read at import. The clip reads its header from the shared dataset and its pixel bytes when loading starts.
  • Encapsulated frames are cut by splitEncapsulatedFrames: one fragment per frame when the counts match, else a Basic Offset Table whose entries each start a fragment, else JPEG End Of Image markers. dicom-parser is no longer a dependency.

Behavior changes for reviewers:

  • A volume removed while a later import brings more files of its series comes back holding only the new files, the same as removing it before that import started.
  • A failed load raises one error notification per load attempt, titled with the series name, instead of one per slice or frame. Its message names the file, and the frame when one frame was lost, and says whether it could not be read or decoded.
  • Thumbnail failures no longer raise their own error notification, except when encoding the thumbnail image itself fails.
  • A clip whose pixel data cannot be read fails as a clip when it loads. It used to fall back to a volume import.
  • A malformed encapsulated Pixel Data stream is an error instead of a best-effort split, except that a Basic Offset Table that does not fit the fragments is passed over. Compressed volumes that a codec decodes are split by the same rules as clips.
  • An uncompressed file cut short loads the frames it still holds and reports the rest. From a local file the missing part used to be shown as zeros with no error.
  • An instance whose frames carry differing modality rescale loads with each frame given its own Pixel Value Transformation. GDCM applied one rescale to a whole instance.
  • The modality rescale comes from a Pixel Value Transformation functional group only for the IODs that define it there (Enhanced and Legacy Converted CT, MR and PET, X-Ray 3D, breast tomosynthesis and projection, Segmentation), as GDCM read it. Other SOP classes, such as multi-frame secondary capture and ophthalmic tomography, use the top-level Rescale.
  • An uncompressed file that declares more frames than its Pixel Data holds fails to load, since the declared count sizes the buffer. It used to load with blank extra frames.
  • A series is planned within its study, so a Series Instance UID reused in another study or patient loads as its own volume.
  • An image with no Image Position (a radiograph, a secondary capture, a positionless multiframe) is named "(position unknown)" only when its series also holds a positioned volume.
  • A volume whose label changes because a sibling arrived is renamed in place. It is no longer reallocated.
  • Patient, study and series text is trimmed of DICOM padding, so a study that holds a clip and a still image no longer shows a second, empty patient.
  • A series with no description, number or Series Instance UID is named "Unnamed series".
  • MONOCHROME1 images keep their stored values and display with the Inverted grayscale preset and inverted thumbnails. GDCM rewrote these samples as their reflection across the stored range, so the header Window Center and Width applied to the wrong values.
  • A JPEG frame whose header says RGB is decoded without a color transform, unless the stream's own JFIF or Adobe segment states one. GDCM never transformed such a frame, so a file labeled RGB that holds JFIF YCbCr showed wrong colors. JPEG frames labeled YBR_FULL or YBR_FULL_422 load as RGB, as do JPEG 2000 and HTJ2K frames labeled YBR_RCT or YBR_ICT. Frames of the other syntaxes labeled YBR_FULL or YBR_FULL_422 are converted to RGB after decoding.
  • A Deflated file is inflated on the calling thread, where GDCM decoded it in a worker. Bytes that follow the deflate stream are ignored.
  • PALETTE COLOR images load as RGB at the depth GDCM decoded them to: 16 bits, or 8 bits for 8-bit pixels, which keep the high byte of each 16-bit palette entry.
  • Files that open without a Part 10 header, with file meta written in implicit VR or a private group ahead of the data set as older scanners wrote, load.
  • An image with one sample per pixel whose Photometric Interpretation is missing, as in ACR-NEMA files, or is anything but MONOCHROME1, MONOCHROME2 or PALETTE COLOR, is read as MONOCHROME2. GDCM inverted an image labeled "MONOCHROME", such as MR16BitsAllocated_8BitsStored.dcm in the GDCM test data, so that file now shows the opposite polarity.
  • Big endian 32 bit samples are read in their byte order. GDCM swapped them as 16 bit pairs.
  • A 1-bit frame, as in a binary SEG, unpacks to 0 and 1.
  • An HTTP failure reports its status. It used to say the resource could not be found for every status.
  • Files with unreadable content inside a defined-length sequence import, since the header scan steps over such sequences. Private elements are dropped in the metadata worker and never copied to the page.
  • Enhanced files whose frames carry no position and no Spacing Between Slices, such as some Ophthalmic Tomography exports, take their slice spacing from Slice Thickness, read per frame, then shared, then top level. Those files loaded with B-scans 1 mm apart, stretching the en face, sagittal and 3D views by tens of times. Zeiss Cirrus cubes declare a 0.002 mm Slice Thickness, which now compresses that axis instead. The "did not load as one sound volume" warning still appears for these files, since Slice Thickness describes the slice, not necessarily the gap.

The browser test pages under tests/fixtures/dicom-pages build straight from the module source and check calibrated voxel hashes and collection composition without VolView startup. The pages that compared GDCM with the other decoders and that tested recovery of a failed GDCM worker are removed with GDCM.

DICOM corpus:

  • Each corpus entry records facts about a public file (tags, which geometry tags it declares, frame axis, geometry and pixels) separately from what the loading module is expected to produce. A reference tool in tests/fixtures/dicom-pages/reference derives the facts with highdicom and pydicom, independent of VolView. Files highdicom cannot read list the tags their geometry comes from, and the tool checks those values against the file. Its README covers adding a file.
  • Files stay at their public sources (pydicom, pydicom-data, GDCM test data, Imaging Data Commons, dcm_qa); the manifests hold URLs, checksums, licenses and attribution. Generated files cover OCT geometry patterns (positioned, Slice Thickness only, Spacing Between Slices, radial, line scan), an encapsulated PDF, signed multi-frame HTJ2K encoded at test time, and RLE files (signed frames behind an offset table, RGB, 32 bit words).
  • Each codec has public files beyond plain grayscale: signed, near-lossless and lossy data, RGB and transformed color, a JP2 wrapped codestream, JPEG labeled RGB with and without a JFIF segment, 12 bit lossy JPEG, a JPEG fragment sequence of defined length, and JPEG 2000 codestreams whose sign or bit depth differs from the header. Lossy and converted color files are compared by per-channel minimum, maximum and mean within the manifest's tolerance, the rest by hash.
  • Files from the GDCM test data cover what GDCM used to decode: palette color, YBR_FULL in RLE, overlay planes, big endian 8 bit RGB, and a radiograph that is a bare implicit VR data set whose Modality LUT Sequence is applied.
  • tests/dicomExtendedCorpus.json is a slower tier run with DICOM_CORPUS=extended or the manual "Extended DICOM corpus" workflow. It covers RT, ultrasound, palette and YBR color, SEG, non-image objects, large radiographs and files without a preamble. A source that cannot be reached is skipped; a changed file fails.
  • The extended tier currently fails on RT Dose, which is left for a follow-up PR.

@netlify

netlify Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

❌ Deploy Preview for volview-dev failed.

Name Link
🔨 Latest commit 09f511f
🔍 Latest deploy log https://app.netlify.com/projects/volview-dev/deploys/6b0cc76d3d413aff1ba7a5cd

DICOM files and URLs share one metadata-first pipeline that loads
volumes frame by frame, in place of the ITK DICOM pipeline. Collections
are planned the same way for batch and incremental imports, splitting
incompatible acquisitions and pixel geometries while keeping stable
identities, reconstruction details and session provenance.

The module lives in src/dicom, split into core and vtk, and
eslint.config.js keeps both apart from the application. Core reads
instances from byte sources (files, blobs and URLs with Range
requests) with an AbortSignal, parses headers with dcmjs in workers,
plans collections with a pure registry reducer and fills a Volume
buffer it owns. A runtime holds the request pool and workers, and
dispose() stops everything it started. The vtk part wraps the buffer
in vtkImageData without copying and widens its scalar range as slices
arrive. VolView keeps its stores and UI. An import plans and commits
each series in one synchronous step, so a series that fails changes
nothing.

The slice in view loads first, then the rest coarse to fine.
Uncompressed MONOCHROME2 and RGB frames are read by their own ranges
and decoded without GDCM, which still decodes other instances whole in
workers. JPIP, video, HTJ2K and JPEG XL syntaxes have no decoder.
Volumes use Float32 buffers where the rescale allows, which vtk.js
renders without converting. Whether a multi-frame ultrasound instance
plays as a clip is decided from its header, and encapsulated frames
are split without dicom-parser.

A file without file meta information is read in the VR form its first
element shows, with a notice. Enhanced frames that carry no position
and no Spacing Between Slices take their slice spacing from Slice
Thickness.

A later import that regroups a volume into others removes it with a
warning, along with the annotations and view settings made on it. A
restored session reports a saved dataset that now loads as several
volumes instead of binding it to one. The itk-dicom WebAssembly build
and its npm scripts are removed, and dcmjs replaces the dicom-parser
and fflate dependencies.
DICOM objects with no Rows element, such as reports, key objects and
directories, hold no image to load. Like RT modality objects, they are
skipped with a warning that names the file and its modality instead of
failing the import. A DICOMweb series whose files partly fail still
shows its volume and raises a single notice that counts the failures
and lists each failed file's error. An HTTP failure names its status
instead of reporting every non-200 response as a missing resource.
HTJ2K transfer syntaxes had no decoder. They now decode whole on up to
decodeConcurrency OpenJPH workers (@cornerstonejs/codec-openjph), each
started on first use. The samples are finished by the same code as
native frames, so the HTJ2K decoder declines what native decoding
declines, and an HTJ2K instance it declines fails to load. Color
stored as YBR_RCT or YBR_ICT, which OpenJPH returns as RGB, loads as
RGB.

The GDCM, HTJ2K and metadata workers each run on a lane pool built
from one shared implementation: one job per worker, the rest queued. A
worker error rejects the running job and drops that worker, so the
next job starts a fresh one.
MONOCHROME1 polarity belongs to display. GDCM rewrote the samples as
their reflection across the stored range, which left the header window
pointing at the wrong values. Native frames now decode uncompressed
MONOCHROME1 instead of handing it to GDCM, and HTJ2K MONOCHROME1, which
had no decoder, now loads. Both keep the stored values, and the GDCM
decoder reflects GDCM's output back so every path agrees.

MONOCHROME1 images open with the Inverted grayscale preset and
inverted thumbnails.
A bare data set has no magic, so its first element decides once every
other magic has failed. Such a file was readable only when named .dcm.
Keying them by path in an object listed integer-like names first and
let two paths that differ only in leading slashes overwrite each other.
Each compressed transfer syntax has its own decoder. The instance is
read as its Pixel Data value and its frames decode on shared codec
workers that start on first use, each loading a codec's WASM the first
time a frame needs it. The samples are then finished by the same code
as uncompressed frames.

- RLE Lossless: rleFrame.ts, no dependency.
- JPEG-LS: CharLS (@cornerstonejs/codec-charls).
- JPEG 2000: OpenJPEG (@cornerstonejs/codec-openjpeg).
- HTJ2K: OpenJPH, now on the shared codec workers.
- JPEG Baseline and Extended: libjpeg-turbo in an 8 bit and a 12 bit
  build, picked by the precision the stream declares.
- JPEG Lossless: @cornerstonejs/jpeg-lossless-decoder-js.
- Deflated Explicit VR Little Endian: inflated on the calling thread
  by the header parser's inflater, then decoded as uncompressed frames.

The module no longer loads itk-wasm, and an ESLint rule keeps it out
of src/dicom. Its decoders take what went to GDCM: PALETTE COLOR with
plain or segmented tables, 8 bit YBR_FULL and YBR_FULL_422 color,
samples of 1 and 12 bits allocated, big endian 8 and 32 bit samples,
and instances with overlay planes, a Modality LUT Sequence or an ICC
profile. Overlay planes and ICC profiles are not applied. Color takes
no rescale, and one sample per pixel with a missing or unknown
photometric interpretation decodes as grayscale. A transfer syntax the
decoder table does not list fails as having no decoder.

Each frame takes its own Pixel Value Transformation. Where GDCM and
other libraries differ, the decoders follow pydicom, DCMTK, fo-dicom
and highdicom: samples are masked to Bits Stored at every width, a
Modality LUT Sequence replaces the rescale for grayscale other than
X-Ray Angiographic and Radiofluoroscopic images, and one fragment is
one frame when the counts match, whatever the Basic Offset Table says.
JPEG 2000 and HTJ2K keep a codestream precision above Bits Stored, and
codestreams of 8 bits or fewer are widened where the header allocates
16.

A JPEG frame the header calls RGB is decoded without a color transform
unless its own JFIF or Adobe segment states one. Workers are built as
ES modules, so the codec worker fetches its 12 bit JPEG build only for
a stream that needs it.

RT Image objects are imported as images; other radiotherapy objects
are still dropped at their Modality. Files skipped for a radiotherapy
modality or for holding no image raise one notice per reason per
session rather than one per file.

A multi-frame instance loads its middle frame first, as a multi-file
stack does.
Collections:
- A replan never merges two loaded volumes. An instance that would
  join them becomes a volume of its own.
- A later copy with the same facts becomes the source for slices that
  failed or never loaded.
- An anonymous collection keeps its id when a sibling splits it.
- One failing collection or cine clip no longer fails its whole series.
- Concatenation parts whose frame offsets tile load as one volume.
- Split parts take their own orientation, the in-plane tolerance grows
  with distance along the stack, positions within 1e-3 mm count as one
  plane, and passes interleaved on an even lattice stay one volume.
- Frames of one instance that lean in orientation are warned about.

Parsing:
- Read each sequence item in the VR form its first element shows, so
  undefined length UN elements holding explicit VR items load, and
  accept delimiter items with a nonzero length.
- Without file meta that names the data set's syntax, read it in the
  VR form its first element shows, with a warning.
- Treat the JPIP Referenced Deflate syntaxes as deflated.
- Trim NUL padding from Modality and Specific Character Set.

Decoding:
- Follow High Bit only when no word sets a bit below the samples.
- Read the LUT Descriptor as unsigned 16 bit and ignore empty LUT Data.
- Decode 16 bit RGB JPEG Lossless, and deflated YBR_FULL_422 that
  inflates to full samples as fully sampled color.
- Read indirect palette segment offsets as byte offsets and swap big
  endian 8 bit palette entries.
- Load JPEG 2000 codestreams deeper than Bits Stored, and NM frames
  that are not one reconstructed stack, with a warning.
- Ignore an unused malformed Basic Offset Table, join every fragment of
  a single frame past a stray FF D9 and accept a nonzero pad after a
  cine EOI.
- Decode instances with more frames than a call takes arguments, and
  packed samples past bit 2^31.
- Replace a codec worker whose decode failed; a stale worker error no
  longer resets its replacement.

Loading:
- Decoding yields to the next task after 30 ms.
- A failed batched read fails only the runs of units it held, never a
  unit already decoding.
- A grayscale thumbnail is windowed to its own slice's values, so it
  does not depend on which slices have been announced.
- A single chunk read is not copied.
- A deleted DICOMweb split volume can be downloaded again, and a clip
  whose first load failed completes and shows its thumbnail once
  playback reads its first frame.

src/dicom now uses undefined for absent values, and store specs record
through injected collaborators instead of reading stores.
Browser pages under tests/fixtures/dicom-pages build straight from the
module source and check calibrated voxel hashes and collection
composition without VolView startup. Playwright specs drive them, and
the application, against generated instances and pinned public files.
Existing specs follow the loader's changed behavior.

Corpus entries record facts about each file, derived by a highdicom
based reference tool in tests/fixtures/dicom-pages/reference, apart
from what the loading module is expected to produce. Files highdicom
cannot read cite the tags their geometry comes from, and the tool
checks those values. Files stay at their public sources, and the
manifests hold URLs, checksums and, for new entries, licenses and
attribution.

Every e2e run downloads the files of the volume and composition
manifests, and the CI dataset cache keys on both. The volume manifest
covers transfer syntaxes, palette and YBR color, MONOCHROME1,
multiframe and non-image files, plus generated OCT geometry patterns,
an encapsulated PDF, signed multi-frame HTJ2K and RLE variants. An
extended manifest covers RT dose, YBR ultrasound, XA and RF
multi-frame, a Siemens mosaic, SEG, a Key Object Selection, a large
radiograph and a file without a preamble. It runs with
DICOM_CORPUS=extended or the manual workflow, skips sources it cannot
reach and fails on changed files.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant